firebase 9.6.11 → 9.7.0
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/CHANGELOG.md +16 -0
- package/app/dist/index.cjs.js +1 -1
- package/app/dist/index.esm.js +1 -1
- package/app/dist/index.mjs +1 -1
- package/compat/app/dist/index.cjs.js +1 -1
- package/compat/app/dist/index.esm.js +1 -1
- package/compat/app/dist/index.mjs +1 -1
- package/compat/dist/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 +3 -3
- package/firebase-app-check-compat.js +2 -2
- package/firebase-app-check-compat.js.map +1 -1
- package/firebase-app-check.js +9 -9
- package/firebase-app-check.js.map +1 -1
- package/firebase-app-compat.js +2 -2
- package/firebase-app-compat.js.map +1 -1
- package/firebase-app.js +9 -9
- package/firebase-auth-cordova.js +1 -1
- package/firebase-auth-react-native.js +1 -1
- package/firebase-auth.js +2 -2
- package/firebase-compat.js +4 -4
- package/firebase-compat.js.map +1 -1
- package/firebase-database.js +4 -4
- package/firebase-firestore-compat.js +1 -1
- package/firebase-firestore-compat.js.map +1 -1
- package/firebase-firestore-lite.js +127 -121
- package/firebase-firestore-lite.js.map +1 -1
- package/firebase-firestore.js +4115 -4023
- package/firebase-firestore.js.map +1 -1
- package/firebase-functions-compat.js +1 -1
- package/firebase-functions-compat.js.map +1 -1
- package/firebase-functions.js +31 -5
- package/firebase-functions.js.map +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.es2017.js.map +1 -1
- package/firebase-performance-standalone-compat.js +1 -1
- package/firebase-performance-standalone-compat.js.map +1 -1
- package/firebase-performance.js +3 -3
- package/firebase-remote-config.js +2 -2
- package/firebase-storage.js +1 -1
- package/package.json +7 -7
|
@@ -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(Kf,jf){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l,t=e(Kf);function n(t){const n=[];let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&s+1<t.length&&56320==(64512&t.charCodeAt(s+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++s)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}const r={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const s=[];for(let c=0;c<n.length;c+=3){var i=n[c],a=c+1<n.length,o=a?n[c+1]:0,u=c+2<n.length,h=u?n[c+2]:0;let e=(15&o)<<2|h>>6,t=63&h;u||(t=64,a||(e=64)),s.push(r[i>>2],r[(3&i)<<4|o>>4],r[e],r[t])}return s.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var s,i,a=e[n++];a<128?t[r++]=String.fromCharCode(a):191<a&&a<224?(s=e[n++],t[r++]=String.fromCharCode((31&a)<<6|63&s)):239<a&&a<365?(i=((7&a)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(i>>10)),t[r++]=String.fromCharCode(56320+(1023&i))):(s=e[n++],i=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&s)<<6|63&i))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let u=0;u<e.length;){var s=n[e.charAt(u++)],i=u<e.length?n[e.charAt(u)]:0;++u;var a=u<e.length?n[e.charAt(u)]:64;++u;var o=u<e.length?n[e.charAt(u)]:64;if(++u,null==s||null==i||null==a||null==o)throw Error();r.push(s<<2|i>>4),64!==a&&(r.push(i<<4&240|a>>2),64!==o&&r.push(a<<6&192|o))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}},a=function(e){return e=e,t=n(e),r.encodeByteArray(t,!0).replace(/\./g,"");var t};function f(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function s(){return!function(){try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return}}()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}class o extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,o.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,i.prototype.create)}}class i{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},s=`${this.service}/${e}`,i=this.errors[e],i=i?(r=n,i.replace(u,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",i=`${this.serviceName}: ${i} (${s}).`;return new o(s,i,n)}}const u=/\{\$([^}]+)}/g;function m(e){return e&&e._delegate?e._delegate:e}class h{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}}(zl=l=l||{})[zl.DEBUG=0]="DEBUG",zl[zl.VERBOSE=1]="VERBOSE",zl[zl.INFO=2]="INFO",zl[zl.WARN=3]="WARN",zl[zl.ERROR=4]="ERROR",zl[zl.SILENT=5]="SILENT";const c={debug:l.DEBUG,verbose:l.VERBOSE,info:l.INFO,warn:l.WARN,error:l.ERROR,silent:l.SILENT},d=l.INFO,g={[l.DEBUG]:"log",[l.VERBOSE]:"log",[l.INFO]:"info",[l.WARN]:"warn",[l.ERROR]:"error"},p=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),s=g[t];if(!s)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[s](`[${r}] ${e.name}:`,...n)}};var y,v="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},w={},b=v||self;function I(){}function E(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 T(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var _="closure_uid_"+(1e9*Math.random()>>>0),S=0;function A(e,t,n){return e.call.apply(e.bind,arguments)}function D(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 x(e,t,n){return(x=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?A:D).apply(null,arguments)}function N(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 C(e,i){function t(){}t.prototype=i.prototype,e.Z=i.prototype,e.prototype=new t,(e.prototype.constructor=e).Vb=function(e,t,n){for(var r=Array(arguments.length-2),s=2;s<arguments.length;s++)r[s-2]=arguments[s];return i.prototype[t].apply(e,r)}}function k(){this.s=this.s,this.o=this.o}var M={};k.prototype.s=!1,k.prototype.na=function(){var e,t;!this.s&&(this.s=!0,this.M(),0)&&(t=this,e=Object.prototype.hasOwnProperty.call(t,_)&&t[_]||(t[_]=++S),delete M[e])},k.prototype.M=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const R=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},L=Array.prototype.forEach?function(e,t,n){Array.prototype.forEach.call(e,t,n)}:function(e,t,n){var r=e.length,s="string"==typeof e?e.split(""):e;for(let i=0;i<r;i++)i in s&&t.call(n,s[i],i,e)};function V(){return Array.prototype.concat.apply([],arguments)}function O(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function F(e){return/^[\s\xa0]*$/.test(e)}var P,B=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]};function q(e,t){return-1!=e.indexOf(t)}function U(e,t){return e<t?-1:t<e?1:0}e:{var K=b.navigator;if(K){K=K.userAgent;if(K){P=K;break e}}P=""}function j(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function G(e){const t={};for(const n in e)t[n]=e[n];return t}var $="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function z(t){let n,r;for(let s=1;s<arguments.length;s++){for(n in r=arguments[s])t[n]=r[n];for(let e=0;e<$.length;e++)n=$[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function W(e){return W[" "](e),e}W[" "]=I;var H,Q=q(P,"Opera"),Y=q(P,"Trident")||q(P,"MSIE"),X=q(P,"Edge"),J=X||Y,Z=q(P,"Gecko")&&!(q(P.toLowerCase(),"webkit")&&!q(P,"Edge"))&&!(q(P,"Trident")||q(P,"MSIE"))&&!q(P,"Edge"),ee=q(P.toLowerCase(),"webkit")&&!q(P,"Edge");function te(){var e=b.document;return e?e.documentMode:void 0}e:{var ne="",re=(re=P,Z?/rv:([^\);]+)(\)|;)/.exec(re):X?/Edge\/([\d\.]+)/.exec(re):Y?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(re):ee?/WebKit\/(\S+)/.exec(re):Q?/(?:Version)[ \/]?(\S+)/.exec(re):void 0);if(re&&(ne=re?re[1]:""),Y){re=te();if(null!=re&&re>parseFloat(ne)){H=String(re);break e}}H=ne}var se={};function ie(){return e=function(){let e=0;var t=B(String(H)).split("."),n=B("9").split("."),r=Math.max(t.length,n.length);for(let a=0;0==e&&a<r;a++)for(var s=t[a]||"",i=n[a]||"";s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],i=/(\d*)(\D*)(.*)/.exec(i)||["","","",""],(0!=s[0].length||0!=i[0].length)&&(e=U(0==s[1].length?0:parseInt(s[1],10),0==i[1].length?0:parseInt(i[1],10))||U(0==s[2].length,0==i[2].length)||U(s[2],i[2]),s=s[3],i=i[3],0==e););return 0<=e},t=se,Object.prototype.hasOwnProperty.call(t,9)?t[9]:t[9]=e(9);var e,t}var ae=b.document&&Y&&(te()||parseInt(H,10))||void 0,oe=function(){if(!b.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{b.addEventListener("test",I,t),b.removeEventListener("test",I,t)}catch(e){}return e}();function ue(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}function he(e,t){if(ue.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(Z){e:{try{W(t.nodeName);var s=!0;break e}catch(e){}s=!1}s||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:ce[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&he.Z.h.call(this)}}ue.prototype.h=function(){this.defaultPrevented=!0},C(he,ue);var ce={2:"touch",3:"pen",4:"mouse"};he.prototype.h=function(){he.Z.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var le="closure_listenable_"+(1e6*Math.random()|0),de=0;function fe(e,t,n,r,s){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ia=s,this.key=++de,this.ca=this.fa=!1}function ge(e){e.ca=!0,e.listener=null,e.proxy=null,e.src=null,e.ia=null}function me(e){this.src=e,this.g={},this.h=0}function pe(e,t){var n,r,s,i=t.type;i in e.g&&(n=e.g[i],(s=0<=(r=R(n,t)))&&Array.prototype.splice.call(n,r,1),s&&(ge(t),0==e.g[i].length&&(delete e.g[i],e.h--)))}function ye(e,t,n,r){for(var s=0;s<e.length;++s){var i=e[s];if(!i.ca&&i.listener==t&&i.capture==!!n&&i.ia==r)return s}return-1}me.prototype.add=function(e,t,n,r,s){var i=e.toString();(e=this.g[i])||(e=this.g[i]=[],this.h++);var a=ye(e,t,r,s);return-1<a?(t=e[a],n||(t.fa=!1)):((t=new fe(t,this.src,i,!!r,s)).fa=n,e.push(t)),t};var ve="closure_lm_"+(1e6*Math.random()|0),we={};function be(e,t,n,r,s){if(r&&r.once)return function e(t,n,r,s,i){if(Array.isArray(n)){for(var a=0;a<n.length;a++)e(t,n[a],r,s,i);return null}r=De(r);return t&&t[le]?t.O(n,r,T(s)?!!s.capture:!!s,i):Ie(t,n,r,!0,s,i)}(e,t,n,r,s);if(Array.isArray(t)){for(var i=0;i<t.length;i++)be(e,t[i],n,r,s);return null}return n=De(n),e&&e[le]?e.N(t,n,T(r)?!!r.capture:!!r,s):Ie(e,t,n,!1,r,s)}function Ie(e,t,n,r,s,i){if(!t)throw Error("Invalid event type");var a,o=T(s)?!!s.capture:!!s,u=Se(e);if(u||(e[ve]=u=new me(e)),(n=u.add(t,n,r,o,i)).proxy)return n;if(a=_e,r=function e(t){return a.call(e.src,e.listener,t)},(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(s=!oe?o:s)&&(s=!1),e.addEventListener(t.toString(),r,s);else if(e.attachEvent)e.attachEvent(Te(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function Ee(e){var t,n,r;"number"!=typeof e&&e&&!e.ca&&((t=e.src)&&t[le]?pe(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(Te(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=Se(t))?(pe(n,e),0==n.h&&(n.src=null,t[ve]=null)):ge(e)))}function Te(e){return e in we?we[e]:we[e]="on"+e}function _e(e,t){var n,r;return e=!!e.ca||(t=new he(t,this),n=e.listener,r=e.ia||e.src,e.fa&&Ee(e),n.call(r,t))}function Se(e){return(e=e[ve])instanceof me?e:null}var Ae="__closure_events_fn_"+(1e9*Math.random()>>>0);function De(t){return"function"==typeof t?t:(t[Ae]||(t[Ae]=function(e){return t.handleEvent(e)}),t[Ae])}function xe(){k.call(this),this.i=new me(this),(this.P=this).I=null}function Ne(e,t){var n,r=e.I;if(r)for(n=[];r;r=r.I)n.push(r);if(e=e.P,r=t.type||t,"string"==typeof t?t=new ue(t,e):t instanceof ue?t.target=t.target||e:(a=t,z(t=new ue(r,e),a)),a=!0,n)for(var s=n.length-1;0<=s;s--)var i=t.g=n[s],a=Ce(i,r,!0,t)&&a;if(a=Ce(i=t.g=e,r,!0,t)&&a,a=Ce(i,r,!1,t)&&a,n)for(s=0;s<n.length;s++)a=Ce(i=t.g=n[s],r,!1,t)&&a}function Ce(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var s=!0,i=0;i<t.length;++i){var a,o,u=t[i];u&&!u.ca&&u.capture==n&&(a=u.listener,o=u.ia||u.src,u.fa&&pe(e.i,u),s=!1!==a.call(o,r)&&s)}return s&&!r.defaultPrevented}C(xe,k),xe.prototype[le]=!0,xe.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,s,i){if(Array.isArray(n))for(var a=0;a<n.length;a++)e(t,n[a],r,s,i);else s=T(s)?!!s.capture:!!s,r=De(r),t&&t[le]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=ye(a=t.g[n],r,s,i))&&(ge(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete t.g[n],t.h--))):(t=t&&Se(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?ye(n,r,s,i):t)?n[t]:null)&&Ee(r))}(this,e,t,n,r)},xe.prototype.M=function(){if(xe.Z.M.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)ge(n[r]);delete t.g[e],t.h--}}this.I=null},xe.prototype.N=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},xe.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var ke=b.JSON.stringify;var Me,Re=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 Le,e=>e.reset());class Le{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function Ve(e,t){var n;Me||(n=b.Promise.resolve(void 0),Me=function(){n.then(Pe)}),Oe||(Me(),Oe=!0),Fe.add(e,t)}var Oe=!1,Fe=new class{constructor(){this.h=this.g=null}add(e,t){const n=Re.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function Pe(){for(var e;e=function(){var e=Fe;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){b.setTimeout(()=>{throw e},0)}(e)}var t=Re;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}Oe=!1}function Be(e,t){xe.call(this),this.h=e||1,this.g=t||b,this.j=x(this.kb,this),this.l=Date.now()}function qe(e){e.da=!1,e.S&&(e.g.clearTimeout(e.S),e.S=null)}function Ue(e,t,n){if("function"==typeof e)n&&(e=x(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=x(e.handleEvent,e)}return 2147483647<Number(t)?-1:b.setTimeout(e,t||0)}C(Be,xe),(y=Be.prototype).da=!1,y.S=null,y.kb=function(){var e;this.da&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.S=this.g.setTimeout(this.j,this.h-e):(this.S&&(this.g.clearTimeout(this.S),this.S=null),Ne(this,"tick"),this.da&&(qe(this),this.start())))},y.start=function(){this.da=!0,this.S||(this.S=this.g.setTimeout(this.j,this.h),this.l=Date.now())},y.M=function(){Be.Z.M.call(this),qe(this),delete this.g};class Ke extends k{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=Ue(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.j);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}M(){super.M(),this.g&&(b.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function je(e){k.call(this),this.h=e,this.g={}}C(je,k);var Ge=[];function $e(e,t,n,r){Array.isArray(n)||(n&&(Ge[0]=n.toString()),n=Ge);for(var s=0;s<n.length;s++){var i=be(t,n[s],r||e.handleEvent,!1,e.h||e);if(!i)break;e.g[i.key]=i}}function ze(e){j(e.g,function(e,t){this.g.hasOwnProperty(t)&&Ee(e)},e),e.g={}}function We(){this.g=!0}function He(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var s=r[1];if(Array.isArray(s)&&!(s.length<1)){var i=s[0];if("noop"!=i&&"stop"!=i&&"close"!=i)for(var a=1;a<s.length;a++)s[a]=""}}}return ke(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}je.prototype.M=function(){je.Z.M.call(this),ze(this)},je.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},We.prototype.Aa=function(){this.g=!1},We.prototype.info=function(){};var Qe={},Ye=null;function Xe(){return Ye=Ye||new xe}function Je(e){ue.call(this,Qe.Ma,e)}function Ze(){var e=Xe();Ne(e,new Je(e))}function et(e,t){ue.call(this,Qe.STAT_EVENT,e),this.stat=t}function tt(e){var t=Xe();Ne(t,new et(t,e))}function nt(e,t){ue.call(this,Qe.Na,e),this.size=t}function rt(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return b.setTimeout(function(){e()},t)}Qe.Ma="serverreachability",C(Je,ue),Qe.STAT_EVENT="statevent",C(et,ue),Qe.Na="timingevent",C(nt,ue);var st={NO_ERROR:0,lb:1,yb:2,xb:3,sb:4,wb:5,zb:6,Ja:7,TIMEOUT:8,Cb:9},it={qb:"complete",Mb:"success",Ka:"error",Ja:"abort",Eb:"ready",Fb:"readystatechange",TIMEOUT:"timeout",Ab:"incrementaldata",Db:"progress",tb:"downloadprogress",Ub:"uploadprogress"};function at(){}function ot(e){return e.h||(e.h=e.i())}function ut(){}at.prototype.h=null;v={OPEN:"a",pb:"b",Ka:"c",Bb:"d"};function ht(){ue.call(this,"d")}function ct(){ue.call(this,"c")}function lt(){}function dt(e,t,n,r){this.l=e,this.j=t,this.m=n,this.X=r||1,this.V=new je(this),this.P=mt,this.W=new Be(e=J?125:void 0),this.H=null,this.i=!1,this.s=this.A=this.v=this.K=this.F=this.Y=this.B=null,this.D=[],this.g=null,this.C=0,this.o=this.u=null,this.N=-1,this.I=!1,this.O=0,this.L=null,this.aa=this.J=this.$=this.U=!1,this.h=new ft}function ft(){this.i=null,this.g="",this.h=!1}C(ht,ue),C(ct,ue),C(lt,at),lt.prototype.g=function(){return new XMLHttpRequest},lt.prototype.i=function(){return{}};var gt=new lt,mt=45e3,pt={},yt={};function vt(e,t,n){e.K=1,e.v=qt(Lt(t)),e.s=n,e.U=!0,wt(e,null)}function wt(e,t){e.F=Date.now(),Et(e),e.A=Lt(e.v);var a,o,u,h,c,l,n=e.A,r=e.X;Array.isArray(r)||(r=[String(r)]),Zt(n.h,"t",r),e.C=0,n=e.l.H,e.h=new ft,e.g=er(e.l,n?t:null,!e.s),0<e.O&&(e.L=new Ke(x(e.Ia,e,e.g),e.O)),$e(e.V,e.g,"readystatechange",e.gb),t=e.H?G(e.H):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.s,t)):(e.u="GET",e.g.ea(e.A,e.u,null,t)),Ze(),a=e.j,o=e.u,u=e.A,h=e.m,c=e.X,l=e.s,a.info(function(){if(a.g)if(l)for(var e="",t=l.split("&"),n=0;n<t.length;n++){var r,s,i=t[n].split("=");1<i.length&&(r=i[0],i=i[1],e=2<=(s=r.split("_")).length&&"type"==s[1]?e+(r+"=")+i+"&":e+(r+"=redacted&"))}else e=null;else e=l;return"XMLHTTP REQ ("+h+") [attempt "+c+"]: "+o+"\n"+u+"\n"+e})}function bt(e){return e.g&&("GET"==e.u&&2!=e.K&&e.l.Ba)}function It(e,t,n){let r=!0,s;for(;!e.I&&e.C<n.length;){if(s=(a=n,u=o=void 0,o=(i=e).C,-1==(u=a.indexOf("\n",o))?yt:(o=Number(a.substring(o,u)),isNaN(o)?pt:(u+=1)+o>a.length?yt:(a=a.substr(u,o),i.C=u+o,a))),s==yt){4==t&&(e.o=4,tt(14),r=!1),He(e.j,e.m,null,"[Incomplete Response]");break}if(s==pt){e.o=4,tt(15),He(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}He(e.j,e.m,s,null),Dt(e,s)}var i,a,o,u;bt(e)&&s!=yt&&s!=pt&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,tt(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.aa&&(e.aa=!0,(t=e.l).g==e&&t.$&&!t.L&&(t.h.info("Great, no buffering proxy detected. Bytes received: "+n.length),zn(t),t.L=!0,tt(11))):(He(e.j,e.m,n,"[Invalid Chunked Response]"),At(e),St(e))}function Et(e){e.Y=Date.now()+e.P,Tt(e,e.P)}function Tt(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=rt(x(e.eb,e),t)}function _t(e){e.B&&(b.clearTimeout(e.B),e.B=null)}function St(e){0==e.l.G||e.I||Qn(e.l,e)}function At(e){_t(e);var t=e.L;t&&"function"==typeof t.na&&t.na(),e.L=null,qe(e.W),ze(e.V),e.g&&(t=e.g,e.g=null,t.abort(),t.na())}function Dt(e,t){try{var n=e.l;if(0!=n.G&&(n.g==e||on(n.i,e)))if(n.I=e.N,!e.J&&on(n.i,e)&&3==n.G){try{var r=n.Ca.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var s=r;if(0==s[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;Hn(n),Fn(n)}$n(n),tt(18)}}else n.ta=s[1],0<n.ta-n.U&&s[2]<37500&&n.N&&0==n.A&&!n.v&&(n.v=rt(x(n.ab,n),6e3));if(an(n.i)<=1&&n.ka){try{n.ka()}catch(e){}n.ka=void 0}}else Xn(n,11)}else if(!e.J&&n.g!=e||Hn(n),!F(t))for(s=n.Ca.g.parse(t),t=0;t<s.length;t++){var i=s[t];if(n.U=i[0],i=i[1],2==n.G)if("c"==i[0]){n.J=i[1],n.la=i[2];var a=i[3];null!=a&&(n.ma=a,n.h.info("VER="+n.ma));var o=i[4];null!=o&&(n.za=o,n.h.info("SVER="+n.za));var u,h,c,l=i[5];null!=l&&"number"==typeof l&&0<l&&(r=1.5*l,n.K=r,n.h.info("backChannelRequestTimeoutMs_="+r)),r=n;const m=e.g;m&&(!(u=m.g?m.g.getResponseHeader("X-Client-Wire-Protocol"):null)||!(h=r.i).g&&(q(u,"spdy")||q(u,"quic")||q(u,"h2"))&&(h.j=h.l,h.g=new Set,h.h&&(un(h,h.h),h.h=null)),!r.D||(c=m.g?m.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.sa=c,Bt(r.F,r.D,c))),n.G=3,n.j&&n.j.xa(),n.$&&(n.O=Date.now()-e.F,n.h.info("Handshake RTT: "+n.O+"ms"));var d,f,g=e;(r=n).oa=Zn(r,r.H?r.la:null,r.W),g.J?(hn(r.i,g),d=g,(f=r.K)&&d.setTimeout(f),d.B&&(_t(d),Et(d)),r.g=g):Gn(r),0<n.l.length&&qn(n)}else"stop"!=i[0]&&"close"!=i[0]||Xn(n,7);else 3==n.G&&("stop"==i[0]||"close"==i[0]?"stop"==i[0]?Xn(n,7):On(n):"noop"!=i[0]&&n.j&&n.j.wa(i),n.A=0)}Ze()}catch(e){}}function xt(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(E(e)||"string"==typeof e)L(e,t,void 0);else{if(e.T&&"function"==typeof e.T)var n=e.T();else if(e.R&&"function"==typeof e.R)n=void 0;else if(E(e)||"string"==typeof e)for(var n=[],r=e.length,s=0;s<r;s++)n.push(s);else for(s in n=[],r=0,e)n[r++]=s;for(var s=(r=function(e){if(e.R&&"function"==typeof e.R)return e.R();if("string"==typeof e)return e.split("");if(E(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)).length,i=0;i<s;i++)t.call(void 0,r[i],n&&n[i],e)}}function Nt(e,t){this.h={},this.g=[],this.i=0;var n=arguments.length;if(1<n){if(n%2)throw Error("Uneven number of arguments");for(var r=0;r<n;r+=2)this.set(arguments[r],arguments[r+1])}else if(e)if(e instanceof Nt)for(n=e.T(),r=0;r<n.length;r++)this.set(n[r],e.get(n[r]));else for(r in e)this.set(r,e[r])}function Ct(e){if(e.i!=e.g.length){for(var t=0,n=0;t<e.g.length;){var r=e.g[t];kt(e.h,r)&&(e.g[n++]=r),t++}e.g.length=n}if(e.i!=e.g.length){for(var s={},n=t=0;t<e.g.length;)kt(s,r=e.g[t])||(s[e.g[n++]=r]=1),t++;e.g.length=n}}function kt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(y=dt.prototype).setTimeout=function(e){this.P=e},y.gb=function(e){e=e.target;const t=this.L;t&&3==kn(e)?t.l():this.Ia(e)},y.Ia=function(e){try{if(e==this.g)e:{var t=kn(this.g),n=this.g.Da();this.g.ba();if(!(t<3)&&(3!=t||J||this.g&&(this.h.h||this.g.ga()||Mn(this.g)))){this.I||4!=t||7==n||Ze(),_t(this);var r=this.g.ba();this.N=r;t:if(bt(this)){var s=Mn(this.g);e="";var i=s.length,a=4==kn(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){At(this),St(this);var o="";break t}this.h.i=new b.TextDecoder}for(n=0;n<i;n++)this.h.h=!0,e+=this.h.i.decode(s[n],{stream:a&&n==i-1});s.splice(0,i),this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.ga();if(this.i=200==r,l=this.j,d=this.u,f=this.A,g=this.m,m=this.X,p=t,y=r,l.info(function(){return"XMLHTTP RESP ("+g+") [ attempt "+m+"]: "+d+"\n"+f+"\n"+p+" "+y}),this.i){if(this.$&&!this.J){t:{if(this.g){var u,h=this.g;if((u=h.g?h.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!F(u)){var c=u;break t}}c=null}if(!(r=c)){this.i=!1,this.o=3,tt(12),At(this),St(this);break e}He(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.J=!0,Dt(this,r)}this.U?(It(this,t,o),J&&this.i&&3==t&&($e(this.V,this.W,"tick",this.fb),this.W.start())):(He(this.j,this.m,o,null),Dt(this,o)),4==t&&At(this),this.i&&!this.I&&(4==t?Qn(this.l,this):(this.i=!1,Et(this)))}else 400==r&&0<o.indexOf("Unknown SID")?(this.o=3,tt(12)):(this.o=0,tt(13)),At(this),St(this)}}}catch(e){}var l,d,f,g,m,p,y},y.fb=function(){var e,t;this.g&&(e=kn(this.g),t=this.g.ga(),this.C<t.length&&(_t(this),It(this,e,t),this.i&&4!=e&&Et(this)))},y.cancel=function(){this.I=!0,At(this)},y.eb=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.K&&(Ze(),tt(17)),At(this),this.o=2,St(this)):Tt(this,this.Y-n)},(y=Nt.prototype).R=function(){Ct(this);for(var e=[],t=0;t<this.g.length;t++)e.push(this.h[this.g[t]]);return e},y.T=function(){return Ct(this),this.g.concat()},y.get=function(e,t){return kt(this.h,e)?this.h[e]:t},y.set=function(e,t){kt(this.h,e)||(this.i++,this.g.push(e)),this.h[e]=t},y.forEach=function(e,t){for(var n=this.T(),r=0;r<n.length;r++){var s=n[r],i=this.get(s);e.call(t,i,s,this)}};var Mt=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function Rt(e,t){var n;this.i=this.s=this.j="",this.m=null,this.o=this.l="",this.g=!1,e instanceof Rt?(this.g=void 0!==t?t:e.g,Vt(this,e.j),this.s=e.s,Ot(this,e.i),Ft(this,e.m),this.l=e.l,t=e.h,(n=new Qt).i=t.i,t.g&&(n.g=new Nt(t.g),n.h=t.h),Pt(this,n),this.o=e.o):e&&(n=String(e).match(Mt))?(this.g=!!t,Vt(this,n[1]||"",!0),this.s=Ut(n[2]||""),Ot(this,n[3]||"",!0),Ft(this,n[4]),this.l=Ut(n[5]||"",!0),Pt(this,n[6]||"",!0),this.o=Ut(n[7]||"")):(this.g=!!t,this.h=new Qt(null,this.g))}function Lt(e){return new Rt(e)}function Vt(e,t,n){e.j=n?Ut(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Ot(e,t,n){e.i=n?Ut(t,!0):t}function Ft(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 Pt(e,t,n){var r,s;t instanceof Qt?(e.h=t,r=e.h,(s=e.g)&&!r.j&&(Yt(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(Xt(this,t),Zt(this,n,e))},r)),r.j=s):(n||(t=Kt(t,Wt)),e.h=new Qt(t,e.g))}function Bt(e,t,n){e.h.set(t,n)}function qt(e){return Bt(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Ut(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Kt(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,jt),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function jt(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}Rt.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Kt(t,Gt,!0),":");var n=this.i;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(Kt(t,Gt,!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.i&&"/"!=n.charAt(0)&&e.push("/"),e.push(Kt(n,"/"==n.charAt(0)?zt:$t,!0))),(n=this.h.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Kt(n,Ht)),e.join("")};var Gt=/[#\/\?@]/g,$t=/[#\?:]/g,zt=/[#\?]/g,Wt=/[#\?@]/g,Ht=/#/g;function Qt(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function Yt(n){n.g||(n.g=new Nt,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,s=e[n].indexOf("="),i=null;0<=s?(r=e[n].substring(0,s),i=e[n].substring(s+1)):r=e[n],t(r,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function Xt(e,t){Yt(e),t=en(e,t),kt(e.g.h,t)&&(e.i=null,e.h-=e.g.get(t).length,kt((e=e.g).h,t)&&(delete e.h[t],e.i--,e.g.length>2*e.i&&Ct(e)))}function Jt(e,t){return Yt(e),t=en(e,t),kt(e.g.h,t)}function Zt(e,t,n){Xt(e,t),0<n.length&&(e.i=null,e.g.set(en(e,t),O(n)),e.h+=n.length)}function en(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(y=Qt.prototype).add=function(e,t){Yt(this),this.i=null,e=en(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},y.forEach=function(n,r){Yt(this),this.g.forEach(function(e,t){L(e,function(e){n.call(r,e,t,this)},this)},this)},y.T=function(){Yt(this);for(var e=this.g.R(),t=this.g.T(),n=[],r=0;r<t.length;r++)for(var s=e[r],i=0;i<s.length;i++)n.push(t[r]);return n},y.R=function(e){Yt(this);var t=[];if("string"==typeof e)Jt(this,e)&&(t=V(t,this.g.get(en(this,e))));else{e=this.g.R();for(var n=0;n<e.length;n++)t=V(t,e[n])}return t},y.set=function(e,t){return Yt(this),this.i=null,Jt(this,e=en(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},y.get=function(e,t){return e&&0<(e=this.R(e)).length?String(e[0]):t},y.toString=function(){if(this.i)return this.i;if(!this.g)return"";for(var e=[],t=this.g.T(),n=0;n<t.length;n++)for(var r=t[n],s=encodeURIComponent(String(r)),r=this.R(r),i=0;i<r.length;i++){var a=s;""!==r[i]&&(a+="="+encodeURIComponent(String(r[i]))),e.push(a)}return this.i=e.join("&")};var tn=class{constructor(e,t){this.h=e,this.g=t}};function nn(e){this.l=e||10,e=b.PerformanceNavigationTiming?0<(e=b.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(b.g&&b.g.Ea&&b.g.Ea()&&b.g.Ea().Zb),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}var rn;function sn(e){return e.h||e.g&&e.g.size>=e.j}function an(e){return e.h?1:e.g?e.g.size:0}function on(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function un(e,t){e.g?e.g.add(t):e.h=t}function hn(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function cn(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return O(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function ln(){}function dn(){this.g=new ln}function fn(e,t,n,r,s){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,s(r)}catch(e){}}function gn(e){this.l=e.$b||null,this.j=e.ib||!1}function mn(e,t){xe.call(this),this.D=e,this.u=t,this.m=void 0,this.readyState=pn,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}nn.prototype.cancel=function(){if(this.i=cn(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()}},ln.prototype.stringify=function(e){return b.JSON.stringify(e,void 0)},ln.prototype.parse=function(e){return b.JSON.parse(e,void 0)},C(gn,at),gn.prototype.g=function(){return new mn(this.l,this.j)},gn.prototype.i=(rn={},function(){return rn}),C(mn,xe);var pn=0;function yn(e){e.j.read().then(e.Sa.bind(e)).catch(e.ha.bind(e))}function vn(e){e.readyState=4,e.l=null,e.j=null,e.A=null,wn(e)}function wn(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(y=mn.prototype).open=function(e,t){if(this.readyState!=pn)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,wn(this)},y.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||b).fetch(new Request(this.B,t)).then(this.Va.bind(this),this.ha.bind(this))},y.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted."),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,vn(this)),this.readyState=pn},y.Va=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,wn(this)),this.g&&(this.readyState=3,wn(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ta.bind(this),this.ha.bind(this));else if(void 0!==b.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;yn(this)}else e.text().then(this.Ua.bind(this),this.ha.bind(this))},y.Sa=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?vn:wn)(this),3==this.readyState&&yn(this))},y.Ua=function(e){this.g&&(this.response=this.responseText=e,vn(this))},y.Ta=function(e){this.g&&(this.response=e,vn(this))},y.ha=function(){this.g&&vn(this)},y.setRequestHeader=function(e,t){this.v.append(e,t)},y.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},y.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(mn.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var bn=b.JSON.parse;function In(e){xe.call(this),this.headers=new Nt,this.u=e||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=En,this.K=this.L=!1}C(In,xe);var En="",Tn=/^https?$/i,_n=["POST","PUT"];function Sn(e){return"content-type"==e.toLowerCase()}function An(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,Dn(e),Nn(e)}function Dn(e){e.D||(e.D=!0,Ne(e,"complete"),Ne(e,"error"))}function xn(e){if(e.h&&void 0!==w&&(!e.C[1]||4!=kn(e)||2!=e.ba()))if(e.v&&4==kn(e))Ue(e.Fa,0,e);else if(Ne(e,"readystatechange"),4==kn(e)){e.h=!1;try{var t,n,r,s,i=e.ba();e:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var a=!0;break e;default:a=!1}if((t=a)||((n=0===i)&&(!(s=String(e.H).match(Mt)[1]||null)&&b.self&&b.self.location&&(s=(r=b.self.location.protocol).substr(0,r.length-1)),n=!Tn.test(s?s.toLowerCase():"")),t=n),t)Ne(e,"complete"),Ne(e,"success");else{e.m=6;try{var o=2<kn(e)?e.g.statusText:""}catch(e){o=""}e.j=o+" ["+e.ba()+"]",Dn(e)}}finally{Nn(e)}}}function Nn(e,t){if(e.g){Cn(e);const n=e.g,r=e.C[0]?I:null;e.g=null,e.C=null,t||Ne(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Cn(e){e.g&&e.K&&(e.g.ontimeout=null),e.A&&(b.clearTimeout(e.A),e.A=null)}function kn(e){return e.g?e.g.readyState:0}function Mn(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.J){case En:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Rn(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=function(e){let n="";return j(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):Bt(e,t,n))}function Ln(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function Vn(e){this.za=0,this.l=[],this.h=new We,this.la=this.oa=this.F=this.W=this.g=this.sa=this.D=this.aa=this.o=this.P=this.s=null,this.Za=this.V=0,this.Xa=Ln("failFast",!1,e),this.N=this.v=this.u=this.m=this.j=null,this.X=!0,this.I=this.ta=this.U=-1,this.Y=this.A=this.C=0,this.Pa=Ln("baseRetryDelayMs",5e3,e),this.$a=Ln("retryDelaySeedMs",1e4,e),this.Ya=Ln("forwardChannelMaxRetries",2,e),this.ra=Ln("forwardChannelRequestTimeoutMs",2e4,e),this.qa=e&&e.xmlHttpFactory||void 0,this.Ba=e&&e.Yb||!1,this.K=void 0,this.H=e&&e.supportsCrossDomainXhr||!1,this.J="",this.i=new nn(e&&e.concurrentRequestLimit),this.Ca=new dn,this.ja=e&&e.fastHandshake||!1,this.Ra=e&&e.Wb||!1,e&&e.Aa&&this.h.Aa(),e&&e.forceLongPolling&&(this.X=!1),this.$=!this.ja&&this.X&&e&&e.detectBufferingProxy||!1,this.ka=void 0,this.O=0,this.L=!1,this.B=null,this.Wa=!e||!1!==e.Xb}function On(e){var t,n;Pn(e),3==e.G&&(t=e.V++,Bt(n=Lt(e.F),"SID",e.J),Bt(n,"RID",t),Bt(n,"TYPE","terminate"),Kn(e,n),(t=new dt(e,e.h,t,void 0)).K=2,t.v=qt(Lt(n)),n=!1,!(n=b.navigator&&b.navigator.sendBeacon?b.navigator.sendBeacon(t.v.toString(),""):n)&&b.Image&&((new Image).src=t.v,n=!0),n||(t.g=er(t.l,null),t.g.ea(t.v)),t.F=Date.now(),Et(t)),Jn(e)}function Fn(e){e.g&&(zn(e),e.g.cancel(),e.g=null)}function Pn(e){Fn(e),e.u&&(b.clearTimeout(e.u),e.u=null),Hn(e),e.i.cancel(),e.m&&("number"==typeof e.m&&b.clearTimeout(e.m),e.m=null)}function Bn(e,t){e.l.push(new tn(e.Za++,t)),3==e.G&&qn(e)}function qn(e){sn(e.i)||e.m||(e.m=!0,Ve(e.Ha,e),e.C=0)}function Un(e,t){var n=t?t.m:e.V++,r=Lt(e.F);Bt(r,"SID",e.J),Bt(r,"RID",n),Bt(r,"AID",e.U),Kn(e,r),e.o&&e.s&&Rn(r,e.o,e.s),n=new dt(e,e.h,n,e.C+1),null===e.o&&(n.H=e.s),t&&(e.l=t.D.concat(e.l)),t=jn(e,n,1e3),n.setTimeout(Math.round(.5*e.ra)+Math.round(.5*e.ra*Math.random())),un(e.i,n),vt(n,r,t)}function Kn(e,n){e.j&&xt({},function(e,t){Bt(n,t,e)})}function jn(e,t,r){r=Math.min(e.l.length,r);var s=e.j?x(e.j.Oa,e.j,e):null;e:{var i=e.l;let n=-1;for(;;){const u=["count="+r];-1==n?0<r?(n=i[0].h,u.push("ofs="+n)):n=0:u.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var a=i[t].h,o=i[t].g;if((a-=n)<0)n=Math.max(0,i[t].h-100),e=!1;else try{!function(e,r,t){const s=t||"";try{xt(e,function(e,t){let n=e;T(e)&&(n=ke(e)),r.push(s+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(s+"type="+encodeURIComponent("_badmap")),e}}(o,u,"req"+a+"_")}catch(e){s&&s(o)}}if(e){s=u.join("&");break e}}}return e=e.l.splice(0,r),t.D=e,s}function Gn(e){e.g||e.u||(e.Y=1,Ve(e.Ga,e),e.A=0)}function $n(e){return!(e.g||e.u||3<=e.A)&&(e.Y++,e.u=rt(x(e.Ga,e),Yn(e,e.A)),e.A++,1)}function zn(e){null!=e.B&&(b.clearTimeout(e.B),e.B=null)}function Wn(e){e.g=new dt(e,e.h,"rpc",e.Y),null===e.o&&(e.g.H=e.s),e.g.O=0;var t=Lt(e.oa);Bt(t,"RID","rpc"),Bt(t,"SID",e.J),Bt(t,"CI",e.N?"0":"1"),Bt(t,"AID",e.U),Kn(e,t),Bt(t,"TYPE","xmlhttp"),e.o&&e.s&&Rn(t,e.o,e.s),e.K&&e.g.setTimeout(e.K);var n=e.g;e=e.la,n.K=1,n.v=qt(Lt(t)),n.s=null,n.U=!0,wt(n,e)}function Hn(e){null!=e.v&&(b.clearTimeout(e.v),e.v=null)}function Qn(e,t){var n,r,s,i=null;if(e.g==t){Hn(e),zn(e),e.g=null;var a=2}else{if(!on(e.i,t))return;i=t.D,hn(e.i,t),a=1}if(e.I=t.N,0!=e.G)if(t.i)1==a?(i=t.s?t.s.length:0,t=Date.now()-t.F,n=e.C,Ne(a=Xe(),new nt(a,i)),qn(e)):Gn(e);else if(3==(n=t.o)||0==n&&0<e.I||(1!=a||(s=t,an((r=e).i)>=r.i.j-(r.m?1:0)||(r.m?(r.l=s.D.concat(r.l),0):1==r.G||2==r.G||r.C>=(r.Xa?0:r.Ya)||(r.m=rt(x(r.Ha,r,s),Yn(r,r.C)),r.C++,0))))&&(2!=a||!$n(e)))switch(i&&0<i.length&&(t=e.i,t.i=t.i.concat(i)),n){case 1:Xn(e,5);break;case 4:Xn(e,10);break;case 3:Xn(e,6);break;default:Xn(e,2)}}function Yn(e,t){let n=e.Pa+Math.floor(Math.random()*e.$a);return e.j||(n*=2),n*t}function Xn(e,t){var n,r;e.h.info("Error code "+t),2==t?(n=null,e.j&&(n=null),r=x(e.jb,e),n||(n=new Rt("//www.google.com/images/cleardot.gif"),b.location&&"http"==b.location.protocol||Vt(n,"https"),qt(n)),function(e,t){var n=new We;if(b.Image){const r=new Image;r.onload=N(fn,n,r,"TestLoadImage: loaded",!0,t),r.onerror=N(fn,n,r,"TestLoadImage: error",!1,t),r.onabort=N(fn,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=N(fn,n,r,"TestLoadImage: timeout",!1,t),b.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):tt(2),e.G=0,e.j&&e.j.va(t),Jn(e),Pn(e)}function Jn(e){e.G=0,e.I=-1,e.j&&(0==cn(e.i).length&&0==e.l.length||(e.i.i.length=0,O(e.l),e.l.length=0),e.j.ua())}function Zn(e,t,n){let r=(o=n)instanceof Rt?Lt(o):new Rt(o,void 0);var s,i,a,o,u;return""!=r.i?(t&&Ot(r,t+"."+r.i),Ft(r,r.m)):(u=b.location,r=(s=u.protocol,i=t?t+"."+u.hostname:u.hostname,a=+u.port,o=n,u=new Rt(null,void 0),s&&Vt(u,s),i&&Ot(u,i),a&&Ft(u,a),o&&(u.l=o),u)),e.aa&&j(e.aa,function(e,t){Bt(r,t,e)}),t=e.D,n=e.sa,t&&n&&Bt(r,t,n),Bt(r,"VER",e.ma),Kn(e,r),r}function er(e,t,n){if(t&&!e.H)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ba&&!e.qa?new In(new gn({ib:!0})):new In(e.qa)).L=e.H,t}function tr(){}function nr(){if(Y&&!(10<=Number(ae)))throw Error("Environmental error: no available transport.")}function rr(e,t){xe.call(this),this.g=new Vn(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.s=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.ya&&(e?e["X-WebChannel-Client-Profile"]=t.ya:e={"X-WebChannel-Client-Profile":t.ya}),this.g.P=e,(e=t&&t.httpHeadersOverwriteParam)&&!F(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!F(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new ar(this)}function sr(e){ht.call(this);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function ir(){ct.call(this),this.status=1}function ar(e){this.g=e}(y=In.prototype).ea=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.H+"; newUri="+e);t=t?t.toUpperCase():"GET",this.H=e,this.j="",this.m=0,this.D=!1,this.h=!0,this.g=(this.u||gt).g(),this.C=this.u?ot(this.u):ot(gt),this.g.onreadystatechange=x(this.Fa,this);try{this.F=!0,this.g.open(t,String(e),!0),this.F=!1}catch(e){return void An(this,e)}e=n||"";const s=new Nt(this.headers);r&&xt(r,function(e,t){s.set(t,e)}),r=function(t){e:{var n=Sn,r=t.length,s="string"==typeof t?t.split(""):t;for(let e=0;e<r;e++)if(e in s&&n.call(void 0,s[e],e,t)){n=e;break e}n=-1}return n<0?null:"string"==typeof t?t.charAt(n):t[n]}(s.T()),n=b.FormData&&e instanceof b.FormData,0<=R(_n,t)&&!r&&!n&&s.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),s.forEach(function(e,t){this.g.setRequestHeader(t,e)},this),this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{Cn(this),0<this.B&&((this.K=(i=this.g,Y&&ie()&&"number"==typeof i.timeout&&void 0!==i.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=x(this.pa,this)):this.A=Ue(this.pa,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){An(this,e)}var i},y.pa=function(){void 0!==w&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,Ne(this,"timeout"),this.abort(8))},y.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,Ne(this,"complete"),Ne(this,"abort"),Nn(this))},y.M=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),Nn(this,!0)),In.Z.M.call(this)},y.Fa=function(){this.s||(this.F||this.v||this.l?xn(this):this.cb())},y.cb=function(){xn(this)},y.ba=function(){try{return 2<kn(this)?this.g.status:-1}catch(e){return-1}},y.ga=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},y.Qa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),bn(t)}},y.Da=function(){return this.m},y.La=function(){return"string"==typeof this.j?this.j:String(this.j)},(y=Vn.prototype).ma=8,y.G=1,y.hb=function(e){try{this.h.info("Origin Trials invoked: "+e)}catch(e){}},y.Ha=function(t){if(this.m)if(this.m=null,1==this.G){if(!t){this.V=Math.floor(1e5*Math.random()),t=this.V++;const i=new dt(this,this.h,t,void 0);let e=this.s;if(this.P&&(e?(e=G(e),z(e,this.P)):e=this.P),null===this.o&&(i.H=e),this.ja)e:{for(var n=0,r=0;r<this.l.length;r++){var s=this.l[r];if("__data__"in s.g&&"string"==typeof(s=s.g.__data__)?s=s.length:s=void 0,void 0===s)break;if(4096<(n+=s)){n=r;break e}if(4096===n||r===this.l.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=jn(this,i,n),Bt(r=Lt(this.F),"RID",t),Bt(r,"CVER",22),this.D&&Bt(r,"X-HTTP-Session-Id",this.D),Kn(this,r),this.o&&e&&Rn(r,this.o,e),un(this.i,i),this.Ra&&Bt(r,"TYPE","init"),this.ja?(Bt(r,"$req",n),Bt(r,"SID","null"),i.$=!0,vt(i,r,null)):vt(i,r,n),this.G=2}}else 3==this.G&&(t?Un(this,t):0==this.l.length||sn(this.i)||Un(this))},y.Ga=function(){var e;this.u=null,Wn(this),this.$&&!(this.L||null==this.g||this.O<=0)&&(e=2*this.O,this.h.info("BP detection timer enabled: "+e),this.B=rt(x(this.bb,this),e))},y.bb=function(){this.B&&(this.B=null,this.h.info("BP detection timeout reached."),this.h.info("Buffering proxy detected and switch to long-polling!"),this.N=!1,this.L=!0,tt(10),Fn(this),Wn(this))},y.ab=function(){null!=this.v&&(this.v=null,Fn(this),$n(this),tt(19))},y.jb=function(e){e?(this.h.info("Successfully pinged google.com"),tt(2)):(this.h.info("Failed to ping google.com"),tt(1))},(y=tr.prototype).xa=function(){},y.wa=function(){},y.va=function(){},y.ua=function(){},y.Oa=function(){},nr.prototype.g=function(e,t){return new rr(e,t)},C(rr,xe),rr.prototype.m=function(){this.g.j=this.j,this.A&&(this.g.H=!0);var e=this.g,t=this.l,n=this.h||void 0;e.Wa&&(e.h.info("Origin Trials enabled."),Ve(x(e.hb,e,t))),tt(0),e.W=t,e.aa=n||{},e.N=e.X,e.F=Zn(e,null,e.W),qn(e)},rr.prototype.close=function(){On(this.g)},rr.prototype.u=function(e){var t;"string"==typeof e?((t={}).__data__=e,Bn(this.g,t)):this.v?((t={}).__data__=ke(e),Bn(this.g,t)):Bn(this.g,e)},rr.prototype.M=function(){this.g.j=null,delete this.j,On(this.g),delete this.g,rr.Z.M.call(this)},C(sr,ht),C(ir,ct),C(ar,tr),ar.prototype.xa=function(){Ne(this.g,"a")},ar.prototype.wa=function(e){Ne(this.g,new sr(e))},ar.prototype.va=function(e){Ne(this.g,new ir)},ar.prototype.ua=function(){Ne(this.g,"b")},nr.prototype.createWebChannel=nr.prototype.g,rr.prototype.send=rr.prototype.u,rr.prototype.open=rr.prototype.m,st.NO_ERROR=0,st.TIMEOUT=8,st.HTTP_ERROR=6,it.COMPLETE="complete",(ut.EventType=v).OPEN="a",v.CLOSE="b",v.ERROR="c",v.MESSAGE="d",xe.prototype.listen=xe.prototype.N,In.prototype.listenOnce=In.prototype.O,In.prototype.getLastError=In.prototype.La,In.prototype.getLastErrorCode=In.prototype.Da,In.prototype.getStatus=In.prototype.ba,In.prototype.getResponseJson=In.prototype.Qa,In.prototype.getResponseText=In.prototype.ga,In.prototype.send=In.prototype.ea;var or,ur=Xe,hr=st,cr=it,lr=Qe,dr=10,fr=11,gr=gn,mr=ut,pr=In;const yr="@firebase/firestore";class vr{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}}vr.UNAUTHENTICATED=new vr(null),vr.GOOGLE_CREDENTIALS=new vr("google-credentials-uid"),vr.FIRST_PARTY=new vr("first-party-uid"),vr.MOCK_USER=new vr("mock-user");let wr="9.6.11";const br=new class{constructor(e){this.name=e,this._logLevel=d,this._logHandler=p,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?c[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 Ir(){return br.logLevel}function Er(e,...t){var n;br.logLevel<=l.DEBUG&&(n=t.map(Sr),br.debug(`Firestore (${wr}): ${e}`,...n))}function Tr(e,...t){var n;br.logLevel<=l.ERROR&&(n=t.map(Sr),br.error(`Firestore (${wr}): ${e}`,...n))}function _r(e,...t){var n;br.logLevel<=l.WARN&&(n=t.map(Sr),br.warn(`Firestore (${wr}): ${e}`,...n))}function Sr(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function Ar(e="Unexpected state"){var t=`FIRESTORE (${wr}) INTERNAL ASSERTION FAILED: `+e;throw Tr(t),new Error(t)}function Dr(e){e||Ar()}const xr={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 Nr extends o{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class Cr{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class kr{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Mr{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(vr.UNAUTHENTICATED))}shutdown(){}}class Rr{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 Lr{constructor(e){this.t=e,this.currentUser=vr.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const s=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let i=new Cr;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new Cr,t.enqueueRetryable(()=>s(this.currentUser))};const a=()=>{const e=i;t.enqueueRetryable(async()=>{await e.promise,await s(this.currentUser)})},o=e=>{Er("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):(Er("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new Cr))},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?(Er("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(Dr("string"==typeof e.accessToken),new kr(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 Dr(null===e||"string"==typeof e),new vr(e)}}class Vr{constructor(e,t,n){this.type="FirstParty",this.user=vr.FIRST_PARTY,this.headers=new Map,this.headers.set("X-Goog-AuthUser",t);var r=e.auth.getAuthHeaderValueForFirstParty([]);r&&this.headers.set("Authorization",r),n&&this.headers.set("X-Goog-Iam-Authorization-Token",n)}}class Or{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new Vr(this.h,this.l,this.m))}start(e,t){e.enqueueRetryable(()=>t(vr.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Fr{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 Pr{constructor(e){this.g=e,this.forceRefresh=!1,this.appCheck=null,this.p=null}start(t,n){const r=e=>{null!=e.error&&Er("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.p;return this.p=e.token,Er("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const s=e=>{Er("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.g.onInit(e=>s(e)),setTimeout(()=>{var e;this.appCheck||((e=this.g.getImmediate({optional:!0}))?s(e):Er("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(Dr("string"==typeof e.token),this.p=e.token,new Fr(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class Br{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.I(e),this.T=e=>t.writeSequenceNumber(e))}I(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.T&&this.T(e),e}}Br.A=-1;class qr{static R(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var s=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<s.length;++e)r.length<20&&s[e]<n&&(r+=t.charAt(s[e]%t.length))}return r}}function Ur(e,t){return e<t?-1:t<e?1:0}function Kr(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function jr(e){return e+"\0"}class Gr{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new Nr(xr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new Nr(xr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new Nr(xr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new Nr(xr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return Gr.fromMillis(Date.now())}static fromDate(e){return Gr.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new Gr(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Ur(this.nanoseconds,e.nanoseconds):Ur(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 $r{constructor(e){this.timestamp=e}static fromTimestamp(e){return new $r(e)}static min(){return new $r(new Gr(0,0))}static max(){return new $r(new Gr(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}}function zr(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function Wr(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function Hr(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class Qr{constructor(e,t,n){void 0===t?t=0:t>e.length&&Ar(),void 0===n?n=e.length-t:n>e.length-t&&Ar(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===Qr.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof Qr?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),s=t.get(r);if(n<s)return-1;if(n>s)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class Yr extends Qr{construct(e,t,n){return new Yr(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 Nr(xr.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new Yr(t)}static emptyPath(){return new Yr([])}}const Xr=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Jr extends Qr{construct(e,t,n){return new Jr(e,t,n)}static isValidIdentifier(e){return Xr.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!Jr.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new Jr(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var s=()=>{if(0===n.length)throw new Nr(xr.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let i=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new Nr(xr.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new Nr(xr.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?i=!i:"."!==t||i?n+=t:s(),r++}if(s(),i)throw new Nr(xr.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Jr(t)}static emptyPath(){return new Jr([])}}class Zr{constructor(e){(this.fields=e).sort(Jr.comparator)}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Kr(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class es{constructor(e){this.binaryString=e}static fromBase64String(e){var t=atob(e);return new es(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 es(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 Ur(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}es.EMPTY_BYTE_STRING=new es("");const ts=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function ns(t){if(Dr(!!t),"string"!=typeof t)return{seconds:rs(t.seconds),nanos:rs(t.nanos)};{let e=0;var n=ts.exec(t);Dr(!!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 rs(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function ss(e){return"string"==typeof e?es.fromBase64String(e):es.fromUint8Array(e)}function is(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 as(e){var t=ns(e.mapValue.fields.__local_write_time__.timestampValue);return new Gr(t.seconds,t.nanos)}class os{constructor(e,t,n,r,s,i,a,o){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=s,this.forceLongPolling=i,this.autoDetectLongPolling=a,this.useFetchStreams=o}}class us{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new us("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof us&&e.projectId===this.projectId&&e.database===this.database}}function hs(e){return null==e}function cs(e){return 0===e&&1/e==-1/0}function ls(e){return"number"==typeof e&&Number.isInteger(e)&&!cs(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}class ds{constructor(e){this.path=e}static fromPath(e){return new ds(Yr.fromString(e))}static fromName(e){return new ds(Yr.fromString(e).popFirst(5))}static empty(){return new ds(Yr.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===Yr.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return Yr.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new ds(new Yr(e.slice()))}}const fs={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},gs={nullValue:"NULL_VALUE"};function ms(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?is(e)?4:xs(e)?9:10:Ar()}function ps(r,s){if(r===s)return!0;var e,t,n=ms(r);if(n!==ms(s))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===s.booleanValue;case 4:return as(r).isEqual(as(s));case 3:return function(e){if("string"==typeof r.timestampValue&&"string"==typeof e.timestampValue&&r.timestampValue.length===e.timestampValue.length)return r.timestampValue===e.timestampValue;var t=ns(r.timestampValue),n=ns(e.timestampValue);return t.seconds===n.seconds&&t.nanos===n.nanos}(s);case 5:return r.stringValue===s.stringValue;case 6:return t=s,ss(r.bytesValue).isEqual(ss(t.bytesValue));case 7:return r.referenceValue===s.referenceValue;case 8:return e=s,rs((t=r).geoPointValue.latitude)===rs(e.geoPointValue.latitude)&&rs(t.geoPointValue.longitude)===rs(e.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return rs(e.integerValue)===rs(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=rs(e.doubleValue),r=rs(t.doubleValue);return n===r?cs(n)===cs(r):isNaN(n)&&isNaN(r)}return!1}(r,s);case 9:return Kr(r.arrayValue.values||[],s.arrayValue.values||[],ps);case 10:return function(e){const t=e.mapValue.fields||{},n=s.mapValue.fields||{};if(zr(t)!==zr(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!ps(t[e],n[e])))return!1;return!0}(r);default:return Ar()}}function ys(e,t){return void 0!==(e.values||[]).find(e=>ps(e,t))}function vs(e,t){if(e===t)return 0;var n,r,s,i,a=ms(e),o=ms(t);if(a!==o)return Ur(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return Ur(e.booleanValue,t.booleanValue);case 2:return r=t,s=rs(e.integerValue||e.doubleValue),i=rs(r.integerValue||r.doubleValue),s<i?-1:i<s?1:s===i?0:isNaN(s)?isNaN(i)?0:-1:1;case 3:return ws(e.timestampValue,t.timestampValue);case 4:return ws(as(e),as(t));case 5:return Ur(e.stringValue,t.stringValue);case 6:return function(e,t){const n=ss(e),r=ss(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let s=0;s<n.length&&s<r.length;s++){const t=Ur(n[s],r[s]);if(0!==t)return t}return Ur(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(i=Ur(rs(n.latitude),rs(r.latitude)))?i:Ur(rs(n.longitude),rs(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let s=0;s<n.length&&s<r.length;++s){const t=vs(n[s],r[s]);if(t)return t}return Ur(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){const n=e.fields||{},r=Object.keys(n),s=t.fields||{},i=Object.keys(s);r.sort(),i.sort();for(let o=0;o<r.length&&o<i.length;++o){const t=Ur(r[o],i[o]);if(0!==t)return t;var a=vs(n[r[o]],s[i[o]]);if(0!==a)return a}return Ur(r.length,i.length)}(e.mapValue,t.mapValue);default:throw Ar()}}function ws(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Ur(e,t);var n=ns(e),r=ns(t),s=Ur(n.seconds,r.seconds);return 0!==s?s:Ur(n.nanos,r.nanos)}function bs(e){return function i(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=ns(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?ss(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,ds.fromName(t).toString()):"geoPointValue"in e?`geo(${(t=e.geoPointValue).latitude},${t.longitude})`:"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=i(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const s of t)r?r=!1:n+=",",n+=`${s}:${i(e.fields[s])}`;return n+"}"}(e.mapValue):Ar();var t}(e)}function Is(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Es(e){return e&&"integerValue"in e}function Ts(e){return!!e&&"arrayValue"in e}function _s(e){return e&&"nullValue"in e}function Ss(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function As(e){return e&&"mapValue"in e}function Ds(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 Wr(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=Ds(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Ds(t.arrayValue.values[e]);return r}return Object.assign({},t)}function xs(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Ns(e,t){return void 0!==e&&(void 0===t||0<vs(e,t))?e:t}function Cs(e,t){return void 0!==e&&(void 0===t||vs(e,t)<0)?e:t}class ks{constructor(e){this.value=e}static empty(){return new ks({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)],!As(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Ds(t)}setAll(e){let n=Jr.emptyPath(),r={},s=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,s),r={},s=[],n=t.popLast()}e?r[t.lastSegment()]=Ds(e):s.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,s)}delete(e){const t=this.field(e.popLast());As(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return ps(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)];As(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){Wr(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new ks(Ds(this.value))}}class Ms{constructor(e,t,n,r,s,i){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.data=s,this.documentState=i}static newInvalidDocument(e){return new Ms(e,0,$r.min(),$r.min(),ks.empty(),0)}static newFoundDocument(e,t,n){return new Ms(e,1,t,$r.min(),n,0)}static newNoDocument(e,t){return new Ms(e,2,t,$r.min(),ks.empty(),0)}static newUnknownDocument(e,t){return new Ms(e,3,t,$r.min(),ks.empty(),2)}convertToFoundDocument(e,t){return this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=ks.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=ks.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,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 Ms&&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 Ms(this.key,this.documentType,this.version,this.readTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Rs{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function Ls(e){return e.fields.find(e=>2===e.kind)}function Vs(e){return e.fields.filter(e=>2!==e.kind)}Rs.UNKNOWN_ID=-1;class Os{constructor(e,t){this.fieldPath=e,this.kind=t}}class Fs{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new Fs(0,Bs.min())}}function Ps(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=$r.fromTimestamp(1e9===r?new Gr(n+1,0):new Gr(n,r));return new Bs(r,ds.empty(),t)}class Bs{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new Bs($r.min(),ds.empty(),-1)}static max(){return new Bs($r.max(),ds.empty(),-1)}}class qs{constructor(e,t=null,n=[],r=[],s=null,i=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=s,this.startAt=i,this.endAt=a,this.P=null}}function Us(e,t=null,n=[],r=[],s=null,i=null,a=null){return new qs(e,t,n,r,s,i,a)}function Ks(e){const t=e;if(null===t.P){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>{return(t=e).field.canonicalString()+t.op.toString()+bs(t.value);var t}).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),hs(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>bs(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>bs(e)).join(",")),t.P=e}return t.P}function js(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let a=0;a<e.orderBy.length;a++)if(n=e.orderBy[a],r=t.orderBy[a],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r,s,i;if(e.filters.length!==t.filters.length)return!1;for(let o=0;o<e.filters.length;o++)if(s=e.filters[o],i=t.filters[o],s.op!==i.op||!s.field.isEqual(i.field)||!ps(s.value,i.value))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!ai(e.startAt,t.startAt)&&ai(e.endAt,t.endAt)}function Gs(e){return ds.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function $s(e,t){return e.filters.filter(e=>e instanceof Hs&&e.field.isEqual(t))}function zs(t,n,r){let s,i=!0;for(const r of $s(t,n)){let e,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?gs:"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?Is(us.empty(),ds.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:Ar();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=gs}Ns(s,e)===e&&(s=e,i=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Ns(s,t)===t&&(s=t,i=r.inclusive);break}return{value:s,inclusive:i}}function Ws(t,n,r){let s,i=!0;for(const r of $s(t,n)){let e,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?Is(us.empty(),ds.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?fs:Ar(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=fs}Cs(s,e)===e&&(s=e,i=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Cs(s,t)===t&&(s=t,i=r.inclusive);break}return{value:s,inclusive:i}}class Hs extends class{}{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.V(e,t,n):new Qs(e,t,n):"array-contains"===t?new Zs(e,n):"in"===t?new ei(e,n):"not-in"===t?new ti(e,n):"array-contains-any"===t?new ni(e,n):new Hs(e,t,n)}static V(e,t,n){return new("in"===t?Ys:Xs)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.v(vs(t,this.value)):null!==t&&ms(this.value)===ms(t)&&this.v(vs(t,this.value))}v(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 Ar()}}S(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}}class Qs extends Hs{constructor(e,t,n){super(e,t,n),this.key=ds.fromName(n.referenceValue)}matches(e){var t=ds.comparator(e.key,this.key);return this.v(t)}}class Ys extends Hs{constructor(e,t){super(e,"in",t),this.keys=Js(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class Xs extends Hs{constructor(e,t){super(e,"not-in",t),this.keys=Js(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function Js(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>ds.fromName(e.referenceValue))}class Zs extends Hs{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return Ts(t)&&ys(t.arrayValue,this.value)}}class ei extends Hs{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&ys(this.value.arrayValue,t)}}class ti extends Hs{constructor(e,t){super(e,"not-in",t)}matches(e){if(ys(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!ys(this.value.arrayValue,t)}}class ni extends Hs{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Ts(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>ys(this.value.arrayValue,e))}}class ri{constructor(e,t){this.position=e,this.inclusive=t}}class si{constructor(e,t="asc"){this.field=e,this.dir=t}}function ii(e,t,n){let r=0;for(let s=0;s<e.position.length;s++){const i=t[s],a=e.position[s];if(r=i.field.isKeyField()?ds.comparator(ds.fromName(a.referenceValue),n.key):vs(a,n.data.field(i.field)),"desc"===i.dir&&(r*=-1),0!==r)break}return r}function ai(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(!ps(e.position[n],t.position[n]))return!1;return!0}class oi{constructor(e,t=null,n=[],r=[],s=null,i="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=s,this.limitType=i,this.startAt=a,this.endAt=o,this.D=null,this.C=null,this.startAt,this.endAt}}function ui(e,t,n,r,s,i,a,o){return new oi(e,t,n,r,s,i,a,o)}function hi(e){return new oi(e)}function ci(e){return!hs(e.limit)&&"F"===e.limitType}function li(e){return!hs(e.limit)&&"L"===e.limitType}function di(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function fi(e){for(const t of e.filters)if(t.S())return t.field;return null}function gi(e){return null!==e.collectionGroup}function mi(t){const n=t;if(null===n.D){n.D=[];const t=fi(n),e=di(n);if(null!==t&&null===e)t.isKeyField()||n.D.push(new si(t)),n.D.push(new si(Jr.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.D.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.D.push(new si(Jr.keyField(),t))}}}return n.D}function pi(e){const t=e;if(!t.C)if("F"===t.limitType)t.C=Us(t.path,t.collectionGroup,mi(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const s of mi(t)){const t="desc"===s.dir?"asc":"desc";e.push(new si(s.field,t))}var n=t.endAt?new ri(t.endAt.position,!t.endAt.inclusive):null,r=t.startAt?new ri(t.startAt.position,!t.startAt.inclusive):null;t.C=Us(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.C}function yi(e,t,n){return new oi(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function vi(e,t){return js(pi(e),pi(t))&&e.limitType===t.limitType}function wi(e){return`${Ks(pi(e))}|lt:${e.limitType}`}function bi(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=>{return`${(t=e).field.canonicalString()} ${t.op} ${bs(t.value)}`;var t}).join(", ")}]`),hs(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=>bs(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>bs(e)).join(",")),`Target(${t})`}(pi(e))}; limitType=${e.limitType})`}function Ii(n,e){return e.isFoundDocument()&&(s=n,a=(i=e).key.path,null!==s.collectionGroup?i.key.hasCollectionId(s.collectionGroup)&&s.path.isPrefixOf(a):ds.isDocumentKey(s.path)?s.path.isEqual(a):s.path.isImmediateParentOf(a))&&function(e){for(const t of n.explicitOrderBy)if(!t.field.isKeyField()&&null===e.data.field(t.field))return;return 1}(e)&&function(e){for(const t of n.filters)if(!t.matches(e))return;return 1}(e)&&(s=e,(!(e=n).startAt||(t=e.startAt,r=ii(t,mi(e),s),t.inclusive?r<=0:r<0))&&(!e.endAt||(t=e.endAt,r=ii(t,mi(e),s),t.inclusive?0<=r:0<r)));var t,r,s,i,a}function Ei(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Ti(s){return(e,t)=>{let n=!1;for(const r of mi(s)){const s=function(e,s,t){var n=e.field.isKeyField()?ds.comparator(s.key,t.key):function(e,t){var n=s.data.field(e),r=t.data.field(e);return null!==n&&null!==r?vs(n,r):Ar()}(e.field,t);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return Ar()}}(r,e,t);if(0!==s)return s;n=n||r.field.isKeyField()}return 0}}function _i(e,t){if(e.N){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:cs(t)?"-0":t}}function Si(e){return{integerValue:""+e}}function Ai(e,t){return ls(t)?Si(t):_i(e,t)}class Di{constructor(){this._=void 0}}function xi(e,t){return e instanceof Li?Es(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class Ni extends Di{}class Ci extends Di{constructor(e){super(),this.elements=e}}function ki(e,t){const n=Oi(t);for(const t of e.elements)n.some(e=>ps(e,t))||n.push(t);return{arrayValue:{values:n}}}class Mi extends Di{constructor(e){super(),this.elements=e}}function Ri(e,t){let n=Oi(t);for(const t of e.elements)n=n.filter(e=>!ps(e,t));return{arrayValue:{values:n}}}class Li extends Di{constructor(e,t){super(),this.M=e,this.k=t}}function Vi(e){return rs(e.integerValue||e.doubleValue)}function Oi(e){return Ts(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class Fi{constructor(e,t){this.field=e,this.transform=t}}class Pi{constructor(e,t){this.version=e,this.transformResults=t}}class Bi{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Bi}static exists(e){return new Bi(void 0,e)}static updateTime(e){return new Bi(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 qi(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Ui{}function Ki(e,t,n){e instanceof zi?function(e,t,n){const r=e.value.clone(),s=Qi(e.fieldTransforms,t,n.transformResults);r.setAll(s),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Wi?function(e,t,n){if(!qi(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=Qi(e.fieldTransforms,t,n.transformResults),s=t.data;s.setAll(Hi(e)),s.setAll(r),t.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function ji(e,t,n){e instanceof zi?function(e,t,n){if(qi(e.precondition,t)){const r=e.value.clone(),s=Yi(e.fieldTransforms,n,t);r.setAll(s),t.convertToFoundDocument($i(t),r).setHasLocalMutations()}}(e,t,n):e instanceof Wi?function(e,t,n){if(qi(e.precondition,t)){const r=Yi(e.fieldTransforms,n,t),s=t.data;s.setAll(Hi(e)),s.setAll(r),t.convertToFoundDocument($i(t),s).setHasLocalMutations()}}(e,t,n):(t=t,qi(e.precondition,t)&&t.convertToNoDocument($r.min()))}function Gi(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&&Kr(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof Ci&&t instanceof Ci||e instanceof Mi&&t instanceof Mi?Kr(e.elements,t.elements,ps):e instanceof Li&&t instanceof Li?ps(e.k,t.k):e instanceof Ni&&t instanceof Ni)}(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}function $i(e){return e.isFoundDocument()?e.version:$r.min()}class zi extends Ui{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}}class Wi extends Ui{constructor(e,t,n,r,s=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=s,this.type=1}}function Hi(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 Qi(e,t,n){const r=new Map;Dr(e.length===n.length);for(let c=0;c<n.length;c++){var s=e[c],i=s.transform,a=t.data.field(s.field);r.set(s.field,(o=i,u=a,h=n[c],o instanceof Ci?ki(o,u):o instanceof Mi?Ri(o,u):h))}var o,u,h;return r}function Yi(e,t,n){const r=new Map;for(const h of e){const e=h.transform,c=n.data.field(h.field);r.set(h.field,(s=e,i=c,a=t,u=o=void 0,s instanceof Ni?function(){const e={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:a.seconds,nanos:a.nanoseconds}}}};return i&&(e.fields.__previous_value__=i),{mapValue:e}}():s instanceof Ci?ki(s,i):s instanceof Mi?Ri(s,i):(o=xi(s=s,i),u=Vi(o)+Vi(s.k),Es(o)&&Es(s.k)?Si(u):_i(s.M,u))))}var s,i,a,o,u;return r}class Xi extends Ui{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}}class Ji extends Ui{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}}class Zi{constructor(e){this.count=e}}function ea(e){switch(e){default:return Ar(),0;case xr.CANCELLED:case xr.UNKNOWN:case xr.DEADLINE_EXCEEDED:case xr.RESOURCE_EXHAUSTED:case xr.INTERNAL:case xr.UNAVAILABLE:case xr.UNAUTHENTICATED:return;case xr.INVALID_ARGUMENT:case xr.NOT_FOUND:case xr.ALREADY_EXISTS:case xr.PERMISSION_DENIED:case xr.FAILED_PRECONDITION:case xr.ABORTED:case xr.OUT_OF_RANGE:case xr.UNIMPLEMENTED:case xr.DATA_LOSS:return 1}}function ta(e){if(void 0===e)return Tr("GRPC error has no .code"),xr.UNKNOWN;switch(e){case or.OK:return xr.OK;case or.CANCELLED:return xr.CANCELLED;case or.UNKNOWN:return xr.UNKNOWN;case or.DEADLINE_EXCEEDED:return xr.DEADLINE_EXCEEDED;case or.RESOURCE_EXHAUSTED:return xr.RESOURCE_EXHAUSTED;case or.INTERNAL:return xr.INTERNAL;case or.UNAVAILABLE:return xr.UNAVAILABLE;case or.UNAUTHENTICATED:return xr.UNAUTHENTICATED;case or.INVALID_ARGUMENT:return xr.INVALID_ARGUMENT;case or.NOT_FOUND:return xr.NOT_FOUND;case or.ALREADY_EXISTS:return xr.ALREADY_EXISTS;case or.PERMISSION_DENIED:return xr.PERMISSION_DENIED;case or.FAILED_PRECONDITION:return xr.FAILED_PRECONDITION;case or.ABORTED:return xr.ABORTED;case or.OUT_OF_RANGE:return xr.OUT_OF_RANGE;case or.UNIMPLEMENTED:return xr.UNIMPLEMENTED;case or.DATA_LOSS:return xr.DATA_LOSS;default:return Ar()}}(it=or=or||{})[it.OK=0]="OK",it[it.CANCELLED=1]="CANCELLED",it[it.UNKNOWN=2]="UNKNOWN",it[it.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",it[it.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",it[it.NOT_FOUND=5]="NOT_FOUND",it[it.ALREADY_EXISTS=6]="ALREADY_EXISTS",it[it.PERMISSION_DENIED=7]="PERMISSION_DENIED",it[it.UNAUTHENTICATED=16]="UNAUTHENTICATED",it[it.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",it[it.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",it[it.ABORTED=10]="ABORTED",it[it.OUT_OF_RANGE=11]="OUT_OF_RANGE",it[it.UNIMPLEMENTED=12]="UNIMPLEMENTED",it[it.INTERNAL=13]="INTERNAL",it[it.UNAVAILABLE=14]="UNAVAILABLE",it[it.DATA_LOSS=15]="DATA_LOSS";class na{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let s=0;s<r.length;s++)if(this.equalsFn(r[s][0],e))return void(r[s]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(r){Wr(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return Hr(this.inner)}size(){return this.innerSize}}class ra{constructor(e,t){this.comparator=e,this.root=t||ia.EMPTY}insert(e,t){return new ra(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,ia.BLACK,null,null))}remove(e){return new ra(this.comparator,this.root.remove(e,this.comparator).copy(null,null,ia.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 sa(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new sa(this.root,e,this.comparator,!1)}getReverseIterator(){return new sa(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new sa(this.root,e,this.comparator,!0)}}class sa{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,t&&r&&(s*=-1),s<0)e=this.isReverse?e.left:e.right;else{if(0===s){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class ia{constructor(e,t,n,r,s){this.key=e,this.value=t,this.color=null!=n?n:ia.RED,this.left=null!=r?r:ia.EMPTY,this.right=null!=s?s:ia.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,s){return new ia(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=s?s:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var s=n(e,r.key);return r=s<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===s?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return ia.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 ia.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,ia.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,ia.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 Ar();if(this.right.isRed())throw Ar();var e=this.left.check();if(e!==this.right.check())throw Ar();return e+(this.isRed()?0:1)}}ia.EMPTY=null,ia.RED=!0,ia.BLACK=!1,ia.EMPTY=new class{constructor(){this.size=0}get key(){throw Ar()}get value(){throw Ar()}get color(){throw Ar()}get left(){throw Ar()}get right(){throw Ar()}copy(e,t,n,r,s){return this}insert(e,t,n){return new ia(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 aa{constructor(e){this.comparator=e,this.data=new ra(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 oa(this.data.getIterator())}getIteratorFrom(e){return new oa(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 aa))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 aa(this.comparator);return t.data=e,t}}class oa{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function ua(e){return e.hasNext()?e.getNext():void 0}const ha=new ra(ds.comparator);const ca=new ra(ds.comparator);function la(){return new na(e=>e.toString(),(e,t)=>e.isEqual(t))}const da=new ra(ds.comparator),fa=new aa(ds.comparator);function ga(...e){let t=fa;for(const n of e)t=t.add(n);return t}const ma=new aa(Ur);class pa{constructor(e,t,n,r,s){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=s}static createSynthesizedRemoteEventForCurrentChange(e,t){const n=new Map;return n.set(e,ya.createSynthesizedTargetChangeForCurrentChange(e,t)),new pa($r.min(),n,ma,ha,ga())}}class ya{constructor(e,t,n,r,s){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=s}static createSynthesizedTargetChangeForCurrentChange(e,t){return new ya(es.EMPTY_BYTE_STRING,t,ga(),ga(),ga())}}class va{constructor(e,t,n,r){this.O=e,this.removedTargetIds=t,this.key=n,this.F=r}}class wa{constructor(e,t){this.targetId=e,this.$=t}}class ba{constructor(e,t,n=es.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class Ia{constructor(){this.B=0,this.L=_a(),this.U=es.EMPTY_BYTE_STRING,this.q=!1,this.K=!0}get current(){return this.q}get resumeToken(){return this.U}get G(){return 0!==this.B}get j(){return this.K}W(e){0<e.approximateByteSize()&&(this.K=!0,this.U=e)}H(){let n=ga(),r=ga(),s=ga();return this.L.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:s=s.add(e);break;default:Ar()}}),new ya(this.U,this.q,n,r,s)}J(){this.K=!1,this.L=_a()}Y(e,t){this.K=!0,this.L=this.L.insert(e,t)}X(e){this.K=!0,this.L=this.L.remove(e)}Z(){this.B+=1}tt(){--this.B}et(){this.K=!0,this.q=!0}}class Ea{constructor(e){this.nt=e,this.st=new Map,this.it=ha,this.rt=Ta(),this.ot=new aa(Ur)}ut(e){for(const t of e.O)e.F&&e.F.isFoundDocument()?this.at(t,e.F):this.ct(t,e.key,e.F);for(const n of e.removedTargetIds)this.ct(n,e.key,e.F)}ht(n){this.forEachTarget(n,e=>{const t=this.lt(e);switch(n.state){case 0:this.ft(e)&&t.W(n.resumeToken);break;case 1:t.tt(),t.G||t.J(),t.W(n.resumeToken);break;case 2:t.tt(),t.G||this.removeTarget(e);break;case 3:this.ft(e)&&(t.et(),t.W(n.resumeToken));break;case 4:this.ft(e)&&(this.dt(e),t.W(n.resumeToken));break;default:Ar()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.st.forEach((e,t)=>{this.ft(t)&&n(t)})}_t(e){const t=e.targetId,n=e.$.count,r=this.wt(t);if(r){const e=r.target;if(Gs(e))if(0===n){const n=new ds(e.path);this.ct(t,n,Ms.newNoDocument(n,$r.min()))}else Dr(1===n);else this.gt(t)!==n&&(this.dt(t),this.ot=this.ot.add(t))}}yt(r){const s=new Map;this.st.forEach((e,t)=>{var n=this.wt(t);if(n){if(e.current&&Gs(n.target)){const s=new ds(n.target.path);null!==this.it.get(s)||this.It(t,s)||this.ct(t,s,Ms.newNoDocument(s,r))}e.j&&(s.set(t,e.H()),e.J())}});let i=ga();this.rt.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.wt(e);return!t||2===t.purpose||(n=!1)}),n&&(i=i.add(e))}),this.it.forEach((e,t)=>t.setReadTime(r));var e=new pa(r,s,this.ot,this.it,i);return this.it=ha,this.rt=Ta(),this.ot=new aa(Ur),e}at(e,t){var n;this.ft(e)&&(n=this.It(e,t.key)?2:0,this.lt(e).Y(t.key,n),this.it=this.it.insert(t.key,t),this.rt=this.rt.insert(t.key,this.Tt(t.key).add(e)))}ct(e,t,n){if(this.ft(e)){const r=this.lt(e);this.It(e,t)?r.Y(t,1):r.X(t),this.rt=this.rt.insert(t,this.Tt(t).delete(e)),n&&(this.it=this.it.insert(t,n))}}removeTarget(e){this.st.delete(e)}gt(e){var t=this.lt(e).H();return this.nt.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Z(e){this.lt(e).Z()}lt(e){let t=this.st.get(e);return t||(t=new Ia,this.st.set(e,t)),t}Tt(e){let t=this.rt.get(e);return t||(t=new aa(Ur),this.rt=this.rt.insert(e,t)),t}ft(e){var t=null!==this.wt(e);return t||Er("WatchChangeAggregator","Detected inactive target",e),t}wt(e){var t=this.st.get(e);return t&&t.G?null:this.nt.Et(e)}dt(t){this.st.set(t,new Ia),this.nt.getRemoteKeysForTarget(t).forEach(e=>{this.ct(t,e,null)})}It(e,t){return this.nt.getRemoteKeysForTarget(e).has(t)}}function Ta(){return new ra(ds.comparator)}function _a(){return new ra(ds.comparator)}const Sa={asc:"ASCENDING",desc:"DESCENDING"},Aa={"<":"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"};class Da{constructor(e,t){this.databaseId=e,this.N=t}}function xa(e,t){return e.N?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function Na(e,t){return e.N?t.toBase64():t.toUint8Array()}function Ca(e){return Dr(!!e),$r.fromTimestamp((t=ns(e),new Gr(t.seconds,t.nanos)));var t}function ka(e,t){return e=e,new Yr(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function Ma(e){var t=Yr.fromString(e);return Dr(Ya(t)),t}function Ra(e,t){return ka(e.databaseId,t.path)}function La(e,t){const n=Ma(t);if(n.get(1)!==e.databaseId.projectId)throw new Nr(xr.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 Nr(xr.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new ds(Pa(n))}function Va(e,t){return ka(e.databaseId,t)}function Oa(e){var t=Ma(e);return 4===t.length?Yr.emptyPath():Pa(t)}function Fa(e){return new Yr(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function Pa(e){return Dr(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function Ba(e,t,n){return{name:Ra(e,t),fields:n.value.mapValue.fields}}function qa(e,t,n){const r=La(e,t.name),s=Ca(t.updateTime),i=new ks({mapValue:{fields:t.fields}}),a=Ms.newFoundDocument(r,s,i);return n&&a.setHasCommittedMutations(),n?a.setHasCommittedMutations():a}function Ua(e,t){let n;if(t instanceof zi)n={update:Ba(e,t.key,t.value)};else if(t instanceof Xi)n={delete:Ra(e,t.key)};else if(t instanceof Wi)n={update:Ba(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 Ji))return Ar();n={verify:Ra(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof Ni)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof Ci)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof Mi)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof Li)return{fieldPath:e.field.canonicalString(),increment:t.k};throw Ar()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,xa(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:Ar()),n;var r}function Ka(t,n){const e=n.currentDocument?void 0!==(s=n.currentDocument).updateTime?Bi.updateTime(Ca(s.updateTime)):void 0!==s.exists?Bi.exists(s.exists):Bi.none():Bi.none(),r=n.updateTransforms?n.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)Dr("REQUEST_TIME"===t.setToServerValue),n=new Ni;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new Ci(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new Mi(e)}else"increment"in t?n=new Li(e,t.increment):Ar();var r=Jr.fromServerFormat(t.fieldPath);return new Fi(r,n)}(t,e)):[];var s;if(n.update){n.update.name;var i=La(t,n.update.name),a=new ks({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new Zr(e.map(e=>Jr.fromServerFormat(e)))}();return new Wi(i,a,t,e,r)}return new zi(i,a,e,r)}if(n.delete){const r=La(t,n.delete);return new Xi(r,e)}if(n.verify){const r=La(t,n.verify);return new Ji(r,e)}return Ar()}function ja(e,t){return{documents:[Va(e,t.path)]}}function Ga(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=Va(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=Va(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var s=function(e){if(0!==e.length){var t=e.map(e=>function(e){if("=="===e.op){if(Ss(e.value))return{unaryFilter:{field:za(e.field),op:"IS_NAN"}};if(_s(e.value))return{unaryFilter:{field:za(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Ss(e.value))return{unaryFilter:{field:za(e.field),op:"IS_NOT_NAN"}};if(_s(e.value))return{unaryFilter:{field:za(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:za(e.field),op:(t=e.op,Aa[t]),value:e.value}};var t}(e));return 1===t.length?t[0]:{compositeFilter:{op:"AND",filters:t}}}}(t.filters);s&&(n.structuredQuery.where=s);s=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:za(e.field),direction:(e=e.dir,Sa[e])}}(e))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);var i,s=(i=t.limit,e.N||hs(i)?i:{value:i});return null!==s&&(n.structuredQuery.limit=s),t.startAt&&(n.structuredQuery.startAt={before:(s=t.startAt).inclusive,values:s.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function $a(e){let t=Oa(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let s=null;if(0<r){Dr(1===r);const g=n.from[0];g.allDescendants?s=g.collectionId:t=t.child(g.collectionId)}let i=[];n.where&&(i=function t(e){return e?void 0!==e.unaryFilter?[Qa(e)]:void 0!==e.fieldFilter?[Ha(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map(e=>t(e)).reduce((e,t)=>e.concat(t)):Ar():[]}(n.where));let a=[];n.orderBy&&(a=n.orderBy.map(e=>function(e){return new si(Wa(e.field),function(){switch(e.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(e)));let o=null;var u,h,c,l;n.limit&&(o=(e=n.limit,hs(u="object"==typeof e?e.value:e)?null:u));let d=null;n.startAt&&(d=(h=n.startAt,l=!!h.before,c=h.values||[],new ri(c,l)));let f=null;return n.endAt&&(f=(h=n.endAt,c=!h.before,l=h.values||[],new ri(l,c))),ui(t,s,a,i,o,"F",d,f)}function za(e){return{fieldPath:e.canonicalString()}}function Wa(e){return Jr.fromServerFormat(e.fieldPath)}function Ha(e){return Hs.create(Wa(e.fieldFilter.field),function(){switch(e.fieldFilter.op){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 Ar()}}(),e.fieldFilter.value)}function Qa(e){switch(e.unaryFilter.op){case"IS_NAN":var t=Wa(e.unaryFilter.field);return Hs.create(t,"==",{doubleValue:NaN});case"IS_NULL":t=Wa(e.unaryFilter.field);return Hs.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=Wa(e.unaryFilter.field);return Hs.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=Wa(e.unaryFilter.field);return Hs.create(n,"!=",{nullValue:"NULL_VALUE"});default:return Ar()}}function Ya(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function Xa(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=Ja(t)),t=function(e,t){let n=t;const r=e.length;for(let s=0;s<r;s++){const r=e.charAt(s);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return Ja(t)}function Ja(e){return e+""}function Za(t){const n=t.length;if(Dr(2<=n),2===n)return Dr(""===t.charAt(0)&&""===t.charAt(1)),Yr.emptyPath();const r=n-2,s=[];let i="";for(let a=0;a<n;){const n=t.indexOf("",a);switch((n<0||n>r)&&Ar(),t.charAt(n+1)){case"":const r=t.substring(a,n);let e;0===i.length?e=r:(i+=r,e=i,i=""),s.push(e);break;case"":i+=t.substring(a,n),i+="\0";break;case"":i+=t.substring(a,n+1);break;default:Ar()}a=n+2}return new Yr(s)}const eo=["userId","batchId"];function to(e,t){return[e,Xa(t)]}function no(e,t,n){return[e,Xa(t),n]}const ro={},so=["prefixPath","collectionGroup","readTime","documentId"],io=["prefixPath","collectionGroup","documentId"],ao=["collectionGroup","readTime","prefixPath","documentId"],oo=["canonicalId","targetId"],uo=["targetId","path"],ho=["path","targetId"],co=["collectionId","parent"],lo=["indexId","uid"],fo=["uid","sequenceNumber"],go=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],mo=["indexId","uid","orderedDocumentKey"],po=["userId","collectionPath","documentId"],yo=["userId","collectionPath","largestBatchId"],vo=["userId","collectionGroup","largestBatchId"],wo=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],bo=[...wo,"documentOverlays"],Io=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],Eo=[...Io,"indexConfiguration","indexState","indexEntries"],To="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class _o{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}class So{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(r,s){return this.callbackAttached&&Ar(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(s,this.error):this.wrapSuccess(r,this.result):new So((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(s,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof So?t:So.resolve(t)}catch(e){return So.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):So.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):So.reject(t)}static resolve(n){return new So((e,t)=>{e(n)})}static reject(n){return new So((e,t)=>{t(n)})}static waitFor(e){return new So((t,n)=>{let r=0,s=0,i=!1;e.forEach(e=>{++r,e.next(()=>{++s,i&&s===r&&t()},e=>n(e))}),i=!0,s===r&&t()})}static or(e){let t=So.resolve(!1);for(const n of e)t=t.next(e=>e?So.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)}}class Ao{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.At=new Cr,this.transaction.oncomplete=()=>{this.At.resolve()},this.transaction.onabort=()=>{e.error?this.At.reject(new No(n,e.error)):this.At.resolve()},this.transaction.onerror=e=>{var t=Lo(e.target.error);this.At.reject(new No(n,t))}}static open(e,t,n,r){try{return new Ao(t,e.transaction(r,n))}catch(e){throw new No(t,e)}}get Rt(){return this.At.promise}abort(e){e&&this.At.reject(e),this.aborted||(Er("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}Pt(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new ko(t)}}class Do{constructor(e,t,n){this.name=e,this.version=t,this.bt=n,12.2===Do.Vt(f())&&Tr("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 Er("SimpleDb","Removing database:",e),Mo(window.indexedDB.deleteDatabase(e)).toPromise()}static vt(){if("object"!=typeof indexedDB)return!1;if(Do.St())return!0;const e=f(),t=Do.Vt(e),n=0<t&&t<10,r=Do.Dt(e),s=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||s)}static St(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.Ct)}static xt(e,t){return e.store(t)}static Vt(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 Dt(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async Nt(i){return this.db||(Er("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const s=indexedDB.open(this.name,this.version);s.onsuccess=e=>{var t=e.target.result;n(t)},s.onblocked=()=>{r(new No(i,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},s.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new Nr(xr.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 Nr(xr.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 No(i,t))},s.onupgradeneeded=e=>{Er("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.bt.kt(t,s.transaction,e.oldVersion,this.version).next(()=>{Er("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.Mt&&(this.db.onversionchange=e=>this.Mt(e)),this.db}Ot(t){this.Mt=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var s="readonly"===t;let i=0;for(;;){++i;try{this.db=await this.Nt(e);const t=Ao.open(this.db,e,s?"readonly":"readwrite",n),i=r(t).next(e=>(t.Pt(),e)).catch(e=>(t.abort(e),So.reject(e))).toPromise();return i.catch(()=>{}),await t.Rt,i}catch(e){const t="FirebaseError"!==e.name&&i<3;if(Er("SimpleDb","Transaction failed with error:",e.message,"Retrying:",t),this.close(),!t)return Promise.reject(e)}}}close(){this.db&&this.db.close(),this.db=void 0}}class xo{constructor(e){this.Ft=e,this.$t=!1,this.Bt=null}get isDone(){return this.$t}get Lt(){return this.Bt}set cursor(e){this.Ft=e}done(){this.$t=!0}Ut(e){this.Bt=e}delete(){return Mo(this.Ft.delete())}}class No extends Nr{constructor(e,t){super(xr.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function Co(e){return"IndexedDbTransactionError"===e.name}class ko{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(Er("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(Er("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),Mo(n)}add(e){return Er("SimpleDb","ADD",this.store.name,e,e),Mo(this.store.add(e))}get(t){return Mo(this.store.get(t)).next(e=>(Er("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return Er("SimpleDb","DELETE",this.store.name,e),Mo(this.store.delete(e))}count(){return Er("SimpleDb","COUNT",this.store.name),Mo(this.store.count())}qt(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.Kt(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new So((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}Gt(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new So((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}Qt(e,t){Er("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.jt=!1;var r=this.cursor(n);return this.Kt(r,(e,t,n)=>n.delete())}Wt(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.Kt(r,t)}zt(s){const e=this.cursor({});return new So((n,r)=>{e.onerror=e=>{var t=Lo(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?s(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}Kt(e,i){const a=[];return new So((s,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new xo(t),r=i(t.primaryKey,t.value,n);if(r instanceof So){const e=r.catch(e=>(n.done(),So.reject(e)));a.push(e)}n.isDone?s():null===n.Lt?t.continue():t.continue(n.Lt)}else s()}}).next(()=>So.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.jt?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function Mo(e){return new So((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=Lo(e.target.error);r(t)}})}let Ro=!1;function Lo(e){const t=Do.Vt(f());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 Nr("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 Ro||(Ro=!0,setTimeout(()=>{throw e},0)),e}}return e}class Vo extends _o{constructor(e,t){super(),this.Ht=e,this.currentSequenceNumber=t}}function Oo(e,t){var n=e;return Do.xt(n.Ht,t)}class Fo{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const s=this.mutations[r];s.key.isEqual(e.key)&&Ki(s,e,n[r])}}applyToLocalView(e){for(const t of this.baseMutations)t.key.isEqual(e.key)&&ji(t,e,this.localWriteTime);for(const n of this.mutations)n.key.isEqual(e.key)&&ji(n,e,this.localWriteTime)}applyToLocalDocumentSet(r){this.mutations.forEach(e=>{const t=r.get(e.key),n=t;this.applyToLocalView(n),t.isValidDocument()||n.convertToNoDocument($r.min())})}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),ga())}isEqual(e){return this.batchId===e.batchId&&Kr(this.mutations,e.mutations,(e,t)=>Gi(e,t))&&Kr(this.baseMutations,e.baseMutations,(e,t)=>Gi(e,t))}}class Po{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){Dr(e.mutations.length===n.length);let r=da;var s=e.mutations;for(let i=0;i<s.length;i++)r=r.insert(s[i].key,n[i].version);return new Po(e,t,n,r)}}class Bo{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 qo{constructor(e,t,n,r,s=$r.min(),i=$r.min(),a=es.EMPTY_BYTE_STRING){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=s,this.lastLimboFreeSnapshotVersion=i,this.resumeToken=a}withSequenceNumber(e){return new qo(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new qo(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new qo(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class Uo{constructor(e){this.Jt=e}}function Ko(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:jo(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:Ra(s=e.Jt,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:xa(s,e.version.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Go(t.version)};else{if(!t.isUnknownDocument())return Ar();r.unknownDocument={path:n.path.toArray(),version:Go(t.version)}}var s;return r}function jo(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Go(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function $o(e){var t=new Gr(e.seconds,e.nanoseconds);return $r.fromTimestamp(t)}function zo(t,e){const n=(e.baseMutations||[]).map(e=>Ka(t.Jt,e));for(let i=0;i<e.mutations.length-1;++i){const n=e.mutations[i];if(i+1<e.mutations.length&&void 0!==e.mutations[i+1].transform){const r=e.mutations[i+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(i+1,1),++i}}const r=e.mutations.map(e=>Ka(t.Jt,e)),s=Gr.fromMillis(e.localWriteTimeMs);return new Fo(e.batchId,s,n,r)}function Wo(e){var t,n=$o(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?$o(e.lastLimboFreeSnapshotVersion):$r.min();let s;return s=void 0!==e.query.documents?(Dr(1===(t=e.query).documents.length),pi(hi(Oa(t.documents[0])))):pi($a(e.query)),new qo(s,e.targetId,0,e.lastListenSequenceNumber,n,r,es.fromBase64String(e.resumeToken))}function Ho(e,t){var n=Go(t.snapshotVersion),r=Go(t.lastLimboFreeSnapshotVersion),s=(Gs(t.target)?ja:Ga)(e.Jt,t.target),i=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Ks(t.target),readTime:n,resumeToken:i,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:s}}function Qo(e){var t=$a({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?yi(t,t.limit,"L"):t}function Yo(e,t){return new Bo(t.largestBatchId,Ka(e.Jt,t.overlayMutation))}function Xo(e,t){var n=t.path.lastSegment();return[e,Xa(t.path.popLast()),n]}class Jo{getBundleMetadata(e,t){return Zo(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:$o(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return Zo(e).put({bundleId:(n=t).id,createTime:Go(Ca(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return eu(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:Qo(t.bundledQuery),readTime:$o(t.readTime)};var t})}saveNamedQuery(e,t){return eu(e).put({name:(t=t).name,readTime:Go(Ca(t.readTime)),bundledQuery:t.bundledQuery})}}function Zo(e){return Oo(e,"bundles")}function eu(e){return Oo(e,"namedQueries")}class tu{constructor(e,t){this.M=e,this.userId=t}static Yt(e,t){var n=t.uid||"";return new tu(e,n)}getOverlay(e,t){return nu(e).get(Xo(this.userId,t)).next(e=>e?Yo(this.M,e):null)}saveOverlays(r,s,e){const i=[];return e.forEach((e,t)=>{var n=new Bo(s,t);i.push(this.Xt(r,n))}),So.waitFor(i)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(Xa(e.getCollectionPath())));const s=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);s.push(nu(n).Qt("collectionPathOverlayIndex",t))}),So.waitFor(s)}getOverlaysForCollection(e,t,n){const r=la(),s=Xa(t),i=IDBKeyRange.bound([this.userId,s,n],[this.userId,s,Number.POSITIVE_INFINITY],!0);return nu(e).qt("collectionPathOverlayIndex",i).next(e=>{for(const t of e){const e=Yo(this.M,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,s){const i=la();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return nu(e).Wt({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=Yo(this.M,t);i.size()<s||r.largestBatchId===a?(i.set(r.getKey(),r),a=r.largestBatchId):n.done()}).next(()=>i)}Xt(e,t){return nu(e).put(function(e,t,n){var[,r,s]=Xo(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:Ua(e.Jt,n.mutation)}}(this.M,this.userId,t))}}function nu(e){return Oo(e,"documentOverlays")}class ru{constructor(){}Zt(e,t){this.te(e,t),t.ee()}te(e,t){var n,r;"nullValue"in e?this.ne(t,5):"booleanValue"in e?(this.ne(t,10),t.se(e.booleanValue?1:0)):"integerValue"in e?(this.ne(t,15),t.se(rs(e.integerValue))):"doubleValue"in e?(n=rs(e.doubleValue),isNaN(n)?this.ne(t,13):(this.ne(t,15),cs(n)?t.se(0):t.se(n))):"timestampValue"in e?(r=e.timestampValue,this.ne(t,20),"string"==typeof r?t.ie(r):(t.ie(`${r.seconds||""}`),t.se(r.nanos||0))):"stringValue"in e?(this.re(e.stringValue,t),this.oe(t)):"bytesValue"in e?(this.ne(t,30),t.ue(ss(e.bytesValue)),this.oe(t)):"referenceValue"in e?this.ae(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.ne(t,45),t.se(r.latitude||0),t.se(r.longitude||0)):"mapValue"in e?xs(e)?this.ne(t,Number.MAX_SAFE_INTEGER):(this.ce(e.mapValue,t),this.oe(t)):"arrayValue"in e?(this.he(e.arrayValue,t),this.oe(t)):Ar()}re(e,t){this.ne(t,25),this.le(e,t)}le(e,t){t.ie(e)}ce(e,t){var n=e.fields||{};this.ne(t,55);for(const e of Object.keys(n))this.re(e,t),this.te(n[e],t)}he(e,t){var n=e.values||[];this.ne(t,50);for(const e of n)this.te(e,t)}ae(e,t){this.ne(t,37),ds.fromName(e).path.forEach(e=>{this.ne(t,60),this.le(e,t)})}ne(e,t){e.se(t)}oe(e){e.se(2)}}function su(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)}ru.fe=new ru;class iu{constructor(){this.buffer=new Uint8Array(1024),this.position=0}de(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this._e(n.value),n=t.next();this.we()}me(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.ge(n.value),n=t.next();this.ye()}pe(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this._e(e);else if(e<2048)this._e(960|e>>>6),this._e(128|63&e);else if(t<"\ud800"||"\udbff"<t)this._e(480|e>>>12),this._e(128|63&e>>>6),this._e(128|63&e);else{const e=t.codePointAt(0);this._e(240|e>>>18),this._e(128|63&e>>>12),this._e(128|63&e>>>6),this._e(128|63&e)}}this.we()}Ie(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.ge(e);else if(e<2048)this.ge(960|e>>>6),this.ge(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.ge(480|e>>>12),this.ge(128|63&e>>>6),this.ge(128|63&e);else{const e=t.codePointAt(0);this.ge(240|e>>>18),this.ge(128|63&e>>>12),this.ge(128|63&e>>>6),this.ge(128|63&e)}}this.ye()}Te(e){var t=this.Ee(e),n=su(t);this.Ae(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]}Re(e){var t=this.Ee(e),n=su(t);this.Ae(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])}Pe(){this.be(255),this.be(255)}Ve(){this.ve(255),this.ve(255)}reset(){this.position=0}seed(e){this.Ae(e.length),this.buffer.set(e,this.position),this.position+=e.length}Se(){return this.buffer.slice(0,this.position)}Ee(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}_e(e){var t=255&e;0==t?(this.be(0),this.be(255)):255==t?(this.be(255),this.be(0)):this.be(t)}ge(e){var t=255&e;0==t?(this.ve(0),this.ve(255)):255==t?(this.ve(255),this.ve(0)):this.ve(e)}we(){this.be(0),this.be(1)}ye(){this.ve(0),this.ve(1)}be(e){this.Ae(1),this.buffer[this.position++]=e}ve(e){this.Ae(1),this.buffer[this.position++]=~e}Ae(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 au{constructor(e){this.De=e}ue(e){this.De.de(e)}ie(e){this.De.pe(e)}se(e){this.De.Te(e)}ee(){this.De.Pe()}}class ou{constructor(e){this.De=e}ue(e){this.De.me(e)}ie(e){this.De.Ie(e)}se(e){this.De.Re(e)}ee(){this.De.Ve()}}class uu{constructor(){this.De=new iu,this.Ce=new au(this.De),this.xe=new ou(this.De)}seed(e){this.De.seed(e)}Ne(e){return 0===e?this.Ce:this.xe}Se(){return this.De.Se()}reset(){this.De.reset()}}class hu{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}ke(){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 hu(this.indexId,this.documentKey,this.arrayValue,n)}}function cu(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=lu(e.arrayValue,t.arrayValue),0!==n?n:(n=lu(e.directionalValue,t.directionalValue),0!==n?n:ds.comparator(e.documentKey,t.documentKey)))}function lu(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 du{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Me=e.orderBy,this.Oe=[];for(const t of e.filters){const e=t;e.S()?this.Fe=e:this.Oe.push(e)}}$e(e){var t=Ls(e);if(void 0!==t&&!this.Be(t))return!1;var n=Vs(e);let r=0,s=0;for(;r<n.length&&this.Be(n[r]);++r);if(r===n.length)return!0;if(void 0!==this.Fe){const e=n[r];if(!this.Le(this.Fe,e)||!this.Ue(this.Me[s++],e))return!1;++r}for(;r<n.length;++r){const e=n[r];if(s>=this.Me.length||!this.Ue(this.Me[s++],e))return!1}return!0}Be(e){for(const t of this.Oe)if(this.Le(t,e))return!0;return!1}Le(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}Ue(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}class fu{constructor(){this.qe=new gu}addToCollectionParentIndex(e,t){return this.qe.add(t),So.resolve()}getCollectionParents(e,t){return So.resolve(this.qe.getEntries(t))}addFieldIndex(e,t){return So.resolve()}deleteFieldIndex(e,t){return So.resolve()}getDocumentsMatchingTarget(e,t){return So.resolve(null)}getFieldIndex(e,t){return So.resolve(null)}getFieldIndexes(e,t){return So.resolve([])}getNextCollectionGroupToUpdate(e){return So.resolve(null)}updateCollectionGroup(e,t,n){return So.resolve()}updateIndexEntries(e,t){return So.resolve()}}class gu{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new aa(Yr.comparator),s=!r.has(n);return this.index[t]=r.add(n),s}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new aa(Yr.comparator)).toArray()}}const mu=new Uint8Array(0);class pu{constructor(e,t){this.user=e,this.databaseId=t,this.Ke=new gu,this.Ge=new na(e=>Ks(e),(e,t)=>js(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.Ke.has(t))return So.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Ke.add(t)});r={collectionId:n,parent:Xa(r)};return yu(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[jr(n),""],!1,!0);return yu(e).qt(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(Za(t.parent))}return r})}addFieldIndex(e,t){const n=wu(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};return delete r.indexId,n.add(r).next()}deleteFieldIndex(e,t){const n=wu(e),r=bu(e),s=vu(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>s.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}getDocumentsMatchingTarget(e,h){const c=vu(e);let l=!0;const n=new Map;return So.forEach(this.Qe(h),t=>this.getFieldIndex(e,t).next(e=>{l=l&&!!e,n.set(t,e)})).next(()=>{if(l){let u=ga();const l=[];return So.forEach(n,(e,t)=>{Er("IndexedDbIndexManager",`Using index ${o=e,`id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${Ks(h)}`);var n=function(e,t){var n=Ls(t);if(void 0===n)return null;for(const t of $s(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),r=function(e,t){const n=new Map;for(const r of Vs(t))for(const t of $s(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),s=function(e,t){const n=[];let r=!0;for(const s of Vs(t)){const t=(0===s.kind?zs:Ws)(e,s.fieldPath,e.startAt);if(!t.value)return null;n.push(t.value),r=r&&t.inclusive}return new ri(n,r)}(t,e),i=function(e,t){const n=[];let r=!0;for(const s of Vs(t)){const t=(0===s.kind?Ws:zs)(e,s.fieldPath,e.endAt);if(!t.value)return null;n.push(t.value),r=r&&t.inclusive}return new ri(n,r)}(t,e),a=this.je(e,t,s),o=this.je(e,t,i),r=this.We(e,t,r),r=this.ze(e.indexId,n,a,!!s&&s.inclusive,o,!!i&&i.inclusive,r);return So.forEach(r,e=>c.Gt(e,h.limit).next(e=>{e.forEach(e=>{var t=ds.fromSegments(e.documentKey);u.has(t)||(u=u.add(t),l.push(t))})}))}).next(()=>l)}return So.resolve(null)})}Qe(e){var t;return(t=this.Ge.get(e))||(this.Ge.set(e,t=[e]),t)}ze(t,e,n,r,s,i,a){const o=(null!=e?e.length:1)*Math.max(null!=n?n.length:1,null!=s?s.length:1),u=o/(null!=e?e.length:1),h=[];for(let c=0;c<o;++c){const o=e?this.He(e[c/u]):mu,l=n?this.Je(t,o,n[c%u],r):this.Ye(t),d=s?this.Xe(t,o,s[c%u],i):this.Ye(t+1);h.push(...this.createRange(l,d,a.map(e=>this.Je(t,o,e,!0))))}return h}Je(e,t,n,r){const s=new hu(e,ds.empty(),t,n);return r?s:s.ke()}Xe(e,t,n,r){const s=new hu(e,ds.empty(),t,n);return r?s.ke():s}Ye(e){return new hu(e,ds.empty(),mu,mu)}getFieldIndex(e,t){const n=new du(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next(e=>{const t=e.filter(e=>n.$e(e));return t.sort((e,t)=>t.fields.length-e.fields.length),0<t.length?t[0]:null})}Ze(e,t){const n=new uu;for(const s of Vs(e)){const e=t.data.field(s.fieldPath);if(null==e)return null;var r=n.Ne(s.kind);ru.fe.Zt(e,r)}return n.Se()}He(e){const t=new uu;return ru.fe.Zt(e,t.Ne(0)),t.Se()}tn(e,t){const n=new uu;return ru.fe.Zt(Is(this.databaseId,t),n.Ne(0===(r=Vs(e)).length?0:r[r.length-1].kind)),n.Se();var r}We(e,t,n){if(null===n)return[];let r=[];r.push(new uu);let s=0;for(const i of Vs(e)){const e=n[s++];for(const n of r)if(this.en(t,i.fieldPath)&&Ts(e))r=this.nn(r,i,e);else{const t=n.Ne(i.kind);ru.fe.Zt(e,t)}}return this.sn(r)}je(e,t,n){return null==n?null:this.We(e,t,n.position)}sn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Se();return t}nn(e,t,n){const r=[...e],s=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new uu;r.seed(n.Se()),ru.fe.Zt(e,r.Ne(t.kind)),s.push(r)}return s}en(e,t){return!!e.filters.find(e=>e instanceof Hs&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=wu(e),r=bu(e);return(t?n.qt("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.qt()).next(e=>{const i=[];return So.forEach(e,s=>r.get([s.indexId,this.uid]).next(e=>{var t,n,r;i.push((t=s,n=(e=e)?new Fs(e.sequenceNumber,new Bs($o(e.readTime),new ds(Za(e.documentKey)),e.largestBatchId)):Fs.empty(),r=t.fields.map(([e,t])=>new Os(Jr.fromServerFormat(e),t)),new Rs(t.indexId,t.collectionGroup,r,n)))})).next(()=>i)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:Ur(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,t,n){const s=wu(e),i=bu(e);return this.rn(e).next(r=>s.qt("collectionGroupIndex",IDBKeyRange.bound(t,t)).next(e=>So.forEach(e,e=>i.put(function(e,t,n){return{indexId:e,uid:t.uid||"",sequenceNumber:r,readTime:Go(n.readTime),documentKey:Xa(n.documentKey.path),largestBatchId:n.largestBatchId}}(e.indexId,this.user,n)))))}updateIndexEntries(s,e){const n=new Map;return So.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?So.resolve(e):this.getFieldIndexes(s,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),So.forEach(e,n=>this.on(s,t,n).next(e=>{var t=this.un(r,n);return e.isEqual(t)?So.resolve():this.an(s,r,n,e,t)}))))})}cn(e,t,n,r){return vu(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.tn(n,t.key),documentKey:t.key.path.toArray()})}hn(e,t,n,r){return vu(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.tn(n,t.key),t.key.path.toArray()])}on(e,n,r){const t=vu(e);let s=new aa(cu);return t.Wt({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.tn(r,n)])},(e,t)=>{s=s.add(new hu(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>s)}un(e,t){let n=new aa(cu);var r=this.Ze(t,e);if(null==r)return n;const s=Ls(t);if(null!=s){var i=e.data.field(s.fieldPath);if(Ts(i))for(const s of i.arrayValue.values||[])n=n.add(new hu(t.indexId,e.key,this.He(s),r))}else n=n.add(new hu(t.indexId,e.key,mu,r));return n}an(t,n,r,h,e){Er("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const s=[];return function(e,n,r,s){var i=h.getIterator(),a=e.getIterator();let o=ua(i),u=ua(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=ua(a)):t?(s(o),o=ua(i)):(o=ua(i),u=ua(a))}}(e,cu,e=>{s.push(this.cn(t,n,r,e))},e=>{s.push(this.hn(t,n,r,e))}),So.waitFor(s)}rn(e){let r=1;return bu(e).Wt({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)=>cu(e,t)).filter((e,t,n)=>!t||0!==cu(e,n[t-1]));const r=[];r.push(e);for(const s of n){const n=cu(s,e),i=cu(s,t);if(0===n)r[0]=e.ke();else if(0<n&&i<0)r.push(s),r.push(s.ke());else if(0<i)break}r.push(t);const s=[];for(let a=0;a<r.length;a+=2)s.push(IDBKeyRange.bound([r[a].indexId,this.uid,r[a].arrayValue,r[a].directionalValue,mu,[]],[r[a+1].indexId,this.uid,r[a+1].arrayValue,r[a+1].directionalValue,mu,[]]));return s}}function yu(e){return Oo(e,"collectionParents")}function vu(e){return Oo(e,"indexEntries")}function wu(e){return Oo(e,"indexConfiguration")}function bu(e){return Oo(e,"indexState")}const Iu={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class Eu{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Eu(e,Eu.DEFAULT_COLLECTION_PERCENTILE,Eu.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function Tu(e,t,n){const r=e.store("mutations"),s=e.store("documentMutations"),i=[],a=IDBKeyRange.only(n.batchId);let o=0;const u=r.Wt({range:a},(e,t,n)=>(o++,n.delete()));i.push(u.next(()=>{Dr(1===o)}));const h=[];for(const e of n.mutations){const r=no(t,e.key.path,n.batchId);i.push(s.delete(r)),h.push(e.key)}return So.waitFor(i).next(()=>h)}function _u(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw Ar();t=e.noDocument}return JSON.stringify(t).length}Eu.DEFAULT_COLLECTION_PERCENTILE=10,Eu.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Eu.DEFAULT=new Eu(41943040,Eu.DEFAULT_COLLECTION_PERCENTILE,Eu.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Eu.DISABLED=new Eu(-1,0,0);class Su{constructor(e,t,n,r){this.userId=e,this.M=t,this.indexManager=n,this.referenceDelegate=r,this.ln={}}static Yt(e,t,n,r){Dr(""!==e.uid);var s=e.isAuthenticated()?e.uid:"";return new Su(s,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Du(e).Wt({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(c,l,d,f){const g=xu(c),m=Du(c);return m.add({}).next(e=>{Dr("number"==typeof e);const t=new Fo(e,l,d,f),n=(s=this.M,i=this.userId,a=t,o=a.baseMutations.map(e=>Ua(s.Jt,e)),u=a.mutations.map(e=>Ua(s.Jt,e)),{userId:i,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:u}),r=[];var s,i,a,o,u;let h=new aa((e,t)=>Ur(e.canonicalString(),t.canonicalString()));for(const c of f){const l=no(this.userId,c.key.path,e);h=h.add(c.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,ro))}return h.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(c,e))}),c.addOnCommittedListener(()=>{this.ln[e]=t.keys()}),So.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return Du(e).get(t).next(e=>e?(Dr(e.userId===this.userId),zo(this.M,e)):null)}fn(e,n){return this.ln[n]?So.resolve(this.ln[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.ln[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let s=null;return Du(e).Wt({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(Dr(t.batchId>=r),s=zo(this.M,t)),n.done()}).next(()=>s)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return Du(e).Wt({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 Du(e).qt("userMutationsIndex",t).next(e=>e.map(e=>zo(this.M,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=to(this.userId,o.path),t=IDBKeyRange.lowerBound(e),u=[];return xu(a).Wt({range:t},(e,t,n)=>{var[r,s,i]=e,s=Za(s);if(r===this.userId&&o.path.isEqual(s))return Du(a).get(i).next(e=>{if(!e)throw Ar();Dr(e.userId===this.userId),u.push(zo(this.M,e))});n.done()}).next(()=>u)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new aa(Ur);const n=[];return e.forEach(a=>{var e=to(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=xu(t).Wt({range:e},(e,t,n)=>{var[r,s,i]=e,s=Za(s);r===this.userId&&a.path.isEqual(s)?o=o.add(i):n.done()});n.push(e)}),So.waitFor(n).next(()=>this.dn(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=to(this.userId,a),r=IDBKeyRange.lowerBound(n);let u=new aa(Ur);return xu(e).Wt({range:r},(e,t,n)=>{var[r,s,i]=e,s=Za(s);r===this.userId&&a.isPrefixOf(s)?s.length===o&&(u=u.add(i)):n.done()}).next(()=>this.dn(e,u))}dn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(Du(t).get(e).next(e=>{if(null===e)throw Ar();Dr(e.userId===this.userId),n.push(zo(this.M,e))}))}),So.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return Tu(t.Ht,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this._n(n.batchId)}),So.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}_n(e){delete this.ln[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return So.resolve();var t=IDBKeyRange.lowerBound([this.userId]);const r=[];return xu(n).Wt({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=Za(e[1]);r.push(t)}else n.done()}).next(()=>{Dr(0===r.length)})})}containsKey(e,t){return Au(e,this.userId,t)}wn(e){return Nu(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function Au(e,i,t){const n=to(i,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return xu(e).Wt({range:r,jt:!0},(e,t,n)=>{var[r,s]=e;r===i&&s===a&&(o=!0),n.done()}).next(()=>o)}function Du(e){return Oo(e,"mutations")}function xu(e){return Oo(e,"documentMutations")}function Nu(e){return Oo(e,"mutationQueues")}class Cu{constructor(e){this.mn=e}next(){return this.mn+=2,this.mn}static gn(){return new Cu(0)}static yn(){return new Cu(-1)}}class ku{constructor(e,t){this.referenceDelegate=e,this.M=t}allocateTargetId(n){return this.pn(n).next(e=>{const t=new Cu(e.highestTargetId);return e.highestTargetId=t.next(),this.In(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.pn(e).next(e=>$r.fromTimestamp(new Gr(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.pn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.pn(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.In(t,e)))}addTargetData(t,n){return this.Tn(t,n).next(()=>this.pn(t).next(e=>(e.targetCount+=1,this.En(n,e),this.In(t,e))))}updateTargetData(e,t){return this.Tn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>Mu(t).delete(e.targetId)).next(()=>this.pn(t)).next(e=>(Dr(0<e.targetCount),--e.targetCount,this.In(t,e)))}removeTargets(r,s,i){let a=0;const o=[];return Mu(r).Wt((e,t)=>{var n=Wo(t);n.sequenceNumber<=s&&null===i.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>So.waitFor(o)).next(()=>a)}forEachTarget(e,r){return Mu(e).Wt((e,t)=>{var n=Wo(t);r(n)})}pn(e){return Ru(e).get("targetGlobalKey").next(e=>(Dr(null!==e),e))}In(e,t){return Ru(e).put("targetGlobalKey",t)}Tn(e,t){return Mu(e).put(Ho(this.M,t))}En(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.pn(e).next(e=>e.targetCount)}getTargetData(e,s){var t=Ks(s),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let i=null;return Mu(e).Wt({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=Wo(t);js(s,r.target)&&(i=r,n.done())}).next(()=>i)}addMatchingKeys(n,e,r){const s=[],i=Lu(n);return e.forEach(e=>{var t=Xa(e.path);s.push(i.put({targetId:r,path:t})),s.push(this.referenceDelegate.addReference(n,r,e))}),So.waitFor(s)}removeMatchingKeys(n,e,r){const s=Lu(n);return So.forEach(e,e=>{var t=Xa(e.path);return So.waitFor([s.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=Lu(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=Lu(e);let s=ga();return r.Wt({range:n,jt:!0},(e,t,n)=>{var r=Za(e[1]),r=new ds(r);s=s.add(r)}).next(()=>s)}containsKey(e,t){var n=Xa(t.path),n=IDBKeyRange.bound([n],[jr(n)],!1,!0);let r=0;return Lu(e).Wt({index:"documentTargetsIndex",jt:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}Et(e,t){return Mu(e).get(t).next(e=>e?Wo(e):null)}}function Mu(e){return Oo(e,"targets")}function Ru(e){return Oo(e,"targetGlobal")}function Lu(e){return Oo(e,"targetDocuments")}async function Vu(e){if(e.code!==xr.FAILED_PRECONDITION||e.message!==To)throw e;Er("LocalStore","Unexpectedly lost primary lease")}function Ou([e,t],[n,r]){var s=Ur(e,n);return 0===s?Ur(t,r):s}class Fu{constructor(e){this.An=e,this.buffer=new aa(Ou),this.Rn=0}Pn(){return++this.Rn}bn(e){var t=[e,this.Pn()];if(this.buffer.size<this.An)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();Ou(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class Pu{constructor(e,t){this.garbageCollector=e,this.asyncQueue=t,this.Vn=!1,this.vn=null}start(e){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Sn(e)}stop(){this.vn&&(this.vn.cancel(),this.vn=null)}get started(){return null!==this.vn}Sn(e){var t=this.Vn?3e5:6e4;Er("LruGarbageCollector",`Garbage collection scheduled in ${t}ms`),this.vn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",t,async()=>{this.vn=null,this.Vn=!0;try{await e.collectGarbage(this.garbageCollector)}catch(e){Co(e)?Er("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await Vu(e)}await this.Sn(e)})}}class Bu{constructor(e,t){this.Dn=e,this.params=t}calculateTargetCount(e,t){return this.Dn.Cn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return So.resolve(Br.A);const n=new Fu(t);return this.Dn.forEachTarget(e,e=>n.bn(e.sequenceNumber)).next(()=>this.Dn.xn(e,e=>n.bn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.Dn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Dn.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(Er("LruGarbageCollector","Garbage collection skipped; disabled"),So.resolve(Iu)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(Er("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),Iu):this.Nn(t,n))}getCacheSize(e){return this.Dn.getCacheSize(e)}Nn(t,n){let r,s,i,a,o,u,h;const c=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(s=e>this.params.maximumSequenceNumbersToCollect?(Er("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,a=Date.now(),this.nthSequenceNumber(t,s))).next(e=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(i=e,u=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(h=Date.now(),Ir()<=l.DEBUG&&Er("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-c}ms\n\tDetermined least recently used ${s} in `+(o-a)+"ms\n"+`\tRemoved ${i} targets in `+(u-o)+"ms\n"+`\tRemoved ${e} documents in `+(h-u)+"ms\n"+`Total Duration: ${h-c}ms`),So.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:e})))}}class qu{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new Bu(e,t))}Cn(e){const n=this.kn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}kn(e){let t=0;return this.xn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}xn(e,n){return this.Mn(e,(e,t)=>n(t))}addReference(e,t,n){return Uu(e,n)}removeReference(e,t,n){return Uu(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return Uu(e,t)}On(t,n){let r=!1;return Nu(t).zt(e=>Au(t,e,n).next(e=>(e&&(r=!0),So.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const s=this.db.getRemoteDocumentCache().newChangeBuffer(),i=[];let a=0;return this.Mn(n,(t,e)=>{if(e<=r){const r=this.On(n,t).next(e=>{if(!e)return a++,s.getEntry(n,t).next(()=>(s.removeEntry(t,$r.min()),Lu(n).delete([0,Xa(t.path)])))});i.push(r)}}).next(()=>So.waitFor(i)).next(()=>s.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return Uu(e,t)}Mn(e,r){const t=Lu(e);let s,i=Br.A;return t.Wt({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(i!==Br.A&&r(new ds(Za(s)),i),i=n,s=t):i=Br.A}).next(()=>{i!==Br.A&&r(new ds(Za(s)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function Uu(e,t){return Lu(e).put((e=e.currentSequenceNumber,{targetId:0,path:Xa(t.path),sequenceNumber:e}))}class Ku{constructor(){this.changes=new na(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,Ms.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?So.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 ju{constructor(e){this.M=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return zu(e).put(n)}removeEntry(e,n,t){return zu(e).delete(function(e){const t=n.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],jo(e),t[t.length-1]]}(t))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Fn(t,e)))}getEntry(e,n){let r=Ms.newInvalidDocument(n);return zu(e).Wt({index:"documentKeyIndex",range:IDBKeyRange.only(Wu(n))},(e,t)=>{r=this.$n(n,t)}).next(()=>r)}Bn(e,n){let r={size:0,document:Ms.newInvalidDocument(n)};return zu(e).Wt({index:"documentKeyIndex",range:IDBKeyRange.only(Wu(n))},(e,t)=>{r={document:this.$n(n,t),size:_u(t)}}).next(()=>r)}getEntries(e,t){let r=ha;return this.Ln(e,t,(e,t)=>{var n=this.$n(e,t);r=r.insert(e,n)}).next(()=>r)}Un(e,t){let r=ha,s=new ra(ds.comparator);return this.Ln(e,t,(e,t)=>{var n=this.$n(e,t);r=r.insert(e,n),s=s.insert(e,_u(t))}).next(()=>({documents:r,qn:s}))}Ln(e,t,s){if(t.isEmpty())return So.resolve();let n=new aa(Qu);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(Wu(n.first()),Wu(n.last())),i=n.getIterator();let a=i.getNext();return zu(e).Wt({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=ds.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&Qu(a,r)<0;)s(a,null),a=i.getNext();a&&a.isEqual(r)&&(s(a,t),a=i.hasNext()?i.getNext():null),a?n.Ut(Wu(a)):n.done()}).next(()=>{for(;a;)s(a,null),a=i.hasNext()?i.getNext():null})}getAllFromCollection(e,t,n){var r=[t.popLast().toArray(),t.lastSegment(),jo(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],s=[t.popLast().toArray(),t.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return zu(e).qt(IDBKeyRange.bound(r,s,!0)).next(e=>{let t=ha;for(const n of e){const e=this.$n(ds.fromSegments(n.prefixPath.concat(n.collectionGroup,n.documentId)),n);t=t.insert(e.key,e)}return t})}getAllFromCollectionGroup(e,t,n,s){let i=ha;var r=Hu(t,n),a=Hu(t,Bs.max());return zu(e).Wt({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.$n(ds.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);i=i.insert(r.key,r),i.size===s&&n.done()}).next(()=>i)}newChangeBuffer(e){return new Gu(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return $u(e).get("remoteDocumentGlobalKey").next(e=>(Dr(!!e),e))}Fn(e,t){return $u(e).put("remoteDocumentGlobalKey",t)}$n(e,t){if(t){const e=function(e,t){let n;if(t.document)n=qa(e.Jt,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=ds.fromSegments(t.noDocument.path),s=$o(t.noDocument.readTime);n=Ms.newNoDocument(e,s),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return Ar();{const e=ds.fromSegments(t.unknownDocument.path),i=$o(t.unknownDocument.version);n=Ms.newUnknownDocument(e,i)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new Gr(t[0],t[1]),$r.fromTimestamp(r))),n;var r}(this.M,t);if(!e.isNoDocument()||!e.version.isEqual($r.min()))return e}return Ms.newInvalidDocument(e)}}class Gu extends Ku{constructor(e,t){super(),this.Kn=e,this.trackRemovals=t,this.Gn=new na(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(i){const a=[];let o=0,u=new aa((e,t)=>Ur(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.Gn.get(e);if(a.push(this.Kn.removeEntry(i,e,n.readTime)),t.isValidDocument()){var r=Ko(this.Kn.M,t);u=u.add(e.path.popLast());var s=_u(r);o+=s-n.size,a.push(this.Kn.addEntry(i,e,r))}else if(o-=n.size,this.trackRemovals){const o=Ko(this.Kn.M,t.convertToNoDocument($r.min()));a.push(this.Kn.addEntry(i,e,o))}}),u.forEach(e=>{a.push(this.Kn.indexManager.addToCollectionParentIndex(i,e))}),a.push(this.Kn.updateMetadata(i,o)),So.waitFor(a)}getFromCache(e,t){return this.Kn.Bn(e,t).next(e=>(this.Gn.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Kn.Un(e,t).next(({documents:n,qn:e})=>(e.forEach((e,t)=>{this.Gn.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function $u(e){return Oo(e,"remoteDocumentGlobal")}function zu(e){return Oo(e,"remoteDocumentsV14")}function Wu(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function Hu(e,t){const n=t.documentKey.path.toArray();return[e,jo(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function Qu(e,t){var n=e.path.toArray(),r=t.path.toArray();let s=0;for(let i=0;i<n.length-2&&i<r.length-2;++i)if(s=Ur(n[i],r[i]),s)return s;return s=Ur(n.length,r.length),s||(s=Ur(n[n.length-2],r[r.length-2]),s||Ur(n[n.length-1],r[r.length-1]))}class Yu{constructor(e){this.M=e}kt(t,e,n,r){const s=new Ao("createOrUpgrade",e);var i;n<1&&1<=r&&(t.createObjectStore("owner"),(i=t).createObjectStore("mutationQueues",{keyPath:"userId"}),i.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",eo,{unique:!0}),i.createObjectStore("documentMutations"),Xu(t),t.createObjectStore("remoteDocuments"));let a=So.resolve();return n<3&&3<=r&&(0!==n&&((i=t).deleteObjectStore("targetDocuments"),i.deleteObjectStore("targets"),i.deleteObjectStore("targetGlobal"),Xu(t)),a=a.next(()=>function(){const e=s.store("targetGlobal"),t={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:$r.min().toTimestamp(),targetCount:0};return e.put("targetGlobalKey",t)}())),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,s){return s.store("mutations").qt().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",eo,{unique:!0});const t=s.store("mutations"),n=e.map(e=>t.put(e));return So.waitFor(n)})}(t,s))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.Qn(s))),n<6&&6<=r&&(a=a.next(()=>(t.createObjectStore("remoteDocumentGlobal"),this.jn(s)))),n<7&&7<=r&&(a=a.next(()=>this.Wn(s))),n<8&&8<=r&&(a=a.next(()=>this.zn(t,s))),n<9&&9<=r&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(a=a.next(()=>this.Hn(s))),n<11&&11<=r&&(a=a.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(a=a.next(()=>{!function(){const e=t.createObjectStore("documentOverlays",{keyPath:po});e.createIndex("collectionPathOverlayIndex",yo,{unique:!1}),e.createIndex("collectionGroupOverlayIndex",vo,{unique:!1})}()})),n<13&&13<=r&&(a=a.next(()=>function(){const e=t.createObjectStore("remoteDocumentsV14",{keyPath:so});e.createIndex("documentKeyIndex",io),e.createIndex("collectionGroupIndex",ao)}()).next(()=>this.Jn(t,s)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>{var e;(e=t).createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:lo}).createIndex("sequenceNumberIndex",fo,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:go}).createIndex("documentKeyIndex",mo,{unique:!1})})),a}jn(t){let n=0;return t.store("remoteDocuments").Wt((e,t)=>{n+=_u(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}Qn(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.qt().next(e=>So.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.qt("userMutationsIndex",e).next(e=>So.forEach(e,e=>{Dr(e.userId===n.userId);var t=zo(this.M,e);return Tu(r,n.userId,t).next(()=>{})}))}))}Wn(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(s=>{const i=[];return t.Wt((e,t)=>{const n=new Yr(e),r=[0,Xa(n)];i.push(a.get(r).next(e=>e?So.resolve():(e=>a.put({targetId:0,path:Xa(e),sequenceNumber:s.highestListenSequenceNumber}))(n)))}).next(()=>So.waitFor(i))})}zn(e,t){e.createObjectStore("collectionParents",{keyPath:co});const n=t.store("collectionParents"),r=new gu,s=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Xa(r)})}};return t.store("remoteDocuments").Wt({jt:!0},(e,t)=>{const n=new Yr(e);return s(n.popLast())}).next(()=>t.store("documentMutations").Wt({jt:!0},([,e],t)=>{const n=Za(e);return s(n.popLast())}))}Hn(e){const r=e.store("targets");return r.Wt((e,t)=>{var n=Wo(t),n=Ho(this.M,n);return r.put(n)})}Jn(e,i){const t=i.store("remoteDocuments"),a=[];return t.Wt((e,t)=>{const n=i.store("remoteDocumentsV14"),r=((s=t).document?new ds(Yr.fromString(s.document.name).popFirst(5)):s.noDocument?ds.fromSegments(s.noDocument.path):s.unknownDocument?ds.fromSegments(s.unknownDocument.path):Ar()).path.toArray();var s={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};a.push(n.put(s))}).next(()=>So.waitFor(a))}}function Xu(e){e.createObjectStore("targetDocuments",{keyPath:uo}).createIndex("documentTargetsIndex",ho,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",oo,{unique:!0}),e.createObjectStore("targetGlobal")}const Ju="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 Zu{constructor(e,t,n,r,s,i,a,o,u,h,c=13){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Yn=s,this.window=i,this.document=a,this.Xn=u,this.Zn=h,this.ts=c,this.es=null,this.ns=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ss=null,this.inForeground=!1,this.rs=null,this.os=null,this.us=Number.NEGATIVE_INFINITY,this.cs=e=>Promise.resolve(),!Zu.vt())throw new Nr(xr.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new qu(this,r),this.hs=t+"main",this.M=new Uo(o),this.ls=new Do(this.hs,this.ts,new Yu(this.M)),this.fs=new ku(this.referenceDelegate,this.M),this.ds=(o=this.M,new ju(o)),this._s=new Jo,this.window&&this.window.localStorage?this.ws=this.window.localStorage:(this.ws=null,!1===h&&Tr("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.gs().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new Nr(xr.FAILED_PRECONDITION,Ju);return this.ys(),this.ps(),this.Is(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.fs.getHighestSequenceNumber(e))}).then(e=>{this.es=new Br(e,this.Xn)}).then(()=>{this.ns=!0}).catch(e=>(this.ls&&this.ls.close(),Promise.reject(e)))}Ts(t){return this.cs=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.ls.Ot(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Yn.enqueueAndForget(async()=>{this.started&&await this.gs()}))}gs(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>th(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.Es(t).next(e=>{e||(this.isPrimary=!1,this.Yn.enqueueRetryable(()=>this.cs(!1)))})}).next(()=>this.As(t)).next(e=>this.isPrimary&&!e?this.Rs(t).next(()=>!1):!!e&&this.Ps(t).next(()=>!0))).catch(e=>{if(Co(e))return Er("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return Er("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Yn.enqueueRetryable(()=>this.cs(e)),this.isPrimary=e})}Es(e){return eh(e).get("owner").next(e=>So.resolve(this.bs(e)))}Vs(e){return th(e).delete(this.clientId)}async vs(){if(this.isPrimary&&!this.Ss(this.us,18e5)){this.us=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=Oo(e,"clientMetadata");return r.qt().next(e=>{const t=this.Ds(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return So.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.ws)for(const t of e)this.ws.removeItem(this.Cs(t.clientId))}}Is(){this.os=this.Yn.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.gs().then(()=>this.vs()).then(()=>this.Is()))}bs(e){return!!e&&e.ownerId===this.clientId}As(t){return this.Zn?So.resolve(!0):eh(t).get("owner").next(e=>{if(null!==e&&this.Ss(e.leaseTimestampMs,5e3)&&!this.xs(e.ownerId)){if(this.bs(e)&&this.networkEnabled)return!0;if(!this.bs(e)){if(!e.allowTabSynchronization)throw new Nr(xr.FAILED_PRECONDITION,Ju);return!1}}return!(!this.networkEnabled||!this.inForeground)||th(t).qt().next(e=>void 0===this.Ds(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&&Er("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.ns=!1,this.Ns(),this.os&&(this.os.cancel(),this.os=null),this.ks(),this.Ms(),await this.ls.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new Vo(e,Br.A);return this.Rs(t).next(()=>this.Vs(t))}),this.ls.close(),this.Os()}Ds(e,t){return e.filter(e=>this.Ss(e.updateTimeMs,t)&&!this.xs(e.clientId))}Fs(){return this.runTransaction("getActiveClients","readonly",e=>th(e).qt().next(e=>this.Ds(e,18e5).map(e=>e.clientId)))}get started(){return this.ns}getMutationQueue(e,t){return Su.Yt(e,this.M,t,this.referenceDelegate)}getTargetCache(){return this.fs}getRemoteDocumentCache(){return this.ds}getIndexManager(e){return new pu(e,this.M.Jt.databaseId)}getDocumentOverlayCache(e){return tu.Yt(this.M,e)}getBundleCache(){return this._s}runTransaction(t,n,r){Er("IndexedDbPersistence","Starting transaction:",t);var e,s="readonly"===n?"readonly":"readwrite",e=14===(e=this.ts)?Eo:13===e?Io:12===e?bo:11===e?wo:void Ar();let i;return this.ls.runTransaction(t,s,e,e=>(i=new Vo(e,this.es?this.es.next():Br.A),"readwrite-primary"===n?this.Es(i).next(e=>!!e||this.As(i)).next(e=>{if(!e)throw Tr(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Yn.enqueueRetryable(()=>this.cs(!1)),new Nr(xr.FAILED_PRECONDITION,To);return r(i)}).next(e=>this.Ps(i).next(()=>e)):this.$s(i).next(()=>r(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}$s(e){return eh(e).get("owner").next(e=>{if(null!==e&&this.Ss(e.leaseTimestampMs,5e3)&&!this.xs(e.ownerId)&&!this.bs(e)&&!(this.Zn||this.allowTabSynchronization&&e.allowTabSynchronization))throw new Nr(xr.FAILED_PRECONDITION,Ju)})}Ps(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return eh(e).put("owner",t)}static vt(){return Do.vt()}Rs(e){const t=eh(e);return t.get("owner").next(e=>this.bs(e)?(Er("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):So.resolve())}Ss(e,t){var n=Date.now();return!(e<n-t||n<e&&(Tr(`Detected an update time that is in the future: ${e} > ${n}`),1))}ys(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.rs=()=>{this.Yn.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.gs()))},this.document.addEventListener("visibilitychange",this.rs),this.inForeground="visible"===this.document.visibilityState)}ks(){this.rs&&(this.document.removeEventListener("visibilitychange",this.rs),this.rs=null)}ps(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ss=()=>{this.Ns(),s()&&navigator.appVersion.match(/Version\/1[45]/)&&this.Yn.enterRestrictedMode(!0),this.Yn.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.ss))}Ms(){this.ss&&(this.window.removeEventListener("pagehide",this.ss),this.ss=null)}xs(e){var t;try{var n=null!==(null===(t=this.ws)||void 0===t?void 0:t.getItem(this.Cs(e)));return Er("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return Tr("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Ns(){if(this.ws)try{this.ws.setItem(this.Cs(this.clientId),String(Date.now()))}catch(e){Tr("Failed to set zombie client id.",e)}}Os(){if(this.ws)try{this.ws.removeItem(this.Cs(this.clientId))}catch(e){}}Cs(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function eh(e){return Oo(e,"owner")}function th(e){return Oo(e,"clientMetadata")}function nh(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class rh{constructor(e,t,n){this.ds=e,this.Bs=t,this.indexManager=n}Ls(t,n){return this.Bs.getAllMutationBatchesAffectingDocumentKey(t,n).next(e=>this.Us(t,n,e))}Us(e,t,n){return this.ds.getEntry(e,t).next(e=>{for(const t of n)t.applyToLocalView(e);return e})}qs(e,n){e.forEach((e,t)=>{for(const e of n)e.applyToLocalView(t)})}Ks(t,e){return this.ds.getEntries(t,e).next(e=>this.Gs(t,e).next(()=>e))}Gs(e,t){return this.Bs.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>this.qs(t,e))}Qs(e,t,n){return r=t,ds.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.js(e,t.path):gi(t)?this.Ws(e,t,n):this.zs(e,t,n);var r}js(e,t){return this.Ls(e,new ds(t)).next(e=>{let t=ca;return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}Ws(r,s,i){const a=s.collectionGroup;let o=ca;return this.indexManager.getCollectionParents(r,a).next(e=>So.forEach(e,e=>{var t,n=(t=s,e=e.child(a),new oi(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.zs(r,n,i).next(e=>{e.forEach((e,t)=>{o=o.insert(e,t)})})}).next(()=>o))}zs(t,n,e){let s;return this.ds.getAllFromCollection(t,n.path,e).next(e=>(s=e,this.Bs.getAllMutationBatchesAffectingQuery(t,n))).next(t=>{for(const r of t)for(const t of r.mutations){var n=t.key;let e=s.get(n);null==e&&(e=Ms.newInvalidDocument(n),s=s.insert(n,e)),ji(t,e,r.localWriteTime),e.isFoundDocument()||(s=s.remove(n))}}).next(()=>(s.forEach((e,t)=>{Ii(n,t)||(s=s.remove(e))}),s))}}class sh{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Hs=n,this.Js=r}static Ys(e,t){let n=ga(),r=ga();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 sh(e,t.fromCache,n,r)}}class ih{Xs(e){this.Zs=e}Qs(t,r,s,i){return 0===(e=r).filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())||s.isEqual($r.min())?this.ti(t,r):this.Zs.Ks(t,i).next(e=>{const n=this.ei(r,e);return(ci(r)||li(r))&&this.ni(r.limitType,n,i,s)?this.ti(t,r):(Ir()<=l.DEBUG&&Er("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),bi(r)),this.Zs.Qs(t,r,Ps(s,-1)).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t)))});var e}ei(n,e){let r=new aa(Ti(n));return e.forEach((e,t)=>{Ii(n,t)&&(r=r.add(t))}),r}ni(e,t,n,r){if(n.size!==t.size)return!0;const s="F"===e?t.last():t.first();return!!s&&(s.hasPendingWrites||0<s.version.compareTo(r))}ti(e,t){return Ir()<=l.DEBUG&&Er("QueryEngine","Using full collection scan to execute query:",bi(t)),this.Zs.Qs(e,t,Bs.min())}}class ah{constructor(e,t,n,r){this.persistence=e,this.si=t,this.M=r,this.ii=new ra(Ur),this.ri=new na(e=>Ks(e),js),this.oi=new Map,this.ui=e.getRemoteDocumentCache(),this.fs=e.getTargetCache(),this._s=e.getBundleCache(),this.ai(n)}ai(e){this.indexManager=this.persistence.getIndexManager(e),this.Bs=this.persistence.getMutationQueue(e,this.indexManager),this.ci=new rh(this.ui,this.Bs,this.indexManager),this.ui.setIndexManager(this.indexManager),this.si.Xs(this.ci)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.ii))}}function oh(e,t,n,r){return new ah(e,t,n,r)}async function uh(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",s=>{let i;return a.Bs.getAllMutationBatches(s).next(e=>(i=e,a.ai(t),a.Bs.getAllMutationBatches(s))).next(e=>{const t=[],n=[];let r=ga();for(const s of i){t.push(s.batchId);for(const e of s.mutations)r=r.add(e.key)}for(const s of e){n.push(s.batchId);for(const e of s.mutations)r=r.add(e.key)}return a.ci.Ks(s,r).next(e=>({hi:e,removedBatchIds:t,addedBatchIds:n}))})})}function hh(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.fs.getLastRemoteSnapshotVersion(e))}function ch(e,h){const c=e,l=h.snapshotVersion;let d=c.ii;return c.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=c.ui.newChangeBuffer({trackRemovals:!0});d=c.ii;const u=[];h.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){u.push(c.fs.removeMatchingKeys(o,t.removedDocuments,n).next(()=>c.fs.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var s,i,a;h.targetMismatches.has(n)?e=e.withResumeToken(es.EMPTY_BYTE_STRING,$r.min()).withLastLimboFreeSnapshotVersion($r.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,l)),d=d.insert(n,e),s=r,i=e,a=t,0!==s.resumeToken.approximateByteSize()&&!(3e8<=i.snapshotVersion.toMicroseconds()-s.snapshotVersion.toMicroseconds()||0<a.addedDocuments.size+a.modifiedDocuments.size+a.removedDocuments.size)||u.push(c.fs.updateTargetData(o,e))}});let t=ha;if(h.documentUpdates.forEach(e=>{h.resolvedLimboDocuments.has(e)&&u.push(c.persistence.referenceDelegate.updateLimboDocument(o,e))}),u.push(lh(o,e,h.documentUpdates).next(e=>{t=e})),!l.isEqual($r.min())){const h=c.fs.getLastRemoteSnapshotVersion(o).next(e=>c.fs.setTargetsMetadata(o,o.currentSequenceNumber,l));u.push(h)}return So.waitFor(u).next(()=>e.apply(o)).next(()=>c.ci.Gs(o,t)).next(()=>t)}).then(e=>(c.ii=d,e))}function lh(e,i,t){let n=ga();return t.forEach(e=>n=n.add(e)),i.getEntries(e,n).next(r=>{let s=ha;return t.forEach((e,t)=>{const n=r.get(e);t.isNoDocument()&&t.version.isEqual($r.min())?(i.removeEntry(e,t.readTime),s=s.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(i.addEntry(t),s=s.insert(e,t)):Er("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),s})}function dh(e,r){const s=e;return s.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return s.fs.getTargetData(t,r).next(e=>e?(n=e,So.resolve(n)):s.fs.allocateTargetId(t).next(e=>(n=new qo(r,e,0,t.currentSequenceNumber),s.fs.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=s.ii.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(s.ii=s.ii.insert(e.targetId,e),s.ri.set(r,e.targetId)),e})}async function fh(e,t,n){const r=e,s=r.ii.get(t),i=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",i,e=>r.persistence.referenceDelegate.removeTarget(e,s))}catch(e){if(!Co(e))throw e;Er("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.ii=r.ii.remove(t),r.ri.delete(s.target)}function gh(e,n,r){const s=e;let i=$r.min(),a=ga();return s.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,s=r.ri.get(n);return void 0!==s?So.resolve(r.ii.get(s)):r.fs.getTargetData(t,n)}(s,t,pi(n)).next(e=>{if(e)return i=e.lastLimboFreeSnapshotVersion,s.fs.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>s.si.Qs(t,n,r?i:$r.min(),r?a:ga())).next(e=>(yh(s,Ei(n),e),{documents:e,li:a})))}function mh(e,t){const n=e,r=n.fs,s=n.ii.get(t);return s?Promise.resolve(s.target):n.persistence.runTransaction("Get target data","readonly",e=>r.Et(e,t).next(e=>e?e.target:null))}function ph(e,t){const n=e,r=n.oi.get(t)||$r.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.ui.getAllFromCollectionGroup(e,t,Ps(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(yh(n,t,e),e))}function yh(e,t,n){let r=$r.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.oi.set(t,r)}class vh{constructor(e){this.M=e,this.wi=new Map,this.mi=new Map}getBundleMetadata(e,t){return So.resolve(this.wi.get(t))}saveBundleMetadata(e,t){return this.wi.set(t.id,{id:t.id,version:t.version,createTime:Ca(t.createTime)}),So.resolve()}getNamedQuery(e,t){return So.resolve(this.mi.get(t))}saveNamedQuery(e,t){return this.mi.set(t.name,{name:(t=t).name,query:Qo(t.bundledQuery),readTime:Ca(t.readTime)}),So.resolve()}}class wh{constructor(){this.overlays=new ra(ds.comparator),this.gi=new Map}getOverlay(e,t){return So.resolve(this.overlays.get(t))}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.Xt(n,r,t)}),So.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.gi.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.gi.delete(n)),So.resolve()}getOverlaysForCollection(e,t,n){const r=la(),s=t.length+1,i=new ds(t.child("")),a=this.overlays.getIteratorFrom(i);for(;a.hasNext();){const e=a.getNext().value,i=e.getKey();if(!t.isPrefixOf(i.path))break;i.path.length===s&&e.largestBatchId>n&&r.set(e.getKey(),e)}return So.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let s=new ra((e,t)=>e-t);const i=this.overlays.getIterator();for(;i.hasNext();){const t=i.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=s.get(t.largestBatchId);null===e&&(e=la(),s=s.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=la(),o=s.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return So.resolve(a)}Xt(t,n,r){if(null!==r){var s=this.overlays.get(r.key);if(null!==s){const t=this.gi.get(s.largestBatchId).delete(r.key);this.gi.set(s.largestBatchId,t)}this.overlays=this.overlays.insert(r.key,new Bo(n,r));let e=this.gi.get(n);void 0===e&&(e=ga(),this.gi.set(n,e)),this.gi.set(n,e.add(r.key))}}}class bh{constructor(){this.yi=new aa(Ih.pi),this.Ii=new aa(Ih.Ti)}isEmpty(){return this.yi.isEmpty()}addReference(e,t){var n=new Ih(e,t);this.yi=this.yi.add(n),this.Ii=this.Ii.add(n)}Ei(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Ai(new Ih(e,t))}Ri(e,t){e.forEach(e=>this.removeReference(e,t))}Pi(e){const t=new ds(new Yr([])),n=new Ih(t,e),r=new Ih(t,e+1),s=[];return this.Ii.forEachInRange([n,r],e=>{this.Ai(e),s.push(e.key)}),s}bi(){this.yi.forEach(e=>this.Ai(e))}Ai(e){this.yi=this.yi.delete(e),this.Ii=this.Ii.delete(e)}Vi(e){var t=new ds(new Yr([])),n=new Ih(t,e),t=new Ih(t,e+1);let r=ga();return this.Ii.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new Ih(e,0),t=this.yi.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class Ih{constructor(e,t){this.key=e,this.vi=t}static pi(e,t){return ds.comparator(e.key,t.key)||Ur(e.vi,t.vi)}static Ti(e,t){return Ur(e.vi,t.vi)||ds.comparator(e.key,t.key)}}class Eh{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.Bs=[],this.Si=1,this.Di=new aa(Ih.pi)}checkEmpty(e){return So.resolve(0===this.Bs.length)}addMutationBatch(e,t,n,r){var s=this.Si;this.Si++,0<this.Bs.length&&this.Bs[this.Bs.length-1];var i=new Fo(s,t,n,r);this.Bs.push(i);for(const t of r)this.Di=this.Di.add(new Ih(t.key,s)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return So.resolve(i)}lookupMutationBatch(e,t){return So.resolve(this.Ci(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.xi(t+1),n=n<0?0:n;return So.resolve(this.Bs.length>n?this.Bs[n]:null)}getHighestUnacknowledgedBatchId(){return So.resolve(0===this.Bs.length?-1:this.Si-1)}getAllMutationBatches(e){return So.resolve(this.Bs.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Ih(t,0),r=new Ih(t,Number.POSITIVE_INFINITY),s=[];return this.Di.forEachInRange([n,r],e=>{var t=this.Ci(e.vi);s.push(t)}),So.resolve(s)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new aa(Ur);return t.forEach(e=>{var t=new Ih(e,0),n=new Ih(e,Number.POSITIVE_INFINITY);this.Di.forEachInRange([t,n],e=>{r=r.add(e.vi)})}),So.resolve(this.Ni(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let s=n;ds.isDocumentKey(s)||(s=s.child(""));var i=new Ih(new ds(s),0);let a=new aa(Ur);return this.Di.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.vi)),!0)},i),So.resolve(this.Ni(a))}Ni(e){const n=[];return e.forEach(e=>{var t=this.Ci(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){Dr(0===this.ki(r.batchId,"removed")),this.Bs.shift();let s=this.Di;return So.forEach(r.mutations,e=>{var t=new Ih(e.key,r.batchId);return s=s.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.Di=s})}_n(e){}containsKey(e,t){var n=new Ih(t,0),n=this.Di.firstAfterOrEqual(n);return So.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.Bs.length,So.resolve()}ki(e,t){return this.xi(e)}xi(e){return 0===this.Bs.length?0:e-this.Bs[0].batchId}Ci(e){var t=this.xi(e);return t<0||t>=this.Bs.length?null:this.Bs[t]}}class Th{constructor(e){this.Mi=e,this.docs=new ra(ds.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),s=r?r.size:0,i=this.Mi(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:i}),this.size+=i-s,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return So.resolve(n?n.document.mutableCopy():Ms.newInvalidDocument(t))}getEntries(e,t){let n=ha;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Ms.newInvalidDocument(e))}),So.resolve(n)}getAllFromCollection(e,t,n){let r=ha;const s=new ds(t.child("")),i=this.docs.getIteratorFrom(s);for(;i.hasNext();){const{key:e,value:{document:s}}=i.getNext();if(!t.isPrefixOf(e.path))break;e.path.length>t.length+1||function(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=ds.comparator(e.documentKey,t.documentKey),0!==n?n:Ur(e.largestBatchId,t.largestBatchId))}((a=s,new Bs(a.readTime,a.key,-1)),n)<=0||(r=r.insert(s.key,s.mutableCopy()))}var a;return So.resolve(r)}getAllFromCollectionGroup(e,t,n,r){Ar()}Oi(e,t){return So.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new _h(this)}getSize(e){return So.resolve(this.size)}}class _h extends Ku{constructor(e){super(),this.Kn=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.Kn.addEntry(n,t)):this.Kn.removeEntry(e)}),So.waitFor(r)}getFromCache(e,t){return this.Kn.getEntry(e,t)}getAllFromCache(e,t){return this.Kn.getEntries(e,t)}}class Sh{constructor(e){this.persistence=e,this.Fi=new na(e=>Ks(e),js),this.lastRemoteSnapshotVersion=$r.min(),this.highestTargetId=0,this.$i=0,this.Bi=new bh,this.targetCount=0,this.Li=Cu.gn()}forEachTarget(e,n){return this.Fi.forEach((e,t)=>n(t)),So.resolve()}getLastRemoteSnapshotVersion(e){return So.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return So.resolve(this.$i)}allocateTargetId(e){return this.highestTargetId=this.Li.next(),So.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.$i&&(this.$i=t),So.resolve()}Tn(e){this.Fi.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Li=new Cu(t),this.highestTargetId=t),e.sequenceNumber>this.$i&&(this.$i=e.sequenceNumber)}addTargetData(e,t){return this.Tn(t),this.targetCount+=1,So.resolve()}updateTargetData(e,t){return this.Tn(t),So.resolve()}removeTargetData(e,t){return this.Fi.delete(t.target),this.Bi.Pi(t.targetId),--this.targetCount,So.resolve()}removeTargets(n,r,s){let i=0;const a=[];return this.Fi.forEach((e,t)=>{t.sequenceNumber<=r&&null===s.get(t.targetId)&&(this.Fi.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),i++)}),So.waitFor(a).next(()=>i)}getTargetCount(e){return So.resolve(this.targetCount)}getTargetData(e,t){var n=this.Fi.get(t)||null;return So.resolve(n)}addMatchingKeys(e,t,n){return this.Bi.Ei(t,n),So.resolve()}removeMatchingKeys(t,e,n){this.Bi.Ri(e,n);const r=this.persistence.referenceDelegate,s=[];return r&&e.forEach(e=>{s.push(r.markPotentiallyOrphaned(t,e))}),So.waitFor(s)}removeMatchingKeysForTargetId(e,t){return this.Bi.Pi(t),So.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Bi.Vi(t);return So.resolve(n)}containsKey(e,t){return So.resolve(this.Bi.containsKey(t))}}class Ah{constructor(e,t){this.Ui={},this.overlays={},this.es=new Br(0),this.ns=!1,this.ns=!0,this.referenceDelegate=e(this),this.fs=new Sh(this),this.indexManager=new fu,this.ds=(e=e=>this.referenceDelegate.qi(e),new Th(e)),this.M=new Uo(t),this._s=new vh(this.M)}start(){return Promise.resolve()}shutdown(){return this.ns=!1,Promise.resolve()}get started(){return this.ns}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new wh,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Ui[e.toKey()];return n||(n=new Eh(t,this.referenceDelegate),this.Ui[e.toKey()]=n),n}getTargetCache(){return this.fs}getRemoteDocumentCache(){return this.ds}getBundleCache(){return this._s}runTransaction(e,t,n){Er("MemoryPersistence","Starting transaction:",e);const r=new Dh(this.es.next());return this.referenceDelegate.Ki(),n(r).next(e=>this.referenceDelegate.Gi(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Qi(t,n){return So.or(Object.values(this.Ui).map(e=>()=>e.containsKey(t,n)))}}class Dh extends _o{constructor(e){super(),this.currentSequenceNumber=e}}class xh{constructor(e){this.persistence=e,this.ji=new bh,this.Wi=null}static zi(e){return new xh(e)}get Hi(){if(this.Wi)return this.Wi;throw Ar()}addReference(e,t,n){return this.ji.addReference(n,t),this.Hi.delete(n.toString()),So.resolve()}removeReference(e,t,n){return this.ji.removeReference(n,t),this.Hi.add(n.toString()),So.resolve()}markPotentiallyOrphaned(e,t){return this.Hi.add(t.toString()),So.resolve()}removeTarget(e,t){this.ji.Pi(t.targetId).forEach(e=>this.Hi.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Hi.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Ki(){this.Wi=new Set}Gi(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return So.forEach(this.Hi,e=>{const t=ds.fromPath(e);return this.Ji(n,t).next(e=>{e||r.removeEntry(t,$r.min())})}).next(()=>(this.Wi=null,r.apply(n)))}updateLimboDocument(e,t){return this.Ji(e,t).next(e=>{e?this.Hi.delete(t.toString()):this.Hi.add(t.toString())})}qi(e){return 0}Ji(e,t){return So.or([()=>So.resolve(this.ji.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Qi(e,t)])}}function Nh(e,t){return`firestore_clients_${e}_${t}`}function Ch(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function kh(e,t){return`firestore_targets_${e}_${t}`}class Mh{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Yi(e,t,n){var r=JSON.parse(n);let s,i="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return i&&r.error&&(i="string"==typeof r.error.message&&"string"==typeof r.error.code,i&&(s=new Nr(r.error.code,r.error.message))),i?new Mh(e,t,r.state,s):(Tr("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}Xi(){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 Rh{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Yi(e,t){var n=JSON.parse(t);let r,s="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return s&&n.error&&(s="string"==typeof n.error.message&&"string"==typeof n.error.code,s&&(r=new Nr(n.error.code,n.error.message))),s?new Rh(e,n.state,r):(Tr("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}Xi(){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 Lh{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Yi(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,s=ma;for(let i=0;r&&i<n.activeTargetIds.length;++i)r=ls(n.activeTargetIds[i]),s=s.add(n.activeTargetIds[i]);return r?new Lh(e,s):(Tr("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class Vh{constructor(e,t){this.clientId=e,this.onlineState=t}static Yi(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new Vh(t.clientId,t.onlineState):(Tr("SharedClientState",`Failed to parse online state: ${e}`),null)}}class Oh{constructor(){this.activeTargetIds=ma}Zi(e){this.activeTargetIds=this.activeTargetIds.add(e)}tr(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Xi(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class Fh{constructor(e,t,n,r,s){this.window=e,this.Yn=t,this.persistenceKey=n,this.er=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.nr=this.sr.bind(this),this.ir=new ra(Ur),this.started=!1,this.rr=[];var i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=s,this.ur=Nh(this.persistenceKey,this.er),this.ar=`firestore_sequence_number_${this.persistenceKey}`,this.ir=this.ir.insert(this.er,new Oh),this.cr=new RegExp(`^firestore_clients_${i}_([^_]*)$`),this.hr=new RegExp(`^firestore_mutations_${i}_(\\d+)(?:_(.*))?$`),this.lr=new RegExp(`^firestore_targets_${i}_(\\d+)$`),this.dr=`firestore_online_state_${this.persistenceKey}`,this._r=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.nr)}static vt(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.Fs();for(const n of e)if(n!==this.er){const e=this.getItem(Nh(this.persistenceKey,n));var t;!e||(t=Lh.Yi(n,e))&&(this.ir=this.ir.insert(t.clientId,t))}this.wr();const n=this.storage.getItem(this.dr);if(n){const e=this.mr(n);e&&this.gr(e)}for(const e of this.rr)this.sr(e);this.rr=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.ar,JSON.stringify(e))}getAllActiveQueryTargets(){return this.yr(this.ir)}isActiveQueryTarget(n){let r=!1;return this.ir.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.pr(e,"pending")}updateMutationState(e,t,n){this.pr(e,t,n),this.Ir(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(kh(this.persistenceKey,e)))||(n=Rh.Yi(e,n))&&(t=n.state)),this.Tr.Zi(e),this.wr(),t}removeLocalQueryTarget(e){this.Tr.tr(e),this.wr()}isLocalQueryTarget(e){return this.Tr.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(kh(this.persistenceKey,e))}updateQueryState(e,t,n){this.Er(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Ir(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Ar(e)}notifyBundleLoaded(e){this.Rr(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.nr),this.removeItem(this.ur),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return Er("SharedClientState","READ",e,t),t}setItem(e,t){Er("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){Er("SharedClientState","REMOVE",e),this.storage.removeItem(e)}sr(e){const s=e;s.storageArea===this.storage&&(Er("SharedClientState","EVENT",s.key,s.newValue),s.key!==this.ur?this.Yn.enqueueRetryable(async()=>{if(this.started){if(null!==s.key)if(this.cr.test(s.key)){if(null==s.newValue){var e=this.Pr(s.key);return this.br(e,null)}e=this.Vr(s.key,s.newValue);if(e)return this.br(e.clientId,e)}else if(this.hr.test(s.key)){if(null!==s.newValue){var t=this.vr(s.key,s.newValue);if(t)return this.Sr(t)}}else if(this.lr.test(s.key)){if(null!==s.newValue){t=this.Dr(s.key,s.newValue);if(t)return this.Cr(t)}}else if(s.key===this.dr){if(null!==s.newValue){var n=this.mr(s.newValue);if(n)return this.gr(n)}}else if(s.key===this.ar){n=function(e){let t=Br.A;if(null!=e)try{var n=JSON.parse(e);Dr("number"==typeof n),t=n}catch(e){Tr("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(s.newValue);n!==Br.A&&this.sequenceNumberHandler(n)}else if(s.key===this._r){const r=this.Nr(s.newValue);await Promise.all(r.map(e=>this.syncEngine.kr(e)))}}else this.rr.push(s)}):Tr("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get Tr(){return this.ir.get(this.er)}wr(){this.setItem(this.ur,this.Tr.Xi())}pr(e,t,n){const r=new Mh(this.currentUser,e,t,n),s=Ch(this.persistenceKey,this.currentUser,e);this.setItem(s,r.Xi())}Ir(e){var t=Ch(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Ar(e){var t={clientId:this.er,onlineState:e};this.storage.setItem(this.dr,JSON.stringify(t))}Er(e,t,n){const r=kh(this.persistenceKey,e),s=new Rh(e,t,n);this.setItem(r,s.Xi())}Rr(e){var t=JSON.stringify(Array.from(e));this.setItem(this._r,t)}Pr(e){var t=this.cr.exec(e);return t?t[1]:null}Vr(e,t){var n=this.Pr(e);return Lh.Yi(n,t)}vr(e,t){var n=this.hr.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return Mh.Yi(new vr(n),r,t)}Dr(e,t){var n=this.lr.exec(e),n=Number(n[1]);return Rh.Yi(n,t)}mr(e){return Vh.Yi(e)}Nr(e){return JSON.parse(e)}async Sr(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Mr(e.batchId,e.state,e.error);Er("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Cr(e){return this.syncEngine.Or(e.targetId,e.state,e.error)}br(e,t){const n=t?this.ir.insert(e,t):this.ir.remove(e),r=this.yr(this.ir),s=this.yr(n),i=[],a=[];return s.forEach(e=>{r.has(e)||i.push(e)}),r.forEach(e=>{s.has(e)||a.push(e)}),this.syncEngine.Fr(i,a).then(()=>{this.ir=n})}gr(e){this.ir.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}yr(e){let n=ma;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class Ph{constructor(){this.$r=new Oh,this.Br={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.$r.Zi(e),this.Br[e]||"not-current"}updateQueryState(e,t,n){this.Br[e]=t}removeLocalQueryTarget(e){this.$r.tr(e)}isLocalQueryTarget(e){return this.$r.activeTargetIds.has(e)}clearQueryState(e){delete this.Br[e]}getAllActiveQueryTargets(){return this.$r.activeTargetIds}isActiveQueryTarget(e){return this.$r.activeTargetIds.has(e)}start(){return this.$r=new Oh,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class Bh{Lr(e){}shutdown(){}}class qh{constructor(){this.Ur=()=>this.qr(),this.Kr=()=>this.Gr(),this.Qr=[],this.jr()}Lr(e){this.Qr.push(e)}shutdown(){window.removeEventListener("online",this.Ur),window.removeEventListener("offline",this.Kr)}jr(){window.addEventListener("online",this.Ur),window.addEventListener("offline",this.Kr)}qr(){Er("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.Qr)e(0)}Gr(){Er("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.Qr)e(1)}static vt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const Uh={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class Kh{constructor(e){this.Wr=e.Wr,this.zr=e.zr}Hr(e){this.Jr=e}Yr(e){this.Xr=e}onMessage(e){this.Zr=e}close(){this.zr()}send(e){this.Wr(e)}eo(){this.Jr()}no(e){this.Xr(e)}so(e){this.Zr(e)}}class jh extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.io=t+"://"+e.host,this.ro="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}oo(t,e,n,r,s){const i=this.uo(t,e);Er("RestConnection","Sending: ",i,n);var a={};return this.ao(a,r,s),this.co(t,i,a,n).then(e=>(Er("RestConnection","Received: ",e),e),e=>{throw _r("RestConnection",`${t} failed with error: `,e,"url: ",i,"request:",n),e})}ho(e,t,n,r,s){return this.oo(e,t,n,r,s)}ao(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+wr,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)}uo(e,t){var n=Uh[e];return`${this.io}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}co(o,t,n,r){return new Promise((s,i)=>{const a=new pr;a.listenOnce(cr.COMPLETE,()=>{try{switch(a.getLastErrorCode()){case hr.NO_ERROR:var e=a.getResponseJson();Er("Connection","XHR received:",JSON.stringify(e)),s(e);break;case hr.TIMEOUT:Er("Connection",'RPC "'+o+'" timed out'),i(new Nr(xr.DEADLINE_EXCEEDED,"Request time out"));break;case hr.HTTP_ERROR:var t,n=a.getStatus();if(Er("Connection",'RPC "'+o+'" failed with status:',n,"response text:",a.getResponseText()),0<n){const o=a.getResponseJson().error;o&&o.status&&o.message?(r=o.status.toLowerCase().replace(/_/g,"-"),t=0<=Object.values(xr).indexOf(r)?r:xr.UNKNOWN,i(new Nr(t,o.message))):i(new Nr(xr.UNKNOWN,"Server responded with status "+a.getStatus()))}else i(new Nr(xr.UNAVAILABLE,"Connection failed."));break;default:Ar()}}finally{Er("Connection",'RPC "'+o+'" completed.')}var r});var e=JSON.stringify(r);a.send(t,"POST",e,n,15)})}lo(e,t,n){const r=[this.io,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=new nr,i=ur(),a={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(a.xmlHttpFactory=new gr({})),this.ao(a.initMessageHeaders,t,n),"undefined"!=typeof window&&(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(f())||"object"==typeof navigator&&"ReactNative"===navigator.product||0<=f().indexOf("Electron/")||function(){const e=f();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}()||0<=f().indexOf("MSAppHost/")||"object"==typeof(o="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0)&&void 0!==o.id||(a.httpHeadersOverwriteParam="$httpHeaders");var o=r.join("");Er("Connection","Creating WebChannel: "+o,a);const u=s.createWebChannel(o,a);let h=!1,c=!1;const l=new Kh({Wr:e=>{c?Er("Connection","Not sending because WebChannel is closed:",e):(h||(Er("Connection","Opening WebChannel transport."),u.open(),h=!0),Er("Connection","WebChannel sending:",e),u.send(e))},zr:()=>u.close()}),d=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return d(u,mr.EventType.OPEN,()=>{c||Er("Connection","WebChannel transport opened.")}),d(u,mr.EventType.CLOSE,()=>{c||(c=!0,Er("Connection","WebChannel transport closed"),l.no())}),d(u,mr.EventType.ERROR,e=>{c||(c=!0,_r("Connection","WebChannel transport errored:",e),l.no(new Nr(xr.UNAVAILABLE,"The operation could not be completed")))}),d(u,mr.EventType.MESSAGE,n=>{if(!c){var e=n.data[0];Dr(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){Er("Connection","WebChannel received error:",r);const n=r.status;let e=function(e){var t=or[e];if(void 0!==t)return ta(t)}(n),t=r.message;void 0===e&&(e=xr.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),c=!0,l.no(new Nr(e,t)),u.close()}else Er("Connection","WebChannel received:",e),l.so(e)}}),d(i,lr.STAT_EVENT,e=>{e.stat===dr?Er("Connection","Detected buffering proxy"):e.stat===fr&&Er("Connection","Detected no buffering proxy")}),setTimeout(()=>{l.eo()},0),l}}function Gh(){return"undefined"!=typeof window?window:null}function $h(){return"undefined"!=typeof document?document:null}function zh(e){return new Da(e,!0)}class Wh{constructor(e,t,n=1e3,r=1.5,s=6e4){this.Yn=e,this.timerId=t,this.fo=n,this._o=r,this.wo=s,this.mo=0,this.yo=null,this.po=Date.now(),this.reset()}reset(){this.mo=0}Io(){this.mo=this.wo}To(e){this.cancel();var t=Math.floor(this.mo+this.Eo()),n=Math.max(0,Date.now()-this.po),r=Math.max(0,t-n);0<r&&Er("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.mo} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.yo=this.Yn.enqueueAfterDelay(this.timerId,r,()=>(this.po=Date.now(),e())),this.mo*=this._o,this.mo<this.fo&&(this.mo=this.fo),this.mo>this.wo&&(this.mo=this.wo)}Ao(){null!==this.yo&&(this.yo.skipDelay(),this.yo=null)}cancel(){null!==this.yo&&(this.yo.cancel(),this.yo=null)}Eo(){return(Math.random()-.5)*this.mo}}class Hh{constructor(e,t,n,r,s,i,a,o){this.Yn=e,this.Ro=n,this.Po=r,this.bo=s,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Vo=0,this.vo=null,this.So=null,this.stream=null,this.Do=new Wh(e,t)}Co(){return 1===this.state||5===this.state||this.xo()}xo(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.No()}async stop(){this.Co()&&await this.close(0)}ko(){this.state=0,this.Do.reset()}Mo(){this.xo()&&null===this.vo&&(this.vo=this.Yn.enqueueAfterDelay(this.Ro,6e4,()=>this.Oo()))}Fo(e){this.$o(),this.stream.send(e)}async Oo(){if(this.xo())return this.close(0)}$o(){this.vo&&(this.vo.cancel(),this.vo=null)}Bo(){this.So&&(this.So.cancel(),this.So=null)}async close(e,t){this.$o(),this.Bo(),this.Do.cancel(),this.Vo++,4!==e?this.Do.reset():t&&t.code===xr.RESOURCE_EXHAUSTED?(Tr(t.toString()),Tr("Using maximum backoff delay to prevent overloading the backend."),this.Do.Io()):t&&t.code===xr.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Lo(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Yr(t)}Lo(){}auth(){this.state=1;const e=this.Uo(this.Vo),n=this.Vo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.Vo===n&&this.qo(e,t)},t=>{e(()=>{var e=new Nr(xr.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Ko(e)})})}qo(e,t){const n=this.Uo(this.Vo);this.stream=this.Go(e,t),this.stream.Hr(()=>{n(()=>(this.state=2,this.So=this.Yn.enqueueAfterDelay(this.Po,1e4,()=>(this.xo()&&(this.state=3),Promise.resolve())),this.listener.Hr()))}),this.stream.Yr(e=>{n(()=>this.Ko(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}No(){this.state=5,this.Do.To(async()=>{this.state=0,this.start()})}Ko(e){return Er("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Uo(t){return e=>{this.Yn.enqueueAndForget(()=>this.Vo===t?e():(Er("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class Qh extends Hh{constructor(e,t,n,r,s,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,i),this.M=s}Go(e,t){return this.bo.lo("Listen",e,t)}onMessage(e){this.Do.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:Ar(),s=t.targetChange.targetIds||[],i=(f=t.targetChange.resumeToken,e.N?(Dr(void 0===f||"string"==typeof f),es.fromBase64String(f||"")):(Dr(void 0===f||f instanceof Uint8Array),es.fromUint8Array(f||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(f=a).code?xr.UNKNOWN:ta(f.code),new Nr(o,f.message||""));n=new ba(r,s,i,o||null)}else if("documentChange"in t){t.documentChange;var u=t.documentChange;u.document,u.document.name,u.document.updateTime;var o=La(e,u.document.name),h=Ca(u.document.updateTime),c=new ks({mapValue:{fields:u.document.fields}}),h=Ms.newFoundDocument(o,h,c),c=u.targetIds||[],u=u.removedTargetIds||[];n=new va(c,u,h.key,h)}else if("documentDelete"in t){t.documentDelete;c=t.documentDelete;c.document;u=La(e,c.document),h=c.readTime?Ca(c.readTime):$r.min(),h=Ms.newNoDocument(u,h),c=c.removedTargetIds||[];n=new va([],c,h.key,h)}else if("documentRemove"in t){t.documentRemove;var l=t.documentRemove;l.document;var d=La(e,l.document),l=l.removedTargetIds||[];n=new va([],l,d,null)}else{if(!("filter"in t))return Ar();{t.filter;const e=t.filter;e.targetId;l=e.count||0,d=new Zi(l),l=e.targetId;n=new wa(l,d)}}var o,f;return n}(this.M,e),n=function(e){if(!("targetChange"in e))return $r.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?Ca(t.readTime):$r.min()}(e);return this.listener.Qo(t,n)}jo(e){const t={};t.database=Fa(this.M),t.addTarget=function(e,t){let n;var r=t.target;return n=Gs(r)?{documents:ja(e,r)}:{query:Ga(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()?n.resumeToken=Na(e,t.resumeToken):0<t.snapshotVersion.compareTo($r.min())&&(n.readTime=xa(e,t.snapshotVersion.toTimestamp())),n}(this.M,e);var n,r,r=(this.M,n=e,null==(r=function(){switch(n.purpose){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return Ar()}}())?null:{"goog-listen-tags":r});r&&(t.labels=r),this.Fo(t)}Wo(e){const t={};t.database=Fa(this.M),t.removeTarget=e,this.Fo(t)}}class Yh extends Hh{constructor(e,t,n,r,s,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,i),this.M=s,this.zo=!1}get Ho(){return this.zo}start(){this.zo=!1,this.lastStreamToken=void 0,super.start()}Lo(){this.zo&&this.Jo([])}Go(e,t){return this.bo.lo("Write",e,t)}onMessage(e){if(Dr(!!e.streamToken),this.lastStreamToken=e.streamToken,this.zo){this.Do.reset();var t=(r=e.writeResults,s=e.commitTime,r&&0<r.length?(Dr(void 0!==s),r.map(e=>function(e,t){let n=e.updateTime?Ca(e.updateTime):Ca(t);return n.isEqual($r.min())&&(n=Ca(t)),new Pi(n,e.transformResults||[])}(e,s))):[]),n=Ca(e.commitTime);return this.listener.Yo(n,t)}var r,s;return Dr(!e.writeResults||0===e.writeResults.length),this.zo=!0,this.listener.Xo()}Zo(){const e={};e.database=Fa(this.M),this.Fo(e)}Jo(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>Ua(this.M,e))};this.Fo(t)}}class Xh extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.bo=n,this.M=r,this.tu=!1}eu(){if(this.tu)throw new Nr(xr.FAILED_PRECONDITION,"The client has already been terminated.")}oo(n,r,s){return this.eu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.bo.oo(n,r,s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===xr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new Nr(xr.UNKNOWN,e.toString())})}ho(n,r,s){return this.eu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.bo.ho(n,r,s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===xr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new Nr(xr.UNKNOWN,e.toString())})}terminate(){this.tu=!0}}class Jh{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.nu=0,this.su=null,this.iu=!0}ru(){0===this.nu&&(this.ou("Unknown"),this.su=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.su=null,this.uu("Backend didn't respond within 10 seconds."),this.ou("Offline"),Promise.resolve())))}au(e){"Online"===this.state?this.ou("Unknown"):(this.nu++,1<=this.nu&&(this.cu(),this.uu(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.ou("Offline")))}set(e){this.cu(),this.nu=0,"Online"===e&&(this.iu=!1),this.ou(e)}ou(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}uu(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.iu?(Tr(t),this.iu=!1):Er("OnlineStateTracker",t)}cu(){null!==this.su&&(this.su.cancel(),this.su=null)}}class Zh{constructor(e,t,n,r,s){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.hu=[],this.lu=new Map,this.fu=new Set,this.du=[],this._u=s,this._u.Lr(e=>{n.enqueueAndForget(async()=>{uc(this)&&(Er("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.fu.add(4),await tc(t),t.wu.set("Unknown"),t.fu.delete(4),await ec(t)}(this))})}),this.wu=new Jh(n,r)}}async function ec(e){if(uc(e))for(const t of e.du)await t(!0)}async function tc(e){for(const t of e.du)await t(!1)}function nc(e,t){const n=e;n.lu.has(t.targetId)||(n.lu.set(t.targetId,t),oc(n)?ac(n):yc(n).xo()&&sc(n,t))}function rc(e,t){const n=e,r=yc(n);n.lu.delete(t),r.xo()&&ic(n,t),0===n.lu.size&&(r.xo()?r.Mo():uc(n)&&n.wu.set("Unknown"))}function sc(e,t){e.mu.Z(t.targetId),yc(e).jo(t)}function ic(e,t){e.mu.Z(t),yc(e).Wo(t)}function ac(t){t.mu=new Ea({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),Et:e=>t.lu.get(e)||null}),yc(t).start(),t.wu.ru()}function oc(e){return uc(e)&&!yc(e).Co()&&0<e.lu.size}function uc(e){return 0===e.fu.size}function hc(e){e.mu=void 0}async function cc(e,t,n){if(!Co(t))throw t;e.fu.add(1),await tc(e),e.wu.set("Offline"),n=n||(()=>hh(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{Er("RemoteStore","Retrying IndexedDB access"),await n(),e.fu.delete(1),await ec(e)})}function lc(t,n){return n().catch(e=>cc(t,e,n))}async function dc(e){const t=e,n=vc(t);let r=0<t.hu.length?t.hu[t.hu.length-1].batchId:-1;for(;uc(s=t)&&s.hu.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.Bs.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.hu.length&&n.Mo();break}r=e.batchId,function(e,t){e.hu.push(t);const n=vc(e);n.xo()&&n.Ho&&n.Jo(t.mutations)}(t,e)}catch(e){await cc(t,e)}var s;fc(t)&&gc(t)}function fc(e){return uc(e)&&!vc(e).Co()&&0<e.hu.length}function gc(e){vc(e).start()}async function mc(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),Er("RemoteStore","RemoteStore received new credentials");var r=uc(n);n.fu.add(3),await tc(n),r&&n.wu.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.fu.delete(3),await ec(n)}async function pc(e,t){const n=e;t?(n.fu.delete(2),await ec(n)):(n.fu.add(2),await tc(n),n.wu.set("Unknown"))}function yc(t){return t.gu||(t.gu=function(e,t,n){const r=e;return r.eu(),new Qh(t,r.bo,r.authCredentials,r.appCheckCredentials,r.M,n)}(t.datastore,t.asyncQueue,{Hr:(async function(n){n.lu.forEach((e,t)=>{sc(n,e)})}).bind(null,t),Yr:(async function(e,t){hc(e),oc(e)?(e.wu.au(t),ac(e)):e.wu.set("Unknown")}).bind(null,t),Qo:(async function(e,r,t){if(e.wu.set("Online"),r instanceof ba&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e.lu.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e.lu.delete(n),e.mu.removeTarget(n))}(e)}catch(t){Er("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await cc(e,t)}else if(r instanceof va?e.mu.ut(r):r instanceof wa?e.mu._t(r):e.mu.ht(r),!t.isEqual($r.min()))try{const r=await hh(e.localStore);0<=t.compareTo(r)&&await function(r,s){const e=r.mu.yt(s);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=r.lu.get(t);n&&r.lu.set(t,n.withResumeToken(e.resumeToken,s))}}),e.targetMismatches.forEach(e=>{const t=r.lu.get(e);var n;t&&(r.lu.set(e,t.withResumeToken(es.EMPTY_BYTE_STRING,t.snapshotVersion)),ic(r,e),n=new qo(t.target,e,1,t.sequenceNumber),sc(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){Er("RemoteStore","Failed to raise snapshot:",r),await cc(e,r)}}).bind(null,t)}),t.du.push(async e=>{e?(t.gu.ko(),oc(t)?ac(t):t.wu.set("Unknown")):(await t.gu.stop(),hc(t))})),t.gu}function vc(t){return t.yu||(t.yu=function(e,t,n){const r=e;return r.eu(),new Yh(t,r.bo,r.authCredentials,r.appCheckCredentials,r.M,n)}(t.datastore,t.asyncQueue,{Hr:(async function(e){vc(e).Zo()}).bind(null,t),Yr:(async function(e,t){t&&vc(e).Ho&&await async function(e,t){if(ea(n=t.code)&&n!==xr.ABORTED){const n=e.hu.shift();vc(e).ko(),await lc(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await dc(e)}var n}(e,t),fc(e)&&gc(e)}).bind(null,t),Xo:(async function(e){const t=vc(e);for(const n of e.hu)t.Jo(n.mutations)}).bind(null,t),Yo:(async function(e,t,n){const r=e.hu.shift(),s=Po.from(r,t,n);await lc(e,()=>e.remoteSyncer.applySuccessfulWrite(s)),await dc(e)}).bind(null,t)}),t.du.push(async e=>{e?(t.yu.ko(),await dc(t)):(await t.yu.stop(),0<t.hu.length&&(Er("RemoteStore",`Stopping write stream with ${t.hu.length} pending writes`),t.hu=[]))})),t.yu}class wc{constructor(e,t,n,r,s){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=s,this.deferred=new Cr,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}static createAndSchedule(e,t,n,r,s){const i=Date.now()+n,a=new wc(e,t,i,r,s);return a.start(n),a}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new Nr(xr.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 bc(e,t){if(Tr("AsyncQueue",`${t}: ${e}`),Co(e))return new Nr(xr.UNAVAILABLE,`${t}: ${e}`);throw e}class Ic{constructor(n){this.comparator=n?(e,t)=>n(e,t)||ds.comparator(e.key,t.key):(e,t)=>ds.comparator(e.key,t.key),this.keyedMap=ca,this.sortedSet=new ra(this.comparator)}static emptySet(e){return new Ic(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 Ic))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 Ic;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class Ec{constructor(){this.pu=new ra(ds.comparator)}track(e){var t=e.doc.key,n=this.pu.get(t);!n||0!==e.type&&3===n.type?this.pu=this.pu.insert(t,e):3===e.type&&1!==n.type?this.pu=this.pu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.pu=this.pu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.pu=this.pu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.pu=this.pu.remove(t):1===e.type&&2===n.type?this.pu=this.pu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.pu=this.pu.insert(t,{type:2,doc:e.doc}):Ar()}Iu(){const n=[];return this.pu.inorderTraversal((e,t)=>{n.push(t)}),n}}class Tc{constructor(e,t,n,r,s,i,a,o){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=s,this.fromCache=i,this.syncStateChanged=a,this.excludesMetadataChanges=o}static fromInitialDocuments(e,t,n,r){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new Tc(e,t,Ic.emptySet(t),s,n,r,!0,!1)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&vi(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 _c{constructor(){this.Tu=void 0,this.listeners=[]}}class Sc{constructor(){this.queries=new na(e=>wi(e),vi),this.onlineState="Unknown",this.Eu=new Set}}async function Ac(e,t){const n=e,r=t.query;let s=!1,i=n.queries.get(r);if(i||(s=!0,i=new _c),s)try{i.Tu=await n.onListen(r)}catch(e){const n=bc(e,`Initialization of query '${bi(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,i),i.listeners.push(t),t.Au(n.onlineState),!i.Tu||t.Ru(i.Tu)&&xc(n)}async function Dc(e,t){const n=e,r=t.query;let s=!1;const i=n.queries.get(r);if(i){const e=i.listeners.indexOf(t);0<=e&&(i.listeners.splice(e,1),s=0===i.listeners.length)}if(s)return n.queries.delete(r),n.onUnlisten(r)}function xc(e){e.Eu.forEach(e=>{e.next()})}class Nc{constructor(e,t,n){this.query=e,this.Pu=t,this.bu=!1,this.Vu=null,this.onlineState="Unknown",this.options=n||{}}Ru(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new Tc(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}let t=!1;return this.bu?this.vu(e)&&(this.Pu.next(e),t=!0):this.Su(e,this.onlineState)&&(this.Du(e),t=!0),this.Vu=e,t}onError(e){this.Pu.error(e)}Au(e){this.onlineState=e;let t=!1;return this.Vu&&!this.bu&&this.Su(this.Vu,e)&&(this.Du(this.Vu),t=!0),t}Su(e,t){return!e.fromCache||!(this.options.Cu&&"Offline"!==t||e.docs.isEmpty()&&"Offline"!==t)}vu(e){if(0<e.docChanges.length)return!0;var t=this.Vu&&this.Vu.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}Du(e){e=Tc.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.bu=!0,this.Pu.next(e)}}class Cc{constructor(e,t){this.payload=e,this.byteLength=t}xu(){return"metadata"in this.payload}}class kc{constructor(e){this.M=e}fi(e){return La(this.M,e)}di(e){return e.metadata.exists?qa(this.M,e.document,!1):Ms.newNoDocument(this.fi(e.metadata.name),this._i(e.metadata.readTime))}_i(e){return Ca(e)}}class Mc{constructor(e,t,n){this.Nu=e,this.localStore=t,this.M=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=Rc(e)}ku(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.payload.namedQuery)this.queries.push(e.payload.namedQuery);else if(e.payload.documentMetadata){this.documents.push({metadata:e.payload.documentMetadata}),e.payload.documentMetadata.exists||++t;const n=Yr.fromString(e.payload.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.payload.document&&(this.documents[this.documents.length-1].document=e.payload.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Mu(e){const t=new Map,n=new kc(this.M);for(const s of e)if(s.metadata.queries){const e=n.fi(s.metadata.name);for(const n of s.metadata.queries){var r=(t.get(n)||ga()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const s=e;let i=ga(),a=ha;for(const e of n){const n=t.fi(e.metadata.name);e.document&&(i=i.add(n));const h=t.di(e);h.setReadTime(t._i(e.metadata.readTime)),a=a.insert(n,h)}const o=s.ui.newChangeBuffer({trackRemovals:!0}),u=await dh(s,(r=r,pi(hi(Yr.fromString(`__bundle__/docs/${r}`)))));return s.persistence.runTransaction("Apply bundle documents","readwrite",t=>lh(t,o,a).next(e=>(o.apply(t),e)).next(e=>s.fs.removeMatchingKeysForTargetId(t,u.targetId).next(()=>s.fs.addMatchingKeys(t,i,u.targetId)).next(()=>s.ci.Gs(t,e)).next(()=>e)))}(this.localStore,new kc(this.M),this.documents,this.Nu.id),t=this.Mu(this.documents);for(const e of this.queries)await async function(e,n,r=ga()){const s=await dh(e,pi(Qo(n.bundledQuery))),i=e;return i.persistence.runTransaction("Save named query","readwrite",e=>{var t=Ca(n.readTime);if(0<=s.snapshotVersion.compareTo(t))return i._s.saveNamedQuery(e,n);t=s.withResumeToken(es.EMPTY_BYTE_STRING,t);return i.ii=i.ii.insert(t.targetId,t),i.fs.updateTargetData(e,t).next(()=>i.fs.removeMatchingKeysForTargetId(e,s.targetId)).next(()=>i.fs.addMatchingKeys(e,r,s.targetId)).next(()=>i._s.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Ou:this.collectionGroups,Fu:e}}}function Rc(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class Lc{constructor(e){this.key=e}}class Vc{constructor(e){this.key=e}}class Oc{constructor(e,t){this.query=e,this.$u=t,this.Bu=null,this.current=!1,this.Lu=ga(),this.mutatedKeys=ga(),this.Uu=Ti(e),this.qu=new Ic(this.Uu)}get Ku(){return this.$u}Gu(e,t){const o=t?t.Qu:new Ec,u=(t||this).qu;let h=(t||this).mutatedKeys,c=u,l=!1;const d=ci(this.query)&&u.size===this.query.limit?u.last():null,f=li(this.query)&&u.size===this.query.limit?u.first():null;if(e.inorderTraversal((e,t)=>{const n=u.get(e),r=Ii(this.query,t)?t:null,s=!!n&&this.mutatedKeys.has(n.key),i=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?s!==i&&(o.track({type:3,doc:r}),a=!0):this.ju(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.Uu(r,d)||f&&this.Uu(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&&(h=r?(c=c.add(r),i?h.add(e):h.delete(e)):(c=c.delete(e),h.delete(e)))}),ci(this.query)||li(this.query))for(;c.size>this.query.limit;){const e=ci(this.query)?c.last():c.first();c=c.delete(e.key),h=h.delete(e.key),o.track({type:1,doc:e})}return{qu:c,Qu:o,ni:l,mutatedKeys:h}}ju(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.qu;this.qu=e.qu,this.mutatedKeys=e.mutatedKeys;const s=e.Qu.Iu();s.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Ar()}};return n(e)-n(t)}(e.type,t.type)||this.Uu(e.doc,t.doc)),this.Wu(n);var i=t?this.zu():[],a=0===this.Lu.size&&this.current?1:0,o=a!==this.Bu;return this.Bu=a,0!==s.length||o?{snapshot:new Tc(this.query,e.qu,r,s,e.mutatedKeys,0==a,o,!1),Hu:i}:{Hu:i}}Au(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({qu:this.qu,Qu:new Ec,mutatedKeys:this.mutatedKeys,ni:!1},!1)):{Hu:[]}}Ju(e){return!this.$u.has(e)&&!!this.qu.has(e)&&!this.qu.get(e).hasLocalMutations}Wu(e){e&&(e.addedDocuments.forEach(e=>this.$u=this.$u.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.$u=this.$u.delete(e)),this.current=e.current)}zu(){if(!this.current)return[];const t=this.Lu;this.Lu=ga(),this.qu.forEach(e=>{this.Ju(e.key)&&(this.Lu=this.Lu.add(e.key))});const n=[];return t.forEach(e=>{this.Lu.has(e)||n.push(new Vc(e))}),this.Lu.forEach(e=>{t.has(e)||n.push(new Lc(e))}),n}Yu(e){this.$u=e.li,this.Lu=ga();var t=this.Gu(e.documents);return this.applyChanges(t,!0)}Xu(){return Tc.fromInitialDocuments(this.query,this.qu,this.mutatedKeys,0===this.Bu)}}class Fc{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Pc{constructor(e){this.key=e,this.Zu=!1}}class Bc{constructor(e,t,n,r,s,i){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=s,this.maxConcurrentLimboResolutions=i,this.ta={},this.ea=new na(e=>wi(e),vi),this.na=new Map,this.sa=new Set,this.ia=new ra(ds.comparator),this.ra=new Map,this.oa=new bh,this.ua={},this.aa=new Map,this.ca=Cu.yn(),this.onlineState="Unknown",this.ha=void 0}get isPrimaryClient(){return!0===this.ha}}async function qc(n,e,t,r){n.la=(e,i,t)=>async function(e,t,n){let r=t.view.Gu(i);r.ni&&(r=await gh(e.localStore,t.query,!1).then(({documents:e})=>t.view.Gu(e,r)));var s=n&&n.targetChanges.get(t.targetId),s=t.view.applyChanges(r,e.isPrimaryClient,s);return Qc(e,t.targetId,s.Hu),s.snapshot}(n,e,t);const s=await gh(n.localStore,e,!0),i=new Oc(e,s.li),a=i.Gu(s.documents),o=ya.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState),u=i.applyChanges(a,n.isPrimaryClient,o);Qc(n,t,u.Hu);var h=new Fc(e,t,i);return n.ea.set(e,h),n.na.has(t)?n.na.get(t).push(e):n.na.set(t,[e]),u.snapshot}async function Uc(e,t,n){const r=nl(e);try{const e=await function(e,r){const s=e,i=Gr.now(),t=r.reduce((e,t)=>e.add(t.key),ga());let a;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>s.ci.Ks(n,t).next(e=>{a=e;const t=[];for(const n of r){const r=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),s=xi(r.transform,e||null);null!=s&&(null==n&&(n=ks.empty()),n.set(r.field,s))}return n||null}(n,a.get(n.key));null!=r&&t.push(new Wi(n.key,r,function r(e){const s=[];return Wr(e.fields,(e,t)=>{const n=new Jr([e]);if(As(t)){const e=r(t.mapValue).fields;if(0===e.length)s.push(n);else for(const t of e)s.push(n.child(t))}else s.push(n)}),new Zr(s)}(r.value.mapValue),Bi.exists(!0)))}return s.Bs.addMutationBatch(n,i,t,r)})).then(e=>(e.applyToLocalDocumentSet(a),{batchId:e.batchId,changes:a}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.ua[e.currentUser.toKey()];r=r||new ra(Ur),r=r.insert(t,n),e.ua[e.currentUser.toKey()]=r}(r,e.batchId,n),await Xc(r,e.changes),await dc(r.remoteStore)}catch(e){const t=bc(e,"Failed to persist write");n.reject(t)}}async function Kc(e,t){const r=e;try{const e=await ch(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.ra.get(t);n&&(Dr(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.Zu=!0:0<e.modifiedDocuments.size?Dr(n.Zu):0<e.removedDocuments.size&&(Dr(n.Zu),n.Zu=!1))}),await Xc(r,e,t)}catch(e){await Vu(e)}}function jc(r,s,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.ea.forEach((e,t)=>{var n=t.view.Au(s);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.listeners)e.Au(n)&&(r=!0)}),r&&xc(t)}(t.eventManager,s),r.length&&t.ta.Qo(r),t.onlineState=s,t.isPrimaryClient&&t.sharedClientState.setOnlineState(s)}}async function Gc(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const s=e;return s.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=s.ui.newChangeBuffer({trackRemovals:!0});return function(e,t,r,s){const i=r.batch,n=i.keys();let a=So.resolve();return n.forEach(n=>{a=a.next(()=>s.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);Dr(null!==t),e.version.compareTo(t)<0&&(i.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),s.addEntry(e)))})}),a.next(()=>e.Bs.removeMutationBatch(t,i))}(s,e,r,n).next(()=>n.apply(e)).next(()=>s.Bs.performConsistencyCheck(e)).next(()=>s.ci.Ks(e,t))})}(n.localStore,t);zc(n,r,null),$c(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Xc(n,e)}catch(e){await Vu(e)}}function $c(e,t){(e.aa.get(t)||[]).forEach(e=>{e.resolve()}),e.aa.delete(t)}function zc(e,t,n){const r=e;let s=r.ua[r.currentUser.toKey()];if(s){const e=s.get(t);e&&(n?e.reject(n):e.resolve(),s=s.remove(t)),r.ua[r.currentUser.toKey()]=s}}function Wc(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.na.get(e))t.ea.delete(r),n&&t.ta.fa(r,n);t.na.delete(e),t.isPrimaryClient&&t.oa.Pi(e).forEach(e=>{t.oa.containsKey(e)||Hc(t,e)})}function Hc(e,t){e.sa.delete(t.path.canonicalString());var n=e.ia.get(t);null!==n&&(rc(e.remoteStore,n),e.ia=e.ia.remove(t),e.ra.delete(n),Yc(e))}function Qc(e,t,n){for(const r of n)r instanceof Lc?(e.oa.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.ia.get(n)||e.sa.has(r)||(Er("SyncEngine","New document in limbo: "+n),e.sa.add(r),Yc(e))}(e,r)):r instanceof Vc?(Er("SyncEngine","Document no longer in limbo: "+r.key),e.oa.removeReference(r.key,t),e.oa.containsKey(r.key)||Hc(e,r.key)):Ar()}function Yc(e){for(;0<e.sa.size&&e.ia.size<e.maxConcurrentLimboResolutions;){var t=e.sa.values().next().value;e.sa.delete(t);var n=new ds(Yr.fromString(t)),t=e.ca.next();e.ra.set(t,new Pc(n)),e.ia=e.ia.insert(n,t),nc(e.remoteStore,new qo(pi(hi(n.path)),t,2,Br.A))}}async function Xc(e,t,r){const s=e,i=[],a=[],o=[];s.ea.isEmpty()||(s.ea.forEach((e,n)=>{o.push(s.la(n,t,r).then(e=>{var t;e&&(s.isPrimaryClient&&s.sharedClientState.updateQueryState(n.targetId,e.fromCache?"not-current":"current"),i.push(e),t=sh.Ys(n.targetId,e),a.push(t))}))}),await Promise.all(o),s.ta.Qo(i),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>So.forEach(t,t=>So.forEach(t.Hs,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>So.forEach(t.Js,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!Co(e))throw e;Er("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.ii.get(t),n=e.snapshotVersion,s=e.withLastLimboFreeSnapshotVersion(n);r.ii=r.ii.insert(t,s)}}}(s.localStore,a))}async function Jc(r,e){const s=r;if(tl(s),nl(s),!0===e&&!0!==s.ha){const r=s.sharedClientState.getAllActiveQueryTargets(),e=await Zc(s,r.toArray());s.ha=!0,await pc(s.remoteStore,!0);for(const r of e)nc(s.remoteStore,r)}else if(!1===e&&!1!==s.ha){const r=[];let n=Promise.resolve();s.na.forEach((e,t)=>{s.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(Wc(s,t),fh(s.localStore,t,!0))),rc(s.remoteStore,t)}),await n,await Zc(s,r),function(){const n=s;n.ra.forEach((e,t)=>{rc(n.remoteStore,t)}),n.oa.bi(),n.ra=new Map,n.ia=new ra(ds.comparator)}(),s.ha=!1,await pc(s.remoteStore,!1)}}async function Zc(t,n){const r=t,s=[],i=[];for(const t of n){let e;const c=r.na.get(t);if(c&&0!==c.length){e=await dh(r.localStore,pi(c[0]));for(const t of c){const n=r.ea.get(t),c=(a=r,o=n,h=u=void 0,h=await gh((u=a).localStore,o.query,!0),h=o.view.Yu(h),u.isPrimaryClient&&Qc(u,o.targetId,h.Hu),await h);c.snapshot&&i.push(c.snapshot)}}else{const c=await mh(r.localStore,t);e=await dh(r.localStore,c),await qc(r,el(c),t,!1)}s.push(e)}var a,o,u,h;return r.ta.Qo(i),s}function el(e){return ui(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function tl(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=Kc.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.ra.get(t);if(r&&r.Zu)return ga().add(r.key);{let e=ga();const r=n.na.get(t);if(!r)return e;for(const t of r){const r=n.ea.get(t);e=e.unionWith(r.view.Ku)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const s=r.ra.get(t),i=s&&s.key;if(i){let e=new ra(ds.comparator);e=e.insert(i,Ms.newNoDocument(i,$r.min()));const n=ga().add(i),s=new pa($r.min(),new Map,new aa(Ur),e,n);await Kc(r,s),r.ia=r.ia.remove(i),r.ra.delete(t),Yc(r)}else await fh(r.localStore,t,!1).then(()=>Wc(r,t,n)).catch(Vu)}).bind(null,t),t.ta.Qo=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,s=n.queries.get(t);if(s){for(const t of s.listeners)t.Ru(e)&&(r=!0);s.Tu=e}}r&&xc(n)}).bind(null,t.eventManager),t.ta.fa=(function(e,t,n){const r=e,s=r.queries.get(t);if(s)for(const e of s.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function nl(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=Gc.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const s=e;return s.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return s.Bs.lookupMutationBatch(t,r).next(e=>(Dr(null!==e),n=e.keys(),s.Bs.removeMutationBatch(t,e))).next(()=>s.Bs.performConsistencyCheck(t)).next(()=>s.ci.Ks(t,n))})}(r.localStore,t);zc(r,t,n),$c(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Xc(r,e)}catch(n){await Vu(n)}}).bind(null,t),t}class rl{constructor(){this.synchronizeTabs=!1}async initialize(e){this.M=zh(e.databaseInfo.databaseId),this.sharedClientState=this._a(e),this.persistence=this.wa(e),await this.persistence.start(),this.gcScheduler=this.ma(e),this.localStore=this.ga(e)}ma(e){return null}ga(e){return oh(this.persistence,new ih,e.initialUser,this.M)}wa(e){return new Ah(xh.zi,this.M)}_a(e){return new Ph}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class sl extends rl{constructor(e,t,n){super(),this.ya=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.ya.initialize(this,e),await nl(this.ya.syncEngine),await dc(this.ya.remoteStore),await this.persistence.Ts(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(this.localStore),Promise.resolve()))}ga(e){return oh(this.persistence,new ih,e.initialUser,this.M)}ma(e){var t=this.persistence.referenceDelegate.garbageCollector;return new Pu(t,e.asyncQueue)}wa(e){var t=nh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?Eu.withCacheSize(this.cacheSizeBytes):Eu.DEFAULT;return new Zu(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,Gh(),$h(),this.M,this.sharedClientState,!!this.forceOwnership)}_a(e){return new Ph}}class il extends sl{constructor(e,t){super(e,t,!1),this.ya=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.ya.syncEngine;this.sharedClientState instanceof Fh&&(this.sharedClientState.syncEngine={Mr:(async function(e,t,n,r){var s=e,i=await function(e,n){const r=e,s=r.Bs;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>s.fn(t,n).next(e=>e?r.ci.Ks(t,e):So.resolve(null)))}(s.localStore,t);null!==i?("pending"===n?await dc(s.remoteStore):"acknowledged"===n||"rejected"===n?(zc(s,t,r||null),$c(s,t),s.localStore.Bs._n(t)):Ar(),await Xc(s,i)):Er("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),Or:(async function(e,t,n,r){const s=e;if(s.ha)Er("SyncEngine","Ignoring unexpected query state notification.");else{var i=s.na.get(t);if(i&&0<i.length)switch(n){case"current":case"not-current":{const e=await ph(s.localStore,Ei(i[0])),r=pa.createSynthesizedRemoteEventForCurrentChange(t,"current"===n);await Xc(s,e,r);break}case"rejected":await fh(s.localStore,t,!0),Wc(s,t,r);break;default:Ar()}}}).bind(null,t),Fr:(async function(e,t,n){const r=tl(e);if(r.ha){for(const e of t)if(r.na.has(e))Er("SyncEngine","Adding an already active target "+e);else{const t=await mh(r.localStore,e),n=await dh(r.localStore,t);await qc(r,el(t),n.targetId,!1),nc(r.remoteStore,n)}for(const e of n)r.na.has(e)&&await fh(r.localStore,e,!1).then(()=>{rc(r.remoteStore,e),Wc(r,e)}).catch(Vu)}}).bind(null,t),Fs:(function(e){return e.localStore.persistence.Fs()}).bind(null,t),kr:(async function(e,t){const n=e;return ph(n.localStore,t).then(e=>Xc(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.Ts(async e=>{await Jc(this.ya.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start(this.localStore):e||this.gcScheduler.stop())})}_a(e){var t=Gh();if(!Fh.vt(t))throw new Nr(xr.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=nh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new Fh(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class al{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>jc(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){Er("SyncEngine","User change. New user:",t.toKey());const r=await uh(n.localStore,t);n.currentUser=t,(e=n).aa.forEach(e=>{e.forEach(e=>{e.reject(new Nr(xr.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.aa.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await Xc(n,r.hi)}}).bind(null,this.syncEngine),await pc(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Sc}createDatastore(e){var t,n,r,s,i=zh(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new jh(t));return n=e.authCredentials,r=e.appCheckCredentials,s=t,e=i,new Xh(n,r,s,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,s=e=>jc(this.syncEngine,e,0),i=new(qh.vt()?qh:Bh),new Zh(t,n,r,s,i);var t,n,r,s,i}createSyncEngine(e,t){return function(e,t,n,r,s,i,a){const o=new Bc(e,t,n,r,s,i);return a&&(o.ha=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;Er("RemoteStore","RemoteStore shutting down."),t.fu.add(5),await tc(t),t._u.shutdown(),t.wu.set("Unknown")}(this.remoteStore)}}function ol(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.reject("unimplemented")}}class ul{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.pa(this.observer.next,e)}error(e){this.observer.error?this.pa(this.observer.error,e):console.error("Uncaught Error in snapshot listener:",e)}Ia(){this.muted=!0}pa(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class hl{constructor(e,t){this.Ta=e,this.M=t,this.metadata=new Cr,this.buffer=new Uint8Array,this.Ea=new TextDecoder("utf-8"),this.Aa().then(e=>{e&&e.xu()?this.metadata.resolve(e.payload.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.payload)}`))},e=>this.metadata.reject(e))}close(){return this.Ta.cancel()}async getMetadata(){return this.metadata.promise}async da(){return await this.getMetadata(),this.Aa()}async Aa(){var e=await this.Ra();if(null===e)return null;var t=this.Ea.decode(e),n=Number(t);isNaN(n)&&this.Pa(`length string (${t}) is not valid number`);t=await this.ba(n);return new Cc(JSON.parse(t),e.length+n)}Va(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Ra(){for(;this.Va()<0&&!await this.va(););if(0===this.buffer.length)return null;var e=this.Va();e<0&&this.Pa("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 ba(e){for(;this.buffer.length<e;)await this.va()&&this.Pa("Reached the end of bundle when more is expected.");var t=this.Ea.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}Pa(e){throw this.Ta.cancel(),new Error(`Invalid bundle format: ${e}`)}async va(){var e=await this.Ta.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 cl{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 Nr(xr.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=Fa(r.M)+"/documents",s={documents:t.map(e=>Ra(r.M,e))},i=await r.ho("BatchGetDocuments",n,s),a=new Map;i.forEach(e=>{const t=(n=r.M,"found"in(e=e)?function(e,t){Dr(!!t.found),t.found.name,t.found.updateTime;var n=La(e,t.found.name),r=Ca(t.found.updateTime),s=new ks({mapValue:{fields:t.found.fields}});return Ms.newFoundDocument(n,r,s)}(n,e):"missing"in e?function(e,t){Dr(!!t.missing),Dr(!!t.readTime);var n=La(e,t.missing),r=Ca(t.readTime);return Ms.newNoDocument(n,r)}(n,e):Ar());var n;a.set(t.key.toString(),t)});const o=[];return t.forEach(e=>{var t=a.get(e.toString());Dr(!!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 Xi(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=ds.fromPath(t);this.mutations.push(new Ji(n,this.precondition(n)))}),await async function(e,t){const n=e,r=Fa(n.M)+"/documents",s={writes:t.map(e=>Ua(n.M,e))};await n.oo("Commit",r,s)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw Ar();t=$r.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new Nr(xr.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){var t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?Bi.updateTime(t):Bi.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return Bi.exists(!0);if(t.isEqual($r.min()))throw new Nr(xr.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Bi.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class ll{constructor(e,t,n,r){this.asyncQueue=e,this.datastore=t,this.updateFunction=n,this.deferred=r,this.Sa=5,this.Do=new Wh(this.asyncQueue,"transaction_retry")}run(){--this.Sa,this.Da()}Da(){this.Do.To(async()=>{const t=new cl(this.datastore),e=this.Ca(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.xa(e)}))}).catch(e=>{this.xa(e)})})}Ca(e){try{var t=this.updateFunction(e);return!hs(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}}xa(e){0<this.Sa&&this.Na(e)?(--this.Sa,this.asyncQueue.enqueueAndForget(()=>(this.Da(),Promise.resolve()))):this.deferred.reject(e)}Na(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||!ea(t)}}class dl{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=vr.UNAUTHENTICATED,this.clientId=qr.R(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{Er("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(Er("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 Nr(xr.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new Cr;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=bc(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function fl(e,t){e.asyncQueue.verifyOperationInProgress(),Er("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await uh(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function gl(e,n){e.asyncQueue.verifyOperationInProgress();var t=await ml(e);Er("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>mc(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>mc(n.remoteStore,t)),e.onlineComponents=n}async function ml(e){return e.offlineComponents||(Er("FirestoreClient","Using default OfflineComponentProvider"),await fl(e,new rl)),e.offlineComponents}async function pl(e){return e.onlineComponents||(Er("FirestoreClient","Using default OnlineComponentProvider"),await gl(e,new al)),e.onlineComponents}function yl(e){return ml(e).then(e=>e.persistence)}function vl(e){return ml(e).then(e=>e.localStore)}function wl(e){return pl(e).then(e=>e.remoteStore)}function bl(e){return pl(e).then(e=>e.syncEngine)}async function Il(e){const t=await pl(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=tl(e);let r,s;const i=n.ea.get(t);if(i)r=i.targetId,n.sharedClientState.addLocalQueryTarget(r),s=i.view.Xu();else{const e=await dh(n.localStore,pi(t));n.isPrimaryClient&&nc(n.remoteStore,e);const i=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,s=await qc(n,t,r,"current"===i)}return s}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.ea.get(t),s=n.na.get(r.targetId);if(1<s.length)return n.na.set(r.targetId,s.filter(e=>!vi(e,t))),void n.ea.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await fh(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),rc(n.remoteStore,r.targetId),Wc(n,r.targetId)}).catch(Vu)):(Wc(n,r.targetId),await fh(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function El(e,t,n={}){const r=new Cr;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,s,i,a){const e=new ul({next:e=>{r.enqueueAndForget(()=>Dc(n,o));var t=e.docs.has(s);!t&&e.fromCache?a.reject(new Nr(xr.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&i&&"server"===i.source?a.reject(new Nr(xr.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 Nc(hi(s.path),e,{includeMetadataChanges:!0,Cu:!0});return Ac(n,o)}(await Il(e),e.asyncQueue,t,n,r)),r.promise}function Tl(e,t,n={}){const r=new Cr;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,s){const i=new ul({next:e=>{n.enqueueAndForget(()=>Dc(t,a)),e.fromCache&&"server"===r.source?s.reject(new Nr(xr.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):s.resolve(e)},error:e=>s.reject(e)}),a=new Nc(e,i,{includeMetadataChanges:!0,Cu:!0});return Ac(t,a)}(await Il(e),e.asyncQueue,t,n,r)),r.promise}function _l(e,t,n,r){const s=(n=n,t=zh(t),i="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return ol(e,void 0);if(e instanceof ArrayBuffer)return ol(new Uint8Array(e),void 0);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(i),t=t,new hl(n,t));var i;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var s=await n.getMetadata();if(await function(e,t){const n=e,r=Ca(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n._s.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,s))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:s.totalDocuments,bytesLoaded:s.totalBytes,totalDocuments:s.totalDocuments,totalBytes:s.totalBytes}),Promise.resolve(new Set);r._updateProgress(Rc(s));const a=new Mc(s,t.localStore,n.M);let e=await n.da();for(;e;){const t=await a.ku(e);t&&r._updateProgress(t),e=await n.da()}var i=await a.complete();return await Xc(t,i.Fu,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n._s.saveBundleMetadata(e,t))}(t.localStore,s),r._completeWith(i.progress),Promise.resolve(i.Ou)}catch(t){return _r("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await bl(e),s,r)})}const Sl=new Map;function Al(e,t,n){if(!n)throw new Nr(xr.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Dl(e,t,n,r){if(!0===t&&!0===r)throw new Nr(xr.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function xl(e){if(!ds.isDocumentKey(e))throw new Nr(xr.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Nl(e){if(ds.isDocumentKey(e))throw new Nr(xr.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Cl(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":Ar();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 kl(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new Nr(xr.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=Cl(e);throw new Nr(xr.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function Ml(e,t){if(t<=0)throw new Nr(xr.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Rl{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new Nr(xr.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new Nr(xr.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,Dl("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling)}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Ll{constructor(e,t,n){this._authCredentials=t,this._appCheckCredentials=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Rl({}),this._settingsFrozen=!1,e instanceof us?this._databaseId=e:(this._app=e,this._databaseId=function(e){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new Nr(xr.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new us(e.options.projectId)}(e))}get app(){if(!this._app)throw new Nr(xr.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 Nr(xr.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 Rl(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new Mr;switch(e.type){case"gapi":var t=e.client;return Dr(!("object"!=typeof t||null===t||!t.auth||!t.auth.getAuthHeaderValueForFirstParty)),new Or(t,e.sessionIndex||"0",e.iamToken||null);case"provider":return e.client;default:throw new Nr(xr.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=Sl.get(e);t&&(Er("ComponentProvider","Removing Datastore"),Sl.delete(e),t.terminate())}(this),Promise.resolve()}}function Vl(n,e,t,r={}){var s;const i=(n=kl(n,Ll))._getSettings();if("firestore.googleapis.com"!==i.host&&i.host!==e&&_r("Host has been set in both settings() and useEmulator(), emulator host will be used"),n._setSettings(Object.assign(Object.assign({},i),{host:`${e}:${t}`,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=vr.MOCK_USER;else{e=function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,s=e.sub||e.user_id;if(!s)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");return s=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:s,user_id:s,firebase:{sign_in_provider:"custom",identities:{}}},e),[a(JSON.stringify({alg:"none",type:"JWT"})),a(JSON.stringify(s)),""].join(".")}(r.mockUserToken,null===(s=n._app)||void 0===s?void 0:s.options.projectId);const i=r.mockUserToken.sub||r.mockUserToken.user_id;if(!i)throw new Nr(xr.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new vr(i)}n._authCredentials=new Rr(new kr(e,t))}}class Ol{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 Pl(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Ol(this.firestore,e,this._key)}}class Fl{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Fl(this.firestore,e,this._query)}}class Pl extends Fl{constructor(e,t,n){super(e,t,hi(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 Ol(this.firestore,null,new ds(e))}withConverter(e){return new Pl(this.firestore,e,this._path)}}function Bl(e,t,...n){if(e=m(e),Al("collection","path",t),e instanceof Ll){var r=Yr.fromString(t,...n);return Nl(r),new Pl(e,null,r)}if(!(e instanceof Ol||e instanceof Pl))throw new Nr(xr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(Yr.fromString(t,...n));return Nl(r),new Pl(e.firestore,null,r)}function ql(e,t,...n){if(e=m(e),Al("doc","path",t=1===arguments.length?qr.R():t),e instanceof Ll){var r=Yr.fromString(t,...n);return xl(r),new Ol(e,null,new ds(r))}if(!(e instanceof Ol||e instanceof Pl))throw new Nr(xr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(Yr.fromString(t,...n));return xl(r),new Ol(e.firestore,e instanceof Pl?e.converter:null,new ds(r))}function Ul(e,t){return e=m(e),t=m(t),(e instanceof Ol||e instanceof Pl)&&(t instanceof Ol||t instanceof Pl)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function Kl(e,t){return e=m(e),t=m(t),e instanceof Fl&&t instanceof Fl&&e.firestore===t.firestore&&vi(e._query,t._query)&&e.converter===t.converter}class jl{constructor(){this.ka=Promise.resolve(),this.Ma=[],this.Oa=!1,this.Fa=[],this.$a=null,this.Ba=!1,this.La=!1,this.Ua=[],this.Do=new Wh(this,"async_queue_retry"),this.qa=()=>{var e=$h();e&&Er("AsyncQueue","Visibility state changed to "+e.visibilityState),this.Do.Ao()};const e=$h();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.qa)}get isShuttingDown(){return this.Oa}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Ka(),this.Ga(e)}enterRestrictedMode(e){if(!this.Oa){this.Oa=!0,this.La=e||!1;const t=$h();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.qa)}}enqueue(e){if(this.Ka(),this.Oa)return new Promise(()=>{});const t=new Cr;return this.Ga(()=>this.Oa&&this.La?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Ma.push(e),this.Qa()))}async Qa(){if(0!==this.Ma.length){try{await this.Ma[0](),this.Ma.shift(),this.Do.reset()}catch(e){if(!Co(e))throw e;Er("AsyncQueue","Operation failed with retryable error: "+e)}0<this.Ma.length&&this.Do.To(()=>this.Qa())}}Ga(e){var t=this.ka.then(()=>(this.Ba=!0,e().catch(e=>{throw this.$a=e,this.Ba=!1,Tr("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.Ba=!1,e))));return this.ka=t}enqueueAfterDelay(e,t,n){this.Ka(),-1<this.Ua.indexOf(e)&&(t=0);var r=wc.createAndSchedule(this,e,t,n,e=>this.ja(e));return this.Fa.push(r),r}Ka(){this.$a&&Ar()}verifyOperationInProgress(){}async Wa(){for(var e;await(e=this.ka),e!==this.ka;);}za(e){for(const t of this.Fa)if(t.timerId===e)return!0;return!1}Ha(t){return this.Wa().then(()=>{this.Fa.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.Fa)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Wa()})}Ja(e){this.Ua.push(e)}ja(e){var t=this.Fa.indexOf(e);this.Fa.splice(t,1)}}function Gl(e){return function(e){if("object"==typeof e&&null!==e){var t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return 1}}(e)}class $l{constructor(){this._progressObserver={},this._taskCompletionResolver=new Cr,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 zl,Wl,Hl;class Ql extends Ll{constructor(e,t,n){super(e,t,n),this.type="firestore",this._queue=new jl,this._persistenceKey="name"in e?e.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||Xl(this),this._firestoreClient.terminate()}}function Yl(e){return e._firestoreClient||Xl(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function Xl(e){var t,n,r,s,i,a=e._freezeSettings(),a=(n=e._databaseId,r=(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",s=e._persistenceKey,i=a,new os(n,r,s,i.host,i.ssl,i.experimentalForceLongPolling,i.experimentalAutoDetectLongPolling,i.useFetchStreams));e._firestoreClient=new dl(e._authCredentials,e._appCheckCredentials,e._queue,a)}function Jl(e,n,r){const s=new Cr;return e.asyncQueue.enqueue(async()=>{try{await fl(e,r),await gl(e,n),s.resolve()}catch(e){if(!("FirebaseError"===(t=e).name?t.code===xr.FAILED_PRECONDITION||t.code===xr.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||(22===t.code||20===t.code||11===t.code)))throw e;console.warn("Error enabling offline persistence. Falling back to persistence disabled: "+e),s.reject(e)}var t}).then(()=>s.promise)}function Zl(e){return function(e){const t=new Cr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;uc(n.remoteStore)||Er("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(){const t=n.localStore;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.Bs.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.aa.get(e)||[];r.push(t),n.aa.set(e,r)}catch(e){const n=bc(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await bl(e),t)),t.promise}(Yl(e=kl(e,Ql)))}function ed(e){return(n=Yl(e=kl(e,Ql))).asyncQueue.enqueue(async()=>{const e=await yl(n),t=await wl(n);return e.setNetworkEnabled(!0),function(){const e=t;return e.fu.delete(0),ec(e)}()});var n}function td(e){return(n=Yl(e=kl(e,Ql))).asyncQueue.enqueue(async()=>{const e=await yl(n),t=await wl(n);return e.setNetworkEnabled(!1),async function(){const e=t;e.fu.add(0),await tc(e),e.wu.set("Offline")}()});var n}function nd(t,e){return n=Yl(t=kl(t,Ql)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n._s.getNamedQuery(e,t))}(await vl(n),r)).then(e=>e?new Fl(t,null,e.query):null);var n,r}function rd(e){if(e._initialized||e._terminated)throw new Nr(xr.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 sd{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new Nr(xr.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Jr(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class id{constructor(e){this._byteString=e}static fromBase64String(e){try{return new id(es.fromBase64String(e))}catch(e){throw new Nr(xr.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new id(es.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 ad{constructor(e){this._methodName=e}}class od{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new Nr(xr.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new Nr(xr.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 Ur(this._lat,e._lat)||Ur(this._long,e._long)}}const ud=/^__.*__$/;class hd{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Wi(e,this.data,this.fieldMask,t,this.fieldTransforms):new zi(e,this.data,t,this.fieldTransforms)}}class cd{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Wi(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function ld(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw Ar()}}class dd{constructor(e,t,n,r,s,i){this.settings=e,this.databaseId=t,this.M=n,this.ignoreUndefinedProperties=r,void 0===s&&this.Ya(),this.fieldTransforms=s||[],this.fieldMask=i||[]}get path(){return this.settings.path}get Xa(){return this.settings.Xa}Za(e){return new dd(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.M,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}tc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Za({path:n,ec:!1});return r.nc(e),r}sc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Za({path:n,ec:!1});return r.Ya(),r}ic(e){return this.Za({path:void 0,ec:!0})}rc(e){return Md(e,this.settings.methodName,this.settings.oc||!1,this.path,this.settings.uc)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}Ya(){if(this.path)for(let e=0;e<this.path.length;e++)this.nc(this.path.get(e))}nc(e){if(0===e.length)throw this.rc("Document fields must not be empty");if(ld(this.Xa)&&ud.test(e))throw this.rc('Document fields cannot begin and end with "__"')}}class fd{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.M=n||zh(e)}ac(e,t,n,r=!1){return new dd({Xa:e,methodName:t,uc:n,path:Jr.emptyPath(),ec:!1,oc:r},this.databaseId,this.M,this.ignoreUndefinedProperties)}}function gd(e){var t=e._freezeSettings(),n=zh(e._databaseId);return new fd(e._databaseId,!!t.ignoreUndefinedProperties,n)}function md(e,t,n,r,s,i={}){const a=e.ac(i.merge||i.mergeFields?2:0,t,n,s);xd("Data must be an object, but it was:",a,r);var o=Ad(r,a);let u,h;if(i.merge)u=new Zr(a.fieldMask),h=a.fieldTransforms;else if(i.mergeFields){const e=[];for(const r of i.mergeFields){const s=Nd(t,r,n);if(!a.contains(s))throw new Nr(xr.INVALID_ARGUMENT,`Field '${s}' is specified in your field mask but missing from your input data.`);Rd(e,s)||e.push(s)}u=new Zr(e),h=a.fieldTransforms.filter(e=>u.covers(e.field))}else u=null,h=a.fieldTransforms;return new hd(new ks(o),u,h)}class pd extends ad{_toFieldTransform(e){if(2!==e.Xa)throw 1===e.Xa?e.rc(`${this._methodName}() can only appear at the top level of your update data`):e.rc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof pd}}function yd(e,t,n){return new dd({Xa:3,uc:t.settings.uc,methodName:e._methodName,ec:n},t.databaseId,t.M,t.ignoreUndefinedProperties)}class vd extends ad{_toFieldTransform(e){return new Fi(e.path,new Ni)}isEqual(e){return e instanceof vd}}class wd extends ad{constructor(e,t){super(e),this.cc=t}_toFieldTransform(e){const t=yd(this,e,!0),n=this.cc.map(e=>Sd(e,t)),r=new Ci(n);return new Fi(e.path,r)}isEqual(e){return this===e}}class bd extends ad{constructor(e,t){super(e),this.cc=t}_toFieldTransform(e){const t=yd(this,e,!0),n=this.cc.map(e=>Sd(e,t)),r=new Mi(n);return new Fi(e.path,r)}isEqual(e){return this===e}}class Id extends ad{constructor(e,t){super(e),this.hc=t}_toFieldTransform(e){var t=new Li(e.M,Ai(e.M,this.hc));return new Fi(e.path,t)}isEqual(e){return this===e}}function Ed(e,s,i,t){const a=e.ac(1,s,i);xd("Data must be an object, but it was:",a,t);const o=[],u=ks.empty();Wr(t,(e,t)=>{var n=kd(s,e,i);t=m(t);var r=a.sc(n);if(t instanceof pd)o.push(n);else{const e=Sd(t,r);null!=e&&(o.push(n),u.set(n,e))}});var n=new Zr(o);return new cd(u,n,a.fieldTransforms)}function Td(e,t,n,r,s,i){const a=e.ac(1,t,n),o=[Nd(t,r,n)],u=[s];if(i.length%2!=0)throw new Nr(xr.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<i.length;f+=2)o.push(Nd(t,i[f])),u.push(i[f+1]);const h=[],c=ks.empty();for(let g=o.length-1;0<=g;--g)if(!Rd(h,o[g])){const t=o[g];var l=m(l=u[g]);const r=a.sc(t);if(l instanceof pd)h.push(t);else{const e=Sd(l,r);null!=e&&(h.push(t),c.set(t,e))}}var d=new Zr(h);return new cd(c,d,a.fieldTransforms)}function _d(e,t,n,r=!1){return Sd(n,e.ac(r?4:3,t))}function Sd(i,e){if(Dd(i=m(i)))return xd("Unsupported field value:",e,i),Ad(i,e);if(i instanceof ad)return function(e,t){if(!ld(t.Xa))throw t.rc(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.rc(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(i,e),null;if(void 0===i&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),i instanceof Array){if(e.settings.ec&&4!==e.Xa)throw e.rc("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const s of i){let e=Sd(s,t.ic(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e)}return function(e,t){if(null===(e=m(i)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return Ai(t.M,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=Gr.fromDate(e);return{timestampValue:xa(t.M,n)}}if(e instanceof Gr){n=new Gr(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:xa(t.M,n)}}if(e instanceof od)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof id)return{bytesValue:Na(t.M,e._byteString)};if(e instanceof Ol){const r=t.databaseId,s=e.firestore._databaseId;if(!s.isEqual(r))throw t.rc(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:ka(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.rc(`Unsupported field value: ${Cl(e)}`)}(0,e)}function Ad(e,r){const s={};return Hr(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):Wr(e,(e,t)=>{var n=Sd(t,r.tc(e));null!=n&&(s[e]=n)}),{mapValue:{fields:s}}}function Dd(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Gr||e instanceof od||e instanceof id||e instanceof Ol||e instanceof ad)}function xd(e,t,n){if(!Dd(n)||("object"!=typeof(s=n)||null===s||Object.getPrototypeOf(s)!==Object.prototype&&null!==Object.getPrototypeOf(s))){var r=Cl(n);throw"an object"===r?t.rc(e+" a custom object"):t.rc(e+" "+r)}var s}function Nd(e,t,n){if((t=m(t))instanceof sd)return t._internalPath;if("string"==typeof t)return kd(e,t);throw Md("Field path arguments must be of type string or ",e,!1,void 0,n)}const Cd=new RegExp("[~\\*/\\[\\]]");function kd(t,n,r){if(0<=n.search(Cd))throw Md(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new sd(...n.split("."))._internalPath}catch(e){throw Md(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function Md(e,t,n,r,s){var i=r&&!r.isEmpty(),a=void 0!==s;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let u="";return(i||a)&&(u+=" (found",i&&(u+=` in field ${r}`),a&&(u+=` in document ${s}`),u+=")"),new Nr(xr.INVALID_ARGUMENT,o+e+u)}function Rd(e,t){return e.some(e=>e.isEqual(t))}class Ld{constructor(e,t,n,r,s){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=s}get id(){return this._key.path.lastSegment()}get ref(){return new Ol(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new Vd(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(Od("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Vd extends Ld{data(){return super.data()}}function Od(e,t){return"string"==typeof t?kd(e,t):(t instanceof sd?t:t._delegate)._internalPath}class Fd{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Pd extends Ld{constructor(e,t,n,r,s,i){super(e,t,n,r,i),this._firestore=e,this._firestoreImpl=e,this.metadata=s}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new Bd(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(Od("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Bd extends Pd{data(e={}){return super.data(e)}}class qd{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new Fd(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 Bd(this._firestore,this._userDataWriter,e.key,e,new Fd(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 Nr(xr.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(i,t){if(i._snapshot.oldDocs.isEmpty()){let t=0;return i._snapshot.docChanges.map(e=>({type:"added",doc:new Bd(i._firestore,i._userDataWriter,e.doc.key,e.doc,new Fd(i._snapshot.mutatedKeys.has(e.doc.key),i._snapshot.fromCache),i.query.converter),oldIndex:-1,newIndex:t++}))}{let s=i._snapshot.oldDocs;return i._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new Bd(i._firestore,i._userDataWriter,e.doc.key,e.doc,new Fd(i._snapshot.mutatedKeys.has(e.doc.key),i._snapshot.fromCache),i.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=s.indexOf(e.doc.key),s=s.delete(e.doc.key)),1!==e.type&&(s=s.add(e.doc),r=s.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Ar()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function Ud(e,t){return e instanceof Pd&&t instanceof Pd?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 qd&&t instanceof qd&&e._firestore===t._firestore&&Kl(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function Kd(e){if(li(e)&&0===e.explicitOrderBy.length)throw new Nr(xr.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class jd{}function Gd(e,...t){for(const n of t)e=n._apply(e);return e}class $d extends jd{constructor(e,t,n){super(),this.lc=e,this.fc=t,this.dc=n,this.type="where"}_apply(e){var t=gd(e.firestore),t=function(e,t,n,r,s,i,a){let o;if(s.isKeyField()){if("array-contains"===i||"array-contains-any"===i)throw new Nr(xr.INVALID_ARGUMENT,`Invalid Query. You can't perform '${i}' queries on documentId().`);if("in"===i||"not-in"===i){Jd(a,i);const t=[];for(const n of a)t.push(Xd(r,e,n));o={arrayValue:{values:t}}}else o=Xd(r,e,a)}else"in"!==i&&"not-in"!==i&&"array-contains-any"!==i||Jd(a,i),o=_d(n,t,a,"in"===i||"not-in"===i);var u=Hs.create(s,i,o);return function(e,t){if(t.S()){const r=fi(e);if(null!==r&&!r.isEqual(t.field))throw new Nr(xr.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 '${t.field.toString()}'`);var n=di(e);null!==n&&Zd(0,t.field,n)}const r=function(e,t){for(const n of e.filters)if(0<=t.indexOf(n.op))return n.op;return null}(e,function(){switch(t.op){case"!=":return["!=","not-in"];case"array-contains":return["array-contains","array-contains-any","not-in"];case"in":return["array-contains-any","in","not-in"];case"array-contains-any":return["array-contains","array-contains-any","in","not-in"];case"not-in":return["array-contains","array-contains-any","in","not-in","!="];default:return[]}}());if(null!==r)throw r===t.op?new Nr(xr.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new Nr(xr.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}(e,u),u}(e._query,"where",t,e.firestore._databaseId,this.lc,this.fc,this.dc);return new Fl(e.firestore,e.converter,(e=e._query,t=e.filters.concat([t]),new oi(e.path,e.collectionGroup,e.explicitOrderBy.slice(),t,e.limit,e.limitType,e.startAt,e.endAt)))}}class zd extends jd{constructor(e,t){super(),this.lc=e,this._c=t,this.type="orderBy"}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new Nr(xr.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new Nr(xr.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,s=new si(t,n);return n=s,null!==di(e=e)||null!==(r=fi(e))&&Zd(0,r,n.field),s}(e._query,this.lc,this._c);return new Fl(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new oi(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class Wd extends jd{constructor(e,t,n){super(),this.type=e,this.wc=t,this.mc=n}_apply(e){return new Fl(e.firestore,e.converter,yi(e._query,this.wc,this.mc))}}class Hd extends jd{constructor(e,t,n){super(),this.type=e,this.gc=t,this.yc=n}_apply(e){var t,n=Yd(e,this.type,this.gc,this.yc);return new Fl(e.firestore,e.converter,(t=e._query,e=n,new oi(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class Qd extends jd{constructor(e,t,n){super(),this.type=e,this.gc=t,this.yc=n}_apply(e){var t,n=Yd(e,this.type,this.gc,this.yc);return new Fl(e.firestore,e.converter,(t=e._query,e=n,new oi(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function Yd(e,t,n,r){if(n[0]=m(n[0]),n[0]instanceof Ld)return function(e,t,n,r,s){if(!r)throw new Nr(xr.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const i=[];for(const n of mi(e))if(n.field.isKeyField())i.push(Is(t,r.key));else{const e=r.data.field(n.field);if(is(e))throw new Nr(xr.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 Nr(xr.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}i.push(e)}return new ri(i,s)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var s=gd(e.firestore);return function(e,t,n,r,s,i){const a=e.explicitOrderBy;if(s.length>a.length)throw new Nr(xr.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const o=[];for(let u=0;u<s.length;u++){const h=s[u];if(a[u].field.isKeyField()){if("string"!=typeof h)throw new Nr(xr.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof h}`);if(!gi(e)&&-1!==h.indexOf("/"))throw new Nr(xr.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${h}' contains a slash.`);const n=e.path.child(Yr.fromString(h));if(!ds.isDocumentKey(n))throw new Nr(xr.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const s=new ds(n);o.push(Is(t,s))}else{const e=_d(n,r,h);o.push(e)}}return new ri(o,i)}(e._query,e.firestore._databaseId,s,t,n,r)}function Xd(e,t,n){if("string"==typeof(n=m(n))){if(""===n)throw new Nr(xr.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!gi(t)&&-1!==n.indexOf("/"))throw new Nr(xr.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(Yr.fromString(n));if(!ds.isDocumentKey(r))throw new Nr(xr.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 Is(e,new ds(r))}if(n instanceof Ol)return Is(e,n._key);throw new Nr(xr.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Cl(n)}.`)}function Jd(e,t){if(!Array.isArray(e)||0===e.length)throw new Nr(xr.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);if(10<e.length)throw new Nr(xr.INVALID_ARGUMENT,`Invalid Query. '${t.toString()}' filters support a maximum of 10 elements in the value array.`)}function Zd(e,t,n){if(!n.isEqual(t))throw new Nr(xr.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 ef{convertValue(e,t="none"){switch(ms(e)){case 0:return null;case 1:return e.booleanValue;case 2:return rs(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(ss(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 Ar()}}convertObject(e,n){const r={};return Wr(e.fields,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new od(rs(e.latitude),rs(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=function e(t){var n=t.mapValue.fields.__previous_value__;return is(n)?e(n):n}(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(as(e));default:return null}}convertTimestamp(e){var t=ns(e);return new Gr(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=Yr.fromString(e);Dr(Ya(n));const r=new us(n.get(1),n.get(3)),s=new ds(n.popFirst(5));return r.isEqual(t)||Tr(`Document ${s} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),s}}function tf(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class nf extends ef{constructor(e){super(),this.firestore=e}convertBytes(e){return new id(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Ol(this.firestore,null,t)}}class rf{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=gd(e)}set(e,t,n){this._verifyNotCommitted();const r=sf(e,this._firestore),s=tf(r.converter,t,n),i=md(this._dataReader,"WriteBatch.set",r._key,s,null!==r.converter,n);return this._mutations.push(i.toMutation(r._key,Bi.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var s=sf(e,this._firestore);let i;return i="string"==typeof(t=m(t))||t instanceof sd?Td(this._dataReader,"WriteBatch.update",s._key,t,n,r):Ed(this._dataReader,"WriteBatch.update",s._key,t),this._mutations.push(i.toMutation(s._key,Bi.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=sf(e,this._firestore);return this._mutations=this._mutations.concat(new Xi(t._key,Bi.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 Nr(xr.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function sf(e,t){if((e=m(e)).firestore!==t)throw new Nr(xr.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class af extends ef{constructor(e){super(),this.firestore=e}convertBytes(e){return new id(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Ol(this.firestore,null,t)}}function of(t){t=kl(t,Ol);const n=kl(t.firestore,Ql),e=Yl(n),r=new af(n);return function(e,t){const n=new Cr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const s=await function(t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.ci.Ls(e,t))}(t);s.isFoundDocument()?n.resolve(s):s.isNoDocument()?n.resolve(null):n.reject(new Nr(xr.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=bc(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await vl(e),t,n)),n.promise}(e,t._key).then(e=>new Pd(n,r,t._key,e,new Fd(null!==e&&e.hasLocalMutations,!0),t.converter))}function uf(t){t=kl(t,Fl);const n=kl(t.firestore,Ql),e=Yl(n),r=new af(n);return function(e,t){const n=new Cr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const s=await gh(e,t,!0),i=new Oc(t,s.li),a=i.Gu(s.documents),o=i.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=bc(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await vl(e),t,n)),n.promise}(e,t._query).then(e=>new qd(n,r,t,e))}function hf(e,t,n){e=kl(e,Ol);var r=kl(e.firestore,Ql),s=tf(e.converter,t,n);return ff(r,[md(gd(r),"setDoc",e._key,s,null!==e.converter,n).toMutation(e._key,Bi.none())])}function cf(e,t,n,...r){e=kl(e,Ol);var s=kl(e.firestore,Ql),i=gd(s);let a;return a="string"==typeof(t=m(t))||t instanceof sd?Td(i,"updateDoc",e._key,t,n,r):Ed(i,"updateDoc",e._key,t),ff(s,[a.toMutation(e._key,Bi.exists(!0))])}function lf(t,...n){var e;t=m(t);let r={includeMetadataChanges:!1},s=0;"object"!=typeof n[s]||Gl(n[s])||(r=n[s],s++);var i={includeMetadataChanges:r.includeMetadataChanges};if(Gl(n[s])){const t=n[s];n[s]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[s+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[s+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,u;if(t instanceof Ol)o=kl(t.firestore,Ql),u=hi(t._key.path),a={next:e=>{n[s]&&n[s](gf(o,t,e))},error:n[s+1],complete:n[s+2]};else{const h=kl(t,Fl);o=kl(h.firestore,Ql),u=h._query;const c=new af(o);a={next:e=>{n[s]&&n[s](new qd(o,c,h,e))},error:n[s+1],complete:n[s+2]},Kd(t._query)}return function(e,t,n,r){const s=new ul(r),i=new Nc(t,s,n);return e.asyncQueue.enqueueAndForget(async()=>Ac(await Il(e),i)),()=>{s.Ia(),e.asyncQueue.enqueueAndForget(async()=>Dc(await Il(e),i))}}(Yl(o),u,i,a)}function df(e,t){return function(e,t){const n=new ul(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Eu.add(t),t.next()}(await Il(e),n)),()=>{n.Ia(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Eu.delete(t)}(await Il(e),n))}}(Yl(e=kl(e,Ql)),Gl(t)?t:{next:t})}function ff(e,t){return function(e,t){const n=new Cr;return e.asyncQueue.enqueueAndForget(async()=>Uc(await bl(e),t,n)),n.promise}(Yl(e),t)}function gf(e,t,n){var r=n.docs.get(t._key),s=new af(e);return new Pd(e,s,t._key,r,new Fd(n.hasPendingWrites,n.fromCache),t.converter)}class mf extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=gd(e)}get(e){const n=sf(e,this._firestore),r=new nf(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return Ar();const t=e[0];if(t.isFoundDocument())return new Ld(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new Ld(this._firestore,r,n._key,null,n.converter);throw Ar()})}set(e,t,n){var r=sf(e,this._firestore),s=tf(r.converter,t,n),s=md(this._dataReader,"Transaction.set",r._key,s,null!==r.converter,n);return this._transaction.set(r._key,s),this}update(e,t,n,...r){var s=sf(e,this._firestore),i="string"==typeof(t=m(t))||t instanceof sd?Td(this._dataReader,"Transaction.update",s._key,t,n,r):Ed(this._dataReader,"Transaction.update",s._key,t);return this._transaction.update(s._key,i),this}delete(e){var t=sf(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=sf(e,this._firestore),n=new af(this._firestore);return super.get(e).then(e=>new Pd(this._firestore,n,t._key,e._document,new Fd(!1,!1),t.converter))}}function pf(t,n){return function(t,n){const r=new Cr;return t.asyncQueue.enqueueAndForget(async()=>{var e=await pl(t).then(e=>e.datastore);new ll(t.asyncQueue,e,n,r).run()}),r.promise}(Yl(t=kl(t,Ql)),e=>n(new mf(t,e)))}zl=jf.SDK_VERSION,wr=zl,jf._registerComponent(new h("firestore",(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=new Ql(n,new Lr(e.getProvider("auth-internal")),new Pr(e.getProvider("app-check-internal")));return t=Object.assign({useFetchStreams:!0},t),r._setSettings(t),r},"PUBLIC")),jf.registerVersion(yr,"3.4.8",void 0),jf.registerVersion(yr,"3.4.8","esm2017");function yf(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new Nr("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function vf(){if("undefined"==typeof Uint8Array)throw new Nr("unimplemented","Uint8Arrays are not available in this environment.")}function wf(){if("undefined"==typeof atob)throw new Nr("unimplemented","Blobs are unavailable in Firestore in this environment.")}class bf{constructor(e){this._delegate=e}static fromBase64String(e){return wf(),new bf(id.fromBase64String(e))}static fromUint8Array(e){return vf(),new bf(id.fromUint8Array(e))}toBase64(){return wf(),this._delegate.toBase64()}toUint8Array(){return vf(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function If(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 Ef{enableIndexedDbPersistence(e,t){return function(e,t){rd(e=kl(e,Ql));var n=Yl(e),r=e._freezeSettings(),s=new al;return Jl(n,s,new sl(s,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){rd(e=kl(e,Ql));var t=Yl(e),n=e._freezeSettings(),r=new al;return Jl(t,r,new il(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new Nr(xr.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new Cr;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!Do.vt())return Promise.resolve();var t=e+"main";await Do.delete(t)}(nh(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class Tf{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof us||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||_r("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={}){Vl(this._delegate,e,t,n)}enableNetwork(){return ed(this._delegate)}disableNetwork(){return td(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,Dl("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 Zl(this._delegate)}onSnapshotsInSync(e){return df(this._delegate,e)}get app(){if(!this._appCompat)throw new Nr("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new Ff(this,Bl(this._delegate,e))}catch(e){throw Nf(e,"collection()","Firestore.collection()")}}doc(e){try{return new xf(this,ql(this._delegate,e))}catch(e){throw Nf(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new Lf(this,function(e,t){if(e=kl(e,Ll),Al("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new Nr(xr.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Fl(e,null,(t=t,new oi(Yr.emptyPath(),t)))}(this._delegate,e))}catch(e){throw Nf(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return pf(this._delegate,e=>t(new Sf(this,e)))}batch(){return Yl(this._delegate),new Af(new rf(this._delegate,e=>ff(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=Yl(t=kl(t,Ql)),r=new $l,_l(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return nd(this._delegate,e).then(e=>e?new Lf(this,e):null)}}class _f extends ef{constructor(e){super(),this.firestore=e}convertBytes(e){return new bf(new id(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return xf.forKey(t,this.firestore,null)}}class Sf{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new _f(e)}get(e){const t=Pf(e);return this._delegate.get(t).then(e=>new Mf(this._firestore,new Pd(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=Pf(e);return n?(yf("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var s=Pf(e);return 2===arguments.length?this._delegate.update(s,t):this._delegate.update(s,t,n,...r),this}delete(e){var t=Pf(e);return this._delegate.delete(t),this}}class Af{constructor(e){this._delegate=e}set(e,t,n){var r=Pf(e);return n?(yf("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var s=Pf(e);return 2===arguments.length?this._delegate.update(s,t):this._delegate.update(s,t,n,...r),this}delete(e){var t=Pf(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Df{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new Bd(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new Rf(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=Df.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let s=r.get(t);return s||(s=new Df(e,new _f(e),t),r.set(t,s)),s}}Df.INSTANCES=new WeakMap;class xf{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new _f(e)}static forPath(e,t,n){if(e.length%2!=0)throw new Nr("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new xf(t,new Ol(t._delegate,n,new ds(e)))}static forKey(e,t,n){return new xf(t,new Ol(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new Ff(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new Ff(this.firestore,Bl(this._delegate,e))}catch(e){throw Nf(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=m(e))instanceof Ol&&Ul(this._delegate,e)}set(e,t){t=yf("DocumentReference.set",t);try{return t?hf(this._delegate,e,t):hf(this._delegate,e)}catch(e){throw Nf(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?cf(this._delegate,e):cf(this._delegate,e,t,...n)}catch(e){throw Nf(e,"updateDoc()","DocumentReference.update()")}}delete(){return ff(kl((e=this._delegate).firestore,Ql),[new Xi(e._key,Bi.none())]);var e}onSnapshot(...e){var t=Cf(e),n=kf(e,e=>new Mf(this.firestore,new Pd(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return lf(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?of:"server"===(null==e?void 0:e.source)?function(t){t=kl(t,Ol);const n=kl(t.firestore,Ql);return El(Yl(n),t._key,{source:"server"}).then(e=>gf(n,t,e))}:function(t){t=kl(t,Ol);const n=kl(t.firestore,Ql);return El(Yl(n),t._key).then(e=>gf(n,t,e))})(this._delegate),t.then(e=>new Mf(this.firestore,new Pd(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new xf(this.firestore,e?this._delegate.withConverter(Df.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Nf(e,t,n){return e.message=e.message.replace(t,n),e}function Cf(e){for(const t of e)if("object"==typeof t&&!If(t))return t;return{}}function kf(e,t){var n;let r;return r=If(e[0])?e[0]:If(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 Mf{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new xf(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 Ud(this._delegate,e._delegate)}}class Rf extends Mf{data(e){var t=this._delegate.data(e);return void 0!==t||Ar(),t}}class Lf{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new _f(e)}where(e,t,n){try{return new Lf(this.firestore,Gd(this._delegate,(r=n,s=t,i=Od("where",e),new $d(i,s,r))))}catch(e){throw Nf(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,s,i}orderBy(e,t){try{return new Lf(this.firestore,Gd(this._delegate,([n,r="asc"]=[e,t],s=r,i=Od("orderBy",n),new zd(i,s))))}catch(e){throw Nf(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,s,i}limit(e){try{return new Lf(this.firestore,Gd(this._delegate,(Ml("limit",t=e),new Wd("limit",t,"F"))))}catch(e){throw Nf(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new Lf(this.firestore,Gd(this._delegate,(Ml("limitToLast",t=e),new Wd("limitToLast",t,"L"))))}catch(e){throw Nf(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new Lf(this.firestore,Gd(this._delegate,function(...e){return new Hd("startAt",e,!0)}(...e)))}catch(e){throw Nf(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new Lf(this.firestore,Gd(this._delegate,function(...e){return new Hd("startAfter",e,!1)}(...e)))}catch(e){throw Nf(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new Lf(this.firestore,Gd(this._delegate,function(...e){return new Qd("endBefore",e,!1)}(...e)))}catch(e){throw Nf(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new Lf(this.firestore,Gd(this._delegate,function(...e){return new Qd("endAt",e,!0)}(...e)))}catch(e){throw Nf(e,"endAt()","Query.endAt()")}}isEqual(e){return Kl(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?uf:"server"===(null==e?void 0:e.source)?function(t){t=kl(t,Fl);const n=kl(t.firestore,Ql),e=Yl(n),r=new af(n);return Tl(e,t._query,{source:"server"}).then(e=>new qd(n,r,t,e))}:function(t){t=kl(t,Fl);const n=kl(t.firestore,Ql),e=Yl(n),r=new af(n);return Kd(t._query),Tl(e,t._query).then(e=>new qd(n,r,t,e))})(this._delegate),t.then(e=>new Of(this.firestore,new qd(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=Cf(e),n=kf(e,e=>new Of(this.firestore,new qd(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return lf(this._delegate,t,n)}withConverter(e){return new Lf(this.firestore,e?this._delegate.withConverter(Df.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class Vf{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new Rf(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class Of{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new Lf(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 Rf(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new Vf(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new Rf(this._firestore,e))})}isEqual(e){return Ud(this._delegate,e._delegate)}}class Ff extends Lf{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 xf(this.firestore,e):null}doc(e){try{return void 0===e?new xf(this.firestore,ql(this._delegate)):new xf(this.firestore,ql(this._delegate,e))}catch(e){throw Nf(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=kl(e.firestore,Ql),r=ql(e),s=tf(e.converter,t);return ff(n,[md(gd(e.firestore),"addDoc",r._key,s,null!==e.converter,{}).toMutation(r._key,Bi.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new xf(this.firestore,e))}isEqual(e){return Ul(this._delegate,e._delegate)}withConverter(e){return new Ff(this.firestore,e?this._delegate.withConverter(Df.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Pf(e){return kl(e,Ol)}const Bf={Firestore:Tf,GeoPoint:od,Timestamp:Gr,Blob:bf,Transaction:Sf,WriteBatch:Af,DocumentReference:xf,DocumentSnapshot:Mf,Query:Lf,QueryDocumentSnapshot:Rf,QuerySnapshot:Of,CollectionReference:Ff,FieldPath:class qf{constructor(...e){this._delegate=new sd(...e)}static documentId(){return new qf(Jr.keyField().canonicalString())}isEqual(e){return(e=m(e))instanceof sd&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class Uf{constructor(e){this._delegate=e}static serverTimestamp(){const e=new vd("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new Uf(e)}static delete(){const e=new pd("deleteField");return e._methodName="FieldValue.delete",new Uf(e)}static arrayUnion(...e){const t=function(...e){return new wd("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new Uf(t)}static arrayRemove(...e){const t=function(...e){return new bd("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new Uf(t)}static increment(e){const t=new Id("increment",e);return t._methodName="FieldValue.increment",new Uf(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,br.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};Wl=t.default,Hl=(e,t)=>new Tf(e,t,new Ef),Wl.INTERNAL.registerComponent(new h("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return Hl(t,n)},"PUBLIC").setServiceProps(Object.assign({},Bf))),Wl.registerVersion("@firebase/firestore-compat","0.1.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.")}});
|
|
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(Kf,jf){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l,t=e(Kf);function n(t){const n=[];let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&s+1<t.length&&56320==(64512&t.charCodeAt(s+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++s)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}const r={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const s=[];for(let c=0;c<n.length;c+=3){var i=n[c],a=c+1<n.length,o=a?n[c+1]:0,u=c+2<n.length,h=u?n[c+2]:0;let e=(15&o)<<2|h>>6,t=63&h;u||(t=64,a||(e=64)),s.push(r[i>>2],r[(3&i)<<4|o>>4],r[e],r[t])}return s.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var s,i,a=e[n++];a<128?t[r++]=String.fromCharCode(a):191<a&&a<224?(s=e[n++],t[r++]=String.fromCharCode((31&a)<<6|63&s)):239<a&&a<365?(i=((7&a)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(i>>10)),t[r++]=String.fromCharCode(56320+(1023&i))):(s=e[n++],i=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&s)<<6|63&i))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let u=0;u<e.length;){var s=n[e.charAt(u++)],i=u<e.length?n[e.charAt(u)]:0;++u;var a=u<e.length?n[e.charAt(u)]:64;++u;var o=u<e.length?n[e.charAt(u)]:64;if(++u,null==s||null==i||null==a||null==o)throw Error();r.push(s<<2|i>>4),64!==a&&(r.push(i<<4&240|a>>2),64!==o&&r.push(a<<6&192|o))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}},a=function(e){return e=e,t=n(e),r.encodeByteArray(t,!0).replace(/\./g,"");var t};function f(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function s(){return!function(){try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return}}()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}class o extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,o.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,i.prototype.create)}}class i{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},s=`${this.service}/${e}`,i=this.errors[e],i=i?(r=n,i.replace(u,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",i=`${this.serviceName}: ${i} (${s}).`;return new o(s,i,n)}}const u=/\{\$([^}]+)}/g;function m(e){return e&&e._delegate?e._delegate:e}class h{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}}(zl=l=l||{})[zl.DEBUG=0]="DEBUG",zl[zl.VERBOSE=1]="VERBOSE",zl[zl.INFO=2]="INFO",zl[zl.WARN=3]="WARN",zl[zl.ERROR=4]="ERROR",zl[zl.SILENT=5]="SILENT";const c={debug:l.DEBUG,verbose:l.VERBOSE,info:l.INFO,warn:l.WARN,error:l.ERROR,silent:l.SILENT},d=l.INFO,g={[l.DEBUG]:"log",[l.VERBOSE]:"log",[l.INFO]:"info",[l.WARN]:"warn",[l.ERROR]:"error"},p=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),s=g[t];if(!s)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[s](`[${r}] ${e.name}:`,...n)}};var y,v="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},w={},b=v||self;function I(){}function E(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 T(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var _="closure_uid_"+(1e9*Math.random()>>>0),S=0;function A(e,t,n){return e.call.apply(e.bind,arguments)}function D(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 x(e,t,n){return(x=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?A:D).apply(null,arguments)}function N(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 C(e,i){function t(){}t.prototype=i.prototype,e.Z=i.prototype,e.prototype=new t,(e.prototype.constructor=e).Vb=function(e,t,n){for(var r=Array(arguments.length-2),s=2;s<arguments.length;s++)r[s-2]=arguments[s];return i.prototype[t].apply(e,r)}}function k(){this.s=this.s,this.o=this.o}var M={};k.prototype.s=!1,k.prototype.na=function(){var e,t;!this.s&&(this.s=!0,this.M(),0)&&(t=this,e=Object.prototype.hasOwnProperty.call(t,_)&&t[_]||(t[_]=++S),delete M[e])},k.prototype.M=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const R=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},L=Array.prototype.forEach?function(e,t,n){Array.prototype.forEach.call(e,t,n)}:function(e,t,n){var r=e.length,s="string"==typeof e?e.split(""):e;for(let i=0;i<r;i++)i in s&&t.call(n,s[i],i,e)};function V(){return Array.prototype.concat.apply([],arguments)}function O(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function F(e){return/^[\s\xa0]*$/.test(e)}var P,B=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]};function q(e,t){return-1!=e.indexOf(t)}function U(e,t){return e<t?-1:t<e?1:0}e:{var K=b.navigator;if(K){K=K.userAgent;if(K){P=K;break e}}P=""}function j(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function G(e){const t={};for(const n in e)t[n]=e[n];return t}var $="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function z(t){let n,r;for(let s=1;s<arguments.length;s++){for(n in r=arguments[s])t[n]=r[n];for(let e=0;e<$.length;e++)n=$[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function W(e){return W[" "](e),e}W[" "]=I;var Q,H=q(P,"Opera"),Y=q(P,"Trident")||q(P,"MSIE"),X=q(P,"Edge"),J=X||Y,Z=q(P,"Gecko")&&!(q(P.toLowerCase(),"webkit")&&!q(P,"Edge"))&&!(q(P,"Trident")||q(P,"MSIE"))&&!q(P,"Edge"),ee=q(P.toLowerCase(),"webkit")&&!q(P,"Edge");function te(){var e=b.document;return e?e.documentMode:void 0}e:{var ne="",re=(re=P,Z?/rv:([^\);]+)(\)|;)/.exec(re):X?/Edge\/([\d\.]+)/.exec(re):Y?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(re):ee?/WebKit\/(\S+)/.exec(re):H?/(?:Version)[ \/]?(\S+)/.exec(re):void 0);if(re&&(ne=re?re[1]:""),Y){re=te();if(null!=re&&re>parseFloat(ne)){Q=String(re);break e}}Q=ne}var se={};function ie(){return e=function(){let e=0;var t=B(String(Q)).split("."),n=B("9").split("."),r=Math.max(t.length,n.length);for(let a=0;0==e&&a<r;a++)for(var s=t[a]||"",i=n[a]||"";s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],i=/(\d*)(\D*)(.*)/.exec(i)||["","","",""],(0!=s[0].length||0!=i[0].length)&&(e=U(0==s[1].length?0:parseInt(s[1],10),0==i[1].length?0:parseInt(i[1],10))||U(0==s[2].length,0==i[2].length)||U(s[2],i[2]),s=s[3],i=i[3],0==e););return 0<=e},t=se,Object.prototype.hasOwnProperty.call(t,9)?t[9]:t[9]=e(9);var e,t}var ae=b.document&&Y&&(te()||parseInt(Q,10))||void 0,oe=function(){if(!b.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{b.addEventListener("test",I,t),b.removeEventListener("test",I,t)}catch(e){}return e}();function ue(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}function he(e,t){if(ue.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(Z){e:{try{W(t.nodeName);var s=!0;break e}catch(e){}s=!1}s||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:ce[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&he.Z.h.call(this)}}ue.prototype.h=function(){this.defaultPrevented=!0},C(he,ue);var ce={2:"touch",3:"pen",4:"mouse"};he.prototype.h=function(){he.Z.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var le="closure_listenable_"+(1e6*Math.random()|0),de=0;function fe(e,t,n,r,s){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ia=s,this.key=++de,this.ca=this.fa=!1}function ge(e){e.ca=!0,e.listener=null,e.proxy=null,e.src=null,e.ia=null}function me(e){this.src=e,this.g={},this.h=0}function pe(e,t){var n,r,s,i=t.type;i in e.g&&(n=e.g[i],(s=0<=(r=R(n,t)))&&Array.prototype.splice.call(n,r,1),s&&(ge(t),0==e.g[i].length&&(delete e.g[i],e.h--)))}function ye(e,t,n,r){for(var s=0;s<e.length;++s){var i=e[s];if(!i.ca&&i.listener==t&&i.capture==!!n&&i.ia==r)return s}return-1}me.prototype.add=function(e,t,n,r,s){var i=e.toString();(e=this.g[i])||(e=this.g[i]=[],this.h++);var a=ye(e,t,r,s);return-1<a?(t=e[a],n||(t.fa=!1)):((t=new fe(t,this.src,i,!!r,s)).fa=n,e.push(t)),t};var ve="closure_lm_"+(1e6*Math.random()|0),we={};function be(e,t,n,r,s){if(r&&r.once)return function e(t,n,r,s,i){if(Array.isArray(n)){for(var a=0;a<n.length;a++)e(t,n[a],r,s,i);return null}r=De(r);return t&&t[le]?t.O(n,r,T(s)?!!s.capture:!!s,i):Ie(t,n,r,!0,s,i)}(e,t,n,r,s);if(Array.isArray(t)){for(var i=0;i<t.length;i++)be(e,t[i],n,r,s);return null}return n=De(n),e&&e[le]?e.N(t,n,T(r)?!!r.capture:!!r,s):Ie(e,t,n,!1,r,s)}function Ie(e,t,n,r,s,i){if(!t)throw Error("Invalid event type");var a,o=T(s)?!!s.capture:!!s,u=Se(e);if(u||(e[ve]=u=new me(e)),(n=u.add(t,n,r,o,i)).proxy)return n;if(a=_e,r=function e(t){return a.call(e.src,e.listener,t)},(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(s=!oe?o:s)&&(s=!1),e.addEventListener(t.toString(),r,s);else if(e.attachEvent)e.attachEvent(Te(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function Ee(e){var t,n,r;"number"!=typeof e&&e&&!e.ca&&((t=e.src)&&t[le]?pe(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(Te(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=Se(t))?(pe(n,e),0==n.h&&(n.src=null,t[ve]=null)):ge(e)))}function Te(e){return e in we?we[e]:we[e]="on"+e}function _e(e,t){var n,r;return e=!!e.ca||(t=new he(t,this),n=e.listener,r=e.ia||e.src,e.fa&&Ee(e),n.call(r,t))}function Se(e){return(e=e[ve])instanceof me?e:null}var Ae="__closure_events_fn_"+(1e9*Math.random()>>>0);function De(t){return"function"==typeof t?t:(t[Ae]||(t[Ae]=function(e){return t.handleEvent(e)}),t[Ae])}function xe(){k.call(this),this.i=new me(this),(this.P=this).I=null}function Ne(e,t){var n,r=e.I;if(r)for(n=[];r;r=r.I)n.push(r);if(e=e.P,r=t.type||t,"string"==typeof t?t=new ue(t,e):t instanceof ue?t.target=t.target||e:(a=t,z(t=new ue(r,e),a)),a=!0,n)for(var s=n.length-1;0<=s;s--)var i=t.g=n[s],a=Ce(i,r,!0,t)&&a;if(a=Ce(i=t.g=e,r,!0,t)&&a,a=Ce(i,r,!1,t)&&a,n)for(s=0;s<n.length;s++)a=Ce(i=t.g=n[s],r,!1,t)&&a}function Ce(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var s=!0,i=0;i<t.length;++i){var a,o,u=t[i];u&&!u.ca&&u.capture==n&&(a=u.listener,o=u.ia||u.src,u.fa&&pe(e.i,u),s=!1!==a.call(o,r)&&s)}return s&&!r.defaultPrevented}C(xe,k),xe.prototype[le]=!0,xe.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,s,i){if(Array.isArray(n))for(var a=0;a<n.length;a++)e(t,n[a],r,s,i);else s=T(s)?!!s.capture:!!s,r=De(r),t&&t[le]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=ye(a=t.g[n],r,s,i))&&(ge(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete t.g[n],t.h--))):(t=t&&Se(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?ye(n,r,s,i):t)?n[t]:null)&&Ee(r))}(this,e,t,n,r)},xe.prototype.M=function(){if(xe.Z.M.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)ge(n[r]);delete t.g[e],t.h--}}this.I=null},xe.prototype.N=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},xe.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var ke=b.JSON.stringify;var Me,Re=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 Le,e=>e.reset());class Le{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function Ve(e,t){var n;Me||(n=b.Promise.resolve(void 0),Me=function(){n.then(Pe)}),Oe||(Me(),Oe=!0),Fe.add(e,t)}var Oe=!1,Fe=new class{constructor(){this.h=this.g=null}add(e,t){const n=Re.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function Pe(){for(var e;e=function(){var e=Fe;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){b.setTimeout(()=>{throw e},0)}(e)}var t=Re;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}Oe=!1}function Be(e,t){xe.call(this),this.h=e||1,this.g=t||b,this.j=x(this.kb,this),this.l=Date.now()}function qe(e){e.da=!1,e.S&&(e.g.clearTimeout(e.S),e.S=null)}function Ue(e,t,n){if("function"==typeof e)n&&(e=x(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=x(e.handleEvent,e)}return 2147483647<Number(t)?-1:b.setTimeout(e,t||0)}C(Be,xe),(y=Be.prototype).da=!1,y.S=null,y.kb=function(){var e;this.da&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.S=this.g.setTimeout(this.j,this.h-e):(this.S&&(this.g.clearTimeout(this.S),this.S=null),Ne(this,"tick"),this.da&&(qe(this),this.start())))},y.start=function(){this.da=!0,this.S||(this.S=this.g.setTimeout(this.j,this.h),this.l=Date.now())},y.M=function(){Be.Z.M.call(this),qe(this),delete this.g};class Ke extends k{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=Ue(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.j);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}M(){super.M(),this.g&&(b.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function je(e){k.call(this),this.h=e,this.g={}}C(je,k);var Ge=[];function $e(e,t,n,r){Array.isArray(n)||(n&&(Ge[0]=n.toString()),n=Ge);for(var s=0;s<n.length;s++){var i=be(t,n[s],r||e.handleEvent,!1,e.h||e);if(!i)break;e.g[i.key]=i}}function ze(e){j(e.g,function(e,t){this.g.hasOwnProperty(t)&&Ee(e)},e),e.g={}}function We(){this.g=!0}function Qe(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var s=r[1];if(Array.isArray(s)&&!(s.length<1)){var i=s[0];if("noop"!=i&&"stop"!=i&&"close"!=i)for(var a=1;a<s.length;a++)s[a]=""}}}return ke(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}je.prototype.M=function(){je.Z.M.call(this),ze(this)},je.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},We.prototype.Aa=function(){this.g=!1},We.prototype.info=function(){};var He={},Ye=null;function Xe(){return Ye=Ye||new xe}function Je(e){ue.call(this,He.Ma,e)}function Ze(){var e=Xe();Ne(e,new Je(e))}function et(e,t){ue.call(this,He.STAT_EVENT,e),this.stat=t}function tt(e){var t=Xe();Ne(t,new et(t,e))}function nt(e,t){ue.call(this,He.Na,e),this.size=t}function rt(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return b.setTimeout(function(){e()},t)}He.Ma="serverreachability",C(Je,ue),He.STAT_EVENT="statevent",C(et,ue),He.Na="timingevent",C(nt,ue);var st={NO_ERROR:0,lb:1,yb:2,xb:3,sb:4,wb:5,zb:6,Ja:7,TIMEOUT:8,Cb:9},it={qb:"complete",Mb:"success",Ka:"error",Ja:"abort",Eb:"ready",Fb:"readystatechange",TIMEOUT:"timeout",Ab:"incrementaldata",Db:"progress",tb:"downloadprogress",Ub:"uploadprogress"};function at(){}function ot(e){return e.h||(e.h=e.i())}function ut(){}at.prototype.h=null;v={OPEN:"a",pb:"b",Ka:"c",Bb:"d"};function ht(){ue.call(this,"d")}function ct(){ue.call(this,"c")}function lt(){}function dt(e,t,n,r){this.l=e,this.j=t,this.m=n,this.X=r||1,this.V=new je(this),this.P=mt,this.W=new Be(e=J?125:void 0),this.H=null,this.i=!1,this.s=this.A=this.v=this.K=this.F=this.Y=this.B=null,this.D=[],this.g=null,this.C=0,this.o=this.u=null,this.N=-1,this.I=!1,this.O=0,this.L=null,this.aa=this.J=this.$=this.U=!1,this.h=new ft}function ft(){this.i=null,this.g="",this.h=!1}C(ht,ue),C(ct,ue),C(lt,at),lt.prototype.g=function(){return new XMLHttpRequest},lt.prototype.i=function(){return{}};var gt=new lt,mt=45e3,pt={},yt={};function vt(e,t,n){e.K=1,e.v=qt(Lt(t)),e.s=n,e.U=!0,wt(e,null)}function wt(e,t){e.F=Date.now(),Et(e),e.A=Lt(e.v);var a,o,u,h,c,l,n=e.A,r=e.X;Array.isArray(r)||(r=[String(r)]),Zt(n.h,"t",r),e.C=0,n=e.l.H,e.h=new ft,e.g=er(e.l,n?t:null,!e.s),0<e.O&&(e.L=new Ke(x(e.Ia,e,e.g),e.O)),$e(e.V,e.g,"readystatechange",e.gb),t=e.H?G(e.H):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.s,t)):(e.u="GET",e.g.ea(e.A,e.u,null,t)),Ze(),a=e.j,o=e.u,u=e.A,h=e.m,c=e.X,l=e.s,a.info(function(){if(a.g)if(l)for(var e="",t=l.split("&"),n=0;n<t.length;n++){var r,s,i=t[n].split("=");1<i.length&&(r=i[0],i=i[1],e=2<=(s=r.split("_")).length&&"type"==s[1]?e+(r+"=")+i+"&":e+(r+"=redacted&"))}else e=null;else e=l;return"XMLHTTP REQ ("+h+") [attempt "+c+"]: "+o+"\n"+u+"\n"+e})}function bt(e){return e.g&&("GET"==e.u&&2!=e.K&&e.l.Ba)}function It(e,t,n){let r=!0,s;for(;!e.I&&e.C<n.length;){if(s=(a=n,u=o=void 0,o=(i=e).C,-1==(u=a.indexOf("\n",o))?yt:(o=Number(a.substring(o,u)),isNaN(o)?pt:(u+=1)+o>a.length?yt:(a=a.substr(u,o),i.C=u+o,a))),s==yt){4==t&&(e.o=4,tt(14),r=!1),Qe(e.j,e.m,null,"[Incomplete Response]");break}if(s==pt){e.o=4,tt(15),Qe(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}Qe(e.j,e.m,s,null),Dt(e,s)}var i,a,o,u;bt(e)&&s!=yt&&s!=pt&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,tt(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.aa&&(e.aa=!0,(t=e.l).g==e&&t.$&&!t.L&&(t.h.info("Great, no buffering proxy detected. Bytes received: "+n.length),zn(t),t.L=!0,tt(11))):(Qe(e.j,e.m,n,"[Invalid Chunked Response]"),At(e),St(e))}function Et(e){e.Y=Date.now()+e.P,Tt(e,e.P)}function Tt(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=rt(x(e.eb,e),t)}function _t(e){e.B&&(b.clearTimeout(e.B),e.B=null)}function St(e){0==e.l.G||e.I||Hn(e.l,e)}function At(e){_t(e);var t=e.L;t&&"function"==typeof t.na&&t.na(),e.L=null,qe(e.W),ze(e.V),e.g&&(t=e.g,e.g=null,t.abort(),t.na())}function Dt(e,t){try{var n=e.l;if(0!=n.G&&(n.g==e||on(n.i,e)))if(n.I=e.N,!e.J&&on(n.i,e)&&3==n.G){try{var r=n.Ca.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var s=r;if(0==s[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;Qn(n),Fn(n)}$n(n),tt(18)}}else n.ta=s[1],0<n.ta-n.U&&s[2]<37500&&n.N&&0==n.A&&!n.v&&(n.v=rt(x(n.ab,n),6e3));if(an(n.i)<=1&&n.ka){try{n.ka()}catch(e){}n.ka=void 0}}else Xn(n,11)}else if(!e.J&&n.g!=e||Qn(n),!F(t))for(s=n.Ca.g.parse(t),t=0;t<s.length;t++){var i=s[t];if(n.U=i[0],i=i[1],2==n.G)if("c"==i[0]){n.J=i[1],n.la=i[2];var a=i[3];null!=a&&(n.ma=a,n.h.info("VER="+n.ma));var o=i[4];null!=o&&(n.za=o,n.h.info("SVER="+n.za));var u,h,c,l=i[5];null!=l&&"number"==typeof l&&0<l&&(r=1.5*l,n.K=r,n.h.info("backChannelRequestTimeoutMs_="+r)),r=n;const m=e.g;m&&(!(u=m.g?m.g.getResponseHeader("X-Client-Wire-Protocol"):null)||!(h=r.i).g&&(q(u,"spdy")||q(u,"quic")||q(u,"h2"))&&(h.j=h.l,h.g=new Set,h.h&&(un(h,h.h),h.h=null)),!r.D||(c=m.g?m.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.sa=c,Bt(r.F,r.D,c))),n.G=3,n.j&&n.j.xa(),n.$&&(n.O=Date.now()-e.F,n.h.info("Handshake RTT: "+n.O+"ms"));var d,f,g=e;(r=n).oa=Zn(r,r.H?r.la:null,r.W),g.J?(hn(r.i,g),d=g,(f=r.K)&&d.setTimeout(f),d.B&&(_t(d),Et(d)),r.g=g):Gn(r),0<n.l.length&&qn(n)}else"stop"!=i[0]&&"close"!=i[0]||Xn(n,7);else 3==n.G&&("stop"==i[0]||"close"==i[0]?"stop"==i[0]?Xn(n,7):On(n):"noop"!=i[0]&&n.j&&n.j.wa(i),n.A=0)}Ze()}catch(e){}}function xt(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(E(e)||"string"==typeof e)L(e,t,void 0);else{if(e.T&&"function"==typeof e.T)var n=e.T();else if(e.R&&"function"==typeof e.R)n=void 0;else if(E(e)||"string"==typeof e)for(var n=[],r=e.length,s=0;s<r;s++)n.push(s);else for(s in n=[],r=0,e)n[r++]=s;for(var s=(r=function(e){if(e.R&&"function"==typeof e.R)return e.R();if("string"==typeof e)return e.split("");if(E(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)).length,i=0;i<s;i++)t.call(void 0,r[i],n&&n[i],e)}}function Nt(e,t){this.h={},this.g=[],this.i=0;var n=arguments.length;if(1<n){if(n%2)throw Error("Uneven number of arguments");for(var r=0;r<n;r+=2)this.set(arguments[r],arguments[r+1])}else if(e)if(e instanceof Nt)for(n=e.T(),r=0;r<n.length;r++)this.set(n[r],e.get(n[r]));else for(r in e)this.set(r,e[r])}function Ct(e){if(e.i!=e.g.length){for(var t=0,n=0;t<e.g.length;){var r=e.g[t];kt(e.h,r)&&(e.g[n++]=r),t++}e.g.length=n}if(e.i!=e.g.length){for(var s={},n=t=0;t<e.g.length;)kt(s,r=e.g[t])||(s[e.g[n++]=r]=1),t++;e.g.length=n}}function kt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(y=dt.prototype).setTimeout=function(e){this.P=e},y.gb=function(e){e=e.target;const t=this.L;t&&3==kn(e)?t.l():this.Ia(e)},y.Ia=function(e){try{if(e==this.g)e:{var t=kn(this.g),n=this.g.Da();this.g.ba();if(!(t<3)&&(3!=t||J||this.g&&(this.h.h||this.g.ga()||Mn(this.g)))){this.I||4!=t||7==n||Ze(),_t(this);var r=this.g.ba();this.N=r;t:if(bt(this)){var s=Mn(this.g);e="";var i=s.length,a=4==kn(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){At(this),St(this);var o="";break t}this.h.i=new b.TextDecoder}for(n=0;n<i;n++)this.h.h=!0,e+=this.h.i.decode(s[n],{stream:a&&n==i-1});s.splice(0,i),this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.ga();if(this.i=200==r,l=this.j,d=this.u,f=this.A,g=this.m,m=this.X,p=t,y=r,l.info(function(){return"XMLHTTP RESP ("+g+") [ attempt "+m+"]: "+d+"\n"+f+"\n"+p+" "+y}),this.i){if(this.$&&!this.J){t:{if(this.g){var u,h=this.g;if((u=h.g?h.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!F(u)){var c=u;break t}}c=null}if(!(r=c)){this.i=!1,this.o=3,tt(12),At(this),St(this);break e}Qe(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.J=!0,Dt(this,r)}this.U?(It(this,t,o),J&&this.i&&3==t&&($e(this.V,this.W,"tick",this.fb),this.W.start())):(Qe(this.j,this.m,o,null),Dt(this,o)),4==t&&At(this),this.i&&!this.I&&(4==t?Hn(this.l,this):(this.i=!1,Et(this)))}else 400==r&&0<o.indexOf("Unknown SID")?(this.o=3,tt(12)):(this.o=0,tt(13)),At(this),St(this)}}}catch(e){}var l,d,f,g,m,p,y},y.fb=function(){var e,t;this.g&&(e=kn(this.g),t=this.g.ga(),this.C<t.length&&(_t(this),It(this,e,t),this.i&&4!=e&&Et(this)))},y.cancel=function(){this.I=!0,At(this)},y.eb=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.K&&(Ze(),tt(17)),At(this),this.o=2,St(this)):Tt(this,this.Y-n)},(y=Nt.prototype).R=function(){Ct(this);for(var e=[],t=0;t<this.g.length;t++)e.push(this.h[this.g[t]]);return e},y.T=function(){return Ct(this),this.g.concat()},y.get=function(e,t){return kt(this.h,e)?this.h[e]:t},y.set=function(e,t){kt(this.h,e)||(this.i++,this.g.push(e)),this.h[e]=t},y.forEach=function(e,t){for(var n=this.T(),r=0;r<n.length;r++){var s=n[r],i=this.get(s);e.call(t,i,s,this)}};var Mt=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function Rt(e,t){var n;this.i=this.s=this.j="",this.m=null,this.o=this.l="",this.g=!1,e instanceof Rt?(this.g=void 0!==t?t:e.g,Vt(this,e.j),this.s=e.s,Ot(this,e.i),Ft(this,e.m),this.l=e.l,t=e.h,(n=new Ht).i=t.i,t.g&&(n.g=new Nt(t.g),n.h=t.h),Pt(this,n),this.o=e.o):e&&(n=String(e).match(Mt))?(this.g=!!t,Vt(this,n[1]||"",!0),this.s=Ut(n[2]||""),Ot(this,n[3]||"",!0),Ft(this,n[4]),this.l=Ut(n[5]||"",!0),Pt(this,n[6]||"",!0),this.o=Ut(n[7]||"")):(this.g=!!t,this.h=new Ht(null,this.g))}function Lt(e){return new Rt(e)}function Vt(e,t,n){e.j=n?Ut(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Ot(e,t,n){e.i=n?Ut(t,!0):t}function Ft(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 Pt(e,t,n){var r,s;t instanceof Ht?(e.h=t,r=e.h,(s=e.g)&&!r.j&&(Yt(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(Xt(this,t),Zt(this,n,e))},r)),r.j=s):(n||(t=Kt(t,Wt)),e.h=new Ht(t,e.g))}function Bt(e,t,n){e.h.set(t,n)}function qt(e){return Bt(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Ut(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Kt(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,jt),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function jt(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}Rt.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Kt(t,Gt,!0),":");var n=this.i;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(Kt(t,Gt,!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.i&&"/"!=n.charAt(0)&&e.push("/"),e.push(Kt(n,"/"==n.charAt(0)?zt:$t,!0))),(n=this.h.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Kt(n,Qt)),e.join("")};var Gt=/[#\/\?@]/g,$t=/[#\?:]/g,zt=/[#\?]/g,Wt=/[#\?@]/g,Qt=/#/g;function Ht(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function Yt(n){n.g||(n.g=new Nt,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,s=e[n].indexOf("="),i=null;0<=s?(r=e[n].substring(0,s),i=e[n].substring(s+1)):r=e[n],t(r,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function Xt(e,t){Yt(e),t=en(e,t),kt(e.g.h,t)&&(e.i=null,e.h-=e.g.get(t).length,kt((e=e.g).h,t)&&(delete e.h[t],e.i--,e.g.length>2*e.i&&Ct(e)))}function Jt(e,t){return Yt(e),t=en(e,t),kt(e.g.h,t)}function Zt(e,t,n){Xt(e,t),0<n.length&&(e.i=null,e.g.set(en(e,t),O(n)),e.h+=n.length)}function en(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(y=Ht.prototype).add=function(e,t){Yt(this),this.i=null,e=en(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},y.forEach=function(n,r){Yt(this),this.g.forEach(function(e,t){L(e,function(e){n.call(r,e,t,this)},this)},this)},y.T=function(){Yt(this);for(var e=this.g.R(),t=this.g.T(),n=[],r=0;r<t.length;r++)for(var s=e[r],i=0;i<s.length;i++)n.push(t[r]);return n},y.R=function(e){Yt(this);var t=[];if("string"==typeof e)Jt(this,e)&&(t=V(t,this.g.get(en(this,e))));else{e=this.g.R();for(var n=0;n<e.length;n++)t=V(t,e[n])}return t},y.set=function(e,t){return Yt(this),this.i=null,Jt(this,e=en(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},y.get=function(e,t){return e&&0<(e=this.R(e)).length?String(e[0]):t},y.toString=function(){if(this.i)return this.i;if(!this.g)return"";for(var e=[],t=this.g.T(),n=0;n<t.length;n++)for(var r=t[n],s=encodeURIComponent(String(r)),r=this.R(r),i=0;i<r.length;i++){var a=s;""!==r[i]&&(a+="="+encodeURIComponent(String(r[i]))),e.push(a)}return this.i=e.join("&")};var tn=class{constructor(e,t){this.h=e,this.g=t}};function nn(e){this.l=e||10,e=b.PerformanceNavigationTiming?0<(e=b.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(b.g&&b.g.Ea&&b.g.Ea()&&b.g.Ea().Zb),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}var rn;function sn(e){return e.h||e.g&&e.g.size>=e.j}function an(e){return e.h?1:e.g?e.g.size:0}function on(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function un(e,t){e.g?e.g.add(t):e.h=t}function hn(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function cn(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return O(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function ln(){}function dn(){this.g=new ln}function fn(e,t,n,r,s){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,s(r)}catch(e){}}function gn(e){this.l=e.$b||null,this.j=e.ib||!1}function mn(e,t){xe.call(this),this.D=e,this.u=t,this.m=void 0,this.readyState=pn,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}nn.prototype.cancel=function(){if(this.i=cn(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()}},ln.prototype.stringify=function(e){return b.JSON.stringify(e,void 0)},ln.prototype.parse=function(e){return b.JSON.parse(e,void 0)},C(gn,at),gn.prototype.g=function(){return new mn(this.l,this.j)},gn.prototype.i=(rn={},function(){return rn}),C(mn,xe);var pn=0;function yn(e){e.j.read().then(e.Sa.bind(e)).catch(e.ha.bind(e))}function vn(e){e.readyState=4,e.l=null,e.j=null,e.A=null,wn(e)}function wn(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(y=mn.prototype).open=function(e,t){if(this.readyState!=pn)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,wn(this)},y.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||b).fetch(new Request(this.B,t)).then(this.Va.bind(this),this.ha.bind(this))},y.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted."),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,vn(this)),this.readyState=pn},y.Va=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,wn(this)),this.g&&(this.readyState=3,wn(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ta.bind(this),this.ha.bind(this));else if(void 0!==b.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;yn(this)}else e.text().then(this.Ua.bind(this),this.ha.bind(this))},y.Sa=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?vn:wn)(this),3==this.readyState&&yn(this))},y.Ua=function(e){this.g&&(this.response=this.responseText=e,vn(this))},y.Ta=function(e){this.g&&(this.response=e,vn(this))},y.ha=function(){this.g&&vn(this)},y.setRequestHeader=function(e,t){this.v.append(e,t)},y.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},y.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(mn.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var bn=b.JSON.parse;function In(e){xe.call(this),this.headers=new Nt,this.u=e||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=En,this.K=this.L=!1}C(In,xe);var En="",Tn=/^https?$/i,_n=["POST","PUT"];function Sn(e){return"content-type"==e.toLowerCase()}function An(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,Dn(e),Nn(e)}function Dn(e){e.D||(e.D=!0,Ne(e,"complete"),Ne(e,"error"))}function xn(e){if(e.h&&void 0!==w&&(!e.C[1]||4!=kn(e)||2!=e.ba()))if(e.v&&4==kn(e))Ue(e.Fa,0,e);else if(Ne(e,"readystatechange"),4==kn(e)){e.h=!1;try{var t,n,r,s,i=e.ba();e:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var a=!0;break e;default:a=!1}if((t=a)||((n=0===i)&&(!(s=String(e.H).match(Mt)[1]||null)&&b.self&&b.self.location&&(s=(r=b.self.location.protocol).substr(0,r.length-1)),n=!Tn.test(s?s.toLowerCase():"")),t=n),t)Ne(e,"complete"),Ne(e,"success");else{e.m=6;try{var o=2<kn(e)?e.g.statusText:""}catch(e){o=""}e.j=o+" ["+e.ba()+"]",Dn(e)}}finally{Nn(e)}}}function Nn(e,t){if(e.g){Cn(e);const n=e.g,r=e.C[0]?I:null;e.g=null,e.C=null,t||Ne(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Cn(e){e.g&&e.K&&(e.g.ontimeout=null),e.A&&(b.clearTimeout(e.A),e.A=null)}function kn(e){return e.g?e.g.readyState:0}function Mn(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.J){case En:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Rn(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=function(e){let n="";return j(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):Bt(e,t,n))}function Ln(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function Vn(e){this.za=0,this.l=[],this.h=new We,this.la=this.oa=this.F=this.W=this.g=this.sa=this.D=this.aa=this.o=this.P=this.s=null,this.Za=this.V=0,this.Xa=Ln("failFast",!1,e),this.N=this.v=this.u=this.m=this.j=null,this.X=!0,this.I=this.ta=this.U=-1,this.Y=this.A=this.C=0,this.Pa=Ln("baseRetryDelayMs",5e3,e),this.$a=Ln("retryDelaySeedMs",1e4,e),this.Ya=Ln("forwardChannelMaxRetries",2,e),this.ra=Ln("forwardChannelRequestTimeoutMs",2e4,e),this.qa=e&&e.xmlHttpFactory||void 0,this.Ba=e&&e.Yb||!1,this.K=void 0,this.H=e&&e.supportsCrossDomainXhr||!1,this.J="",this.i=new nn(e&&e.concurrentRequestLimit),this.Ca=new dn,this.ja=e&&e.fastHandshake||!1,this.Ra=e&&e.Wb||!1,e&&e.Aa&&this.h.Aa(),e&&e.forceLongPolling&&(this.X=!1),this.$=!this.ja&&this.X&&e&&e.detectBufferingProxy||!1,this.ka=void 0,this.O=0,this.L=!1,this.B=null,this.Wa=!e||!1!==e.Xb}function On(e){var t,n;Pn(e),3==e.G&&(t=e.V++,Bt(n=Lt(e.F),"SID",e.J),Bt(n,"RID",t),Bt(n,"TYPE","terminate"),Kn(e,n),(t=new dt(e,e.h,t,void 0)).K=2,t.v=qt(Lt(n)),n=!1,!(n=b.navigator&&b.navigator.sendBeacon?b.navigator.sendBeacon(t.v.toString(),""):n)&&b.Image&&((new Image).src=t.v,n=!0),n||(t.g=er(t.l,null),t.g.ea(t.v)),t.F=Date.now(),Et(t)),Jn(e)}function Fn(e){e.g&&(zn(e),e.g.cancel(),e.g=null)}function Pn(e){Fn(e),e.u&&(b.clearTimeout(e.u),e.u=null),Qn(e),e.i.cancel(),e.m&&("number"==typeof e.m&&b.clearTimeout(e.m),e.m=null)}function Bn(e,t){e.l.push(new tn(e.Za++,t)),3==e.G&&qn(e)}function qn(e){sn(e.i)||e.m||(e.m=!0,Ve(e.Ha,e),e.C=0)}function Un(e,t){var n=t?t.m:e.V++,r=Lt(e.F);Bt(r,"SID",e.J),Bt(r,"RID",n),Bt(r,"AID",e.U),Kn(e,r),e.o&&e.s&&Rn(r,e.o,e.s),n=new dt(e,e.h,n,e.C+1),null===e.o&&(n.H=e.s),t&&(e.l=t.D.concat(e.l)),t=jn(e,n,1e3),n.setTimeout(Math.round(.5*e.ra)+Math.round(.5*e.ra*Math.random())),un(e.i,n),vt(n,r,t)}function Kn(e,n){e.j&&xt({},function(e,t){Bt(n,t,e)})}function jn(e,t,r){r=Math.min(e.l.length,r);var s=e.j?x(e.j.Oa,e.j,e):null;e:{var i=e.l;let n=-1;for(;;){const u=["count="+r];-1==n?0<r?(n=i[0].h,u.push("ofs="+n)):n=0:u.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var a=i[t].h,o=i[t].g;if((a-=n)<0)n=Math.max(0,i[t].h-100),e=!1;else try{!function(e,r,t){const s=t||"";try{xt(e,function(e,t){let n=e;T(e)&&(n=ke(e)),r.push(s+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(s+"type="+encodeURIComponent("_badmap")),e}}(o,u,"req"+a+"_")}catch(e){s&&s(o)}}if(e){s=u.join("&");break e}}}return e=e.l.splice(0,r),t.D=e,s}function Gn(e){e.g||e.u||(e.Y=1,Ve(e.Ga,e),e.A=0)}function $n(e){return!(e.g||e.u||3<=e.A)&&(e.Y++,e.u=rt(x(e.Ga,e),Yn(e,e.A)),e.A++,1)}function zn(e){null!=e.B&&(b.clearTimeout(e.B),e.B=null)}function Wn(e){e.g=new dt(e,e.h,"rpc",e.Y),null===e.o&&(e.g.H=e.s),e.g.O=0;var t=Lt(e.oa);Bt(t,"RID","rpc"),Bt(t,"SID",e.J),Bt(t,"CI",e.N?"0":"1"),Bt(t,"AID",e.U),Kn(e,t),Bt(t,"TYPE","xmlhttp"),e.o&&e.s&&Rn(t,e.o,e.s),e.K&&e.g.setTimeout(e.K);var n=e.g;e=e.la,n.K=1,n.v=qt(Lt(t)),n.s=null,n.U=!0,wt(n,e)}function Qn(e){null!=e.v&&(b.clearTimeout(e.v),e.v=null)}function Hn(e,t){var n,r,s,i=null;if(e.g==t){Qn(e),zn(e),e.g=null;var a=2}else{if(!on(e.i,t))return;i=t.D,hn(e.i,t),a=1}if(e.I=t.N,0!=e.G)if(t.i)1==a?(i=t.s?t.s.length:0,t=Date.now()-t.F,n=e.C,Ne(a=Xe(),new nt(a,i)),qn(e)):Gn(e);else if(3==(n=t.o)||0==n&&0<e.I||(1!=a||(s=t,an((r=e).i)>=r.i.j-(r.m?1:0)||(r.m?(r.l=s.D.concat(r.l),0):1==r.G||2==r.G||r.C>=(r.Xa?0:r.Ya)||(r.m=rt(x(r.Ha,r,s),Yn(r,r.C)),r.C++,0))))&&(2!=a||!$n(e)))switch(i&&0<i.length&&(t=e.i,t.i=t.i.concat(i)),n){case 1:Xn(e,5);break;case 4:Xn(e,10);break;case 3:Xn(e,6);break;default:Xn(e,2)}}function Yn(e,t){let n=e.Pa+Math.floor(Math.random()*e.$a);return e.j||(n*=2),n*t}function Xn(e,t){var n,r;e.h.info("Error code "+t),2==t?(n=null,e.j&&(n=null),r=x(e.jb,e),n||(n=new Rt("//www.google.com/images/cleardot.gif"),b.location&&"http"==b.location.protocol||Vt(n,"https"),qt(n)),function(e,t){var n=new We;if(b.Image){const r=new Image;r.onload=N(fn,n,r,"TestLoadImage: loaded",!0,t),r.onerror=N(fn,n,r,"TestLoadImage: error",!1,t),r.onabort=N(fn,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=N(fn,n,r,"TestLoadImage: timeout",!1,t),b.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):tt(2),e.G=0,e.j&&e.j.va(t),Jn(e),Pn(e)}function Jn(e){e.G=0,e.I=-1,e.j&&(0==cn(e.i).length&&0==e.l.length||(e.i.i.length=0,O(e.l),e.l.length=0),e.j.ua())}function Zn(e,t,n){let r=(o=n)instanceof Rt?Lt(o):new Rt(o,void 0);var s,i,a,o,u;return""!=r.i?(t&&Ot(r,t+"."+r.i),Ft(r,r.m)):(u=b.location,r=(s=u.protocol,i=t?t+"."+u.hostname:u.hostname,a=+u.port,o=n,u=new Rt(null,void 0),s&&Vt(u,s),i&&Ot(u,i),a&&Ft(u,a),o&&(u.l=o),u)),e.aa&&j(e.aa,function(e,t){Bt(r,t,e)}),t=e.D,n=e.sa,t&&n&&Bt(r,t,n),Bt(r,"VER",e.ma),Kn(e,r),r}function er(e,t,n){if(t&&!e.H)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ba&&!e.qa?new In(new gn({ib:!0})):new In(e.qa)).L=e.H,t}function tr(){}function nr(){if(Y&&!(10<=Number(ae)))throw Error("Environmental error: no available transport.")}function rr(e,t){xe.call(this),this.g=new Vn(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.s=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.ya&&(e?e["X-WebChannel-Client-Profile"]=t.ya:e={"X-WebChannel-Client-Profile":t.ya}),this.g.P=e,(e=t&&t.httpHeadersOverwriteParam)&&!F(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!F(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new ar(this)}function sr(e){ht.call(this);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function ir(){ct.call(this),this.status=1}function ar(e){this.g=e}(y=In.prototype).ea=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.H+"; newUri="+e);t=t?t.toUpperCase():"GET",this.H=e,this.j="",this.m=0,this.D=!1,this.h=!0,this.g=(this.u||gt).g(),this.C=this.u?ot(this.u):ot(gt),this.g.onreadystatechange=x(this.Fa,this);try{this.F=!0,this.g.open(t,String(e),!0),this.F=!1}catch(e){return void An(this,e)}e=n||"";const s=new Nt(this.headers);r&&xt(r,function(e,t){s.set(t,e)}),r=function(t){e:{var n=Sn,r=t.length,s="string"==typeof t?t.split(""):t;for(let e=0;e<r;e++)if(e in s&&n.call(void 0,s[e],e,t)){n=e;break e}n=-1}return n<0?null:"string"==typeof t?t.charAt(n):t[n]}(s.T()),n=b.FormData&&e instanceof b.FormData,0<=R(_n,t)&&!r&&!n&&s.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),s.forEach(function(e,t){this.g.setRequestHeader(t,e)},this),this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{Cn(this),0<this.B&&((this.K=(i=this.g,Y&&ie()&&"number"==typeof i.timeout&&void 0!==i.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=x(this.pa,this)):this.A=Ue(this.pa,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){An(this,e)}var i},y.pa=function(){void 0!==w&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,Ne(this,"timeout"),this.abort(8))},y.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,Ne(this,"complete"),Ne(this,"abort"),Nn(this))},y.M=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),Nn(this,!0)),In.Z.M.call(this)},y.Fa=function(){this.s||(this.F||this.v||this.l?xn(this):this.cb())},y.cb=function(){xn(this)},y.ba=function(){try{return 2<kn(this)?this.g.status:-1}catch(e){return-1}},y.ga=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},y.Qa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),bn(t)}},y.Da=function(){return this.m},y.La=function(){return"string"==typeof this.j?this.j:String(this.j)},(y=Vn.prototype).ma=8,y.G=1,y.hb=function(e){try{this.h.info("Origin Trials invoked: "+e)}catch(e){}},y.Ha=function(t){if(this.m)if(this.m=null,1==this.G){if(!t){this.V=Math.floor(1e5*Math.random()),t=this.V++;const i=new dt(this,this.h,t,void 0);let e=this.s;if(this.P&&(e?(e=G(e),z(e,this.P)):e=this.P),null===this.o&&(i.H=e),this.ja)e:{for(var n=0,r=0;r<this.l.length;r++){var s=this.l[r];if("__data__"in s.g&&"string"==typeof(s=s.g.__data__)?s=s.length:s=void 0,void 0===s)break;if(4096<(n+=s)){n=r;break e}if(4096===n||r===this.l.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=jn(this,i,n),Bt(r=Lt(this.F),"RID",t),Bt(r,"CVER",22),this.D&&Bt(r,"X-HTTP-Session-Id",this.D),Kn(this,r),this.o&&e&&Rn(r,this.o,e),un(this.i,i),this.Ra&&Bt(r,"TYPE","init"),this.ja?(Bt(r,"$req",n),Bt(r,"SID","null"),i.$=!0,vt(i,r,null)):vt(i,r,n),this.G=2}}else 3==this.G&&(t?Un(this,t):0==this.l.length||sn(this.i)||Un(this))},y.Ga=function(){var e;this.u=null,Wn(this),this.$&&!(this.L||null==this.g||this.O<=0)&&(e=2*this.O,this.h.info("BP detection timer enabled: "+e),this.B=rt(x(this.bb,this),e))},y.bb=function(){this.B&&(this.B=null,this.h.info("BP detection timeout reached."),this.h.info("Buffering proxy detected and switch to long-polling!"),this.N=!1,this.L=!0,tt(10),Fn(this),Wn(this))},y.ab=function(){null!=this.v&&(this.v=null,Fn(this),$n(this),tt(19))},y.jb=function(e){e?(this.h.info("Successfully pinged google.com"),tt(2)):(this.h.info("Failed to ping google.com"),tt(1))},(y=tr.prototype).xa=function(){},y.wa=function(){},y.va=function(){},y.ua=function(){},y.Oa=function(){},nr.prototype.g=function(e,t){return new rr(e,t)},C(rr,xe),rr.prototype.m=function(){this.g.j=this.j,this.A&&(this.g.H=!0);var e=this.g,t=this.l,n=this.h||void 0;e.Wa&&(e.h.info("Origin Trials enabled."),Ve(x(e.hb,e,t))),tt(0),e.W=t,e.aa=n||{},e.N=e.X,e.F=Zn(e,null,e.W),qn(e)},rr.prototype.close=function(){On(this.g)},rr.prototype.u=function(e){var t;"string"==typeof e?((t={}).__data__=e,Bn(this.g,t)):this.v?((t={}).__data__=ke(e),Bn(this.g,t)):Bn(this.g,e)},rr.prototype.M=function(){this.g.j=null,delete this.j,On(this.g),delete this.g,rr.Z.M.call(this)},C(sr,ht),C(ir,ct),C(ar,tr),ar.prototype.xa=function(){Ne(this.g,"a")},ar.prototype.wa=function(e){Ne(this.g,new sr(e))},ar.prototype.va=function(e){Ne(this.g,new ir)},ar.prototype.ua=function(){Ne(this.g,"b")},nr.prototype.createWebChannel=nr.prototype.g,rr.prototype.send=rr.prototype.u,rr.prototype.open=rr.prototype.m,st.NO_ERROR=0,st.TIMEOUT=8,st.HTTP_ERROR=6,it.COMPLETE="complete",(ut.EventType=v).OPEN="a",v.CLOSE="b",v.ERROR="c",v.MESSAGE="d",xe.prototype.listen=xe.prototype.N,In.prototype.listenOnce=In.prototype.O,In.prototype.getLastError=In.prototype.La,In.prototype.getLastErrorCode=In.prototype.Da,In.prototype.getStatus=In.prototype.ba,In.prototype.getResponseJson=In.prototype.Qa,In.prototype.getResponseText=In.prototype.ga,In.prototype.send=In.prototype.ea;var or,ur=Xe,hr=st,cr=it,lr=He,dr=10,fr=11,gr=gn,mr=ut,pr=In;const yr="@firebase/firestore";class vr{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}}vr.UNAUTHENTICATED=new vr(null),vr.GOOGLE_CREDENTIALS=new vr("google-credentials-uid"),vr.FIRST_PARTY=new vr("first-party-uid"),vr.MOCK_USER=new vr("mock-user");let wr="9.7.0";const br=new class{constructor(e){this.name=e,this._logLevel=d,this._logHandler=p,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?c[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 Ir(){return br.logLevel}function Er(e,...t){var n;br.logLevel<=l.DEBUG&&(n=t.map(Sr),br.debug(`Firestore (${wr}): ${e}`,...n))}function Tr(e,...t){var n;br.logLevel<=l.ERROR&&(n=t.map(Sr),br.error(`Firestore (${wr}): ${e}`,...n))}function _r(e,...t){var n;br.logLevel<=l.WARN&&(n=t.map(Sr),br.warn(`Firestore (${wr}): ${e}`,...n))}function Sr(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function Ar(e="Unexpected state"){var t=`FIRESTORE (${wr}) INTERNAL ASSERTION FAILED: `+e;throw Tr(t),new Error(t)}function Dr(e){e||Ar()}const xr={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 Nr extends o{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class Cr{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class kr{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Mr{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(vr.UNAUTHENTICATED))}shutdown(){}}class Rr{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 Lr{constructor(e){this.t=e,this.currentUser=vr.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const s=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let i=new Cr;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new Cr,t.enqueueRetryable(()=>s(this.currentUser))};const a=()=>{const e=i;t.enqueueRetryable(async()=>{await e.promise,await s(this.currentUser)})},o=e=>{Er("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):(Er("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new Cr))},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?(Er("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(Dr("string"==typeof e.accessToken),new kr(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 Dr(null===e||"string"==typeof e),new vr(e)}}class Vr{constructor(e,t,n){this.type="FirstParty",this.user=vr.FIRST_PARTY,this.headers=new Map,this.headers.set("X-Goog-AuthUser",t);var r=e.auth.getAuthHeaderValueForFirstParty([]);r&&this.headers.set("Authorization",r),n&&this.headers.set("X-Goog-Iam-Authorization-Token",n)}}class Or{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new Vr(this.h,this.l,this.m))}start(e,t){e.enqueueRetryable(()=>t(vr.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Fr{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 Pr{constructor(e){this.g=e,this.forceRefresh=!1,this.appCheck=null,this.p=null}start(t,n){const r=e=>{null!=e.error&&Er("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.p;return this.p=e.token,Er("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const s=e=>{Er("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.g.onInit(e=>s(e)),setTimeout(()=>{var e;this.appCheck||((e=this.g.getImmediate({optional:!0}))?s(e):Er("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(Dr("string"==typeof e.token),this.p=e.token,new Fr(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class Br{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.I(e),this.T=e=>t.writeSequenceNumber(e))}I(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.T&&this.T(e),e}}Br.A=-1;class qr{static R(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var s=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<s.length;++e)r.length<20&&s[e]<n&&(r+=t.charAt(s[e]%t.length))}return r}}function Ur(e,t){return e<t?-1:t<e?1:0}function Kr(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function jr(e){return e+"\0"}class Gr{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new Nr(xr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new Nr(xr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new Nr(xr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new Nr(xr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return Gr.fromMillis(Date.now())}static fromDate(e){return Gr.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new Gr(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Ur(this.nanoseconds,e.nanoseconds):Ur(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 $r{constructor(e){this.timestamp=e}static fromTimestamp(e){return new $r(e)}static min(){return new $r(new Gr(0,0))}static max(){return new $r(new Gr(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}}function zr(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function Wr(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function Qr(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class Hr{constructor(e,t,n){void 0===t?t=0:t>e.length&&Ar(),void 0===n?n=e.length-t:n>e.length-t&&Ar(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===Hr.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof Hr?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),s=t.get(r);if(n<s)return-1;if(n>s)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class Yr extends Hr{construct(e,t,n){return new Yr(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 Nr(xr.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new Yr(t)}static emptyPath(){return new Yr([])}}const Xr=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Jr extends Hr{construct(e,t,n){return new Jr(e,t,n)}static isValidIdentifier(e){return Xr.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!Jr.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new Jr(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var s=()=>{if(0===n.length)throw new Nr(xr.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let i=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new Nr(xr.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new Nr(xr.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?i=!i:"."!==t||i?n+=t:s(),r++}if(s(),i)throw new Nr(xr.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Jr(t)}static emptyPath(){return new Jr([])}}class Zr{constructor(e){(this.fields=e).sort(Jr.comparator)}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Kr(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class es{constructor(e){this.binaryString=e}static fromBase64String(e){var t=atob(e);return new es(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 es(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 Ur(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}es.EMPTY_BYTE_STRING=new es("");const ts=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function ns(t){if(Dr(!!t),"string"!=typeof t)return{seconds:rs(t.seconds),nanos:rs(t.nanos)};{let e=0;var n=ts.exec(t);Dr(!!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 rs(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function ss(e){return"string"==typeof e?es.fromBase64String(e):es.fromUint8Array(e)}function is(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 as(e){var t=ns(e.mapValue.fields.__local_write_time__.timestampValue);return new Gr(t.seconds,t.nanos)}class os{constructor(e,t,n,r,s,i,a,o){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=s,this.forceLongPolling=i,this.autoDetectLongPolling=a,this.useFetchStreams=o}}class us{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new us("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof us&&e.projectId===this.projectId&&e.database===this.database}}function hs(e){return null==e}function cs(e){return 0===e&&1/e==-1/0}function ls(e){return"number"==typeof e&&Number.isInteger(e)&&!cs(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}class ds{constructor(e){this.path=e}static fromPath(e){return new ds(Yr.fromString(e))}static fromName(e){return new ds(Yr.fromString(e).popFirst(5))}static empty(){return new ds(Yr.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===Yr.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return Yr.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new ds(new Yr(e.slice()))}}const fs={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},gs={nullValue:"NULL_VALUE"};function ms(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?is(e)?4:xs(e)?9007199254740991:10:Ar()}function ps(r,s){if(r===s)return!0;var e,t,n=ms(r);if(n!==ms(s))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===s.booleanValue;case 4:return as(r).isEqual(as(s));case 3:return function(e){if("string"==typeof r.timestampValue&&"string"==typeof e.timestampValue&&r.timestampValue.length===e.timestampValue.length)return r.timestampValue===e.timestampValue;var t=ns(r.timestampValue),n=ns(e.timestampValue);return t.seconds===n.seconds&&t.nanos===n.nanos}(s);case 5:return r.stringValue===s.stringValue;case 6:return t=s,ss(r.bytesValue).isEqual(ss(t.bytesValue));case 7:return r.referenceValue===s.referenceValue;case 8:return e=s,rs((t=r).geoPointValue.latitude)===rs(e.geoPointValue.latitude)&&rs(t.geoPointValue.longitude)===rs(e.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return rs(e.integerValue)===rs(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=rs(e.doubleValue),r=rs(t.doubleValue);return n===r?cs(n)===cs(r):isNaN(n)&&isNaN(r)}return!1}(r,s);case 9:return Kr(r.arrayValue.values||[],s.arrayValue.values||[],ps);case 10:return function(e){const t=e.mapValue.fields||{},n=s.mapValue.fields||{};if(zr(t)!==zr(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!ps(t[e],n[e])))return!1;return!0}(r);default:return Ar()}}function ys(e,t){return void 0!==(e.values||[]).find(e=>ps(e,t))}function vs(e,t){if(e===t)return 0;var n,r,s,i,a=ms(e),o=ms(t);if(a!==o)return Ur(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return Ur(e.booleanValue,t.booleanValue);case 2:return r=t,s=rs(e.integerValue||e.doubleValue),i=rs(r.integerValue||r.doubleValue),s<i?-1:i<s?1:s===i?0:isNaN(s)?isNaN(i)?0:-1:1;case 3:return ws(e.timestampValue,t.timestampValue);case 4:return ws(as(e),as(t));case 5:return Ur(e.stringValue,t.stringValue);case 6:return function(e,t){const n=ss(e),r=ss(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let s=0;s<n.length&&s<r.length;s++){const t=Ur(n[s],r[s]);if(0!==t)return t}return Ur(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(i=Ur(rs(n.latitude),rs(r.latitude)))?i:Ur(rs(n.longitude),rs(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let s=0;s<n.length&&s<r.length;++s){const t=vs(n[s],r[s]);if(t)return t}return Ur(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===fs.mapValue&&t===fs.mapValue)return 0;if(e===fs.mapValue)return 1;if(t===fs.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),s=t.fields||{},i=Object.keys(s);r.sort(),i.sort();for(let o=0;o<r.length&&o<i.length;++o){const t=Ur(r[o],i[o]);if(0!==t)return t;var a=vs(n[r[o]],s[i[o]]);if(0!==a)return a}return Ur(r.length,i.length)}(e.mapValue,t.mapValue);default:throw Ar()}}function ws(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Ur(e,t);var n=ns(e),r=ns(t),s=Ur(n.seconds,r.seconds);return 0!==s?s:Ur(n.nanos,r.nanos)}function bs(e){return function i(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=ns(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?ss(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,ds.fromName(t).toString()):"geoPointValue"in e?`geo(${(t=e.geoPointValue).latitude},${t.longitude})`:"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=i(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const s of t)r?r=!1:n+=",",n+=`${s}:${i(e.fields[s])}`;return n+"}"}(e.mapValue):Ar();var t}(e)}function Is(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Es(e){return e&&"integerValue"in e}function Ts(e){return!!e&&"arrayValue"in e}function _s(e){return e&&"nullValue"in e}function Ss(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function As(e){return e&&"mapValue"in e}function Ds(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 Wr(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=Ds(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Ds(t.arrayValue.values[e]);return r}return Object.assign({},t)}function xs(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Ns(e,t){var n=vs(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Cs(e,t){var n=vs(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class ks{constructor(e){this.value=e}static empty(){return new ks({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)],!As(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Ds(t)}setAll(e){let n=Jr.emptyPath(),r={},s=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,s),r={},s=[],n=t.popLast()}e?r[t.lastSegment()]=Ds(e):s.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,s)}delete(e){const t=this.field(e.popLast());As(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return ps(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)];As(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){Wr(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new ks(Ds(this.value))}}class Ms{constructor(e,t,n,r,s,i){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.data=s,this.documentState=i}static newInvalidDocument(e){return new Ms(e,0,$r.min(),$r.min(),ks.empty(),0)}static newFoundDocument(e,t,n){return new Ms(e,1,t,$r.min(),n,0)}static newNoDocument(e,t){return new Ms(e,2,t,$r.min(),ks.empty(),0)}static newUnknownDocument(e,t){return new Ms(e,3,t,$r.min(),ks.empty(),2)}convertToFoundDocument(e,t){return this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=ks.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=ks.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,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 Ms&&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 Ms(this.key,this.documentType,this.version,this.readTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Rs{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function Ls(e){return e.fields.find(e=>2===e.kind)}function Vs(e){return e.fields.filter(e=>2!==e.kind)}Rs.UNKNOWN_ID=-1;class Os{constructor(e,t){this.fieldPath=e,this.kind=t}}class Fs{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new Fs(0,Bs.min())}}function Ps(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=$r.fromTimestamp(1e9===r?new Gr(n+1,0):new Gr(n,r));return new Bs(r,ds.empty(),t)}class Bs{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new Bs($r.min(),ds.empty(),-1)}static max(){return new Bs($r.max(),ds.empty(),-1)}}function qs(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=ds.comparator(e.documentKey,t.documentKey),0!==n?n:Ur(e.largestBatchId,t.largestBatchId))}class Us{constructor(e,t){this.comparator=e,this.root=t||js.EMPTY}insert(e,t){return new Us(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,js.BLACK,null,null))}remove(e){return new Us(this.comparator,this.root.remove(e,this.comparator).copy(null,null,js.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 Ks(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new Ks(this.root,e,this.comparator,!1)}getReverseIterator(){return new Ks(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new Ks(this.root,e,this.comparator,!0)}}class Ks{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,t&&r&&(s*=-1),s<0)e=this.isReverse?e.left:e.right;else{if(0===s){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class js{constructor(e,t,n,r,s){this.key=e,this.value=t,this.color=null!=n?n:js.RED,this.left=null!=r?r:js.EMPTY,this.right=null!=s?s:js.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,s){return new js(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=s?s:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var s=n(e,r.key);return r=s<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===s?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return js.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 js.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,js.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,js.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 Ar();if(this.right.isRed())throw Ar();var e=this.left.check();if(e!==this.right.check())throw Ar();return e+(this.isRed()?0:1)}}js.EMPTY=null,js.RED=!0,js.BLACK=!1,js.EMPTY=new class{constructor(){this.size=0}get key(){throw Ar()}get value(){throw Ar()}get color(){throw Ar()}get left(){throw Ar()}get right(){throw Ar()}copy(e,t,n,r,s){return this}insert(e,t,n){return new js(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 Gs{constructor(e){this.comparator=e,this.data=new Us(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 $s(this.data.getIterator())}getIteratorFrom(e){return new $s(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 Gs))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 Gs(this.comparator);return t.data=e,t}}class $s{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function zs(e){return e.hasNext()?e.getNext():void 0}class Ws{constructor(e,t=null,n=[],r=[],s=null,i=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=s,this.startAt=i,this.endAt=a,this.P=null}}function Qs(e,t=null,n=[],r=[],s=null,i=null,a=null){return new Ws(e,t,n,r,s,i,a)}function Hs(e){const t=e;if(null===t.P){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>{return(t=e).field.canonicalString()+t.op.toString()+bs(t.value);var t}).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),hs(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>bs(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>bs(e)).join(",")),t.P=e}return t.P}function Ys(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let a=0;a<e.orderBy.length;a++)if(n=e.orderBy[a],r=t.orderBy[a],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r,s,i;if(e.filters.length!==t.filters.length)return!1;for(let o=0;o<e.filters.length;o++)if(s=e.filters[o],i=t.filters[o],s.op!==i.op||!s.field.isEqual(i.field)||!ps(s.value,i.value))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!fi(e.startAt,t.startAt)&&fi(e.endAt,t.endAt)}function Xs(e){return ds.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Js(e,t){return e.filters.filter(e=>e instanceof ti&&e.field.isEqual(t))}function Zs(t,n,r){let s=gs,i=!0;for(const r of Js(t,n)){let e=gs,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?gs:"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?Is(us.empty(),ds.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:Ar();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=gs}Ns({value:s,inclusive:i},{value:e,inclusive:t})<0&&(s=e,i=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Ns({value:s,inclusive:i},{value:t,inclusive:r.inclusive})<0&&(s=t,i=r.inclusive);break}return{value:s,inclusive:i}}function ei(t,n,r){let s=fs,i=!0;for(const r of Js(t,n)){let e=fs,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?Is(us.empty(),ds.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?fs:Ar(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=fs}0<Cs({value:s,inclusive:i},{value:e,inclusive:t})&&(s=e,i=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];0<Cs({value:s,inclusive:i},{value:t,inclusive:r.inclusive})&&(s=t,i=r.inclusive);break}return{value:s,inclusive:i}}class ti extends class{}{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.V(e,t,n):new ni(e,t,n):"array-contains"===t?new ai(e,n):"in"===t?new oi(e,n):"not-in"===t?new ui(e,n):"array-contains-any"===t?new hi(e,n):new ti(e,t,n)}static V(e,t,n){return new("in"===t?ri:si)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.v(vs(t,this.value)):null!==t&&ms(this.value)===ms(t)&&this.v(vs(t,this.value))}v(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 Ar()}}S(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}}class ni extends ti{constructor(e,t,n){super(e,t,n),this.key=ds.fromName(n.referenceValue)}matches(e){var t=ds.comparator(e.key,this.key);return this.v(t)}}class ri extends ti{constructor(e,t){super(e,"in",t),this.keys=ii(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class si extends ti{constructor(e,t){super(e,"not-in",t),this.keys=ii(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function ii(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>ds.fromName(e.referenceValue))}class ai extends ti{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return Ts(t)&&ys(t.arrayValue,this.value)}}class oi extends ti{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&ys(this.value.arrayValue,t)}}class ui extends ti{constructor(e,t){super(e,"not-in",t)}matches(e){if(ys(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!ys(this.value.arrayValue,t)}}class hi extends ti{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Ts(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>ys(this.value.arrayValue,e))}}class ci{constructor(e,t){this.position=e,this.inclusive=t}}class li{constructor(e,t="asc"){this.field=e,this.dir=t}}function di(e,t,n){let r=0;for(let s=0;s<e.position.length;s++){const i=t[s],a=e.position[s];if(r=i.field.isKeyField()?ds.comparator(ds.fromName(a.referenceValue),n.key):vs(a,n.data.field(i.field)),"desc"===i.dir&&(r*=-1),0!==r)break}return r}function fi(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(!ps(e.position[n],t.position[n]))return!1;return!0}class gi{constructor(e,t=null,n=[],r=[],s=null,i="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=s,this.limitType=i,this.startAt=a,this.endAt=o,this.D=null,this.C=null,this.startAt,this.endAt}}function mi(e,t,n,r,s,i,a,o){return new gi(e,t,n,r,s,i,a,o)}function pi(e){return new gi(e)}function yi(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function vi(e){for(const t of e.filters)if(t.S())return t.field;return null}function wi(e){return null!==e.collectionGroup}function bi(t){const n=t;if(null===n.D){n.D=[];const t=vi(n),e=yi(n);if(null!==t&&null===e)t.isKeyField()||n.D.push(new li(t)),n.D.push(new li(Jr.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.D.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.D.push(new li(Jr.keyField(),t))}}}return n.D}function Ii(e){const t=e;if(!t.C)if("F"===t.limitType)t.C=Qs(t.path,t.collectionGroup,bi(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const s of bi(t)){const t="desc"===s.dir?"asc":"desc";e.push(new li(s.field,t))}var n=t.endAt?new ci(t.endAt.position,t.endAt.inclusive):null,r=t.startAt?new ci(t.startAt.position,t.startAt.inclusive):null;t.C=Qs(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.C}function Ei(e,t,n){return new gi(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Ti(e,t){return Ys(Ii(e),Ii(t))&&e.limitType===t.limitType}function _i(e){return`${Hs(Ii(e))}|lt:${e.limitType}`}function Si(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=>{return`${(t=e).field.canonicalString()} ${t.op} ${bs(t.value)}`;var t}).join(", ")}]`),hs(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=>bs(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>bs(e)).join(",")),`Target(${t})`}(Ii(e))}; limitType=${e.limitType})`}function Ai(n,e){return e.isFoundDocument()&&(s=n,a=(i=e).key.path,null!==s.collectionGroup?i.key.hasCollectionId(s.collectionGroup)&&s.path.isPrefixOf(a):ds.isDocumentKey(s.path)?s.path.isEqual(a):s.path.isImmediateParentOf(a))&&function(e){for(const t of n.explicitOrderBy)if(!t.field.isKeyField()&&null===e.data.field(t.field))return;return 1}(e)&&function(e){for(const t of n.filters)if(!t.matches(e))return;return 1}(e)&&(s=e,(!(e=n).startAt||(t=e.startAt,r=di(t,bi(e),s),t.inclusive?r<=0:r<0))&&(!e.endAt||(t=e.endAt,r=di(t,bi(e),s),t.inclusive?0<=r:0<r)));var t,r,s,i,a}function Di(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function xi(s){return(e,t)=>{let n=!1;for(const r of bi(s)){const s=function(e,s,t){var n=e.field.isKeyField()?ds.comparator(s.key,t.key):function(e,t){var n=s.data.field(e),r=t.data.field(e);return null!==n&&null!==r?vs(n,r):Ar()}(e.field,t);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return Ar()}}(r,e,t);if(0!==s)return s;n=n||r.field.isKeyField()}return 0}}function Ni(e,t){if(e.N){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:cs(t)?"-0":t}}function Ci(e){return{integerValue:""+e}}function ki(e,t){return ls(t)?Ci(t):Ni(e,t)}class Mi{constructor(){this._=void 0}}function Ri(e,t){return e instanceof Bi?Es(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class Li extends Mi{}class Vi extends Mi{constructor(e){super(),this.elements=e}}function Oi(e,t){const n=Ui(t);for(const t of e.elements)n.some(e=>ps(e,t))||n.push(t);return{arrayValue:{values:n}}}class Fi extends Mi{constructor(e){super(),this.elements=e}}function Pi(e,t){let n=Ui(t);for(const t of e.elements)n=n.filter(e=>!ps(e,t));return{arrayValue:{values:n}}}class Bi extends Mi{constructor(e,t){super(),this.M=e,this.k=t}}function qi(e){return rs(e.integerValue||e.doubleValue)}function Ui(e){return Ts(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class Ki{constructor(e,t){this.field=e,this.transform=t}}class ji{constructor(e,t){this.version=e,this.transformResults=t}}class Gi{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Gi}static exists(e){return new Gi(void 0,e)}static updateTime(e){return new Gi(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 $i(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class zi{}function Wi(e,t,n){e instanceof Xi?function(e,t,n){const r=e.value.clone(),s=ea(e.fieldTransforms,t,n.transformResults);r.setAll(s),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Ji?function(e,t,n){if(!$i(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=ea(e.fieldTransforms,t,n.transformResults),s=t.data;s.setAll(Zi(e)),s.setAll(r),t.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function Qi(e,t,n){e instanceof Xi?function(e,t,n){if($i(e.precondition,t)){const r=e.value.clone(),s=ta(e.fieldTransforms,n,t);r.setAll(s),t.convertToFoundDocument(Yi(t),r).setHasLocalMutations()}}(e,t,n):e instanceof Ji?function(e,t,n){if($i(e.precondition,t)){const r=ta(e.fieldTransforms,n,t),s=t.data;s.setAll(Zi(e)),s.setAll(r),t.convertToFoundDocument(Yi(t),s).setHasLocalMutations()}}(e,t,n):(t=t,$i(e.precondition,t)&&t.convertToNoDocument($r.min()))}function Hi(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&&Kr(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof Vi&&t instanceof Vi||e instanceof Fi&&t instanceof Fi?Kr(e.elements,t.elements,ps):e instanceof Bi&&t instanceof Bi?ps(e.k,t.k):e instanceof Li&&t instanceof Li)}(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}function Yi(e){return e.isFoundDocument()?e.version:$r.min()}class Xi extends zi{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}}class Ji extends zi{constructor(e,t,n,r,s=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=s,this.type=1}}function Zi(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 ea(e,t,n){const r=new Map;Dr(e.length===n.length);for(let c=0;c<n.length;c++){var s=e[c],i=s.transform,a=t.data.field(s.field);r.set(s.field,(o=i,u=a,h=n[c],o instanceof Vi?Oi(o,u):o instanceof Fi?Pi(o,u):h))}var o,u,h;return r}function ta(e,t,n){const r=new Map;for(const h of e){const e=h.transform,c=n.data.field(h.field);r.set(h.field,(s=e,i=c,a=t,u=o=void 0,s instanceof Li?function(){const e={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:a.seconds,nanos:a.nanoseconds}}}};return i&&(e.fields.__previous_value__=i),{mapValue:e}}():s instanceof Vi?Oi(s,i):s instanceof Fi?Pi(s,i):(o=Ri(s=s,i),u=qi(o)+qi(s.k),Es(o)&&Es(s.k)?Ci(u):Ni(s.M,u))))}var s,i,a,o,u;return r}class na extends zi{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}}class ra extends zi{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}}class sa{constructor(e){this.count=e}}function ia(e){switch(e){default:return Ar(),0;case xr.CANCELLED:case xr.UNKNOWN:case xr.DEADLINE_EXCEEDED:case xr.RESOURCE_EXHAUSTED:case xr.INTERNAL:case xr.UNAVAILABLE:case xr.UNAUTHENTICATED:return;case xr.INVALID_ARGUMENT:case xr.NOT_FOUND:case xr.ALREADY_EXISTS:case xr.PERMISSION_DENIED:case xr.FAILED_PRECONDITION:case xr.ABORTED:case xr.OUT_OF_RANGE:case xr.UNIMPLEMENTED:case xr.DATA_LOSS:return 1}}function aa(e){if(void 0===e)return Tr("GRPC error has no .code"),xr.UNKNOWN;switch(e){case or.OK:return xr.OK;case or.CANCELLED:return xr.CANCELLED;case or.UNKNOWN:return xr.UNKNOWN;case or.DEADLINE_EXCEEDED:return xr.DEADLINE_EXCEEDED;case or.RESOURCE_EXHAUSTED:return xr.RESOURCE_EXHAUSTED;case or.INTERNAL:return xr.INTERNAL;case or.UNAVAILABLE:return xr.UNAVAILABLE;case or.UNAUTHENTICATED:return xr.UNAUTHENTICATED;case or.INVALID_ARGUMENT:return xr.INVALID_ARGUMENT;case or.NOT_FOUND:return xr.NOT_FOUND;case or.ALREADY_EXISTS:return xr.ALREADY_EXISTS;case or.PERMISSION_DENIED:return xr.PERMISSION_DENIED;case or.FAILED_PRECONDITION:return xr.FAILED_PRECONDITION;case or.ABORTED:return xr.ABORTED;case or.OUT_OF_RANGE:return xr.OUT_OF_RANGE;case or.UNIMPLEMENTED:return xr.UNIMPLEMENTED;case or.DATA_LOSS:return xr.DATA_LOSS;default:return Ar()}}(it=or=or||{})[it.OK=0]="OK",it[it.CANCELLED=1]="CANCELLED",it[it.UNKNOWN=2]="UNKNOWN",it[it.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",it[it.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",it[it.NOT_FOUND=5]="NOT_FOUND",it[it.ALREADY_EXISTS=6]="ALREADY_EXISTS",it[it.PERMISSION_DENIED=7]="PERMISSION_DENIED",it[it.UNAUTHENTICATED=16]="UNAUTHENTICATED",it[it.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",it[it.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",it[it.ABORTED=10]="ABORTED",it[it.OUT_OF_RANGE=11]="OUT_OF_RANGE",it[it.UNIMPLEMENTED=12]="UNIMPLEMENTED",it[it.INTERNAL=13]="INTERNAL",it[it.UNAVAILABLE=14]="UNAVAILABLE",it[it.DATA_LOSS=15]="DATA_LOSS";class oa{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let s=0;s<r.length;s++)if(this.equalsFn(r[s][0],e))return void(r[s]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(r){Wr(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return Qr(this.inner)}size(){return this.innerSize}}const ua=new Us(ds.comparator);const ha=new Us(ds.comparator);function ca(...e){let t=ha;for(const n of e)t=t.insert(n.key,n);return t}function la(){return new oa(e=>e.toString(),(e,t)=>e.isEqual(t))}const da=new Us(ds.comparator),fa=new Gs(ds.comparator);function ga(...e){let t=fa;for(const n of e)t=t.add(n);return t}const ma=new Gs(Ur);class pa{constructor(e,t,n,r,s){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=s}static createSynthesizedRemoteEventForCurrentChange(e,t){const n=new Map;return n.set(e,ya.createSynthesizedTargetChangeForCurrentChange(e,t)),new pa($r.min(),n,ma,ua,ga())}}class ya{constructor(e,t,n,r,s){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=s}static createSynthesizedTargetChangeForCurrentChange(e,t){return new ya(es.EMPTY_BYTE_STRING,t,ga(),ga(),ga())}}class va{constructor(e,t,n,r){this.O=e,this.removedTargetIds=t,this.key=n,this.F=r}}class wa{constructor(e,t){this.targetId=e,this.$=t}}class ba{constructor(e,t,n=es.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class Ia{constructor(){this.B=0,this.L=_a(),this.U=es.EMPTY_BYTE_STRING,this.q=!1,this.K=!0}get current(){return this.q}get resumeToken(){return this.U}get G(){return 0!==this.B}get j(){return this.K}W(e){0<e.approximateByteSize()&&(this.K=!0,this.U=e)}H(){let n=ga(),r=ga(),s=ga();return this.L.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:s=s.add(e);break;default:Ar()}}),new ya(this.U,this.q,n,r,s)}J(){this.K=!1,this.L=_a()}Y(e,t){this.K=!0,this.L=this.L.insert(e,t)}X(e){this.K=!0,this.L=this.L.remove(e)}Z(){this.B+=1}tt(){--this.B}et(){this.K=!0,this.q=!0}}class Ea{constructor(e){this.nt=e,this.st=new Map,this.it=ua,this.rt=Ta(),this.ot=new Gs(Ur)}ut(e){for(const t of e.O)e.F&&e.F.isFoundDocument()?this.at(t,e.F):this.ct(t,e.key,e.F);for(const n of e.removedTargetIds)this.ct(n,e.key,e.F)}ht(n){this.forEachTarget(n,e=>{const t=this.lt(e);switch(n.state){case 0:this.ft(e)&&t.W(n.resumeToken);break;case 1:t.tt(),t.G||t.J(),t.W(n.resumeToken);break;case 2:t.tt(),t.G||this.removeTarget(e);break;case 3:this.ft(e)&&(t.et(),t.W(n.resumeToken));break;case 4:this.ft(e)&&(this.dt(e),t.W(n.resumeToken));break;default:Ar()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.st.forEach((e,t)=>{this.ft(t)&&n(t)})}_t(e){const t=e.targetId,n=e.$.count,r=this.wt(t);if(r){const e=r.target;if(Xs(e))if(0===n){const n=new ds(e.path);this.ct(t,n,Ms.newNoDocument(n,$r.min()))}else Dr(1===n);else this.gt(t)!==n&&(this.dt(t),this.ot=this.ot.add(t))}}yt(r){const s=new Map;this.st.forEach((e,t)=>{var n=this.wt(t);if(n){if(e.current&&Xs(n.target)){const s=new ds(n.target.path);null!==this.it.get(s)||this.It(t,s)||this.ct(t,s,Ms.newNoDocument(s,r))}e.j&&(s.set(t,e.H()),e.J())}});let i=ga();this.rt.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.wt(e);return!t||2===t.purpose||(n=!1)}),n&&(i=i.add(e))}),this.it.forEach((e,t)=>t.setReadTime(r));var e=new pa(r,s,this.ot,this.it,i);return this.it=ua,this.rt=Ta(),this.ot=new Gs(Ur),e}at(e,t){var n;this.ft(e)&&(n=this.It(e,t.key)?2:0,this.lt(e).Y(t.key,n),this.it=this.it.insert(t.key,t),this.rt=this.rt.insert(t.key,this.Tt(t.key).add(e)))}ct(e,t,n){if(this.ft(e)){const r=this.lt(e);this.It(e,t)?r.Y(t,1):r.X(t),this.rt=this.rt.insert(t,this.Tt(t).delete(e)),n&&(this.it=this.it.insert(t,n))}}removeTarget(e){this.st.delete(e)}gt(e){var t=this.lt(e).H();return this.nt.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Z(e){this.lt(e).Z()}lt(e){let t=this.st.get(e);return t||(t=new Ia,this.st.set(e,t)),t}Tt(e){let t=this.rt.get(e);return t||(t=new Gs(Ur),this.rt=this.rt.insert(e,t)),t}ft(e){var t=null!==this.wt(e);return t||Er("WatchChangeAggregator","Detected inactive target",e),t}wt(e){var t=this.st.get(e);return t&&t.G?null:this.nt.Et(e)}dt(t){this.st.set(t,new Ia),this.nt.getRemoteKeysForTarget(t).forEach(e=>{this.ct(t,e,null)})}It(e,t){return this.nt.getRemoteKeysForTarget(e).has(t)}}function Ta(){return new Us(ds.comparator)}function _a(){return new Us(ds.comparator)}const Sa={asc:"ASCENDING",desc:"DESCENDING"},Aa={"<":"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"};class Da{constructor(e,t){this.databaseId=e,this.N=t}}function xa(e,t){return e.N?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function Na(e,t){return e.N?t.toBase64():t.toUint8Array()}function Ca(e){return Dr(!!e),$r.fromTimestamp((t=ns(e),new Gr(t.seconds,t.nanos)));var t}function ka(e,t){return e=e,new Yr(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function Ma(e){var t=Yr.fromString(e);return Dr(Ya(t)),t}function Ra(e,t){return ka(e.databaseId,t.path)}function La(e,t){const n=Ma(t);if(n.get(1)!==e.databaseId.projectId)throw new Nr(xr.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 Nr(xr.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new ds(Pa(n))}function Va(e,t){return ka(e.databaseId,t)}function Oa(e){var t=Ma(e);return 4===t.length?Yr.emptyPath():Pa(t)}function Fa(e){return new Yr(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function Pa(e){return Dr(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function Ba(e,t,n){return{name:Ra(e,t),fields:n.value.mapValue.fields}}function qa(e,t,n){const r=La(e,t.name),s=Ca(t.updateTime),i=new ks({mapValue:{fields:t.fields}}),a=Ms.newFoundDocument(r,s,i);return n&&a.setHasCommittedMutations(),n?a.setHasCommittedMutations():a}function Ua(e,t){let n;if(t instanceof Xi)n={update:Ba(e,t.key,t.value)};else if(t instanceof na)n={delete:Ra(e,t.key)};else if(t instanceof Ji)n={update:Ba(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 ra))return Ar();n={verify:Ra(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof Li)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof Vi)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof Fi)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof Bi)return{fieldPath:e.field.canonicalString(),increment:t.k};throw Ar()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,xa(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:Ar()),n;var r}function Ka(t,n){const e=n.currentDocument?void 0!==(s=n.currentDocument).updateTime?Gi.updateTime(Ca(s.updateTime)):void 0!==s.exists?Gi.exists(s.exists):Gi.none():Gi.none(),r=n.updateTransforms?n.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)Dr("REQUEST_TIME"===t.setToServerValue),n=new Li;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new Vi(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new Fi(e)}else"increment"in t?n=new Bi(e,t.increment):Ar();var r=Jr.fromServerFormat(t.fieldPath);return new Ki(r,n)}(t,e)):[];var s;if(n.update){n.update.name;var i=La(t,n.update.name),a=new ks({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new Zr(e.map(e=>Jr.fromServerFormat(e)))}();return new Ji(i,a,t,e,r)}return new Xi(i,a,e,r)}if(n.delete){const r=La(t,n.delete);return new na(r,e)}if(n.verify){const r=La(t,n.verify);return new ra(r,e)}return Ar()}function ja(e,t){return{documents:[Va(e,t.path)]}}function Ga(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=Va(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=Va(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var s=function(e){if(0!==e.length){var t=e.map(e=>function(e){if("=="===e.op){if(Ss(e.value))return{unaryFilter:{field:za(e.field),op:"IS_NAN"}};if(_s(e.value))return{unaryFilter:{field:za(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Ss(e.value))return{unaryFilter:{field:za(e.field),op:"IS_NOT_NAN"}};if(_s(e.value))return{unaryFilter:{field:za(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:za(e.field),op:(t=e.op,Aa[t]),value:e.value}};var t}(e));return 1===t.length?t[0]:{compositeFilter:{op:"AND",filters:t}}}}(t.filters);s&&(n.structuredQuery.where=s);s=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:za(e.field),direction:(e=e.dir,Sa[e])}}(e))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);var i,s=(i=t.limit,e.N||hs(i)?i:{value:i});return null!==s&&(n.structuredQuery.limit=s),t.startAt&&(n.structuredQuery.startAt={before:(s=t.startAt).inclusive,values:s.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function $a(e){let t=Oa(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let s=null;if(0<r){Dr(1===r);const g=n.from[0];g.allDescendants?s=g.collectionId:t=t.child(g.collectionId)}let i=[];n.where&&(i=function t(e){return e?void 0!==e.unaryFilter?[Ha(e)]:void 0!==e.fieldFilter?[Qa(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map(e=>t(e)).reduce((e,t)=>e.concat(t)):Ar():[]}(n.where));let a=[];n.orderBy&&(a=n.orderBy.map(e=>function(e){return new li(Wa(e.field),function(){switch(e.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(e)));let o=null;var u,h,c,l;n.limit&&(o=(e=n.limit,hs(u="object"==typeof e?e.value:e)?null:u));let d=null;n.startAt&&(d=(h=n.startAt,l=!!h.before,c=h.values||[],new ci(c,l)));let f=null;return n.endAt&&(f=(h=n.endAt,c=!h.before,l=h.values||[],new ci(l,c))),mi(t,s,a,i,o,"F",d,f)}function za(e){return{fieldPath:e.canonicalString()}}function Wa(e){return Jr.fromServerFormat(e.fieldPath)}function Qa(e){return ti.create(Wa(e.fieldFilter.field),function(){switch(e.fieldFilter.op){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 Ar()}}(),e.fieldFilter.value)}function Ha(e){switch(e.unaryFilter.op){case"IS_NAN":var t=Wa(e.unaryFilter.field);return ti.create(t,"==",{doubleValue:NaN});case"IS_NULL":t=Wa(e.unaryFilter.field);return ti.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=Wa(e.unaryFilter.field);return ti.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=Wa(e.unaryFilter.field);return ti.create(n,"!=",{nullValue:"NULL_VALUE"});default:return Ar()}}function Ya(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function Xa(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=Ja(t)),t=function(e,t){let n=t;const r=e.length;for(let s=0;s<r;s++){const r=e.charAt(s);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return Ja(t)}function Ja(e){return e+""}function Za(t){const n=t.length;if(Dr(2<=n),2===n)return Dr(""===t.charAt(0)&&""===t.charAt(1)),Yr.emptyPath();const r=n-2,s=[];let i="";for(let a=0;a<n;){const n=t.indexOf("",a);switch((n<0||n>r)&&Ar(),t.charAt(n+1)){case"":const r=t.substring(a,n);let e;0===i.length?e=r:(i+=r,e=i,i=""),s.push(e);break;case"":i+=t.substring(a,n),i+="\0";break;case"":i+=t.substring(a,n+1);break;default:Ar()}a=n+2}return new Yr(s)}const eo=["userId","batchId"];function to(e,t){return[e,Xa(t)]}function no(e,t,n){return[e,Xa(t),n]}const ro={},so=["prefixPath","collectionGroup","readTime","documentId"],io=["prefixPath","collectionGroup","documentId"],ao=["collectionGroup","readTime","prefixPath","documentId"],oo=["canonicalId","targetId"],uo=["targetId","path"],ho=["path","targetId"],co=["collectionId","parent"],lo=["indexId","uid"],fo=["uid","sequenceNumber"],go=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],mo=["indexId","uid","orderedDocumentKey"],po=["userId","collectionPath","documentId"],yo=["userId","collectionPath","largestBatchId"],vo=["userId","collectionGroup","largestBatchId"],wo=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],bo=[...wo,"documentOverlays"],Io=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],Eo=[...Io,"indexConfiguration","indexState","indexEntries"],To="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class _o{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}class So{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(r,s){return this.callbackAttached&&Ar(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(s,this.error):this.wrapSuccess(r,this.result):new So((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(s,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof So?t:So.resolve(t)}catch(e){return So.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):So.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):So.reject(t)}static resolve(n){return new So((e,t)=>{e(n)})}static reject(n){return new So((e,t)=>{t(n)})}static waitFor(e){return new So((t,n)=>{let r=0,s=0,i=!1;e.forEach(e=>{++r,e.next(()=>{++s,i&&s===r&&t()},e=>n(e))}),i=!0,s===r&&t()})}static or(e){let t=So.resolve(!1);for(const n of e)t=t.next(e=>e?So.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)}}class Ao{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.At=new Cr,this.transaction.oncomplete=()=>{this.At.resolve()},this.transaction.onabort=()=>{e.error?this.At.reject(new No(n,e.error)):this.At.resolve()},this.transaction.onerror=e=>{var t=Lo(e.target.error);this.At.reject(new No(n,t))}}static open(e,t,n,r){try{return new Ao(t,e.transaction(r,n))}catch(e){throw new No(t,e)}}get Rt(){return this.At.promise}abort(e){e&&this.At.reject(e),this.aborted||(Er("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}Pt(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new ko(t)}}class Do{constructor(e,t,n){this.name=e,this.version=t,this.bt=n,12.2===Do.Vt(f())&&Tr("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 Er("SimpleDb","Removing database:",e),Mo(window.indexedDB.deleteDatabase(e)).toPromise()}static vt(){if("object"!=typeof indexedDB)return!1;if(Do.St())return!0;const e=f(),t=Do.Vt(e),n=0<t&&t<10,r=Do.Dt(e),s=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||s)}static St(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.Ct)}static xt(e,t){return e.store(t)}static Vt(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 Dt(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async Nt(i){return this.db||(Er("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const s=indexedDB.open(this.name,this.version);s.onsuccess=e=>{var t=e.target.result;n(t)},s.onblocked=()=>{r(new No(i,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},s.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new Nr(xr.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 Nr(xr.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 No(i,t))},s.onupgradeneeded=e=>{Er("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.bt.kt(t,s.transaction,e.oldVersion,this.version).next(()=>{Er("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.Mt&&(this.db.onversionchange=e=>this.Mt(e)),this.db}Ot(t){this.Mt=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var s="readonly"===t;let i=0;for(;;){++i;try{this.db=await this.Nt(e);const t=Ao.open(this.db,e,s?"readonly":"readwrite",n),i=r(t).next(e=>(t.Pt(),e)).catch(e=>(t.abort(e),So.reject(e))).toPromise();return i.catch(()=>{}),await t.Rt,i}catch(e){const t="FirebaseError"!==e.name&&i<3;if(Er("SimpleDb","Transaction failed with error:",e.message,"Retrying:",t),this.close(),!t)return Promise.reject(e)}}}close(){this.db&&this.db.close(),this.db=void 0}}class xo{constructor(e){this.Ft=e,this.$t=!1,this.Bt=null}get isDone(){return this.$t}get Lt(){return this.Bt}set cursor(e){this.Ft=e}done(){this.$t=!0}Ut(e){this.Bt=e}delete(){return Mo(this.Ft.delete())}}class No extends Nr{constructor(e,t){super(xr.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function Co(e){return"IndexedDbTransactionError"===e.name}class ko{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(Er("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(Er("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),Mo(n)}add(e){return Er("SimpleDb","ADD",this.store.name,e,e),Mo(this.store.add(e))}get(t){return Mo(this.store.get(t)).next(e=>(Er("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return Er("SimpleDb","DELETE",this.store.name,e),Mo(this.store.delete(e))}count(){return Er("SimpleDb","COUNT",this.store.name),Mo(this.store.count())}qt(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.Kt(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new So((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}Gt(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new So((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}Qt(e,t){Er("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.jt=!1;var r=this.cursor(n);return this.Kt(r,(e,t,n)=>n.delete())}Wt(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.Kt(r,t)}zt(s){const e=this.cursor({});return new So((n,r)=>{e.onerror=e=>{var t=Lo(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?s(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}Kt(e,i){const a=[];return new So((s,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new xo(t),r=i(t.primaryKey,t.value,n);if(r instanceof So){const e=r.catch(e=>(n.done(),So.reject(e)));a.push(e)}n.isDone?s():null===n.Lt?t.continue():t.continue(n.Lt)}else s()}}).next(()=>So.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.jt?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function Mo(e){return new So((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=Lo(e.target.error);r(t)}})}let Ro=!1;function Lo(e){const t=Do.Vt(f());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 Nr("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 Ro||(Ro=!0,setTimeout(()=>{throw e},0)),e}}return e}class Vo extends _o{constructor(e,t){super(),this.Ht=e,this.currentSequenceNumber=t}}function Oo(e,t){var n=e;return Do.xt(n.Ht,t)}class Fo{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const s=this.mutations[r];s.key.isEqual(e.key)&&Wi(s,e,n[r])}}applyToLocalView(e){for(const t of this.baseMutations)t.key.isEqual(e.key)&&Qi(t,e,this.localWriteTime);for(const n of this.mutations)n.key.isEqual(e.key)&&Qi(n,e,this.localWriteTime)}applyToLocalDocumentSet(r){this.mutations.forEach(e=>{const t=r.get(e.key),n=t;this.applyToLocalView(n),t.isValidDocument()||n.convertToNoDocument($r.min())})}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),ga())}isEqual(e){return this.batchId===e.batchId&&Kr(this.mutations,e.mutations,(e,t)=>Hi(e,t))&&Kr(this.baseMutations,e.baseMutations,(e,t)=>Hi(e,t))}}class Po{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){Dr(e.mutations.length===n.length);let r=da;var s=e.mutations;for(let i=0;i<s.length;i++)r=r.insert(s[i].key,n[i].version);return new Po(e,t,n,r)}}class Bo{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 qo{constructor(e,t,n,r,s=$r.min(),i=$r.min(),a=es.EMPTY_BYTE_STRING){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=s,this.lastLimboFreeSnapshotVersion=i,this.resumeToken=a}withSequenceNumber(e){return new qo(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new qo(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new qo(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class Uo{constructor(e){this.Jt=e}}function Ko(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:jo(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:Ra(s=e.Jt,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:xa(s,e.version.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Go(t.version)};else{if(!t.isUnknownDocument())return Ar();r.unknownDocument={path:n.path.toArray(),version:Go(t.version)}}var s;return r}function jo(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Go(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function $o(e){var t=new Gr(e.seconds,e.nanoseconds);return $r.fromTimestamp(t)}function zo(t,e){const n=(e.baseMutations||[]).map(e=>Ka(t.Jt,e));for(let i=0;i<e.mutations.length-1;++i){const n=e.mutations[i];if(i+1<e.mutations.length&&void 0!==e.mutations[i+1].transform){const r=e.mutations[i+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(i+1,1),++i}}const r=e.mutations.map(e=>Ka(t.Jt,e)),s=Gr.fromMillis(e.localWriteTimeMs);return new Fo(e.batchId,s,n,r)}function Wo(e){var t,n=$o(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?$o(e.lastLimboFreeSnapshotVersion):$r.min();let s;return s=void 0!==e.query.documents?(Dr(1===(t=e.query).documents.length),Ii(pi(Oa(t.documents[0])))):Ii($a(e.query)),new qo(s,e.targetId,0,e.lastListenSequenceNumber,n,r,es.fromBase64String(e.resumeToken))}function Qo(e,t){var n=Go(t.snapshotVersion),r=Go(t.lastLimboFreeSnapshotVersion),s=(Xs(t.target)?ja:Ga)(e.Jt,t.target),i=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Hs(t.target),readTime:n,resumeToken:i,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:s}}function Ho(e){var t=$a({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Ei(t,t.limit,"L"):t}function Yo(e,t){return new Bo(t.largestBatchId,Ka(e.Jt,t.overlayMutation))}function Xo(e,t){var n=t.path.lastSegment();return[e,Xa(t.path.popLast()),n]}class Jo{getBundleMetadata(e,t){return Zo(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:$o(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return Zo(e).put({bundleId:(n=t).id,createTime:Go(Ca(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return eu(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:Ho(t.bundledQuery),readTime:$o(t.readTime)};var t})}saveNamedQuery(e,t){return eu(e).put({name:(t=t).name,readTime:Go(Ca(t.readTime)),bundledQuery:t.bundledQuery})}}function Zo(e){return Oo(e,"bundles")}function eu(e){return Oo(e,"namedQueries")}class tu{constructor(e,t){this.M=e,this.userId=t}static Yt(e,t){var n=t.uid||"";return new tu(e,n)}getOverlay(e,t){return nu(e).get(Xo(this.userId,t)).next(e=>e?Yo(this.M,e):null)}saveOverlays(r,s,e){const i=[];return e.forEach((e,t)=>{var n=new Bo(s,t);i.push(this.Xt(r,n))}),So.waitFor(i)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(Xa(e.getCollectionPath())));const s=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);s.push(nu(n).Qt("collectionPathOverlayIndex",t))}),So.waitFor(s)}getOverlaysForCollection(e,t,n){const r=la(),s=Xa(t),i=IDBKeyRange.bound([this.userId,s,n],[this.userId,s,Number.POSITIVE_INFINITY],!0);return nu(e).qt("collectionPathOverlayIndex",i).next(e=>{for(const t of e){const e=Yo(this.M,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,s){const i=la();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return nu(e).Wt({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=Yo(this.M,t);i.size()<s||r.largestBatchId===a?(i.set(r.getKey(),r),a=r.largestBatchId):n.done()}).next(()=>i)}Xt(e,t){return nu(e).put(function(e,t,n){var[,r,s]=Xo(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:Ua(e.Jt,n.mutation)}}(this.M,this.userId,t))}}function nu(e){return Oo(e,"documentOverlays")}class ru{constructor(){}Zt(e,t){this.te(e,t),t.ee()}te(e,t){var n,r;"nullValue"in e?this.ne(t,5):"booleanValue"in e?(this.ne(t,10),t.se(e.booleanValue?1:0)):"integerValue"in e?(this.ne(t,15),t.se(rs(e.integerValue))):"doubleValue"in e?(n=rs(e.doubleValue),isNaN(n)?this.ne(t,13):(this.ne(t,15),cs(n)?t.se(0):t.se(n))):"timestampValue"in e?(r=e.timestampValue,this.ne(t,20),"string"==typeof r?t.ie(r):(t.ie(`${r.seconds||""}`),t.se(r.nanos||0))):"stringValue"in e?(this.re(e.stringValue,t),this.oe(t)):"bytesValue"in e?(this.ne(t,30),t.ue(ss(e.bytesValue)),this.oe(t)):"referenceValue"in e?this.ae(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.ne(t,45),t.se(r.latitude||0),t.se(r.longitude||0)):"mapValue"in e?xs(e)?this.ne(t,Number.MAX_SAFE_INTEGER):(this.ce(e.mapValue,t),this.oe(t)):"arrayValue"in e?(this.he(e.arrayValue,t),this.oe(t)):Ar()}re(e,t){this.ne(t,25),this.le(e,t)}le(e,t){t.ie(e)}ce(e,t){var n=e.fields||{};this.ne(t,55);for(const e of Object.keys(n))this.re(e,t),this.te(n[e],t)}he(e,t){var n=e.values||[];this.ne(t,50);for(const e of n)this.te(e,t)}ae(e,t){this.ne(t,37),ds.fromName(e).path.forEach(e=>{this.ne(t,60),this.le(e,t)})}ne(e,t){e.se(t)}oe(e){e.se(2)}}function su(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)}ru.fe=new ru;class iu{constructor(){this.buffer=new Uint8Array(1024),this.position=0}de(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this._e(n.value),n=t.next();this.we()}me(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.ge(n.value),n=t.next();this.ye()}pe(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this._e(e);else if(e<2048)this._e(960|e>>>6),this._e(128|63&e);else if(t<"\ud800"||"\udbff"<t)this._e(480|e>>>12),this._e(128|63&e>>>6),this._e(128|63&e);else{const e=t.codePointAt(0);this._e(240|e>>>18),this._e(128|63&e>>>12),this._e(128|63&e>>>6),this._e(128|63&e)}}this.we()}Ie(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.ge(e);else if(e<2048)this.ge(960|e>>>6),this.ge(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.ge(480|e>>>12),this.ge(128|63&e>>>6),this.ge(128|63&e);else{const e=t.codePointAt(0);this.ge(240|e>>>18),this.ge(128|63&e>>>12),this.ge(128|63&e>>>6),this.ge(128|63&e)}}this.ye()}Te(e){var t=this.Ee(e),n=su(t);this.Ae(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]}Re(e){var t=this.Ee(e),n=su(t);this.Ae(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])}Pe(){this.be(255),this.be(255)}Ve(){this.ve(255),this.ve(255)}reset(){this.position=0}seed(e){this.Ae(e.length),this.buffer.set(e,this.position),this.position+=e.length}Se(){return this.buffer.slice(0,this.position)}Ee(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}_e(e){var t=255&e;0==t?(this.be(0),this.be(255)):255==t?(this.be(255),this.be(0)):this.be(t)}ge(e){var t=255&e;0==t?(this.ve(0),this.ve(255)):255==t?(this.ve(255),this.ve(0)):this.ve(e)}we(){this.be(0),this.be(1)}ye(){this.ve(0),this.ve(1)}be(e){this.Ae(1),this.buffer[this.position++]=e}ve(e){this.Ae(1),this.buffer[this.position++]=~e}Ae(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 au{constructor(e){this.De=e}ue(e){this.De.de(e)}ie(e){this.De.pe(e)}se(e){this.De.Te(e)}ee(){this.De.Pe()}}class ou{constructor(e){this.De=e}ue(e){this.De.me(e)}ie(e){this.De.Ie(e)}se(e){this.De.Re(e)}ee(){this.De.Ve()}}class uu{constructor(){this.De=new iu,this.Ce=new au(this.De),this.xe=new ou(this.De)}seed(e){this.De.seed(e)}Ne(e){return 0===e?this.Ce:this.xe}Se(){return this.De.Se()}reset(){this.De.reset()}}class hu{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}ke(){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 hu(this.indexId,this.documentKey,this.arrayValue,n)}}function cu(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=lu(e.arrayValue,t.arrayValue),0!==n?n:(n=lu(e.directionalValue,t.directionalValue),0!==n?n:ds.comparator(e.documentKey,t.documentKey)))}function lu(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 du{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Me=e.orderBy,this.Oe=[];for(const t of e.filters){const e=t;e.S()?this.Fe=e:this.Oe.push(e)}}$e(e){var t=Ls(e);if(void 0!==t&&!this.Be(t))return!1;var n=Vs(e);let r=0,s=0;for(;r<n.length&&this.Be(n[r]);++r);if(r===n.length)return!0;if(void 0!==this.Fe){const e=n[r];if(!this.Le(this.Fe,e)||!this.Ue(this.Me[s++],e))return!1;++r}for(;r<n.length;++r){const e=n[r];if(s>=this.Me.length||!this.Ue(this.Me[s++],e))return!1}return!0}Be(e){for(const t of this.Oe)if(this.Le(t,e))return!0;return!1}Le(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}Ue(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}class fu{constructor(){this.qe=new gu}addToCollectionParentIndex(e,t){return this.qe.add(t),So.resolve()}getCollectionParents(e,t){return So.resolve(this.qe.getEntries(t))}addFieldIndex(e,t){return So.resolve()}deleteFieldIndex(e,t){return So.resolve()}getDocumentsMatchingTarget(e,t){return So.resolve(null)}getIndexType(e,t){return So.resolve(0)}getFieldIndexes(e,t){return So.resolve([])}getNextCollectionGroupToUpdate(e){return So.resolve(null)}getMinOffset(e,t){return So.resolve(Bs.min())}updateCollectionGroup(e,t,n){return So.resolve()}updateIndexEntries(e,t){return So.resolve()}}class gu{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new Gs(Yr.comparator),s=!r.has(n);return this.index[t]=r.add(n),s}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new Gs(Yr.comparator)).toArray()}}const mu=new Uint8Array(0);class pu{constructor(e,t){this.user=e,this.databaseId=t,this.Ke=new gu,this.Ge=new oa(e=>Hs(e),(e,t)=>Ys(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.Ke.has(t))return So.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Ke.add(t)});r={collectionId:n,parent:Xa(r)};return yu(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[jr(n),""],!1,!0);return yu(e).qt(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(Za(t.parent))}return r})}addFieldIndex(e,t){const n=wu(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};return delete r.indexId,n.add(r).next()}deleteFieldIndex(e,t){const n=wu(e),r=bu(e),s=vu(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>s.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}getDocumentsMatchingTarget(e,h){const c=vu(e);let l=!0;const n=new Map;return So.forEach(this.Qe(h),t=>this.je(e,t).next(e=>{l=l&&!!e,n.set(t,e)})).next(()=>{if(l){let u=ga();const l=[];return So.forEach(n,(e,t)=>{Er("IndexedDbIndexManager",`Using index ${o=e,`id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${Hs(h)}`);var n=function(e,t){var n=Ls(t);if(void 0===n)return null;for(const t of Js(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),r=function(e,t){const n=new Map;for(const r of Vs(t))for(const t of Js(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),s=function(e,t){const n=[];let r=!0;for(const s of Vs(t)){const t=(0===s.kind?Zs:ei)(e,s.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new ci(n,r)}(t,e),i=function(e,t){const n=[];let r=!0;for(const s of Vs(t)){const t=(0===s.kind?ei:Zs)(e,s.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new ci(n,r)}(t,e),a=this.We(e,t,s),o=this.We(e,t,i),r=this.ze(e,t,r),r=this.He(e.indexId,n,a,s.inclusive,o,i.inclusive,r);return So.forEach(r,e=>c.Gt(e,h.limit).next(e=>{e.forEach(e=>{var t=ds.fromSegments(e.documentKey);u.has(t)||(u=u.add(t),l.push(t))})}))}).next(()=>l)}return So.resolve(null)})}Qe(e){var t;return(t=this.Ge.get(e))||(this.Ge.set(e,t=[e]),t)}He(t,e,n,r,s,i,a){const o=(null!=e?e.length:1)*Math.max(n.length,s.length),u=o/(null!=e?e.length:1),h=[];for(let c=0;c<o;++c){const o=e?this.Je(e[c/u]):mu,l=this.Ye(t,o,n[c%u],r),d=this.Xe(t,o,s[c%u],i),f=a.map(e=>this.Ye(t,o,e,!0));h.push(...this.createRange(l,d,f))}return h}Ye(e,t,n,r){const s=new hu(e,ds.empty(),t,n);return r?s:s.ke()}Xe(e,t,n,r){const s=new hu(e,ds.empty(),t,n);return r?s.ke():s}je(e,t){const r=new du(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.$e(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;return So.forEach(this.Qe(t),t=>this.je(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new Gs(Jr.comparator),n=!1;for(const r of e.filters){const e=r;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(()=>n)}Ze(e,t){const n=new uu;for(const s of Vs(e)){const e=t.data.field(s.fieldPath);if(null==e)return null;var r=n.Ne(s.kind);ru.fe.Zt(e,r)}return n.Se()}Je(e){const t=new uu;return ru.fe.Zt(e,t.Ne(0)),t.Se()}tn(e,t){const n=new uu;return ru.fe.Zt(Is(this.databaseId,t),n.Ne(0===(r=Vs(e)).length?0:r[r.length-1].kind)),n.Se();var r}ze(e,t,n){if(null===n)return[];let r=[];r.push(new uu);let s=0;for(const i of Vs(e)){const e=n[s++];for(const n of r)if(this.en(t,i.fieldPath)&&Ts(e))r=this.nn(r,i,e);else{const t=n.Ne(i.kind);ru.fe.Zt(e,t)}}return this.sn(r)}We(e,t,n){return this.ze(e,t,n.position)}sn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Se();return t}nn(e,t,n){const r=[...e],s=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new uu;r.seed(n.Se()),ru.fe.Zt(e,r.Ne(t.kind)),s.push(r)}return s}en(e,t){return!!e.filters.find(e=>e instanceof ti&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=wu(e),r=bu(e);return(t?n.qt("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.qt()).next(e=>{const i=[];return So.forEach(e,s=>r.get([s.indexId,this.uid]).next(e=>{var t,n,r;i.push((t=s,n=(e=e)?new Fs(e.sequenceNumber,new Bs($o(e.readTime),new ds(Za(e.documentKey)),e.largestBatchId)):Fs.empty(),r=t.fields.map(([e,t])=>new Os(Jr.fromServerFormat(e),t)),new Rs(t.indexId,t.collectionGroup,r,n)))})).next(()=>i)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:Ur(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,t,n){const s=wu(e),i=bu(e);return this.rn(e).next(r=>s.qt("collectionGroupIndex",IDBKeyRange.bound(t,t)).next(e=>So.forEach(e,e=>i.put(function(e,t,n){return{indexId:e,uid:t.uid||"",sequenceNumber:r,readTime:Go(n.readTime),documentKey:Xa(n.documentKey.path),largestBatchId:n.largestBatchId}}(e.indexId,this.user,n)))))}updateIndexEntries(s,e){const n=new Map;return So.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?So.resolve(e):this.getFieldIndexes(s,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),So.forEach(e,n=>this.on(s,t,n).next(e=>{var t=this.un(r,n);return e.isEqual(t)?So.resolve():this.an(s,r,n,e,t)}))))})}cn(e,t,n,r){return vu(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.tn(n,t.key),documentKey:t.key.path.toArray()})}hn(e,t,n,r){return vu(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.tn(n,t.key),t.key.path.toArray()])}on(e,n,r){const t=vu(e);let s=new Gs(cu);return t.Wt({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.tn(r,n)])},(e,t)=>{s=s.add(new hu(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>s)}un(e,t){let n=new Gs(cu);var r=this.Ze(t,e);if(null==r)return n;const s=Ls(t);if(null!=s){var i=e.data.field(s.fieldPath);if(Ts(i))for(const s of i.arrayValue.values||[])n=n.add(new hu(t.indexId,e.key,this.Je(s),r))}else n=n.add(new hu(t.indexId,e.key,mu,r));return n}an(t,n,r,h,e){Er("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const s=[];return function(e,n,r,s){var i=h.getIterator(),a=e.getIterator();let o=zs(i),u=zs(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=zs(a)):t?(s(o),o=zs(i)):(o=zs(i),u=zs(a))}}(e,cu,e=>{s.push(this.cn(t,n,r,e))},e=>{s.push(this.hn(t,n,r,e))}),So.waitFor(s)}rn(e){let r=1;return bu(e).Wt({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)=>cu(e,t)).filter((e,t,n)=>!t||0!==cu(e,n[t-1]));const r=[];r.push(e);for(const s of n){const n=cu(s,e),i=cu(s,t);if(0===n)r[0]=e.ke();else if(0<n&&i<0)r.push(s),r.push(s.ke());else if(0<i)break}r.push(t);const s=[];for(let a=0;a<r.length;a+=2)s.push(IDBKeyRange.bound([r[a].indexId,this.uid,r[a].arrayValue,r[a].directionalValue,mu,[]],[r[a+1].indexId,this.uid,r[a+1].arrayValue,r[a+1].directionalValue,mu,[]]));return s}getMinOffset(t,e){let n;return So.forEach(this.Qe(e),e=>this.je(t,e).next(e=>{e?(!n||qs(e.indexState.offset,n)<0)&&(n=e.indexState.offset):n=Bs.min()})).next(()=>n)}}function yu(e){return Oo(e,"collectionParents")}function vu(e){return Oo(e,"indexEntries")}function wu(e){return Oo(e,"indexConfiguration")}function bu(e){return Oo(e,"indexState")}const Iu={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class Eu{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Eu(e,Eu.DEFAULT_COLLECTION_PERCENTILE,Eu.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function Tu(e,t,n){const r=e.store("mutations"),s=e.store("documentMutations"),i=[],a=IDBKeyRange.only(n.batchId);let o=0;const u=r.Wt({range:a},(e,t,n)=>(o++,n.delete()));i.push(u.next(()=>{Dr(1===o)}));const h=[];for(const e of n.mutations){const r=no(t,e.key.path,n.batchId);i.push(s.delete(r)),h.push(e.key)}return So.waitFor(i).next(()=>h)}function _u(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw Ar();t=e.noDocument}return JSON.stringify(t).length}Eu.DEFAULT_COLLECTION_PERCENTILE=10,Eu.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Eu.DEFAULT=new Eu(41943040,Eu.DEFAULT_COLLECTION_PERCENTILE,Eu.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Eu.DISABLED=new Eu(-1,0,0);class Su{constructor(e,t,n,r){this.userId=e,this.M=t,this.indexManager=n,this.referenceDelegate=r,this.ln={}}static Yt(e,t,n,r){Dr(""!==e.uid);var s=e.isAuthenticated()?e.uid:"";return new Su(s,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Du(e).Wt({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(c,l,d,f){const g=xu(c),m=Du(c);return m.add({}).next(e=>{Dr("number"==typeof e);const t=new Fo(e,l,d,f),n=(s=this.M,i=this.userId,a=t,o=a.baseMutations.map(e=>Ua(s.Jt,e)),u=a.mutations.map(e=>Ua(s.Jt,e)),{userId:i,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:u}),r=[];var s,i,a,o,u;let h=new Gs((e,t)=>Ur(e.canonicalString(),t.canonicalString()));for(const c of f){const l=no(this.userId,c.key.path,e);h=h.add(c.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,ro))}return h.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(c,e))}),c.addOnCommittedListener(()=>{this.ln[e]=t.keys()}),So.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return Du(e).get(t).next(e=>e?(Dr(e.userId===this.userId),zo(this.M,e)):null)}fn(e,n){return this.ln[n]?So.resolve(this.ln[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.ln[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let s=null;return Du(e).Wt({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(Dr(t.batchId>=r),s=zo(this.M,t)),n.done()}).next(()=>s)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return Du(e).Wt({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 Du(e).qt("userMutationsIndex",t).next(e=>e.map(e=>zo(this.M,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=to(this.userId,o.path),t=IDBKeyRange.lowerBound(e),u=[];return xu(a).Wt({range:t},(e,t,n)=>{var[r,s,i]=e,s=Za(s);if(r===this.userId&&o.path.isEqual(s))return Du(a).get(i).next(e=>{if(!e)throw Ar();Dr(e.userId===this.userId),u.push(zo(this.M,e))});n.done()}).next(()=>u)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new Gs(Ur);const n=[];return e.forEach(a=>{var e=to(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=xu(t).Wt({range:e},(e,t,n)=>{var[r,s,i]=e,s=Za(s);r===this.userId&&a.path.isEqual(s)?o=o.add(i):n.done()});n.push(e)}),So.waitFor(n).next(()=>this.dn(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=to(this.userId,a),r=IDBKeyRange.lowerBound(n);let u=new Gs(Ur);return xu(e).Wt({range:r},(e,t,n)=>{var[r,s,i]=e,s=Za(s);r===this.userId&&a.isPrefixOf(s)?s.length===o&&(u=u.add(i)):n.done()}).next(()=>this.dn(e,u))}dn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(Du(t).get(e).next(e=>{if(null===e)throw Ar();Dr(e.userId===this.userId),n.push(zo(this.M,e))}))}),So.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return Tu(t.Ht,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this._n(n.batchId)}),So.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}_n(e){delete this.ln[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return So.resolve();var t=IDBKeyRange.lowerBound([this.userId]);const r=[];return xu(n).Wt({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=Za(e[1]);r.push(t)}else n.done()}).next(()=>{Dr(0===r.length)})})}containsKey(e,t){return Au(e,this.userId,t)}wn(e){return Nu(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function Au(e,i,t){const n=to(i,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return xu(e).Wt({range:r,jt:!0},(e,t,n)=>{var[r,s]=e;r===i&&s===a&&(o=!0),n.done()}).next(()=>o)}function Du(e){return Oo(e,"mutations")}function xu(e){return Oo(e,"documentMutations")}function Nu(e){return Oo(e,"mutationQueues")}class Cu{constructor(e){this.mn=e}next(){return this.mn+=2,this.mn}static gn(){return new Cu(0)}static yn(){return new Cu(-1)}}class ku{constructor(e,t){this.referenceDelegate=e,this.M=t}allocateTargetId(n){return this.pn(n).next(e=>{const t=new Cu(e.highestTargetId);return e.highestTargetId=t.next(),this.In(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.pn(e).next(e=>$r.fromTimestamp(new Gr(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.pn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.pn(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.In(t,e)))}addTargetData(t,n){return this.Tn(t,n).next(()=>this.pn(t).next(e=>(e.targetCount+=1,this.En(n,e),this.In(t,e))))}updateTargetData(e,t){return this.Tn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>Mu(t).delete(e.targetId)).next(()=>this.pn(t)).next(e=>(Dr(0<e.targetCount),--e.targetCount,this.In(t,e)))}removeTargets(r,s,i){let a=0;const o=[];return Mu(r).Wt((e,t)=>{var n=Wo(t);n.sequenceNumber<=s&&null===i.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>So.waitFor(o)).next(()=>a)}forEachTarget(e,r){return Mu(e).Wt((e,t)=>{var n=Wo(t);r(n)})}pn(e){return Ru(e).get("targetGlobalKey").next(e=>(Dr(null!==e),e))}In(e,t){return Ru(e).put("targetGlobalKey",t)}Tn(e,t){return Mu(e).put(Qo(this.M,t))}En(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.pn(e).next(e=>e.targetCount)}getTargetData(e,s){var t=Hs(s),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let i=null;return Mu(e).Wt({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=Wo(t);Ys(s,r.target)&&(i=r,n.done())}).next(()=>i)}addMatchingKeys(n,e,r){const s=[],i=Lu(n);return e.forEach(e=>{var t=Xa(e.path);s.push(i.put({targetId:r,path:t})),s.push(this.referenceDelegate.addReference(n,r,e))}),So.waitFor(s)}removeMatchingKeys(n,e,r){const s=Lu(n);return So.forEach(e,e=>{var t=Xa(e.path);return So.waitFor([s.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=Lu(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=Lu(e);let s=ga();return r.Wt({range:n,jt:!0},(e,t,n)=>{var r=Za(e[1]),r=new ds(r);s=s.add(r)}).next(()=>s)}containsKey(e,t){var n=Xa(t.path),n=IDBKeyRange.bound([n],[jr(n)],!1,!0);let r=0;return Lu(e).Wt({index:"documentTargetsIndex",jt:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}Et(e,t){return Mu(e).get(t).next(e=>e?Wo(e):null)}}function Mu(e){return Oo(e,"targets")}function Ru(e){return Oo(e,"targetGlobal")}function Lu(e){return Oo(e,"targetDocuments")}async function Vu(e){if(e.code!==xr.FAILED_PRECONDITION||e.message!==To)throw e;Er("LocalStore","Unexpectedly lost primary lease")}function Ou([e,t],[n,r]){var s=Ur(e,n);return 0===s?Ur(t,r):s}class Fu{constructor(e){this.An=e,this.buffer=new Gs(Ou),this.Rn=0}Pn(){return++this.Rn}bn(e){var t=[e,this.Pn()];if(this.buffer.size<this.An)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();Ou(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class Pu{constructor(e,t){this.garbageCollector=e,this.asyncQueue=t,this.Vn=!1,this.vn=null}start(e){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Sn(e)}stop(){this.vn&&(this.vn.cancel(),this.vn=null)}get started(){return null!==this.vn}Sn(e){var t=this.Vn?3e5:6e4;Er("LruGarbageCollector",`Garbage collection scheduled in ${t}ms`),this.vn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",t,async()=>{this.vn=null,this.Vn=!0;try{await e.collectGarbage(this.garbageCollector)}catch(e){Co(e)?Er("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await Vu(e)}await this.Sn(e)})}}class Bu{constructor(e,t){this.Dn=e,this.params=t}calculateTargetCount(e,t){return this.Dn.Cn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return So.resolve(Br.A);const n=new Fu(t);return this.Dn.forEachTarget(e,e=>n.bn(e.sequenceNumber)).next(()=>this.Dn.xn(e,e=>n.bn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.Dn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Dn.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(Er("LruGarbageCollector","Garbage collection skipped; disabled"),So.resolve(Iu)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(Er("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),Iu):this.Nn(t,n))}getCacheSize(e){return this.Dn.getCacheSize(e)}Nn(t,n){let r,s,i,a,o,u,h;const c=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(s=e>this.params.maximumSequenceNumbersToCollect?(Er("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,a=Date.now(),this.nthSequenceNumber(t,s))).next(e=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(i=e,u=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(h=Date.now(),Ir()<=l.DEBUG&&Er("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-c}ms\n\tDetermined least recently used ${s} in `+(o-a)+"ms\n"+`\tRemoved ${i} targets in `+(u-o)+"ms\n"+`\tRemoved ${e} documents in `+(h-u)+"ms\n"+`Total Duration: ${h-c}ms`),So.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:e})))}}class qu{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new Bu(e,t))}Cn(e){const n=this.kn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}kn(e){let t=0;return this.xn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}xn(e,n){return this.Mn(e,(e,t)=>n(t))}addReference(e,t,n){return Uu(e,n)}removeReference(e,t,n){return Uu(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return Uu(e,t)}On(t,n){let r=!1;return Nu(t).zt(e=>Au(t,e,n).next(e=>(e&&(r=!0),So.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const s=this.db.getRemoteDocumentCache().newChangeBuffer(),i=[];let a=0;return this.Mn(n,(t,e)=>{if(e<=r){const r=this.On(n,t).next(e=>{if(!e)return a++,s.getEntry(n,t).next(()=>(s.removeEntry(t,$r.min()),Lu(n).delete([0,Xa(t.path)])))});i.push(r)}}).next(()=>So.waitFor(i)).next(()=>s.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return Uu(e,t)}Mn(e,r){const t=Lu(e);let s,i=Br.A;return t.Wt({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(i!==Br.A&&r(new ds(Za(s)),i),i=n,s=t):i=Br.A}).next(()=>{i!==Br.A&&r(new ds(Za(s)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function Uu(e,t){return Lu(e).put((e=e.currentSequenceNumber,{targetId:0,path:Xa(t.path),sequenceNumber:e}))}class Ku{constructor(){this.changes=new oa(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,Ms.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?So.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 ju{constructor(e){this.M=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return zu(e).put(n)}removeEntry(e,n,t){return zu(e).delete(function(e){const t=n.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],jo(e),t[t.length-1]]}(t))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Fn(t,e)))}getEntry(e,n){let r=Ms.newInvalidDocument(n);return zu(e).Wt({index:"documentKeyIndex",range:IDBKeyRange.only(Wu(n))},(e,t)=>{r=this.$n(n,t)}).next(()=>r)}Bn(e,n){let r={size:0,document:Ms.newInvalidDocument(n)};return zu(e).Wt({index:"documentKeyIndex",range:IDBKeyRange.only(Wu(n))},(e,t)=>{r={document:this.$n(n,t),size:_u(t)}}).next(()=>r)}getEntries(e,t){let r=ua;return this.Ln(e,t,(e,t)=>{var n=this.$n(e,t);r=r.insert(e,n)}).next(()=>r)}Un(e,t){let r=ua,s=new Us(ds.comparator);return this.Ln(e,t,(e,t)=>{var n=this.$n(e,t);r=r.insert(e,n),s=s.insert(e,_u(t))}).next(()=>({documents:r,qn:s}))}Ln(e,t,s){if(t.isEmpty())return So.resolve();let n=new Gs(Hu);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(Wu(n.first()),Wu(n.last())),i=n.getIterator();let a=i.getNext();return zu(e).Wt({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=ds.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&Hu(a,r)<0;)s(a,null),a=i.getNext();a&&a.isEqual(r)&&(s(a,t),a=i.hasNext()?i.getNext():null),a?n.Ut(Wu(a)):n.done()}).next(()=>{for(;a;)s(a,null),a=i.hasNext()?i.getNext():null})}getAllFromCollection(e,t,n){var r=[t.popLast().toArray(),t.lastSegment(),jo(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],s=[t.popLast().toArray(),t.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return zu(e).qt(IDBKeyRange.bound(r,s,!0)).next(e=>{let t=ua;for(const n of e){const e=this.$n(ds.fromSegments(n.prefixPath.concat(n.collectionGroup,n.documentId)),n);t=t.insert(e.key,e)}return t})}getAllFromCollectionGroup(e,t,n,s){let i=ua;var r=Qu(t,n),a=Qu(t,Bs.max());return zu(e).Wt({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.$n(ds.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);i=i.insert(r.key,r),i.size===s&&n.done()}).next(()=>i)}newChangeBuffer(e){return new Gu(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return $u(e).get("remoteDocumentGlobalKey").next(e=>(Dr(!!e),e))}Fn(e,t){return $u(e).put("remoteDocumentGlobalKey",t)}$n(e,t){if(t){const e=function(e,t){let n;if(t.document)n=qa(e.Jt,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=ds.fromSegments(t.noDocument.path),s=$o(t.noDocument.readTime);n=Ms.newNoDocument(e,s),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return Ar();{const e=ds.fromSegments(t.unknownDocument.path),i=$o(t.unknownDocument.version);n=Ms.newUnknownDocument(e,i)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new Gr(t[0],t[1]),$r.fromTimestamp(r))),n;var r}(this.M,t);if(!e.isNoDocument()||!e.version.isEqual($r.min()))return e}return Ms.newInvalidDocument(e)}}class Gu extends Ku{constructor(e,t){super(),this.Kn=e,this.trackRemovals=t,this.Gn=new oa(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(i){const a=[];let o=0,u=new Gs((e,t)=>Ur(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.Gn.get(e);if(a.push(this.Kn.removeEntry(i,e,n.readTime)),t.isValidDocument()){var r=Ko(this.Kn.M,t);u=u.add(e.path.popLast());var s=_u(r);o+=s-n.size,a.push(this.Kn.addEntry(i,e,r))}else if(o-=n.size,this.trackRemovals){const o=Ko(this.Kn.M,t.convertToNoDocument($r.min()));a.push(this.Kn.addEntry(i,e,o))}}),u.forEach(e=>{a.push(this.Kn.indexManager.addToCollectionParentIndex(i,e))}),a.push(this.Kn.updateMetadata(i,o)),So.waitFor(a)}getFromCache(e,t){return this.Kn.Bn(e,t).next(e=>(this.Gn.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Kn.Un(e,t).next(({documents:n,qn:e})=>(e.forEach((e,t)=>{this.Gn.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function $u(e){return Oo(e,"remoteDocumentGlobal")}function zu(e){return Oo(e,"remoteDocumentsV14")}function Wu(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function Qu(e,t){const n=t.documentKey.path.toArray();return[e,jo(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function Hu(e,t){var n=e.path.toArray(),r=t.path.toArray();let s=0;for(let i=0;i<n.length-2&&i<r.length-2;++i)if(s=Ur(n[i],r[i]),s)return s;return s=Ur(n.length,r.length),s||(s=Ur(n[n.length-2],r[r.length-2]),s||Ur(n[n.length-1],r[r.length-1]))}class Yu{constructor(e){this.M=e}kt(t,e,n,r){const s=new Ao("createOrUpgrade",e);var i;n<1&&1<=r&&(t.createObjectStore("owner"),(i=t).createObjectStore("mutationQueues",{keyPath:"userId"}),i.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",eo,{unique:!0}),i.createObjectStore("documentMutations"),Xu(t),t.createObjectStore("remoteDocuments"));let a=So.resolve();return n<3&&3<=r&&(0!==n&&((i=t).deleteObjectStore("targetDocuments"),i.deleteObjectStore("targets"),i.deleteObjectStore("targetGlobal"),Xu(t)),a=a.next(()=>function(){const e=s.store("targetGlobal"),t={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:$r.min().toTimestamp(),targetCount:0};return e.put("targetGlobalKey",t)}())),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,s){return s.store("mutations").qt().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",eo,{unique:!0});const t=s.store("mutations"),n=e.map(e=>t.put(e));return So.waitFor(n)})}(t,s))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.Qn(s))),n<6&&6<=r&&(a=a.next(()=>(t.createObjectStore("remoteDocumentGlobal"),this.jn(s)))),n<7&&7<=r&&(a=a.next(()=>this.Wn(s))),n<8&&8<=r&&(a=a.next(()=>this.zn(t,s))),n<9&&9<=r&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(a=a.next(()=>this.Hn(s))),n<11&&11<=r&&(a=a.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(a=a.next(()=>{!function(){const e=t.createObjectStore("documentOverlays",{keyPath:po});e.createIndex("collectionPathOverlayIndex",yo,{unique:!1}),e.createIndex("collectionGroupOverlayIndex",vo,{unique:!1})}()})),n<13&&13<=r&&(a=a.next(()=>function(){const e=t.createObjectStore("remoteDocumentsV14",{keyPath:so});e.createIndex("documentKeyIndex",io),e.createIndex("collectionGroupIndex",ao)}()).next(()=>this.Jn(t,s)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>{var e;(e=t).createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:lo}).createIndex("sequenceNumberIndex",fo,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:go}).createIndex("documentKeyIndex",mo,{unique:!1})})),a}jn(t){let n=0;return t.store("remoteDocuments").Wt((e,t)=>{n+=_u(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}Qn(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.qt().next(e=>So.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.qt("userMutationsIndex",e).next(e=>So.forEach(e,e=>{Dr(e.userId===n.userId);var t=zo(this.M,e);return Tu(r,n.userId,t).next(()=>{})}))}))}Wn(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(s=>{const i=[];return t.Wt((e,t)=>{const n=new Yr(e),r=[0,Xa(n)];i.push(a.get(r).next(e=>e?So.resolve():(e=>a.put({targetId:0,path:Xa(e),sequenceNumber:s.highestListenSequenceNumber}))(n)))}).next(()=>So.waitFor(i))})}zn(e,t){e.createObjectStore("collectionParents",{keyPath:co});const n=t.store("collectionParents"),r=new gu,s=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Xa(r)})}};return t.store("remoteDocuments").Wt({jt:!0},(e,t)=>{const n=new Yr(e);return s(n.popLast())}).next(()=>t.store("documentMutations").Wt({jt:!0},([,e],t)=>{const n=Za(e);return s(n.popLast())}))}Hn(e){const r=e.store("targets");return r.Wt((e,t)=>{var n=Wo(t),n=Qo(this.M,n);return r.put(n)})}Jn(e,i){const t=i.store("remoteDocuments"),a=[];return t.Wt((e,t)=>{const n=i.store("remoteDocumentsV14"),r=((s=t).document?new ds(Yr.fromString(s.document.name).popFirst(5)):s.noDocument?ds.fromSegments(s.noDocument.path):s.unknownDocument?ds.fromSegments(s.unknownDocument.path):Ar()).path.toArray();var s={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};a.push(n.put(s))}).next(()=>So.waitFor(a))}}function Xu(e){e.createObjectStore("targetDocuments",{keyPath:uo}).createIndex("documentTargetsIndex",ho,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",oo,{unique:!0}),e.createObjectStore("targetGlobal")}const Ju="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 Zu{constructor(e,t,n,r,s,i,a,o,u,h,c=13){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Yn=s,this.window=i,this.document=a,this.Xn=u,this.Zn=h,this.ts=c,this.es=null,this.ns=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ss=null,this.inForeground=!1,this.rs=null,this.os=null,this.us=Number.NEGATIVE_INFINITY,this.cs=e=>Promise.resolve(),!Zu.vt())throw new Nr(xr.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new qu(this,r),this.hs=t+"main",this.M=new Uo(o),this.ls=new Do(this.hs,this.ts,new Yu(this.M)),this.fs=new ku(this.referenceDelegate,this.M),this.ds=(o=this.M,new ju(o)),this._s=new Jo,this.window&&this.window.localStorage?this.ws=this.window.localStorage:(this.ws=null,!1===h&&Tr("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.gs().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new Nr(xr.FAILED_PRECONDITION,Ju);return this.ys(),this.ps(),this.Is(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.fs.getHighestSequenceNumber(e))}).then(e=>{this.es=new Br(e,this.Xn)}).then(()=>{this.ns=!0}).catch(e=>(this.ls&&this.ls.close(),Promise.reject(e)))}Ts(t){return this.cs=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.ls.Ot(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Yn.enqueueAndForget(async()=>{this.started&&await this.gs()}))}gs(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>th(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.Es(t).next(e=>{e||(this.isPrimary=!1,this.Yn.enqueueRetryable(()=>this.cs(!1)))})}).next(()=>this.As(t)).next(e=>this.isPrimary&&!e?this.Rs(t).next(()=>!1):!!e&&this.Ps(t).next(()=>!0))).catch(e=>{if(Co(e))return Er("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return Er("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Yn.enqueueRetryable(()=>this.cs(e)),this.isPrimary=e})}Es(e){return eh(e).get("owner").next(e=>So.resolve(this.bs(e)))}Vs(e){return th(e).delete(this.clientId)}async vs(){if(this.isPrimary&&!this.Ss(this.us,18e5)){this.us=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=Oo(e,"clientMetadata");return r.qt().next(e=>{const t=this.Ds(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return So.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.ws)for(const t of e)this.ws.removeItem(this.Cs(t.clientId))}}Is(){this.os=this.Yn.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.gs().then(()=>this.vs()).then(()=>this.Is()))}bs(e){return!!e&&e.ownerId===this.clientId}As(t){return this.Zn?So.resolve(!0):eh(t).get("owner").next(e=>{if(null!==e&&this.Ss(e.leaseTimestampMs,5e3)&&!this.xs(e.ownerId)){if(this.bs(e)&&this.networkEnabled)return!0;if(!this.bs(e)){if(!e.allowTabSynchronization)throw new Nr(xr.FAILED_PRECONDITION,Ju);return!1}}return!(!this.networkEnabled||!this.inForeground)||th(t).qt().next(e=>void 0===this.Ds(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&&Er("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.ns=!1,this.Ns(),this.os&&(this.os.cancel(),this.os=null),this.ks(),this.Ms(),await this.ls.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new Vo(e,Br.A);return this.Rs(t).next(()=>this.Vs(t))}),this.ls.close(),this.Os()}Ds(e,t){return e.filter(e=>this.Ss(e.updateTimeMs,t)&&!this.xs(e.clientId))}Fs(){return this.runTransaction("getActiveClients","readonly",e=>th(e).qt().next(e=>this.Ds(e,18e5).map(e=>e.clientId)))}get started(){return this.ns}getMutationQueue(e,t){return Su.Yt(e,this.M,t,this.referenceDelegate)}getTargetCache(){return this.fs}getRemoteDocumentCache(){return this.ds}getIndexManager(e){return new pu(e,this.M.Jt.databaseId)}getDocumentOverlayCache(e){return tu.Yt(this.M,e)}getBundleCache(){return this._s}runTransaction(t,n,r){Er("IndexedDbPersistence","Starting transaction:",t);var e,s="readonly"===n?"readonly":"readwrite",e=14===(e=this.ts)?Eo:13===e?Io:12===e?bo:11===e?wo:void Ar();let i;return this.ls.runTransaction(t,s,e,e=>(i=new Vo(e,this.es?this.es.next():Br.A),"readwrite-primary"===n?this.Es(i).next(e=>!!e||this.As(i)).next(e=>{if(!e)throw Tr(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Yn.enqueueRetryable(()=>this.cs(!1)),new Nr(xr.FAILED_PRECONDITION,To);return r(i)}).next(e=>this.Ps(i).next(()=>e)):this.$s(i).next(()=>r(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}$s(e){return eh(e).get("owner").next(e=>{if(null!==e&&this.Ss(e.leaseTimestampMs,5e3)&&!this.xs(e.ownerId)&&!this.bs(e)&&!(this.Zn||this.allowTabSynchronization&&e.allowTabSynchronization))throw new Nr(xr.FAILED_PRECONDITION,Ju)})}Ps(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return eh(e).put("owner",t)}static vt(){return Do.vt()}Rs(e){const t=eh(e);return t.get("owner").next(e=>this.bs(e)?(Er("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):So.resolve())}Ss(e,t){var n=Date.now();return!(e<n-t||n<e&&(Tr(`Detected an update time that is in the future: ${e} > ${n}`),1))}ys(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.rs=()=>{this.Yn.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.gs()))},this.document.addEventListener("visibilitychange",this.rs),this.inForeground="visible"===this.document.visibilityState)}ks(){this.rs&&(this.document.removeEventListener("visibilitychange",this.rs),this.rs=null)}ps(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ss=()=>{this.Ns(),s()&&navigator.appVersion.match(/Version\/1[45]/)&&this.Yn.enterRestrictedMode(!0),this.Yn.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.ss))}Ms(){this.ss&&(this.window.removeEventListener("pagehide",this.ss),this.ss=null)}xs(e){var t;try{var n=null!==(null===(t=this.ws)||void 0===t?void 0:t.getItem(this.Cs(e)));return Er("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return Tr("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Ns(){if(this.ws)try{this.ws.setItem(this.Cs(this.clientId),String(Date.now()))}catch(e){Tr("Failed to set zombie client id.",e)}}Os(){if(this.ws)try{this.ws.removeItem(this.Cs(this.clientId))}catch(e){}}Cs(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function eh(e){return Oo(e,"owner")}function th(e){return Oo(e,"clientMetadata")}function nh(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class rh{constructor(e,t,n){this.ds=e,this.Bs=t,this.indexManager=n}Ls(t,n){return this.Bs.getAllMutationBatchesAffectingDocumentKey(t,n).next(e=>this.Us(t,n,e))}Us(e,t,n){return this.ds.getEntry(e,t).next(e=>{for(const t of n)t.applyToLocalView(e);return e})}qs(e,n){e.forEach((e,t)=>{for(const e of n)e.applyToLocalView(t)})}Ks(t,e){return this.ds.getEntries(t,e).next(e=>this.Gs(t,e).next(()=>e))}Gs(e,t){return this.Bs.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>this.qs(t,e))}Qs(e,t,n){return r=t,ds.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.js(e,t.path):wi(t)?this.Ws(e,t,n):this.zs(e,t,n);var r}js(e,t){return this.Ls(e,new ds(t)).next(e=>{let t=ca();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}Ws(r,s,i){const a=s.collectionGroup;let o=ca();return this.indexManager.getCollectionParents(r,a).next(e=>So.forEach(e,e=>{var t,n=(t=s,e=e.child(a),new gi(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.zs(r,n,i).next(e=>{e.forEach((e,t)=>{o=o.insert(e,t)})})}).next(()=>o))}zs(t,n,e){let s;return this.ds.getAllFromCollection(t,n.path,e).next(e=>(s=e,this.Bs.getAllMutationBatchesAffectingQuery(t,n))).next(t=>{for(const r of t)for(const t of r.mutations){var n=t.key;let e=s.get(n);null==e&&(e=Ms.newInvalidDocument(n),s=s.insert(n,e)),Qi(t,e,r.localWriteTime),e.isFoundDocument()||(s=s.remove(n))}}).next(()=>(s.forEach((e,t)=>{Ai(n,t)||(s=s.remove(e))}),s))}}class sh{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Hs=n,this.Js=r}static Ys(e,t){let n=ga(),r=ga();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 sh(e,t.fromCache,n,r)}}class ih{constructor(){this.Xs=!1}initialize(e,t){this.Zs=e,this.indexManager=t,this.Xs=!0}Qs(t,n,r,s){return this.ti(t,n).next(e=>e||this.ei(t,n,s,r)).next(e=>e||this.ni(t,n))}ti(e,t){return So.resolve(null)}ei(n,r,s,i){return 0===(e=r).filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())||i.isEqual($r.min())?this.ni(n,r):this.Zs.Ks(n,s).next(e=>{var t=this.si(r,e);return this.ii(r,t,s,i)?this.ni(n,r):(Ir()<=l.DEBUG&&Er("QueryEngine","Re-using previous result from %s to execute query: %s",i.toString(),Si(r)),this.ri(n,t,r,Ps(i,-1)))});var e}si(n,e){let r=new Gs(xi(n));return e.forEach((e,t)=>{Ai(n,t)&&(r=r.add(t))}),r}ii(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const s="F"===e.limitType?t.last():t.first();return!!s&&(s.hasPendingWrites||0<s.version.compareTo(r))}ni(e,t){return Ir()<=l.DEBUG&&Er("QueryEngine","Using full collection scan to execute query:",Si(t)),this.Zs.Qs(e,t,Bs.min())}ri(e,n,t,r){return this.Zs.Qs(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class ah{constructor(e,t,n,r){this.persistence=e,this.oi=t,this.M=r,this.ui=new Us(Ur),this.ai=new oa(e=>Hs(e),Ys),this.ci=new Map,this.hi=e.getRemoteDocumentCache(),this.fs=e.getTargetCache(),this._s=e.getBundleCache(),this.li(n)}li(e){this.indexManager=this.persistence.getIndexManager(e),this.Bs=this.persistence.getMutationQueue(e,this.indexManager),this.fi=new rh(this.hi,this.Bs,this.indexManager),this.hi.setIndexManager(this.indexManager),this.oi.initialize(this.fi,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.ui))}}function oh(e,t,n,r){return new ah(e,t,n,r)}async function uh(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",s=>{let i;return a.Bs.getAllMutationBatches(s).next(e=>(i=e,a.li(t),a.Bs.getAllMutationBatches(s))).next(e=>{const t=[],n=[];let r=ga();for(const s of i){t.push(s.batchId);for(const e of s.mutations)r=r.add(e.key)}for(const s of e){n.push(s.batchId);for(const e of s.mutations)r=r.add(e.key)}return a.fi.Ks(s,r).next(e=>({di:e,removedBatchIds:t,addedBatchIds:n}))})})}function hh(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.fs.getLastRemoteSnapshotVersion(e))}function ch(e,h){const c=e,l=h.snapshotVersion;let d=c.ui;return c.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=c.hi.newChangeBuffer({trackRemovals:!0});d=c.ui;const u=[];h.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){u.push(c.fs.removeMatchingKeys(o,t.removedDocuments,n).next(()=>c.fs.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var s,i,a;h.targetMismatches.has(n)?e=e.withResumeToken(es.EMPTY_BYTE_STRING,$r.min()).withLastLimboFreeSnapshotVersion($r.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,l)),d=d.insert(n,e),s=r,i=e,a=t,0!==s.resumeToken.approximateByteSize()&&!(3e8<=i.snapshotVersion.toMicroseconds()-s.snapshotVersion.toMicroseconds()||0<a.addedDocuments.size+a.modifiedDocuments.size+a.removedDocuments.size)||u.push(c.fs.updateTargetData(o,e))}});let t=ua;if(h.documentUpdates.forEach(e=>{h.resolvedLimboDocuments.has(e)&&u.push(c.persistence.referenceDelegate.updateLimboDocument(o,e))}),u.push(lh(o,e,h.documentUpdates).next(e=>{t=e})),!l.isEqual($r.min())){const h=c.fs.getLastRemoteSnapshotVersion(o).next(e=>c.fs.setTargetsMetadata(o,o.currentSequenceNumber,l));u.push(h)}return So.waitFor(u).next(()=>e.apply(o)).next(()=>c.fi.Gs(o,t)).next(()=>t)}).then(e=>(c.ui=d,e))}function lh(e,i,t){let n=ga();return t.forEach(e=>n=n.add(e)),i.getEntries(e,n).next(r=>{let s=ua;return t.forEach((e,t)=>{const n=r.get(e);t.isNoDocument()&&t.version.isEqual($r.min())?(i.removeEntry(e,t.readTime),s=s.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(i.addEntry(t),s=s.insert(e,t)):Er("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),s})}function dh(e,r){const s=e;return s.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return s.fs.getTargetData(t,r).next(e=>e?(n=e,So.resolve(n)):s.fs.allocateTargetId(t).next(e=>(n=new qo(r,e,0,t.currentSequenceNumber),s.fs.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=s.ui.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(s.ui=s.ui.insert(e.targetId,e),s.ai.set(r,e.targetId)),e})}async function fh(e,t,n){const r=e,s=r.ui.get(t),i=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",i,e=>r.persistence.referenceDelegate.removeTarget(e,s))}catch(e){if(!Co(e))throw e;Er("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.ui=r.ui.remove(t),r.ai.delete(s.target)}function gh(e,n,r){const s=e;let i=$r.min(),a=ga();return s.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,s=r.ai.get(n);return void 0!==s?So.resolve(r.ui.get(s)):r.fs.getTargetData(t,n)}(s,t,Ii(n)).next(e=>{if(e)return i=e.lastLimboFreeSnapshotVersion,s.fs.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>s.oi.Qs(t,n,r?i:$r.min(),r?a:ga())).next(e=>(yh(s,Di(n),e),{documents:e,_i:a})))}function mh(e,t){const n=e,r=n.fs,s=n.ui.get(t);return s?Promise.resolve(s.target):n.persistence.runTransaction("Get target data","readonly",e=>r.Et(e,t).next(e=>e?e.target:null))}function ph(e,t){const n=e,r=n.ci.get(t)||$r.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.hi.getAllFromCollectionGroup(e,t,Ps(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(yh(n,t,e),e))}function yh(e,t,n){let r=$r.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.ci.set(t,r)}class vh{constructor(e){this.M=e,this.yi=new Map,this.pi=new Map}getBundleMetadata(e,t){return So.resolve(this.yi.get(t))}saveBundleMetadata(e,t){return this.yi.set(t.id,{id:t.id,version:t.version,createTime:Ca(t.createTime)}),So.resolve()}getNamedQuery(e,t){return So.resolve(this.pi.get(t))}saveNamedQuery(e,t){return this.pi.set(t.name,{name:(t=t).name,query:Ho(t.bundledQuery),readTime:Ca(t.readTime)}),So.resolve()}}class wh{constructor(){this.overlays=new Us(ds.comparator),this.Ii=new Map}getOverlay(e,t){return So.resolve(this.overlays.get(t))}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.Xt(n,r,t)}),So.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.Ii.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.Ii.delete(n)),So.resolve()}getOverlaysForCollection(e,t,n){const r=la(),s=t.length+1,i=new ds(t.child("")),a=this.overlays.getIteratorFrom(i);for(;a.hasNext();){const e=a.getNext().value,i=e.getKey();if(!t.isPrefixOf(i.path))break;i.path.length===s&&e.largestBatchId>n&&r.set(e.getKey(),e)}return So.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let s=new Us((e,t)=>e-t);const i=this.overlays.getIterator();for(;i.hasNext();){const t=i.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=s.get(t.largestBatchId);null===e&&(e=la(),s=s.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=la(),o=s.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return So.resolve(a)}Xt(t,n,r){if(null!==r){var s=this.overlays.get(r.key);if(null!==s){const t=this.Ii.get(s.largestBatchId).delete(r.key);this.Ii.set(s.largestBatchId,t)}this.overlays=this.overlays.insert(r.key,new Bo(n,r));let e=this.Ii.get(n);void 0===e&&(e=ga(),this.Ii.set(n,e)),this.Ii.set(n,e.add(r.key))}}}class bh{constructor(){this.Ti=new Gs(Ih.Ei),this.Ai=new Gs(Ih.Ri)}isEmpty(){return this.Ti.isEmpty()}addReference(e,t){var n=new Ih(e,t);this.Ti=this.Ti.add(n),this.Ai=this.Ai.add(n)}Pi(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.bi(new Ih(e,t))}Vi(e,t){e.forEach(e=>this.removeReference(e,t))}vi(e){const t=new ds(new Yr([])),n=new Ih(t,e),r=new Ih(t,e+1),s=[];return this.Ai.forEachInRange([n,r],e=>{this.bi(e),s.push(e.key)}),s}Si(){this.Ti.forEach(e=>this.bi(e))}bi(e){this.Ti=this.Ti.delete(e),this.Ai=this.Ai.delete(e)}Di(e){var t=new ds(new Yr([])),n=new Ih(t,e),t=new Ih(t,e+1);let r=ga();return this.Ai.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new Ih(e,0),t=this.Ti.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class Ih{constructor(e,t){this.key=e,this.Ci=t}static Ei(e,t){return ds.comparator(e.key,t.key)||Ur(e.Ci,t.Ci)}static Ri(e,t){return Ur(e.Ci,t.Ci)||ds.comparator(e.key,t.key)}}class Eh{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.Bs=[],this.xi=1,this.Ni=new Gs(Ih.Ei)}checkEmpty(e){return So.resolve(0===this.Bs.length)}addMutationBatch(e,t,n,r){var s=this.xi;this.xi++,0<this.Bs.length&&this.Bs[this.Bs.length-1];var i=new Fo(s,t,n,r);this.Bs.push(i);for(const t of r)this.Ni=this.Ni.add(new Ih(t.key,s)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return So.resolve(i)}lookupMutationBatch(e,t){return So.resolve(this.ki(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.Mi(t+1),n=n<0?0:n;return So.resolve(this.Bs.length>n?this.Bs[n]:null)}getHighestUnacknowledgedBatchId(){return So.resolve(0===this.Bs.length?-1:this.xi-1)}getAllMutationBatches(e){return So.resolve(this.Bs.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Ih(t,0),r=new Ih(t,Number.POSITIVE_INFINITY),s=[];return this.Ni.forEachInRange([n,r],e=>{var t=this.ki(e.Ci);s.push(t)}),So.resolve(s)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new Gs(Ur);return t.forEach(e=>{var t=new Ih(e,0),n=new Ih(e,Number.POSITIVE_INFINITY);this.Ni.forEachInRange([t,n],e=>{r=r.add(e.Ci)})}),So.resolve(this.Oi(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let s=n;ds.isDocumentKey(s)||(s=s.child(""));var i=new Ih(new ds(s),0);let a=new Gs(Ur);return this.Ni.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.Ci)),!0)},i),So.resolve(this.Oi(a))}Oi(e){const n=[];return e.forEach(e=>{var t=this.ki(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){Dr(0===this.Fi(r.batchId,"removed")),this.Bs.shift();let s=this.Ni;return So.forEach(r.mutations,e=>{var t=new Ih(e.key,r.batchId);return s=s.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.Ni=s})}_n(e){}containsKey(e,t){var n=new Ih(t,0),n=this.Ni.firstAfterOrEqual(n);return So.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.Bs.length,So.resolve()}Fi(e,t){return this.Mi(e)}Mi(e){return 0===this.Bs.length?0:e-this.Bs[0].batchId}ki(e){var t=this.Mi(e);return t<0||t>=this.Bs.length?null:this.Bs[t]}}class Th{constructor(e){this.$i=e,this.docs=new Us(ds.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),s=r?r.size:0,i=this.$i(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:i}),this.size+=i-s,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return So.resolve(n?n.document.mutableCopy():Ms.newInvalidDocument(t))}getEntries(e,t){let n=ua;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Ms.newInvalidDocument(e))}),So.resolve(n)}getAllFromCollection(e,t,n){let r=ua;const s=new ds(t.child("")),i=this.docs.getIteratorFrom(s);for(;i.hasNext();){const{key:e,value:{document:s}}=i.getNext();if(!t.isPrefixOf(e.path))break;e.path.length>t.length+1||qs((a=s,new Bs(a.readTime,a.key,-1)),n)<=0||(r=r.insert(s.key,s.mutableCopy()))}var a;return So.resolve(r)}getAllFromCollectionGroup(e,t,n,r){Ar()}Bi(e,t){return So.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new _h(this)}getSize(e){return So.resolve(this.size)}}class _h extends Ku{constructor(e){super(),this.Kn=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.Kn.addEntry(n,t)):this.Kn.removeEntry(e)}),So.waitFor(r)}getFromCache(e,t){return this.Kn.getEntry(e,t)}getAllFromCache(e,t){return this.Kn.getEntries(e,t)}}class Sh{constructor(e){this.persistence=e,this.Li=new oa(e=>Hs(e),Ys),this.lastRemoteSnapshotVersion=$r.min(),this.highestTargetId=0,this.Ui=0,this.qi=new bh,this.targetCount=0,this.Ki=Cu.gn()}forEachTarget(e,n){return this.Li.forEach((e,t)=>n(t)),So.resolve()}getLastRemoteSnapshotVersion(e){return So.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return So.resolve(this.Ui)}allocateTargetId(e){return this.highestTargetId=this.Ki.next(),So.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Ui&&(this.Ui=t),So.resolve()}Tn(e){this.Li.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Ki=new Cu(t),this.highestTargetId=t),e.sequenceNumber>this.Ui&&(this.Ui=e.sequenceNumber)}addTargetData(e,t){return this.Tn(t),this.targetCount+=1,So.resolve()}updateTargetData(e,t){return this.Tn(t),So.resolve()}removeTargetData(e,t){return this.Li.delete(t.target),this.qi.vi(t.targetId),--this.targetCount,So.resolve()}removeTargets(n,r,s){let i=0;const a=[];return this.Li.forEach((e,t)=>{t.sequenceNumber<=r&&null===s.get(t.targetId)&&(this.Li.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),i++)}),So.waitFor(a).next(()=>i)}getTargetCount(e){return So.resolve(this.targetCount)}getTargetData(e,t){var n=this.Li.get(t)||null;return So.resolve(n)}addMatchingKeys(e,t,n){return this.qi.Pi(t,n),So.resolve()}removeMatchingKeys(t,e,n){this.qi.Vi(e,n);const r=this.persistence.referenceDelegate,s=[];return r&&e.forEach(e=>{s.push(r.markPotentiallyOrphaned(t,e))}),So.waitFor(s)}removeMatchingKeysForTargetId(e,t){return this.qi.vi(t),So.resolve()}getMatchingKeysForTargetId(e,t){var n=this.qi.Di(t);return So.resolve(n)}containsKey(e,t){return So.resolve(this.qi.containsKey(t))}}class Ah{constructor(e,t){this.Gi={},this.overlays={},this.es=new Br(0),this.ns=!1,this.ns=!0,this.referenceDelegate=e(this),this.fs=new Sh(this),this.indexManager=new fu,this.ds=(e=e=>this.referenceDelegate.Qi(e),new Th(e)),this.M=new Uo(t),this._s=new vh(this.M)}start(){return Promise.resolve()}shutdown(){return this.ns=!1,Promise.resolve()}get started(){return this.ns}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new wh,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Gi[e.toKey()];return n||(n=new Eh(t,this.referenceDelegate),this.Gi[e.toKey()]=n),n}getTargetCache(){return this.fs}getRemoteDocumentCache(){return this.ds}getBundleCache(){return this._s}runTransaction(e,t,n){Er("MemoryPersistence","Starting transaction:",e);const r=new Dh(this.es.next());return this.referenceDelegate.ji(),n(r).next(e=>this.referenceDelegate.Wi(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}zi(t,n){return So.or(Object.values(this.Gi).map(e=>()=>e.containsKey(t,n)))}}class Dh extends _o{constructor(e){super(),this.currentSequenceNumber=e}}class xh{constructor(e){this.persistence=e,this.Hi=new bh,this.Ji=null}static Yi(e){return new xh(e)}get Xi(){if(this.Ji)return this.Ji;throw Ar()}addReference(e,t,n){return this.Hi.addReference(n,t),this.Xi.delete(n.toString()),So.resolve()}removeReference(e,t,n){return this.Hi.removeReference(n,t),this.Xi.add(n.toString()),So.resolve()}markPotentiallyOrphaned(e,t){return this.Xi.add(t.toString()),So.resolve()}removeTarget(e,t){this.Hi.vi(t.targetId).forEach(e=>this.Xi.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Xi.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}ji(){this.Ji=new Set}Wi(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return So.forEach(this.Xi,e=>{const t=ds.fromPath(e);return this.Zi(n,t).next(e=>{e||r.removeEntry(t,$r.min())})}).next(()=>(this.Ji=null,r.apply(n)))}updateLimboDocument(e,t){return this.Zi(e,t).next(e=>{e?this.Xi.delete(t.toString()):this.Xi.add(t.toString())})}Qi(e){return 0}Zi(e,t){return So.or([()=>So.resolve(this.Hi.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.zi(e,t)])}}function Nh(e,t){return`firestore_clients_${e}_${t}`}function Ch(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function kh(e,t){return`firestore_targets_${e}_${t}`}class Mh{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static tr(e,t,n){var r=JSON.parse(n);let s,i="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return i&&r.error&&(i="string"==typeof r.error.message&&"string"==typeof r.error.code,i&&(s=new Nr(r.error.code,r.error.message))),i?new Mh(e,t,r.state,s):(Tr("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}er(){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 Rh{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static tr(e,t){var n=JSON.parse(t);let r,s="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return s&&n.error&&(s="string"==typeof n.error.message&&"string"==typeof n.error.code,s&&(r=new Nr(n.error.code,n.error.message))),s?new Rh(e,n.state,r):(Tr("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}er(){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 Lh{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static tr(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,s=ma;for(let i=0;r&&i<n.activeTargetIds.length;++i)r=ls(n.activeTargetIds[i]),s=s.add(n.activeTargetIds[i]);return r?new Lh(e,s):(Tr("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class Vh{constructor(e,t){this.clientId=e,this.onlineState=t}static tr(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new Vh(t.clientId,t.onlineState):(Tr("SharedClientState",`Failed to parse online state: ${e}`),null)}}class Oh{constructor(){this.activeTargetIds=ma}nr(e){this.activeTargetIds=this.activeTargetIds.add(e)}sr(e){this.activeTargetIds=this.activeTargetIds.delete(e)}er(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class Fh{constructor(e,t,n,r,s){this.window=e,this.Yn=t,this.persistenceKey=n,this.ir=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.rr=this.ur.bind(this),this.ar=new Us(Ur),this.started=!1,this.cr=[];var i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=s,this.hr=Nh(this.persistenceKey,this.ir),this.lr=`firestore_sequence_number_${this.persistenceKey}`,this.ar=this.ar.insert(this.ir,new Oh),this.dr=new RegExp(`^firestore_clients_${i}_([^_]*)$`),this._r=new RegExp(`^firestore_mutations_${i}_(\\d+)(?:_(.*))?$`),this.wr=new RegExp(`^firestore_targets_${i}_(\\d+)$`),this.mr=`firestore_online_state_${this.persistenceKey}`,this.gr=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.rr)}static vt(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.Fs();for(const n of e)if(n!==this.ir){const e=this.getItem(Nh(this.persistenceKey,n));var t;!e||(t=Lh.tr(n,e))&&(this.ar=this.ar.insert(t.clientId,t))}this.yr();const n=this.storage.getItem(this.mr);if(n){const e=this.pr(n);e&&this.Ir(e)}for(const e of this.cr)this.ur(e);this.cr=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.lr,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Tr(this.ar)}isActiveQueryTarget(n){let r=!1;return this.ar.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Er(e,"pending")}updateMutationState(e,t,n){this.Er(e,t,n),this.Ar(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(kh(this.persistenceKey,e)))||(n=Rh.tr(e,n))&&(t=n.state)),this.Rr.nr(e),this.yr(),t}removeLocalQueryTarget(e){this.Rr.sr(e),this.yr()}isLocalQueryTarget(e){return this.Rr.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(kh(this.persistenceKey,e))}updateQueryState(e,t,n){this.Pr(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Ar(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.br(e)}notifyBundleLoaded(e){this.Vr(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.rr),this.removeItem(this.hr),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return Er("SharedClientState","READ",e,t),t}setItem(e,t){Er("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){Er("SharedClientState","REMOVE",e),this.storage.removeItem(e)}ur(e){const s=e;s.storageArea===this.storage&&(Er("SharedClientState","EVENT",s.key,s.newValue),s.key!==this.hr?this.Yn.enqueueRetryable(async()=>{if(this.started){if(null!==s.key)if(this.dr.test(s.key)){if(null==s.newValue){var e=this.vr(s.key);return this.Sr(e,null)}e=this.Dr(s.key,s.newValue);if(e)return this.Sr(e.clientId,e)}else if(this._r.test(s.key)){if(null!==s.newValue){var t=this.Cr(s.key,s.newValue);if(t)return this.Nr(t)}}else if(this.wr.test(s.key)){if(null!==s.newValue){t=this.kr(s.key,s.newValue);if(t)return this.Mr(t)}}else if(s.key===this.mr){if(null!==s.newValue){var n=this.pr(s.newValue);if(n)return this.Ir(n)}}else if(s.key===this.lr){n=function(e){let t=Br.A;if(null!=e)try{var n=JSON.parse(e);Dr("number"==typeof n),t=n}catch(e){Tr("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(s.newValue);n!==Br.A&&this.sequenceNumberHandler(n)}else if(s.key===this.gr){const r=this.Or(s.newValue);await Promise.all(r.map(e=>this.syncEngine.Fr(e)))}}else this.cr.push(s)}):Tr("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get Rr(){return this.ar.get(this.ir)}yr(){this.setItem(this.hr,this.Rr.er())}Er(e,t,n){const r=new Mh(this.currentUser,e,t,n),s=Ch(this.persistenceKey,this.currentUser,e);this.setItem(s,r.er())}Ar(e){var t=Ch(this.persistenceKey,this.currentUser,e);this.removeItem(t)}br(e){var t={clientId:this.ir,onlineState:e};this.storage.setItem(this.mr,JSON.stringify(t))}Pr(e,t,n){const r=kh(this.persistenceKey,e),s=new Rh(e,t,n);this.setItem(r,s.er())}Vr(e){var t=JSON.stringify(Array.from(e));this.setItem(this.gr,t)}vr(e){var t=this.dr.exec(e);return t?t[1]:null}Dr(e,t){var n=this.vr(e);return Lh.tr(n,t)}Cr(e,t){var n=this._r.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return Mh.tr(new vr(n),r,t)}kr(e,t){var n=this.wr.exec(e),n=Number(n[1]);return Rh.tr(n,t)}pr(e){return Vh.tr(e)}Or(e){return JSON.parse(e)}async Nr(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.$r(e.batchId,e.state,e.error);Er("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Mr(e){return this.syncEngine.Br(e.targetId,e.state,e.error)}Sr(e,t){const n=t?this.ar.insert(e,t):this.ar.remove(e),r=this.Tr(this.ar),s=this.Tr(n),i=[],a=[];return s.forEach(e=>{r.has(e)||i.push(e)}),r.forEach(e=>{s.has(e)||a.push(e)}),this.syncEngine.Lr(i,a).then(()=>{this.ar=n})}Ir(e){this.ar.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Tr(e){let n=ma;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class Ph{constructor(){this.Ur=new Oh,this.qr={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Ur.nr(e),this.qr[e]||"not-current"}updateQueryState(e,t,n){this.qr[e]=t}removeLocalQueryTarget(e){this.Ur.sr(e)}isLocalQueryTarget(e){return this.Ur.activeTargetIds.has(e)}clearQueryState(e){delete this.qr[e]}getAllActiveQueryTargets(){return this.Ur.activeTargetIds}isActiveQueryTarget(e){return this.Ur.activeTargetIds.has(e)}start(){return this.Ur=new Oh,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class Bh{Kr(e){}shutdown(){}}class qh{constructor(){this.Gr=()=>this.Qr(),this.jr=()=>this.Wr(),this.zr=[],this.Hr()}Kr(e){this.zr.push(e)}shutdown(){window.removeEventListener("online",this.Gr),window.removeEventListener("offline",this.jr)}Hr(){window.addEventListener("online",this.Gr),window.addEventListener("offline",this.jr)}Qr(){Er("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.zr)e(0)}Wr(){Er("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.zr)e(1)}static vt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const Uh={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class Kh{constructor(e){this.Jr=e.Jr,this.Yr=e.Yr}Xr(e){this.Zr=e}eo(e){this.no=e}onMessage(e){this.so=e}close(){this.Yr()}send(e){this.Jr(e)}io(){this.Zr()}ro(e){this.no(e)}oo(e){this.so(e)}}class jh extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.uo=t+"://"+e.host,this.ao="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}co(t,e,n,r,s){const i=this.ho(t,e);Er("RestConnection","Sending: ",i,n);var a={};return this.lo(a,r,s),this.fo(t,i,a,n).then(e=>(Er("RestConnection","Received: ",e),e),e=>{throw _r("RestConnection",`${t} failed with error: `,e,"url: ",i,"request:",n),e})}_o(e,t,n,r,s){return this.co(e,t,n,r,s)}lo(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+wr,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}ho(e,t){var n=Uh[e];return`${this.uo}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}fo(o,t,n,r){return new Promise((s,i)=>{const a=new pr;a.listenOnce(cr.COMPLETE,()=>{try{switch(a.getLastErrorCode()){case hr.NO_ERROR:var e=a.getResponseJson();Er("Connection","XHR received:",JSON.stringify(e)),s(e);break;case hr.TIMEOUT:Er("Connection",'RPC "'+o+'" timed out'),i(new Nr(xr.DEADLINE_EXCEEDED,"Request time out"));break;case hr.HTTP_ERROR:var t,n=a.getStatus();if(Er("Connection",'RPC "'+o+'" failed with status:',n,"response text:",a.getResponseText()),0<n){const o=a.getResponseJson().error;o&&o.status&&o.message?(r=o.status.toLowerCase().replace(/_/g,"-"),t=0<=Object.values(xr).indexOf(r)?r:xr.UNKNOWN,i(new Nr(t,o.message))):i(new Nr(xr.UNKNOWN,"Server responded with status "+a.getStatus()))}else i(new Nr(xr.UNAVAILABLE,"Connection failed."));break;default:Ar()}}finally{Er("Connection",'RPC "'+o+'" completed.')}var r});var e=JSON.stringify(r);a.send(t,"POST",e,n,15)})}wo(e,t,n){const r=[this.uo,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=new nr,i=ur(),a={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(a.xmlHttpFactory=new gr({})),this.lo(a.initMessageHeaders,t,n),"undefined"!=typeof window&&(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(f())||"object"==typeof navigator&&"ReactNative"===navigator.product||0<=f().indexOf("Electron/")||function(){const e=f();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}()||0<=f().indexOf("MSAppHost/")||"object"==typeof(o="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0)&&void 0!==o.id||(a.httpHeadersOverwriteParam="$httpHeaders");var o=r.join("");Er("Connection","Creating WebChannel: "+o,a);const u=s.createWebChannel(o,a);let h=!1,c=!1;const l=new Kh({Jr:e=>{c?Er("Connection","Not sending because WebChannel is closed:",e):(h||(Er("Connection","Opening WebChannel transport."),u.open(),h=!0),Er("Connection","WebChannel sending:",e),u.send(e))},Yr:()=>u.close()}),d=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return d(u,mr.EventType.OPEN,()=>{c||Er("Connection","WebChannel transport opened.")}),d(u,mr.EventType.CLOSE,()=>{c||(c=!0,Er("Connection","WebChannel transport closed"),l.ro())}),d(u,mr.EventType.ERROR,e=>{c||(c=!0,_r("Connection","WebChannel transport errored:",e),l.ro(new Nr(xr.UNAVAILABLE,"The operation could not be completed")))}),d(u,mr.EventType.MESSAGE,n=>{if(!c){var e=n.data[0];Dr(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){Er("Connection","WebChannel received error:",r);const n=r.status;let e=function(e){var t=or[e];if(void 0!==t)return aa(t)}(n),t=r.message;void 0===e&&(e=xr.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),c=!0,l.ro(new Nr(e,t)),u.close()}else Er("Connection","WebChannel received:",e),l.oo(e)}}),d(i,lr.STAT_EVENT,e=>{e.stat===dr?Er("Connection","Detected buffering proxy"):e.stat===fr&&Er("Connection","Detected no buffering proxy")}),setTimeout(()=>{l.io()},0),l}}function Gh(){return"undefined"!=typeof window?window:null}function $h(){return"undefined"!=typeof document?document:null}function zh(e){return new Da(e,!0)}class Wh{constructor(e,t,n=1e3,r=1.5,s=6e4){this.Yn=e,this.timerId=t,this.mo=n,this.yo=r,this.po=s,this.Io=0,this.To=null,this.Eo=Date.now(),this.reset()}reset(){this.Io=0}Ao(){this.Io=this.po}Ro(e){this.cancel();var t=Math.floor(this.Io+this.Po()),n=Math.max(0,Date.now()-this.Eo),r=Math.max(0,t-n);0<r&&Er("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Io} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.To=this.Yn.enqueueAfterDelay(this.timerId,r,()=>(this.Eo=Date.now(),e())),this.Io*=this.yo,this.Io<this.mo&&(this.Io=this.mo),this.Io>this.po&&(this.Io=this.po)}bo(){null!==this.To&&(this.To.skipDelay(),this.To=null)}cancel(){null!==this.To&&(this.To.cancel(),this.To=null)}Po(){return(Math.random()-.5)*this.Io}}class Qh{constructor(e,t,n,r,s,i,a,o){this.Yn=e,this.Vo=n,this.vo=r,this.So=s,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Do=0,this.Co=null,this.xo=null,this.stream=null,this.No=new Wh(e,t)}ko(){return 1===this.state||5===this.state||this.Mo()}Mo(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Oo()}async stop(){this.ko()&&await this.close(0)}Fo(){this.state=0,this.No.reset()}$o(){this.Mo()&&null===this.Co&&(this.Co=this.Yn.enqueueAfterDelay(this.Vo,6e4,()=>this.Bo()))}Lo(e){this.Uo(),this.stream.send(e)}async Bo(){if(this.Mo())return this.close(0)}Uo(){this.Co&&(this.Co.cancel(),this.Co=null)}qo(){this.xo&&(this.xo.cancel(),this.xo=null)}async close(e,t){this.Uo(),this.qo(),this.No.cancel(),this.Do++,4!==e?this.No.reset():t&&t.code===xr.RESOURCE_EXHAUSTED?(Tr(t.toString()),Tr("Using maximum backoff delay to prevent overloading the backend."),this.No.Ao()):t&&t.code===xr.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Ko(),this.stream.close(),this.stream=null),this.state=e,await this.listener.eo(t)}Ko(){}auth(){this.state=1;const e=this.Go(this.Do),n=this.Do;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.Do===n&&this.Qo(e,t)},t=>{e(()=>{var e=new Nr(xr.UNKNOWN,"Fetching auth token failed: "+t.message);return this.jo(e)})})}Qo(e,t){const n=this.Go(this.Do);this.stream=this.Wo(e,t),this.stream.Xr(()=>{n(()=>(this.state=2,this.xo=this.Yn.enqueueAfterDelay(this.vo,1e4,()=>(this.Mo()&&(this.state=3),Promise.resolve())),this.listener.Xr()))}),this.stream.eo(e=>{n(()=>this.jo(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}Oo(){this.state=5,this.No.Ro(async()=>{this.state=0,this.start()})}jo(e){return Er("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Go(t){return e=>{this.Yn.enqueueAndForget(()=>this.Do===t?e():(Er("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class Hh extends Qh{constructor(e,t,n,r,s,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,i),this.M=s}Wo(e,t){return this.So.wo("Listen",e,t)}onMessage(e){this.No.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:Ar(),s=t.targetChange.targetIds||[],i=(f=t.targetChange.resumeToken,e.N?(Dr(void 0===f||"string"==typeof f),es.fromBase64String(f||"")):(Dr(void 0===f||f instanceof Uint8Array),es.fromUint8Array(f||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(f=a).code?xr.UNKNOWN:aa(f.code),new Nr(o,f.message||""));n=new ba(r,s,i,o||null)}else if("documentChange"in t){t.documentChange;var u=t.documentChange;u.document,u.document.name,u.document.updateTime;var o=La(e,u.document.name),h=Ca(u.document.updateTime),c=new ks({mapValue:{fields:u.document.fields}}),h=Ms.newFoundDocument(o,h,c),c=u.targetIds||[],u=u.removedTargetIds||[];n=new va(c,u,h.key,h)}else if("documentDelete"in t){t.documentDelete;c=t.documentDelete;c.document;u=La(e,c.document),h=c.readTime?Ca(c.readTime):$r.min(),h=Ms.newNoDocument(u,h),c=c.removedTargetIds||[];n=new va([],c,h.key,h)}else if("documentRemove"in t){t.documentRemove;var l=t.documentRemove;l.document;var d=La(e,l.document),l=l.removedTargetIds||[];n=new va([],l,d,null)}else{if(!("filter"in t))return Ar();{t.filter;const e=t.filter;e.targetId;l=e.count||0,d=new sa(l),l=e.targetId;n=new wa(l,d)}}var o,f;return n}(this.M,e),n=function(e){if(!("targetChange"in e))return $r.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?Ca(t.readTime):$r.min()}(e);return this.listener.zo(t,n)}Ho(e){const t={};t.database=Fa(this.M),t.addTarget=function(e,t){let n;var r=t.target;return n=Xs(r)?{documents:ja(e,r)}:{query:Ga(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()?n.resumeToken=Na(e,t.resumeToken):0<t.snapshotVersion.compareTo($r.min())&&(n.readTime=xa(e,t.snapshotVersion.toTimestamp())),n}(this.M,e);var n,r,r=(this.M,n=e,null==(r=function(){switch(n.purpose){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return Ar()}}())?null:{"goog-listen-tags":r});r&&(t.labels=r),this.Lo(t)}Jo(e){const t={};t.database=Fa(this.M),t.removeTarget=e,this.Lo(t)}}class Yh extends Qh{constructor(e,t,n,r,s,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,i),this.M=s,this.Yo=!1}get Xo(){return this.Yo}start(){this.Yo=!1,this.lastStreamToken=void 0,super.start()}Ko(){this.Yo&&this.Zo([])}Wo(e,t){return this.So.wo("Write",e,t)}onMessage(e){if(Dr(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Yo){this.No.reset();var t=(r=e.writeResults,s=e.commitTime,r&&0<r.length?(Dr(void 0!==s),r.map(e=>function(e,t){let n=e.updateTime?Ca(e.updateTime):Ca(t);return n.isEqual($r.min())&&(n=Ca(t)),new ji(n,e.transformResults||[])}(e,s))):[]),n=Ca(e.commitTime);return this.listener.tu(n,t)}var r,s;return Dr(!e.writeResults||0===e.writeResults.length),this.Yo=!0,this.listener.eu()}nu(){const e={};e.database=Fa(this.M),this.Lo(e)}Zo(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>Ua(this.M,e))};this.Lo(t)}}class Xh extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.So=n,this.M=r,this.su=!1}iu(){if(this.su)throw new Nr(xr.FAILED_PRECONDITION,"The client has already been terminated.")}co(n,r,s){return this.iu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.So.co(n,r,s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===xr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new Nr(xr.UNKNOWN,e.toString())})}_o(n,r,s){return this.iu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.So._o(n,r,s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===xr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new Nr(xr.UNKNOWN,e.toString())})}terminate(){this.su=!0}}class Jh{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.ru=0,this.ou=null,this.uu=!0}au(){0===this.ru&&(this.cu("Unknown"),this.ou=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.ou=null,this.hu("Backend didn't respond within 10 seconds."),this.cu("Offline"),Promise.resolve())))}lu(e){"Online"===this.state?this.cu("Unknown"):(this.ru++,1<=this.ru&&(this.fu(),this.hu(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.cu("Offline")))}set(e){this.fu(),this.ru=0,"Online"===e&&(this.uu=!1),this.cu(e)}cu(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}hu(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.uu?(Tr(t),this.uu=!1):Er("OnlineStateTracker",t)}fu(){null!==this.ou&&(this.ou.cancel(),this.ou=null)}}class Zh{constructor(e,t,n,r,s){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.du=[],this._u=new Map,this.wu=new Set,this.mu=[],this.gu=s,this.gu.Kr(e=>{n.enqueueAndForget(async()=>{uc(this)&&(Er("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.wu.add(4),await tc(t),t.yu.set("Unknown"),t.wu.delete(4),await ec(t)}(this))})}),this.yu=new Jh(n,r)}}async function ec(e){if(uc(e))for(const t of e.mu)await t(!0)}async function tc(e){for(const t of e.mu)await t(!1)}function nc(e,t){const n=e;n._u.has(t.targetId)||(n._u.set(t.targetId,t),oc(n)?ac(n):yc(n).Mo()&&sc(n,t))}function rc(e,t){const n=e,r=yc(n);n._u.delete(t),r.Mo()&&ic(n,t),0===n._u.size&&(r.Mo()?r.$o():uc(n)&&n.yu.set("Unknown"))}function sc(e,t){e.pu.Z(t.targetId),yc(e).Ho(t)}function ic(e,t){e.pu.Z(t),yc(e).Jo(t)}function ac(t){t.pu=new Ea({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),Et:e=>t._u.get(e)||null}),yc(t).start(),t.yu.au()}function oc(e){return uc(e)&&!yc(e).ko()&&0<e._u.size}function uc(e){return 0===e.wu.size}function hc(e){e.pu=void 0}async function cc(e,t,n){if(!Co(t))throw t;e.wu.add(1),await tc(e),e.yu.set("Offline"),n=n||(()=>hh(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{Er("RemoteStore","Retrying IndexedDB access"),await n(),e.wu.delete(1),await ec(e)})}function lc(t,n){return n().catch(e=>cc(t,e,n))}async function dc(e){const t=e,n=vc(t);let r=0<t.du.length?t.du[t.du.length-1].batchId:-1;for(;uc(s=t)&&s.du.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.Bs.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.du.length&&n.$o();break}r=e.batchId,function(e,t){e.du.push(t);const n=vc(e);n.Mo()&&n.Xo&&n.Zo(t.mutations)}(t,e)}catch(e){await cc(t,e)}var s;fc(t)&&gc(t)}function fc(e){return uc(e)&&!vc(e).ko()&&0<e.du.length}function gc(e){vc(e).start()}async function mc(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),Er("RemoteStore","RemoteStore received new credentials");var r=uc(n);n.wu.add(3),await tc(n),r&&n.yu.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.wu.delete(3),await ec(n)}async function pc(e,t){const n=e;t?(n.wu.delete(2),await ec(n)):(n.wu.add(2),await tc(n),n.yu.set("Unknown"))}function yc(t){return t.Iu||(t.Iu=function(e,t,n){const r=e;return r.iu(),new Hh(t,r.So,r.authCredentials,r.appCheckCredentials,r.M,n)}(t.datastore,t.asyncQueue,{Xr:(async function(n){n._u.forEach((e,t)=>{sc(n,e)})}).bind(null,t),eo:(async function(e,t){hc(e),oc(e)?(e.yu.lu(t),ac(e)):e.yu.set("Unknown")}).bind(null,t),zo:(async function(e,r,t){if(e.yu.set("Online"),r instanceof ba&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e._u.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e._u.delete(n),e.pu.removeTarget(n))}(e)}catch(t){Er("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await cc(e,t)}else if(r instanceof va?e.pu.ut(r):r instanceof wa?e.pu._t(r):e.pu.ht(r),!t.isEqual($r.min()))try{const r=await hh(e.localStore);0<=t.compareTo(r)&&await function(r,s){const e=r.pu.yt(s);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=r._u.get(t);n&&r._u.set(t,n.withResumeToken(e.resumeToken,s))}}),e.targetMismatches.forEach(e=>{const t=r._u.get(e);var n;t&&(r._u.set(e,t.withResumeToken(es.EMPTY_BYTE_STRING,t.snapshotVersion)),ic(r,e),n=new qo(t.target,e,1,t.sequenceNumber),sc(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){Er("RemoteStore","Failed to raise snapshot:",r),await cc(e,r)}}).bind(null,t)}),t.mu.push(async e=>{e?(t.Iu.Fo(),oc(t)?ac(t):t.yu.set("Unknown")):(await t.Iu.stop(),hc(t))})),t.Iu}function vc(t){return t.Tu||(t.Tu=function(e,t,n){const r=e;return r.iu(),new Yh(t,r.So,r.authCredentials,r.appCheckCredentials,r.M,n)}(t.datastore,t.asyncQueue,{Xr:(async function(e){vc(e).nu()}).bind(null,t),eo:(async function(e,t){t&&vc(e).Xo&&await async function(e,t){if(ia(n=t.code)&&n!==xr.ABORTED){const n=e.du.shift();vc(e).Fo(),await lc(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await dc(e)}var n}(e,t),fc(e)&&gc(e)}).bind(null,t),eu:(async function(e){const t=vc(e);for(const n of e.du)t.Zo(n.mutations)}).bind(null,t),tu:(async function(e,t,n){const r=e.du.shift(),s=Po.from(r,t,n);await lc(e,()=>e.remoteSyncer.applySuccessfulWrite(s)),await dc(e)}).bind(null,t)}),t.mu.push(async e=>{e?(t.Tu.Fo(),await dc(t)):(await t.Tu.stop(),0<t.du.length&&(Er("RemoteStore",`Stopping write stream with ${t.du.length} pending writes`),t.du=[]))})),t.Tu}class wc{constructor(e,t,n,r,s){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=s,this.deferred=new Cr,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}static createAndSchedule(e,t,n,r,s){const i=Date.now()+n,a=new wc(e,t,i,r,s);return a.start(n),a}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new Nr(xr.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 bc(e,t){if(Tr("AsyncQueue",`${t}: ${e}`),Co(e))return new Nr(xr.UNAVAILABLE,`${t}: ${e}`);throw e}class Ic{constructor(n){this.comparator=n?(e,t)=>n(e,t)||ds.comparator(e.key,t.key):(e,t)=>ds.comparator(e.key,t.key),this.keyedMap=ca(),this.sortedSet=new Us(this.comparator)}static emptySet(e){return new Ic(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 Ic))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 Ic;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class Ec{constructor(){this.Eu=new Us(ds.comparator)}track(e){var t=e.doc.key,n=this.Eu.get(t);!n||0!==e.type&&3===n.type?this.Eu=this.Eu.insert(t,e):3===e.type&&1!==n.type?this.Eu=this.Eu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Eu=this.Eu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Eu=this.Eu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Eu=this.Eu.remove(t):1===e.type&&2===n.type?this.Eu=this.Eu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Eu=this.Eu.insert(t,{type:2,doc:e.doc}):Ar()}Au(){const n=[];return this.Eu.inorderTraversal((e,t)=>{n.push(t)}),n}}class Tc{constructor(e,t,n,r,s,i,a,o){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=s,this.fromCache=i,this.syncStateChanged=a,this.excludesMetadataChanges=o}static fromInitialDocuments(e,t,n,r){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new Tc(e,t,Ic.emptySet(t),s,n,r,!0,!1)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&Ti(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 _c{constructor(){this.Ru=void 0,this.listeners=[]}}class Sc{constructor(){this.queries=new oa(e=>_i(e),Ti),this.onlineState="Unknown",this.Pu=new Set}}async function Ac(e,t){const n=e,r=t.query;let s=!1,i=n.queries.get(r);if(i||(s=!0,i=new _c),s)try{i.Ru=await n.onListen(r)}catch(e){const n=bc(e,`Initialization of query '${Si(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,i),i.listeners.push(t),t.bu(n.onlineState),!i.Ru||t.Vu(i.Ru)&&xc(n)}async function Dc(e,t){const n=e,r=t.query;let s=!1;const i=n.queries.get(r);if(i){const e=i.listeners.indexOf(t);0<=e&&(i.listeners.splice(e,1),s=0===i.listeners.length)}if(s)return n.queries.delete(r),n.onUnlisten(r)}function xc(e){e.Pu.forEach(e=>{e.next()})}class Nc{constructor(e,t,n){this.query=e,this.vu=t,this.Su=!1,this.Du=null,this.onlineState="Unknown",this.options=n||{}}Vu(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new Tc(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}let t=!1;return this.Su?this.Cu(e)&&(this.vu.next(e),t=!0):this.xu(e,this.onlineState)&&(this.Nu(e),t=!0),this.Du=e,t}onError(e){this.vu.error(e)}bu(e){this.onlineState=e;let t=!1;return this.Du&&!this.Su&&this.xu(this.Du,e)&&(this.Nu(this.Du),t=!0),t}xu(e,t){return!e.fromCache||!(this.options.ku&&"Offline"!==t||e.docs.isEmpty()&&"Offline"!==t)}Cu(e){if(0<e.docChanges.length)return!0;var t=this.Du&&this.Du.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}Nu(e){e=Tc.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.Su=!0,this.vu.next(e)}}class Cc{constructor(e,t){this.payload=e,this.byteLength=t}Mu(){return"metadata"in this.payload}}class kc{constructor(e){this.M=e}wi(e){return La(this.M,e)}mi(e){return e.metadata.exists?qa(this.M,e.document,!1):Ms.newNoDocument(this.wi(e.metadata.name),this.gi(e.metadata.readTime))}gi(e){return Ca(e)}}class Mc{constructor(e,t,n){this.Ou=e,this.localStore=t,this.M=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=Rc(e)}Fu(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.payload.namedQuery)this.queries.push(e.payload.namedQuery);else if(e.payload.documentMetadata){this.documents.push({metadata:e.payload.documentMetadata}),e.payload.documentMetadata.exists||++t;const n=Yr.fromString(e.payload.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.payload.document&&(this.documents[this.documents.length-1].document=e.payload.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}$u(e){const t=new Map,n=new kc(this.M);for(const s of e)if(s.metadata.queries){const e=n.wi(s.metadata.name);for(const n of s.metadata.queries){var r=(t.get(n)||ga()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const s=e;let i=ga(),a=ua;for(const e of n){const n=t.wi(e.metadata.name);e.document&&(i=i.add(n));const h=t.mi(e);h.setReadTime(t.gi(e.metadata.readTime)),a=a.insert(n,h)}const o=s.hi.newChangeBuffer({trackRemovals:!0}),u=await dh(s,(r=r,Ii(pi(Yr.fromString(`__bundle__/docs/${r}`)))));return s.persistence.runTransaction("Apply bundle documents","readwrite",t=>lh(t,o,a).next(e=>(o.apply(t),e)).next(e=>s.fs.removeMatchingKeysForTargetId(t,u.targetId).next(()=>s.fs.addMatchingKeys(t,i,u.targetId)).next(()=>s.fi.Gs(t,e)).next(()=>e)))}(this.localStore,new kc(this.M),this.documents,this.Ou.id),t=this.$u(this.documents);for(const e of this.queries)await async function(e,n,r=ga()){const s=await dh(e,Ii(Ho(n.bundledQuery))),i=e;return i.persistence.runTransaction("Save named query","readwrite",e=>{var t=Ca(n.readTime);if(0<=s.snapshotVersion.compareTo(t))return i._s.saveNamedQuery(e,n);t=s.withResumeToken(es.EMPTY_BYTE_STRING,t);return i.ui=i.ui.insert(t.targetId,t),i.fs.updateTargetData(e,t).next(()=>i.fs.removeMatchingKeysForTargetId(e,s.targetId)).next(()=>i.fs.addMatchingKeys(e,r,s.targetId)).next(()=>i._s.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Bu:this.collectionGroups,Lu:e}}}function Rc(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class Lc{constructor(e){this.key=e}}class Vc{constructor(e){this.key=e}}class Oc{constructor(e,t){this.query=e,this.Uu=t,this.qu=null,this.current=!1,this.Ku=ga(),this.mutatedKeys=ga(),this.Gu=xi(e),this.Qu=new Ic(this.Gu)}get ju(){return this.Uu}Wu(e,t){const o=t?t.zu:new Ec,u=(t||this).Qu;let h=(t||this).mutatedKeys,c=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=Ai(this.query,t)?t:null,s=!!n&&this.mutatedKeys.has(n.key),i=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?s!==i&&(o.track({type:3,doc:r}),a=!0):this.Hu(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.Gu(r,d)||f&&this.Gu(r,f)<0)&&(l=!0)):!n&&r?(o.track({type:0,doc:r}),a=!0):n&&!r&&(o.track({type:1,doc:n}),a=!0,(d||f)&&(l=!0)),a&&(h=r?(c=c.add(r),i?h.add(e):h.delete(e)):(c=c.delete(e),h.delete(e)))}),null!==this.query.limit)for(;c.size>this.query.limit;){const e="F"===this.query.limitType?c.last():c.first();c=c.delete(e.key),h=h.delete(e.key),o.track({type:1,doc:e})}return{Qu:c,zu:o,ii:l,mutatedKeys:h}}Hu(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.Qu;this.Qu=e.Qu,this.mutatedKeys=e.mutatedKeys;const s=e.zu.Au();s.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Ar()}};return n(e)-n(t)}(e.type,t.type)||this.Gu(e.doc,t.doc)),this.Ju(n);var i=t?this.Yu():[],a=0===this.Ku.size&&this.current?1:0,o=a!==this.qu;return this.qu=a,0!==s.length||o?{snapshot:new Tc(this.query,e.Qu,r,s,e.mutatedKeys,0==a,o,!1),Xu:i}:{Xu:i}}bu(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Qu:this.Qu,zu:new Ec,mutatedKeys:this.mutatedKeys,ii:!1},!1)):{Xu:[]}}Zu(e){return!this.Uu.has(e)&&!!this.Qu.has(e)&&!this.Qu.get(e).hasLocalMutations}Ju(e){e&&(e.addedDocuments.forEach(e=>this.Uu=this.Uu.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Uu=this.Uu.delete(e)),this.current=e.current)}Yu(){if(!this.current)return[];const t=this.Ku;this.Ku=ga(),this.Qu.forEach(e=>{this.Zu(e.key)&&(this.Ku=this.Ku.add(e.key))});const n=[];return t.forEach(e=>{this.Ku.has(e)||n.push(new Vc(e))}),this.Ku.forEach(e=>{t.has(e)||n.push(new Lc(e))}),n}ta(e){this.Uu=e._i,this.Ku=ga();var t=this.Wu(e.documents);return this.applyChanges(t,!0)}ea(){return Tc.fromInitialDocuments(this.query,this.Qu,this.mutatedKeys,0===this.qu)}}class Fc{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Pc{constructor(e){this.key=e,this.na=!1}}class Bc{constructor(e,t,n,r,s,i){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=s,this.maxConcurrentLimboResolutions=i,this.sa={},this.ia=new oa(e=>_i(e),Ti),this.ra=new Map,this.oa=new Set,this.ua=new Us(ds.comparator),this.aa=new Map,this.ca=new bh,this.ha={},this.la=new Map,this.fa=Cu.yn(),this.onlineState="Unknown",this.da=void 0}get isPrimaryClient(){return!0===this.da}}async function qc(n,e,t,r){n._a=(e,i,t)=>async function(e,t,n){let r=t.view.Wu(i);r.ii&&(r=await gh(e.localStore,t.query,!1).then(({documents:e})=>t.view.Wu(e,r)));var s=n&&n.targetChanges.get(t.targetId),s=t.view.applyChanges(r,e.isPrimaryClient,s);return Hc(e,t.targetId,s.Xu),s.snapshot}(n,e,t);const s=await gh(n.localStore,e,!0),i=new Oc(e,s._i),a=i.Wu(s.documents),o=ya.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState),u=i.applyChanges(a,n.isPrimaryClient,o);Hc(n,t,u.Xu);var h=new Fc(e,t,i);return n.ia.set(e,h),n.ra.has(t)?n.ra.get(t).push(e):n.ra.set(t,[e]),u.snapshot}async function Uc(e,t,n){const r=nl(e);try{const e=await function(e,r){const s=e,i=Gr.now(),t=r.reduce((e,t)=>e.add(t.key),ga());let a;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>s.fi.Ks(n,t).next(e=>{a=e;const t=[];for(const n of r){const r=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),s=Ri(r.transform,e||null);null!=s&&(null==n&&(n=ks.empty()),n.set(r.field,s))}return n||null}(n,a.get(n.key));null!=r&&t.push(new Ji(n.key,r,function r(e){const s=[];return Wr(e.fields,(e,t)=>{const n=new Jr([e]);if(As(t)){const e=r(t.mapValue).fields;if(0===e.length)s.push(n);else for(const t of e)s.push(n.child(t))}else s.push(n)}),new Zr(s)}(r.value.mapValue),Gi.exists(!0)))}return s.Bs.addMutationBatch(n,i,t,r)})).then(e=>(e.applyToLocalDocumentSet(a),{batchId:e.batchId,changes:a}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.ha[e.currentUser.toKey()];r=r||new Us(Ur),r=r.insert(t,n),e.ha[e.currentUser.toKey()]=r}(r,e.batchId,n),await Xc(r,e.changes),await dc(r.remoteStore)}catch(e){const t=bc(e,"Failed to persist write");n.reject(t)}}async function Kc(e,t){const r=e;try{const e=await ch(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.aa.get(t);n&&(Dr(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.na=!0:0<e.modifiedDocuments.size?Dr(n.na):0<e.removedDocuments.size&&(Dr(n.na),n.na=!1))}),await Xc(r,e,t)}catch(e){await Vu(e)}}function jc(r,s,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.ia.forEach((e,t)=>{var n=t.view.bu(s);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.listeners)e.bu(n)&&(r=!0)}),r&&xc(t)}(t.eventManager,s),r.length&&t.sa.zo(r),t.onlineState=s,t.isPrimaryClient&&t.sharedClientState.setOnlineState(s)}}async function Gc(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const s=e;return s.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=s.hi.newChangeBuffer({trackRemovals:!0});return function(e,t,r,s){const i=r.batch,n=i.keys();let a=So.resolve();return n.forEach(n=>{a=a.next(()=>s.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);Dr(null!==t),e.version.compareTo(t)<0&&(i.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),s.addEntry(e)))})}),a.next(()=>e.Bs.removeMutationBatch(t,i))}(s,e,r,n).next(()=>n.apply(e)).next(()=>s.Bs.performConsistencyCheck(e)).next(()=>s.fi.Ks(e,t))})}(n.localStore,t);zc(n,r,null),$c(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Xc(n,e)}catch(e){await Vu(e)}}function $c(e,t){(e.la.get(t)||[]).forEach(e=>{e.resolve()}),e.la.delete(t)}function zc(e,t,n){const r=e;let s=r.ha[r.currentUser.toKey()];if(s){const e=s.get(t);e&&(n?e.reject(n):e.resolve(),s=s.remove(t)),r.ha[r.currentUser.toKey()]=s}}function Wc(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.ra.get(e))t.ia.delete(r),n&&t.sa.wa(r,n);t.ra.delete(e),t.isPrimaryClient&&t.ca.vi(e).forEach(e=>{t.ca.containsKey(e)||Qc(t,e)})}function Qc(e,t){e.oa.delete(t.path.canonicalString());var n=e.ua.get(t);null!==n&&(rc(e.remoteStore,n),e.ua=e.ua.remove(t),e.aa.delete(n),Yc(e))}function Hc(e,t,n){for(const r of n)r instanceof Lc?(e.ca.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.ua.get(n)||e.oa.has(r)||(Er("SyncEngine","New document in limbo: "+n),e.oa.add(r),Yc(e))}(e,r)):r instanceof Vc?(Er("SyncEngine","Document no longer in limbo: "+r.key),e.ca.removeReference(r.key,t),e.ca.containsKey(r.key)||Qc(e,r.key)):Ar()}function Yc(e){for(;0<e.oa.size&&e.ua.size<e.maxConcurrentLimboResolutions;){var t=e.oa.values().next().value;e.oa.delete(t);var n=new ds(Yr.fromString(t)),t=e.fa.next();e.aa.set(t,new Pc(n)),e.ua=e.ua.insert(n,t),nc(e.remoteStore,new qo(Ii(pi(n.path)),t,2,Br.A))}}async function Xc(e,t,r){const s=e,i=[],a=[],o=[];s.ia.isEmpty()||(s.ia.forEach((e,n)=>{o.push(s._a(n,t,r).then(e=>{var t;e&&(s.isPrimaryClient&&s.sharedClientState.updateQueryState(n.targetId,e.fromCache?"not-current":"current"),i.push(e),t=sh.Ys(n.targetId,e),a.push(t))}))}),await Promise.all(o),s.sa.zo(i),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>So.forEach(t,t=>So.forEach(t.Hs,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>So.forEach(t.Js,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!Co(e))throw e;Er("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.ui.get(t),n=e.snapshotVersion,s=e.withLastLimboFreeSnapshotVersion(n);r.ui=r.ui.insert(t,s)}}}(s.localStore,a))}async function Jc(r,e){const s=r;if(tl(s),nl(s),!0===e&&!0!==s.da){const r=s.sharedClientState.getAllActiveQueryTargets(),e=await Zc(s,r.toArray());s.da=!0,await pc(s.remoteStore,!0);for(const r of e)nc(s.remoteStore,r)}else if(!1===e&&!1!==s.da){const r=[];let n=Promise.resolve();s.ra.forEach((e,t)=>{s.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(Wc(s,t),fh(s.localStore,t,!0))),rc(s.remoteStore,t)}),await n,await Zc(s,r),function(){const n=s;n.aa.forEach((e,t)=>{rc(n.remoteStore,t)}),n.ca.Si(),n.aa=new Map,n.ua=new Us(ds.comparator)}(),s.da=!1,await pc(s.remoteStore,!1)}}async function Zc(t,n){const r=t,s=[],i=[];for(const t of n){let e;const c=r.ra.get(t);if(c&&0!==c.length){e=await dh(r.localStore,Ii(c[0]));for(const t of c){const n=r.ia.get(t),c=(a=r,o=n,h=u=void 0,h=await gh((u=a).localStore,o.query,!0),h=o.view.ta(h),u.isPrimaryClient&&Hc(u,o.targetId,h.Xu),await h);c.snapshot&&i.push(c.snapshot)}}else{const c=await mh(r.localStore,t);e=await dh(r.localStore,c),await qc(r,el(c),t,!1)}s.push(e)}var a,o,u,h;return r.sa.zo(i),s}function el(e){return mi(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function tl(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=Kc.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.aa.get(t);if(r&&r.na)return ga().add(r.key);{let e=ga();const r=n.ra.get(t);if(!r)return e;for(const t of r){const r=n.ia.get(t);e=e.unionWith(r.view.ju)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const s=r.aa.get(t),i=s&&s.key;if(i){let e=new Us(ds.comparator);e=e.insert(i,Ms.newNoDocument(i,$r.min()));const n=ga().add(i),s=new pa($r.min(),new Map,new Gs(Ur),e,n);await Kc(r,s),r.ua=r.ua.remove(i),r.aa.delete(t),Yc(r)}else await fh(r.localStore,t,!1).then(()=>Wc(r,t,n)).catch(Vu)}).bind(null,t),t.sa.zo=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,s=n.queries.get(t);if(s){for(const t of s.listeners)t.Vu(e)&&(r=!0);s.Ru=e}}r&&xc(n)}).bind(null,t.eventManager),t.sa.wa=(function(e,t,n){const r=e,s=r.queries.get(t);if(s)for(const e of s.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function nl(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=Gc.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const s=e;return s.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return s.Bs.lookupMutationBatch(t,r).next(e=>(Dr(null!==e),n=e.keys(),s.Bs.removeMutationBatch(t,e))).next(()=>s.Bs.performConsistencyCheck(t)).next(()=>s.fi.Ks(t,n))})}(r.localStore,t);zc(r,t,n),$c(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Xc(r,e)}catch(n){await Vu(n)}}).bind(null,t),t}class rl{constructor(){this.synchronizeTabs=!1}async initialize(e){this.M=zh(e.databaseInfo.databaseId),this.sharedClientState=this.ga(e),this.persistence=this.ya(e),await this.persistence.start(),this.gcScheduler=this.pa(e),this.localStore=this.Ia(e)}pa(e){return null}Ia(e){return oh(this.persistence,new ih,e.initialUser,this.M)}ya(e){return new Ah(xh.Yi,this.M)}ga(e){return new Ph}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class sl extends rl{constructor(e,t,n){super(),this.Ta=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Ta.initialize(this,e),await nl(this.Ta.syncEngine),await dc(this.Ta.remoteStore),await this.persistence.Ts(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(this.localStore),Promise.resolve()))}Ia(e){return oh(this.persistence,new ih,e.initialUser,this.M)}pa(e){var t=this.persistence.referenceDelegate.garbageCollector;return new Pu(t,e.asyncQueue)}ya(e){var t=nh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?Eu.withCacheSize(this.cacheSizeBytes):Eu.DEFAULT;return new Zu(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,Gh(),$h(),this.M,this.sharedClientState,!!this.forceOwnership)}ga(e){return new Ph}}class il extends sl{constructor(e,t){super(e,t,!1),this.Ta=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Ta.syncEngine;this.sharedClientState instanceof Fh&&(this.sharedClientState.syncEngine={$r:(async function(e,t,n,r){var s=e,i=await function(e,n){const r=e,s=r.Bs;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>s.fn(t,n).next(e=>e?r.fi.Ks(t,e):So.resolve(null)))}(s.localStore,t);null!==i?("pending"===n?await dc(s.remoteStore):"acknowledged"===n||"rejected"===n?(zc(s,t,r||null),$c(s,t),s.localStore.Bs._n(t)):Ar(),await Xc(s,i)):Er("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),Br:(async function(e,t,n,r){const s=e;if(s.da)Er("SyncEngine","Ignoring unexpected query state notification.");else{var i=s.ra.get(t);if(i&&0<i.length)switch(n){case"current":case"not-current":{const e=await ph(s.localStore,Di(i[0])),r=pa.createSynthesizedRemoteEventForCurrentChange(t,"current"===n);await Xc(s,e,r);break}case"rejected":await fh(s.localStore,t,!0),Wc(s,t,r);break;default:Ar()}}}).bind(null,t),Lr:(async function(e,t,n){const r=tl(e);if(r.da){for(const e of t)if(r.ra.has(e))Er("SyncEngine","Adding an already active target "+e);else{const t=await mh(r.localStore,e),n=await dh(r.localStore,t);await qc(r,el(t),n.targetId,!1),nc(r.remoteStore,n)}for(const e of n)r.ra.has(e)&&await fh(r.localStore,e,!1).then(()=>{rc(r.remoteStore,e),Wc(r,e)}).catch(Vu)}}).bind(null,t),Fs:(function(e){return e.localStore.persistence.Fs()}).bind(null,t),Fr:(async function(e,t){const n=e;return ph(n.localStore,t).then(e=>Xc(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.Ts(async e=>{await Jc(this.Ta.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start(this.localStore):e||this.gcScheduler.stop())})}ga(e){var t=Gh();if(!Fh.vt(t))throw new Nr(xr.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=nh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new Fh(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class al{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>jc(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){Er("SyncEngine","User change. New user:",t.toKey());const r=await uh(n.localStore,t);n.currentUser=t,(e=n).la.forEach(e=>{e.forEach(e=>{e.reject(new Nr(xr.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.la.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await Xc(n,r.di)}}).bind(null,this.syncEngine),await pc(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Sc}createDatastore(e){var t,n,r,s,i=zh(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new jh(t));return n=e.authCredentials,r=e.appCheckCredentials,s=t,e=i,new Xh(n,r,s,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,s=e=>jc(this.syncEngine,e,0),i=new(qh.vt()?qh:Bh),new Zh(t,n,r,s,i);var t,n,r,s,i}createSyncEngine(e,t){return function(e,t,n,r,s,i,a){const o=new Bc(e,t,n,r,s,i);return a&&(o.da=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;Er("RemoteStore","RemoteStore shutting down."),t.wu.add(5),await tc(t),t.gu.shutdown(),t.yu.set("Unknown")}(this.remoteStore)}}function ol(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.reject("unimplemented")}}class ul{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Ea(this.observer.next,e)}error(e){this.observer.error?this.Ea(this.observer.error,e):console.error("Uncaught Error in snapshot listener:",e)}Aa(){this.muted=!0}Ea(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class hl{constructor(e,t){this.Ra=e,this.M=t,this.metadata=new Cr,this.buffer=new Uint8Array,this.Pa=new TextDecoder("utf-8"),this.ba().then(e=>{e&&e.Mu()?this.metadata.resolve(e.payload.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.payload)}`))},e=>this.metadata.reject(e))}close(){return this.Ra.cancel()}async getMetadata(){return this.metadata.promise}async ma(){return await this.getMetadata(),this.ba()}async ba(){var e=await this.Va();if(null===e)return null;var t=this.Pa.decode(e),n=Number(t);isNaN(n)&&this.va(`length string (${t}) is not valid number`);t=await this.Sa(n);return new Cc(JSON.parse(t),e.length+n)}Da(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Va(){for(;this.Da()<0&&!await this.Ca(););if(0===this.buffer.length)return null;var e=this.Da();e<0&&this.va("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 Sa(e){for(;this.buffer.length<e;)await this.Ca()&&this.va("Reached the end of bundle when more is expected.");var t=this.Pa.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}va(e){throw this.Ra.cancel(),new Error(`Invalid bundle format: ${e}`)}async Ca(){var e=await this.Ra.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 cl{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 Nr(xr.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=Fa(r.M)+"/documents",s={documents:t.map(e=>Ra(r.M,e))},i=await r._o("BatchGetDocuments",n,s),a=new Map;i.forEach(e=>{const t=(n=r.M,"found"in(e=e)?function(e,t){Dr(!!t.found),t.found.name,t.found.updateTime;var n=La(e,t.found.name),r=Ca(t.found.updateTime),s=new ks({mapValue:{fields:t.found.fields}});return Ms.newFoundDocument(n,r,s)}(n,e):"missing"in e?function(e,t){Dr(!!t.missing),Dr(!!t.readTime);var n=La(e,t.missing),r=Ca(t.readTime);return Ms.newNoDocument(n,r)}(n,e):Ar());var n;a.set(t.key.toString(),t)});const o=[];return t.forEach(e=>{var t=a.get(e.toString());Dr(!!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 na(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=ds.fromPath(t);this.mutations.push(new ra(n,this.precondition(n)))}),await async function(e,t){const n=e,r=Fa(n.M)+"/documents",s={writes:t.map(e=>Ua(n.M,e))};await n.co("Commit",r,s)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw Ar();t=$r.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new Nr(xr.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){var t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?Gi.updateTime(t):Gi.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return Gi.exists(!0);if(t.isEqual($r.min()))throw new Nr(xr.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Gi.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class ll{constructor(e,t,n,r){this.asyncQueue=e,this.datastore=t,this.updateFunction=n,this.deferred=r,this.xa=5,this.No=new Wh(this.asyncQueue,"transaction_retry")}run(){--this.xa,this.Na()}Na(){this.No.Ro(async()=>{const t=new cl(this.datastore),e=this.ka(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Ma(e)}))}).catch(e=>{this.Ma(e)})})}ka(e){try{var t=this.updateFunction(e);return!hs(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}}Ma(e){0<this.xa&&this.Oa(e)?(--this.xa,this.asyncQueue.enqueueAndForget(()=>(this.Na(),Promise.resolve()))):this.deferred.reject(e)}Oa(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||!ia(t)}}class dl{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=vr.UNAUTHENTICATED,this.clientId=qr.R(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{Er("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(Er("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 Nr(xr.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new Cr;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=bc(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function fl(e,t){e.asyncQueue.verifyOperationInProgress(),Er("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await uh(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function gl(e,n){e.asyncQueue.verifyOperationInProgress();var t=await ml(e);Er("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>mc(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>mc(n.remoteStore,t)),e.onlineComponents=n}async function ml(e){return e.offlineComponents||(Er("FirestoreClient","Using default OfflineComponentProvider"),await fl(e,new rl)),e.offlineComponents}async function pl(e){return e.onlineComponents||(Er("FirestoreClient","Using default OnlineComponentProvider"),await gl(e,new al)),e.onlineComponents}function yl(e){return ml(e).then(e=>e.persistence)}function vl(e){return ml(e).then(e=>e.localStore)}function wl(e){return pl(e).then(e=>e.remoteStore)}function bl(e){return pl(e).then(e=>e.syncEngine)}async function Il(e){const t=await pl(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=tl(e);let r,s;const i=n.ia.get(t);if(i)r=i.targetId,n.sharedClientState.addLocalQueryTarget(r),s=i.view.ea();else{const e=await dh(n.localStore,Ii(t));n.isPrimaryClient&&nc(n.remoteStore,e);const i=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,s=await qc(n,t,r,"current"===i)}return s}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.ia.get(t),s=n.ra.get(r.targetId);if(1<s.length)return n.ra.set(r.targetId,s.filter(e=>!Ti(e,t))),void n.ia.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await fh(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),rc(n.remoteStore,r.targetId),Wc(n,r.targetId)}).catch(Vu)):(Wc(n,r.targetId),await fh(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function El(e,t,n={}){const r=new Cr;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,s,i,a){const e=new ul({next:e=>{r.enqueueAndForget(()=>Dc(n,o));var t=e.docs.has(s);!t&&e.fromCache?a.reject(new Nr(xr.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&i&&"server"===i.source?a.reject(new Nr(xr.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 Nc(pi(s.path),e,{includeMetadataChanges:!0,ku:!0});return Ac(n,o)}(await Il(e),e.asyncQueue,t,n,r)),r.promise}function Tl(e,t,n={}){const r=new Cr;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,s){const i=new ul({next:e=>{n.enqueueAndForget(()=>Dc(t,a)),e.fromCache&&"server"===r.source?s.reject(new Nr(xr.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):s.resolve(e)},error:e=>s.reject(e)}),a=new Nc(e,i,{includeMetadataChanges:!0,ku:!0});return Ac(t,a)}(await Il(e),e.asyncQueue,t,n,r)),r.promise}function _l(e,t,n,r){const s=(n=n,t=zh(t),i="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return ol(e,void 0);if(e instanceof ArrayBuffer)return ol(new Uint8Array(e),void 0);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(i),t=t,new hl(n,t));var i;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var s=await n.getMetadata();if(await function(e,t){const n=e,r=Ca(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n._s.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,s))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:s.totalDocuments,bytesLoaded:s.totalBytes,totalDocuments:s.totalDocuments,totalBytes:s.totalBytes}),Promise.resolve(new Set);r._updateProgress(Rc(s));const a=new Mc(s,t.localStore,n.M);let e=await n.ma();for(;e;){const t=await a.Fu(e);t&&r._updateProgress(t),e=await n.ma()}var i=await a.complete();return await Xc(t,i.Lu,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n._s.saveBundleMetadata(e,t))}(t.localStore,s),r._completeWith(i.progress),Promise.resolve(i.Bu)}catch(t){return _r("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await bl(e),s,r)})}const Sl=new Map;function Al(e,t,n){if(!n)throw new Nr(xr.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Dl(e,t,n,r){if(!0===t&&!0===r)throw new Nr(xr.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function xl(e){if(!ds.isDocumentKey(e))throw new Nr(xr.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Nl(e){if(ds.isDocumentKey(e))throw new Nr(xr.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Cl(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":Ar();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 kl(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new Nr(xr.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=Cl(e);throw new Nr(xr.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function Ml(e,t){if(t<=0)throw new Nr(xr.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Rl{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new Nr(xr.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new Nr(xr.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,Dl("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling)}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Ll{constructor(e,t,n){this._authCredentials=t,this._appCheckCredentials=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Rl({}),this._settingsFrozen=!1,e instanceof us?this._databaseId=e:(this._app=e,this._databaseId=function(e){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new Nr(xr.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new us(e.options.projectId)}(e))}get app(){if(!this._app)throw new Nr(xr.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 Nr(xr.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 Rl(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new Mr;switch(e.type){case"gapi":var t=e.client;return Dr(!("object"!=typeof t||null===t||!t.auth||!t.auth.getAuthHeaderValueForFirstParty)),new Or(t,e.sessionIndex||"0",e.iamToken||null);case"provider":return e.client;default:throw new Nr(xr.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=Sl.get(e);t&&(Er("ComponentProvider","Removing Datastore"),Sl.delete(e),t.terminate())}(this),Promise.resolve()}}function Vl(n,e,t,r={}){var s;const i=(n=kl(n,Ll))._getSettings();if("firestore.googleapis.com"!==i.host&&i.host!==e&&_r("Host has been set in both settings() and useEmulator(), emulator host will be used"),n._setSettings(Object.assign(Object.assign({},i),{host:`${e}:${t}`,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=vr.MOCK_USER;else{e=function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,s=e.sub||e.user_id;if(!s)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");return s=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:s,user_id:s,firebase:{sign_in_provider:"custom",identities:{}}},e),[a(JSON.stringify({alg:"none",type:"JWT"})),a(JSON.stringify(s)),""].join(".")}(r.mockUserToken,null===(s=n._app)||void 0===s?void 0:s.options.projectId);const i=r.mockUserToken.sub||r.mockUserToken.user_id;if(!i)throw new Nr(xr.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new vr(i)}n._authCredentials=new Rr(new kr(e,t))}}class Ol{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 Pl(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Ol(this.firestore,e,this._key)}}class Fl{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Fl(this.firestore,e,this._query)}}class Pl extends Fl{constructor(e,t,n){super(e,t,pi(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 Ol(this.firestore,null,new ds(e))}withConverter(e){return new Pl(this.firestore,e,this._path)}}function Bl(e,t,...n){if(e=m(e),Al("collection","path",t),e instanceof Ll){var r=Yr.fromString(t,...n);return Nl(r),new Pl(e,null,r)}if(!(e instanceof Ol||e instanceof Pl))throw new Nr(xr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(Yr.fromString(t,...n));return Nl(r),new Pl(e.firestore,null,r)}function ql(e,t,...n){if(e=m(e),Al("doc","path",t=1===arguments.length?qr.R():t),e instanceof Ll){var r=Yr.fromString(t,...n);return xl(r),new Ol(e,null,new ds(r))}if(!(e instanceof Ol||e instanceof Pl))throw new Nr(xr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(Yr.fromString(t,...n));return xl(r),new Ol(e.firestore,e instanceof Pl?e.converter:null,new ds(r))}function Ul(e,t){return e=m(e),t=m(t),(e instanceof Ol||e instanceof Pl)&&(t instanceof Ol||t instanceof Pl)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function Kl(e,t){return e=m(e),t=m(t),e instanceof Fl&&t instanceof Fl&&e.firestore===t.firestore&&Ti(e._query,t._query)&&e.converter===t.converter}class jl{constructor(){this.Fa=Promise.resolve(),this.$a=[],this.Ba=!1,this.La=[],this.Ua=null,this.qa=!1,this.Ka=!1,this.Ga=[],this.No=new Wh(this,"async_queue_retry"),this.Qa=()=>{var e=$h();e&&Er("AsyncQueue","Visibility state changed to "+e.visibilityState),this.No.bo()};const e=$h();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Qa)}get isShuttingDown(){return this.Ba}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.ja(),this.Wa(e)}enterRestrictedMode(e){if(!this.Ba){this.Ba=!0,this.Ka=e||!1;const t=$h();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Qa)}}enqueue(e){if(this.ja(),this.Ba)return new Promise(()=>{});const t=new Cr;return this.Wa(()=>this.Ba&&this.Ka?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.$a.push(e),this.za()))}async za(){if(0!==this.$a.length){try{await this.$a[0](),this.$a.shift(),this.No.reset()}catch(e){if(!Co(e))throw e;Er("AsyncQueue","Operation failed with retryable error: "+e)}0<this.$a.length&&this.No.Ro(()=>this.za())}}Wa(e){var t=this.Fa.then(()=>(this.qa=!0,e().catch(e=>{throw this.Ua=e,this.qa=!1,Tr("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.qa=!1,e))));return this.Fa=t}enqueueAfterDelay(e,t,n){this.ja(),-1<this.Ga.indexOf(e)&&(t=0);var r=wc.createAndSchedule(this,e,t,n,e=>this.Ha(e));return this.La.push(r),r}ja(){this.Ua&&Ar()}verifyOperationInProgress(){}async Ja(){for(var e;await(e=this.Fa),e!==this.Fa;);}Ya(e){for(const t of this.La)if(t.timerId===e)return!0;return!1}Xa(t){return this.Ja().then(()=>{this.La.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.La)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Ja()})}Za(e){this.Ga.push(e)}Ha(e){var t=this.La.indexOf(e);this.La.splice(t,1)}}function Gl(e){return function(e){if("object"==typeof e&&null!==e){var t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return 1}}(e)}class $l{constructor(){this._progressObserver={},this._taskCompletionResolver=new Cr,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 zl,Wl,Ql;class Hl extends Ll{constructor(e,t,n){super(e,t,n),this.type="firestore",this._queue=new jl,this._persistenceKey="name"in e?e.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||Xl(this),this._firestoreClient.terminate()}}function Yl(e){return e._firestoreClient||Xl(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function Xl(e){var t,n,r,s,i,a=e._freezeSettings(),a=(n=e._databaseId,r=(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",s=e._persistenceKey,i=a,new os(n,r,s,i.host,i.ssl,i.experimentalForceLongPolling,i.experimentalAutoDetectLongPolling,i.useFetchStreams));e._firestoreClient=new dl(e._authCredentials,e._appCheckCredentials,e._queue,a)}function Jl(e,n,r){const s=new Cr;return e.asyncQueue.enqueue(async()=>{try{await fl(e,r),await gl(e,n),s.resolve()}catch(e){if(!("FirebaseError"===(t=e).name?t.code===xr.FAILED_PRECONDITION||t.code===xr.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||(22===t.code||20===t.code||11===t.code)))throw e;console.warn("Error enabling offline persistence. Falling back to persistence disabled: "+e),s.reject(e)}var t}).then(()=>s.promise)}function Zl(e){return function(e){const t=new Cr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;uc(n.remoteStore)||Er("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(){const t=n.localStore;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.Bs.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.la.get(e)||[];r.push(t),n.la.set(e,r)}catch(e){const n=bc(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await bl(e),t)),t.promise}(Yl(e=kl(e,Hl)))}function ed(e){return(n=Yl(e=kl(e,Hl))).asyncQueue.enqueue(async()=>{const e=await yl(n),t=await wl(n);return e.setNetworkEnabled(!0),function(){const e=t;return e.wu.delete(0),ec(e)}()});var n}function td(e){return(n=Yl(e=kl(e,Hl))).asyncQueue.enqueue(async()=>{const e=await yl(n),t=await wl(n);return e.setNetworkEnabled(!1),async function(){const e=t;e.wu.add(0),await tc(e),e.yu.set("Offline")}()});var n}function nd(t,e){return n=Yl(t=kl(t,Hl)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n._s.getNamedQuery(e,t))}(await vl(n),r)).then(e=>e?new Fl(t,null,e.query):null);var n,r}function rd(e){if(e._initialized||e._terminated)throw new Nr(xr.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 sd{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new Nr(xr.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Jr(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class id{constructor(e){this._byteString=e}static fromBase64String(e){try{return new id(es.fromBase64String(e))}catch(e){throw new Nr(xr.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new id(es.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 ad{constructor(e){this._methodName=e}}class od{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new Nr(xr.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new Nr(xr.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 Ur(this._lat,e._lat)||Ur(this._long,e._long)}}const ud=/^__.*__$/;class hd{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Ji(e,this.data,this.fieldMask,t,this.fieldTransforms):new Xi(e,this.data,t,this.fieldTransforms)}}class cd{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Ji(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function ld(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw Ar()}}class dd{constructor(e,t,n,r,s,i){this.settings=e,this.databaseId=t,this.M=n,this.ignoreUndefinedProperties=r,void 0===s&&this.tc(),this.fieldTransforms=s||[],this.fieldMask=i||[]}get path(){return this.settings.path}get ec(){return this.settings.ec}nc(e){return new dd(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.M,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}sc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.nc({path:n,ic:!1});return r.rc(e),r}oc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.nc({path:n,ic:!1});return r.tc(),r}uc(e){return this.nc({path:void 0,ic:!0})}ac(e){return Md(e,this.settings.methodName,this.settings.cc||!1,this.path,this.settings.hc)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}tc(){if(this.path)for(let e=0;e<this.path.length;e++)this.rc(this.path.get(e))}rc(e){if(0===e.length)throw this.ac("Document fields must not be empty");if(ld(this.ec)&&ud.test(e))throw this.ac('Document fields cannot begin and end with "__"')}}class fd{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.M=n||zh(e)}lc(e,t,n,r=!1){return new dd({ec:e,methodName:t,hc:n,path:Jr.emptyPath(),ic:!1,cc:r},this.databaseId,this.M,this.ignoreUndefinedProperties)}}function gd(e){var t=e._freezeSettings(),n=zh(e._databaseId);return new fd(e._databaseId,!!t.ignoreUndefinedProperties,n)}function md(e,t,n,r,s,i={}){const a=e.lc(i.merge||i.mergeFields?2:0,t,n,s);xd("Data must be an object, but it was:",a,r);var o=Ad(r,a);let u,h;if(i.merge)u=new Zr(a.fieldMask),h=a.fieldTransforms;else if(i.mergeFields){const e=[];for(const r of i.mergeFields){const s=Nd(t,r,n);if(!a.contains(s))throw new Nr(xr.INVALID_ARGUMENT,`Field '${s}' is specified in your field mask but missing from your input data.`);Rd(e,s)||e.push(s)}u=new Zr(e),h=a.fieldTransforms.filter(e=>u.covers(e.field))}else u=null,h=a.fieldTransforms;return new hd(new ks(o),u,h)}class pd extends ad{_toFieldTransform(e){if(2!==e.ec)throw 1===e.ec?e.ac(`${this._methodName}() can only appear at the top level of your update data`):e.ac(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof pd}}function yd(e,t,n){return new dd({ec:3,hc:t.settings.hc,methodName:e._methodName,ic:n},t.databaseId,t.M,t.ignoreUndefinedProperties)}class vd extends ad{_toFieldTransform(e){return new Ki(e.path,new Li)}isEqual(e){return e instanceof vd}}class wd extends ad{constructor(e,t){super(e),this.fc=t}_toFieldTransform(e){const t=yd(this,e,!0),n=this.fc.map(e=>Sd(e,t)),r=new Vi(n);return new Ki(e.path,r)}isEqual(e){return this===e}}class bd extends ad{constructor(e,t){super(e),this.fc=t}_toFieldTransform(e){const t=yd(this,e,!0),n=this.fc.map(e=>Sd(e,t)),r=new Fi(n);return new Ki(e.path,r)}isEqual(e){return this===e}}class Id extends ad{constructor(e,t){super(e),this.dc=t}_toFieldTransform(e){var t=new Bi(e.M,ki(e.M,this.dc));return new Ki(e.path,t)}isEqual(e){return this===e}}function Ed(e,s,i,t){const a=e.lc(1,s,i);xd("Data must be an object, but it was:",a,t);const o=[],u=ks.empty();Wr(t,(e,t)=>{var n=kd(s,e,i);t=m(t);var r=a.oc(n);if(t instanceof pd)o.push(n);else{const e=Sd(t,r);null!=e&&(o.push(n),u.set(n,e))}});var n=new Zr(o);return new cd(u,n,a.fieldTransforms)}function Td(e,t,n,r,s,i){const a=e.lc(1,t,n),o=[Nd(t,r,n)],u=[s];if(i.length%2!=0)throw new Nr(xr.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<i.length;f+=2)o.push(Nd(t,i[f])),u.push(i[f+1]);const h=[],c=ks.empty();for(let g=o.length-1;0<=g;--g)if(!Rd(h,o[g])){const t=o[g];var l=m(l=u[g]);const r=a.oc(t);if(l instanceof pd)h.push(t);else{const e=Sd(l,r);null!=e&&(h.push(t),c.set(t,e))}}var d=new Zr(h);return new cd(c,d,a.fieldTransforms)}function _d(e,t,n,r=!1){return Sd(n,e.lc(r?4:3,t))}function Sd(i,e){if(Dd(i=m(i)))return xd("Unsupported field value:",e,i),Ad(i,e);if(i instanceof ad)return function(e,t){if(!ld(t.ec))throw t.ac(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.ac(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(i,e),null;if(void 0===i&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),i instanceof Array){if(e.settings.ic&&4!==e.ec)throw e.ac("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const s of i){let e=Sd(s,t.uc(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e)}return function(e,t){if(null===(e=m(i)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return ki(t.M,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=Gr.fromDate(e);return{timestampValue:xa(t.M,n)}}if(e instanceof Gr){n=new Gr(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:xa(t.M,n)}}if(e instanceof od)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof id)return{bytesValue:Na(t.M,e._byteString)};if(e instanceof Ol){const r=t.databaseId,s=e.firestore._databaseId;if(!s.isEqual(r))throw t.ac(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:ka(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.ac(`Unsupported field value: ${Cl(e)}`)}(0,e)}function Ad(e,r){const s={};return Qr(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):Wr(e,(e,t)=>{var n=Sd(t,r.sc(e));null!=n&&(s[e]=n)}),{mapValue:{fields:s}}}function Dd(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Gr||e instanceof od||e instanceof id||e instanceof Ol||e instanceof ad)}function xd(e,t,n){if(!Dd(n)||("object"!=typeof(s=n)||null===s||Object.getPrototypeOf(s)!==Object.prototype&&null!==Object.getPrototypeOf(s))){var r=Cl(n);throw"an object"===r?t.ac(e+" a custom object"):t.ac(e+" "+r)}var s}function Nd(e,t,n){if((t=m(t))instanceof sd)return t._internalPath;if("string"==typeof t)return kd(e,t);throw Md("Field path arguments must be of type string or ",e,!1,void 0,n)}const Cd=new RegExp("[~\\*/\\[\\]]");function kd(t,n,r){if(0<=n.search(Cd))throw Md(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new sd(...n.split("."))._internalPath}catch(e){throw Md(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function Md(e,t,n,r,s){var i=r&&!r.isEmpty(),a=void 0!==s;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let u="";return(i||a)&&(u+=" (found",i&&(u+=` in field ${r}`),a&&(u+=` in document ${s}`),u+=")"),new Nr(xr.INVALID_ARGUMENT,o+e+u)}function Rd(e,t){return e.some(e=>e.isEqual(t))}class Ld{constructor(e,t,n,r,s){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=s}get id(){return this._key.path.lastSegment()}get ref(){return new Ol(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new Vd(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(Od("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Vd extends Ld{data(){return super.data()}}function Od(e,t){return"string"==typeof t?kd(e,t):(t instanceof sd?t:t._delegate)._internalPath}class Fd{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Pd extends Ld{constructor(e,t,n,r,s,i){super(e,t,n,r,i),this._firestore=e,this._firestoreImpl=e,this.metadata=s}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new Bd(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(Od("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Bd extends Pd{data(e={}){return super.data(e)}}class qd{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new Fd(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 Bd(this._firestore,this._userDataWriter,e.key,e,new Fd(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 Nr(xr.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(i,t){if(i._snapshot.oldDocs.isEmpty()){let t=0;return i._snapshot.docChanges.map(e=>({type:"added",doc:new Bd(i._firestore,i._userDataWriter,e.doc.key,e.doc,new Fd(i._snapshot.mutatedKeys.has(e.doc.key),i._snapshot.fromCache),i.query.converter),oldIndex:-1,newIndex:t++}))}{let s=i._snapshot.oldDocs;return i._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new Bd(i._firestore,i._userDataWriter,e.doc.key,e.doc,new Fd(i._snapshot.mutatedKeys.has(e.doc.key),i._snapshot.fromCache),i.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=s.indexOf(e.doc.key),s=s.delete(e.doc.key)),1!==e.type&&(s=s.add(e.doc),r=s.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Ar()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function Ud(e,t){return e instanceof Pd&&t instanceof Pd?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 qd&&t instanceof qd&&e._firestore===t._firestore&&Kl(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function Kd(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new Nr(xr.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class jd{}function Gd(e,...t){for(const n of t)e=n._apply(e);return e}class $d extends jd{constructor(e,t,n){super(),this._c=e,this.wc=t,this.mc=n,this.type="where"}_apply(e){var t=gd(e.firestore),t=function(e,t,n,r,s,i,a){let o;if(s.isKeyField()){if("array-contains"===i||"array-contains-any"===i)throw new Nr(xr.INVALID_ARGUMENT,`Invalid Query. You can't perform '${i}' queries on documentId().`);if("in"===i||"not-in"===i){Jd(a,i);const t=[];for(const n of a)t.push(Xd(r,e,n));o={arrayValue:{values:t}}}else o=Xd(r,e,a)}else"in"!==i&&"not-in"!==i&&"array-contains-any"!==i||Jd(a,i),o=_d(n,t,a,"in"===i||"not-in"===i);var u=ti.create(s,i,o);return function(e,t){if(t.S()){const r=vi(e);if(null!==r&&!r.isEqual(t.field))throw new Nr(xr.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 '${t.field.toString()}'`);var n=yi(e);null!==n&&Zd(0,t.field,n)}const r=function(e,t){for(const n of e.filters)if(0<=t.indexOf(n.op))return n.op;return null}(e,function(){switch(t.op){case"!=":return["!=","not-in"];case"array-contains":return["array-contains","array-contains-any","not-in"];case"in":return["array-contains-any","in","not-in"];case"array-contains-any":return["array-contains","array-contains-any","in","not-in"];case"not-in":return["array-contains","array-contains-any","in","not-in","!="];default:return[]}}());if(null!==r)throw r===t.op?new Nr(xr.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new Nr(xr.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}(e,u),u}(e._query,"where",t,e.firestore._databaseId,this._c,this.wc,this.mc);return new Fl(e.firestore,e.converter,(e=e._query,t=e.filters.concat([t]),new gi(e.path,e.collectionGroup,e.explicitOrderBy.slice(),t,e.limit,e.limitType,e.startAt,e.endAt)))}}class zd extends jd{constructor(e,t){super(),this._c=e,this.gc=t,this.type="orderBy"}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new Nr(xr.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new Nr(xr.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,s=new li(t,n);return n=s,null!==yi(e=e)||null!==(r=vi(e))&&Zd(0,r,n.field),s}(e._query,this._c,this.gc);return new Fl(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new gi(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class Wd extends jd{constructor(e,t,n){super(),this.type=e,this.yc=t,this.Ic=n}_apply(e){return new Fl(e.firestore,e.converter,Ei(e._query,this.yc,this.Ic))}}class Qd extends jd{constructor(e,t,n){super(),this.type=e,this.Tc=t,this.Ec=n}_apply(e){var t,n=Yd(e,this.type,this.Tc,this.Ec);return new Fl(e.firestore,e.converter,(t=e._query,e=n,new gi(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class Hd extends jd{constructor(e,t,n){super(),this.type=e,this.Tc=t,this.Ec=n}_apply(e){var t,n=Yd(e,this.type,this.Tc,this.Ec);return new Fl(e.firestore,e.converter,(t=e._query,e=n,new gi(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function Yd(e,t,n,r){if(n[0]=m(n[0]),n[0]instanceof Ld)return function(e,t,n,r,s){if(!r)throw new Nr(xr.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const i=[];for(const n of bi(e))if(n.field.isKeyField())i.push(Is(t,r.key));else{const e=r.data.field(n.field);if(is(e))throw new Nr(xr.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 Nr(xr.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}i.push(e)}return new ci(i,s)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var s=gd(e.firestore);return function(e,t,n,r,s,i){const a=e.explicitOrderBy;if(s.length>a.length)throw new Nr(xr.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const o=[];for(let u=0;u<s.length;u++){const h=s[u];if(a[u].field.isKeyField()){if("string"!=typeof h)throw new Nr(xr.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof h}`);if(!wi(e)&&-1!==h.indexOf("/"))throw new Nr(xr.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${h}' contains a slash.`);const n=e.path.child(Yr.fromString(h));if(!ds.isDocumentKey(n))throw new Nr(xr.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const s=new ds(n);o.push(Is(t,s))}else{const e=_d(n,r,h);o.push(e)}}return new ci(o,i)}(e._query,e.firestore._databaseId,s,t,n,r)}function Xd(e,t,n){if("string"==typeof(n=m(n))){if(""===n)throw new Nr(xr.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!wi(t)&&-1!==n.indexOf("/"))throw new Nr(xr.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(Yr.fromString(n));if(!ds.isDocumentKey(r))throw new Nr(xr.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 Is(e,new ds(r))}if(n instanceof Ol)return Is(e,n._key);throw new Nr(xr.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Cl(n)}.`)}function Jd(e,t){if(!Array.isArray(e)||0===e.length)throw new Nr(xr.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);if(10<e.length)throw new Nr(xr.INVALID_ARGUMENT,`Invalid Query. '${t.toString()}' filters support a maximum of 10 elements in the value array.`)}function Zd(e,t,n){if(!n.isEqual(t))throw new Nr(xr.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 ef{convertValue(e,t="none"){switch(ms(e)){case 0:return null;case 1:return e.booleanValue;case 2:return rs(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(ss(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 Ar()}}convertObject(e,n){const r={};return Wr(e.fields,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new od(rs(e.latitude),rs(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=function e(t){var n=t.mapValue.fields.__previous_value__;return is(n)?e(n):n}(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(as(e));default:return null}}convertTimestamp(e){var t=ns(e);return new Gr(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=Yr.fromString(e);Dr(Ya(n));const r=new us(n.get(1),n.get(3)),s=new ds(n.popFirst(5));return r.isEqual(t)||Tr(`Document ${s} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),s}}function tf(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class nf extends ef{constructor(e){super(),this.firestore=e}convertBytes(e){return new id(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Ol(this.firestore,null,t)}}class rf{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=gd(e)}set(e,t,n){this._verifyNotCommitted();const r=sf(e,this._firestore),s=tf(r.converter,t,n),i=md(this._dataReader,"WriteBatch.set",r._key,s,null!==r.converter,n);return this._mutations.push(i.toMutation(r._key,Gi.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var s=sf(e,this._firestore);let i;return i="string"==typeof(t=m(t))||t instanceof sd?Td(this._dataReader,"WriteBatch.update",s._key,t,n,r):Ed(this._dataReader,"WriteBatch.update",s._key,t),this._mutations.push(i.toMutation(s._key,Gi.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=sf(e,this._firestore);return this._mutations=this._mutations.concat(new na(t._key,Gi.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 Nr(xr.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function sf(e,t){if((e=m(e)).firestore!==t)throw new Nr(xr.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class af extends ef{constructor(e){super(),this.firestore=e}convertBytes(e){return new id(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Ol(this.firestore,null,t)}}function of(t){t=kl(t,Ol);const n=kl(t.firestore,Hl),e=Yl(n),r=new af(n);return function(e,t){const n=new Cr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const s=await function(t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.fi.Ls(e,t))}(t);s.isFoundDocument()?n.resolve(s):s.isNoDocument()?n.resolve(null):n.reject(new Nr(xr.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=bc(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await vl(e),t,n)),n.promise}(e,t._key).then(e=>new Pd(n,r,t._key,e,new Fd(null!==e&&e.hasLocalMutations,!0),t.converter))}function uf(t){t=kl(t,Fl);const n=kl(t.firestore,Hl),e=Yl(n),r=new af(n);return function(e,t){const n=new Cr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const s=await gh(e,t,!0),i=new Oc(t,s._i),a=i.Wu(s.documents),o=i.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=bc(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await vl(e),t,n)),n.promise}(e,t._query).then(e=>new qd(n,r,t,e))}function hf(e,t,n){e=kl(e,Ol);var r=kl(e.firestore,Hl),s=tf(e.converter,t,n);return ff(r,[md(gd(r),"setDoc",e._key,s,null!==e.converter,n).toMutation(e._key,Gi.none())])}function cf(e,t,n,...r){e=kl(e,Ol);var s=kl(e.firestore,Hl),i=gd(s);let a;return a="string"==typeof(t=m(t))||t instanceof sd?Td(i,"updateDoc",e._key,t,n,r):Ed(i,"updateDoc",e._key,t),ff(s,[a.toMutation(e._key,Gi.exists(!0))])}function lf(t,...n){var e;t=m(t);let r={includeMetadataChanges:!1},s=0;"object"!=typeof n[s]||Gl(n[s])||(r=n[s],s++);var i={includeMetadataChanges:r.includeMetadataChanges};if(Gl(n[s])){const t=n[s];n[s]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[s+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[s+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,u;if(t instanceof Ol)o=kl(t.firestore,Hl),u=pi(t._key.path),a={next:e=>{n[s]&&n[s](gf(o,t,e))},error:n[s+1],complete:n[s+2]};else{const h=kl(t,Fl);o=kl(h.firestore,Hl),u=h._query;const c=new af(o);a={next:e=>{n[s]&&n[s](new qd(o,c,h,e))},error:n[s+1],complete:n[s+2]},Kd(t._query)}return function(e,t,n,r){const s=new ul(r),i=new Nc(t,s,n);return e.asyncQueue.enqueueAndForget(async()=>Ac(await Il(e),i)),()=>{s.Aa(),e.asyncQueue.enqueueAndForget(async()=>Dc(await Il(e),i))}}(Yl(o),u,i,a)}function df(e,t){return function(e,t){const n=new ul(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Pu.add(t),t.next()}(await Il(e),n)),()=>{n.Aa(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Pu.delete(t)}(await Il(e),n))}}(Yl(e=kl(e,Hl)),Gl(t)?t:{next:t})}function ff(e,t){return function(e,t){const n=new Cr;return e.asyncQueue.enqueueAndForget(async()=>Uc(await bl(e),t,n)),n.promise}(Yl(e),t)}function gf(e,t,n){var r=n.docs.get(t._key),s=new af(e);return new Pd(e,s,t._key,r,new Fd(n.hasPendingWrites,n.fromCache),t.converter)}class mf extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=gd(e)}get(e){const n=sf(e,this._firestore),r=new nf(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return Ar();const t=e[0];if(t.isFoundDocument())return new Ld(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new Ld(this._firestore,r,n._key,null,n.converter);throw Ar()})}set(e,t,n){var r=sf(e,this._firestore),s=tf(r.converter,t,n),s=md(this._dataReader,"Transaction.set",r._key,s,null!==r.converter,n);return this._transaction.set(r._key,s),this}update(e,t,n,...r){var s=sf(e,this._firestore),i="string"==typeof(t=m(t))||t instanceof sd?Td(this._dataReader,"Transaction.update",s._key,t,n,r):Ed(this._dataReader,"Transaction.update",s._key,t);return this._transaction.update(s._key,i),this}delete(e){var t=sf(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=sf(e,this._firestore),n=new af(this._firestore);return super.get(e).then(e=>new Pd(this._firestore,n,t._key,e._document,new Fd(!1,!1),t.converter))}}function pf(t,n){return function(t,n){const r=new Cr;return t.asyncQueue.enqueueAndForget(async()=>{var e=await pl(t).then(e=>e.datastore);new ll(t.asyncQueue,e,n,r).run()}),r.promise}(Yl(t=kl(t,Hl)),e=>n(new mf(t,e)))}zl=jf.SDK_VERSION,wr=zl,jf._registerComponent(new h("firestore",(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=new Hl(n,new Lr(e.getProvider("auth-internal")),new Pr(e.getProvider("app-check-internal")));return t=Object.assign({useFetchStreams:!0},t),r._setSettings(t),r},"PUBLIC")),jf.registerVersion(yr,"3.4.8",void 0),jf.registerVersion(yr,"3.4.8","esm2017");function yf(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new Nr("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function vf(){if("undefined"==typeof Uint8Array)throw new Nr("unimplemented","Uint8Arrays are not available in this environment.")}function wf(){if("undefined"==typeof atob)throw new Nr("unimplemented","Blobs are unavailable in Firestore in this environment.")}class bf{constructor(e){this._delegate=e}static fromBase64String(e){return wf(),new bf(id.fromBase64String(e))}static fromUint8Array(e){return vf(),new bf(id.fromUint8Array(e))}toBase64(){return wf(),this._delegate.toBase64()}toUint8Array(){return vf(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function If(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 Ef{enableIndexedDbPersistence(e,t){return function(e,t){rd(e=kl(e,Hl));var n=Yl(e),r=e._freezeSettings(),s=new al;return Jl(n,s,new sl(s,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){rd(e=kl(e,Hl));var t=Yl(e),n=e._freezeSettings(),r=new al;return Jl(t,r,new il(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new Nr(xr.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new Cr;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!Do.vt())return Promise.resolve();var t=e+"main";await Do.delete(t)}(nh(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class Tf{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof us||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||_r("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={}){Vl(this._delegate,e,t,n)}enableNetwork(){return ed(this._delegate)}disableNetwork(){return td(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,Dl("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 Zl(this._delegate)}onSnapshotsInSync(e){return df(this._delegate,e)}get app(){if(!this._appCompat)throw new Nr("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new Ff(this,Bl(this._delegate,e))}catch(e){throw Nf(e,"collection()","Firestore.collection()")}}doc(e){try{return new xf(this,ql(this._delegate,e))}catch(e){throw Nf(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new Lf(this,function(e,t){if(e=kl(e,Ll),Al("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new Nr(xr.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Fl(e,null,(t=t,new gi(Yr.emptyPath(),t)))}(this._delegate,e))}catch(e){throw Nf(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return pf(this._delegate,e=>t(new Sf(this,e)))}batch(){return Yl(this._delegate),new Af(new rf(this._delegate,e=>ff(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=Yl(t=kl(t,Hl)),r=new $l,_l(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return nd(this._delegate,e).then(e=>e?new Lf(this,e):null)}}class _f extends ef{constructor(e){super(),this.firestore=e}convertBytes(e){return new bf(new id(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return xf.forKey(t,this.firestore,null)}}class Sf{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new _f(e)}get(e){const t=Pf(e);return this._delegate.get(t).then(e=>new Mf(this._firestore,new Pd(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=Pf(e);return n?(yf("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var s=Pf(e);return 2===arguments.length?this._delegate.update(s,t):this._delegate.update(s,t,n,...r),this}delete(e){var t=Pf(e);return this._delegate.delete(t),this}}class Af{constructor(e){this._delegate=e}set(e,t,n){var r=Pf(e);return n?(yf("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var s=Pf(e);return 2===arguments.length?this._delegate.update(s,t):this._delegate.update(s,t,n,...r),this}delete(e){var t=Pf(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Df{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new Bd(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new Rf(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=Df.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let s=r.get(t);return s||(s=new Df(e,new _f(e),t),r.set(t,s)),s}}Df.INSTANCES=new WeakMap;class xf{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new _f(e)}static forPath(e,t,n){if(e.length%2!=0)throw new Nr("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new xf(t,new Ol(t._delegate,n,new ds(e)))}static forKey(e,t,n){return new xf(t,new Ol(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new Ff(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new Ff(this.firestore,Bl(this._delegate,e))}catch(e){throw Nf(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=m(e))instanceof Ol&&Ul(this._delegate,e)}set(e,t){t=yf("DocumentReference.set",t);try{return t?hf(this._delegate,e,t):hf(this._delegate,e)}catch(e){throw Nf(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?cf(this._delegate,e):cf(this._delegate,e,t,...n)}catch(e){throw Nf(e,"updateDoc()","DocumentReference.update()")}}delete(){return ff(kl((e=this._delegate).firestore,Hl),[new na(e._key,Gi.none())]);var e}onSnapshot(...e){var t=Cf(e),n=kf(e,e=>new Mf(this.firestore,new Pd(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return lf(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?of:"server"===(null==e?void 0:e.source)?function(t){t=kl(t,Ol);const n=kl(t.firestore,Hl);return El(Yl(n),t._key,{source:"server"}).then(e=>gf(n,t,e))}:function(t){t=kl(t,Ol);const n=kl(t.firestore,Hl);return El(Yl(n),t._key).then(e=>gf(n,t,e))})(this._delegate),t.then(e=>new Mf(this.firestore,new Pd(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new xf(this.firestore,e?this._delegate.withConverter(Df.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Nf(e,t,n){return e.message=e.message.replace(t,n),e}function Cf(e){for(const t of e)if("object"==typeof t&&!If(t))return t;return{}}function kf(e,t){var n;let r;return r=If(e[0])?e[0]:If(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 Mf{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new xf(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 Ud(this._delegate,e._delegate)}}class Rf extends Mf{data(e){var t=this._delegate.data(e);return void 0!==t||Ar(),t}}class Lf{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new _f(e)}where(e,t,n){try{return new Lf(this.firestore,Gd(this._delegate,(r=n,s=t,i=Od("where",e),new $d(i,s,r))))}catch(e){throw Nf(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,s,i}orderBy(e,t){try{return new Lf(this.firestore,Gd(this._delegate,([n,r="asc"]=[e,t],s=r,i=Od("orderBy",n),new zd(i,s))))}catch(e){throw Nf(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,s,i}limit(e){try{return new Lf(this.firestore,Gd(this._delegate,(Ml("limit",t=e),new Wd("limit",t,"F"))))}catch(e){throw Nf(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new Lf(this.firestore,Gd(this._delegate,(Ml("limitToLast",t=e),new Wd("limitToLast",t,"L"))))}catch(e){throw Nf(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new Lf(this.firestore,Gd(this._delegate,function(...e){return new Qd("startAt",e,!0)}(...e)))}catch(e){throw Nf(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new Lf(this.firestore,Gd(this._delegate,function(...e){return new Qd("startAfter",e,!1)}(...e)))}catch(e){throw Nf(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new Lf(this.firestore,Gd(this._delegate,function(...e){return new Hd("endBefore",e,!1)}(...e)))}catch(e){throw Nf(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new Lf(this.firestore,Gd(this._delegate,function(...e){return new Hd("endAt",e,!0)}(...e)))}catch(e){throw Nf(e,"endAt()","Query.endAt()")}}isEqual(e){return Kl(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?uf:"server"===(null==e?void 0:e.source)?function(t){t=kl(t,Fl);const n=kl(t.firestore,Hl),e=Yl(n),r=new af(n);return Tl(e,t._query,{source:"server"}).then(e=>new qd(n,r,t,e))}:function(t){t=kl(t,Fl);const n=kl(t.firestore,Hl),e=Yl(n),r=new af(n);return Kd(t._query),Tl(e,t._query).then(e=>new qd(n,r,t,e))})(this._delegate),t.then(e=>new Of(this.firestore,new qd(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=Cf(e),n=kf(e,e=>new Of(this.firestore,new qd(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return lf(this._delegate,t,n)}withConverter(e){return new Lf(this.firestore,e?this._delegate.withConverter(Df.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class Vf{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new Rf(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class Of{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new Lf(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 Rf(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new Vf(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new Rf(this._firestore,e))})}isEqual(e){return Ud(this._delegate,e._delegate)}}class Ff extends Lf{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 xf(this.firestore,e):null}doc(e){try{return void 0===e?new xf(this.firestore,ql(this._delegate)):new xf(this.firestore,ql(this._delegate,e))}catch(e){throw Nf(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=kl(e.firestore,Hl),r=ql(e),s=tf(e.converter,t);return ff(n,[md(gd(e.firestore),"addDoc",r._key,s,null!==e.converter,{}).toMutation(r._key,Gi.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new xf(this.firestore,e))}isEqual(e){return Ul(this._delegate,e._delegate)}withConverter(e){return new Ff(this.firestore,e?this._delegate.withConverter(Df.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Pf(e){return kl(e,Ol)}const Bf={Firestore:Tf,GeoPoint:od,Timestamp:Gr,Blob:bf,Transaction:Sf,WriteBatch:Af,DocumentReference:xf,DocumentSnapshot:Mf,Query:Lf,QueryDocumentSnapshot:Rf,QuerySnapshot:Of,CollectionReference:Ff,FieldPath:class qf{constructor(...e){this._delegate=new sd(...e)}static documentId(){return new qf(Jr.keyField().canonicalString())}isEqual(e){return(e=m(e))instanceof sd&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class Uf{constructor(e){this._delegate=e}static serverTimestamp(){const e=new vd("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new Uf(e)}static delete(){const e=new pd("deleteField");return e._methodName="FieldValue.delete",new Uf(e)}static arrayUnion(...e){const t=function(...e){return new wd("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new Uf(t)}static arrayRemove(...e){const t=function(...e){return new bd("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new Uf(t)}static increment(e){const t=new Id("increment",e);return t._methodName="FieldValue.increment",new Uf(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,br.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};Wl=t.default,Ql=(e,t)=>new Tf(e,t,new Ef),Wl.INTERNAL.registerComponent(new h("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return Ql(t,n)},"PUBLIC").setServiceProps(Object.assign({},Bf))),Wl.registerVersion("@firebase/firestore-compat","0.1.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
|