firebase 9.6.2 → 9.6.3

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.
Files changed (55) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/app/dist/index.cjs.js +1 -1
  3. package/app/dist/index.esm.js +1 -1
  4. package/app/dist/index.mjs +1 -1
  5. package/compat/app/dist/index.cjs.js +1 -1
  6. package/compat/app/dist/index.esm.js +1 -1
  7. package/compat/app/dist/index.mjs +1 -1
  8. package/compat/dist/index.esm.js +2 -2
  9. package/compat/dist/index.node.cjs +2 -2
  10. package/compat/dist/index.rn.cjs.js +2 -2
  11. package/firebase-analytics-compat.js.map +1 -1
  12. package/firebase-analytics.js +3 -3
  13. package/firebase-analytics.js.map +1 -1
  14. package/firebase-app-check-compat.js.map +1 -1
  15. package/firebase-app-check.js +4 -4
  16. package/firebase-app-check.js.map +1 -1
  17. package/firebase-app-compat.js +2 -2
  18. package/firebase-app-compat.js.map +1 -1
  19. package/firebase-app.js +9 -9
  20. package/firebase-app.js.map +1 -1
  21. package/firebase-auth-compat.js.map +1 -1
  22. package/firebase-auth.js +4 -4
  23. package/firebase-auth.js.map +1 -1
  24. package/firebase-compat.js +3 -3
  25. package/firebase-compat.js.map +1 -1
  26. package/firebase-database.js +4 -4
  27. package/firebase-firestore-compat.js +1 -1
  28. package/firebase-firestore-compat.js.map +1 -1
  29. package/firebase-firestore-lite.js +1141 -1141
  30. package/firebase-firestore-lite.js.map +1 -1
  31. package/firebase-firestore.js +874 -874
  32. package/firebase-firestore.js.map +1 -1
  33. package/firebase-functions-compat.js.map +1 -1
  34. package/firebase-functions.js +2 -2
  35. package/firebase-functions.js.map +1 -1
  36. package/firebase-messaging-compat.js +1 -1
  37. package/firebase-messaging-compat.js.map +1 -1
  38. package/firebase-messaging-sw.js +4 -4
  39. package/firebase-messaging-sw.js.map +1 -1
  40. package/firebase-messaging.js +3 -3
  41. package/firebase-messaging.js.map +1 -1
  42. package/firebase-performance-compat.js.map +1 -1
  43. package/firebase-performance-standalone-compat.es2017.js +5 -5
  44. package/firebase-performance-standalone-compat.es2017.js.map +1 -1
  45. package/firebase-performance-standalone-compat.js +1 -1
  46. package/firebase-performance-standalone-compat.js.map +1 -1
  47. package/firebase-performance.js +3 -3
  48. package/firebase-performance.js.map +1 -1
  49. package/firebase-remote-config-compat.js.map +1 -1
  50. package/firebase-remote-config.js +2 -2
  51. package/firebase-remote-config.js.map +1 -1
  52. package/firebase-storage-compat.js.map +1 -1
  53. package/firebase-storage.js +1 -1
  54. package/firebase-storage.js.map +1 -1
  55. 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(ef,tf){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l,t=e(ef);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,h=c+2<n.length,u=h?n[c+2]:0;let e=(15&o)<<2|u>>6,t=63&u;h||(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 h=0;h<e.length;){var s=n[e.charAt(h++)],i=h<e.length?n[e.charAt(h)]:0;++h;var a=h<e.length?n[e.charAt(h)]:64;++h;var o=h<e.length?n[e.charAt(h)]:64;if(++h,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(h,(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 h=/\{\$([^}]+)}/g;function m(e){return e&&e._delegate?e._delegate:e}class u{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}}(il=l=l||{})[il.DEBUG=0]="DEBUG",il[il.VERBOSE=1]="VERBOSE",il[il.INFO=2]="INFO",il[il.WARN=3]="WARN",il[il.ERROR=4]="ERROR",il[il.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 T(){}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 I(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 C(e,t,n){return(C=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?A:D).apply(null,arguments)}function k(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 N(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 x(){this.s=this.s,this.o=this.o}var R={};x.prototype.s=!1,x.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 R[e])},x.prototype.M=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const L=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},M=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 O(){return Array.prototype.concat.apply([],arguments)}function F(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function P(e){return/^[\s\xa0]*$/.test(e)}var V,U=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 B(e,t){return e<t?-1:t<e?1:0}e:{var j=b.navigator;if(j){j=j.userAgent;if(j){V=j;break e}}V=""}function K(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function $(e){const t={};for(const n in e)t[n]=e[n];return t}var G="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function H(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<G.length;e++)n=G[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function W(e){return W[" "](e),e}W[" "]=T;var z,Q=q(V,"Opera"),Y=q(V,"Trident")||q(V,"MSIE"),J=q(V,"Edge"),X=J||Y,Z=q(V,"Gecko")&&!(q(V.toLowerCase(),"webkit")&&!q(V,"Edge"))&&!(q(V,"Trident")||q(V,"MSIE"))&&!q(V,"Edge"),ee=q(V.toLowerCase(),"webkit")&&!q(V,"Edge");function te(){var e=b.document;return e?e.documentMode:void 0}e:{var ne="",re=(re=V,Z?/rv:([^\);]+)(\)|;)/.exec(re):J?/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)){z=String(re);break e}}z=ne}var se={};function ie(){return e=function(){let e=0;var t=U(String(z)).split("."),n=U("9").split("."),r=Math.max(t.length,n.length);for(let a=0;0==e&&a<r;a++)for(var s=t[a]||"",i=n[a]||"";s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],i=/(\d*)(\D*)(.*)/.exec(i)||["","","",""],(0!=s[0].length||0!=i[0].length)&&(e=B(0==s[1].length?0:parseInt(s[1],10),0==i[1].length?0:parseInt(i[1],10))||B(0==s[2].length,0==i[2].length)||B(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(z,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",T,t),b.removeEventListener("test",T,t)}catch(e){}return e}();function he(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}function ue(e,t){if(he.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&&ue.Z.h.call(this)}}he.prototype.h=function(){this.defaultPrevented=!0},N(ue,he);var ce={2:"touch",3:"pen",4:"mouse"};ue.prototype.h=function(){ue.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=L(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,I(s)?!!s.capture:!!s,i):Te(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,I(r)?!!r.capture:!!r,s):Te(e,t,n,!1,r,s)}function Te(e,t,n,r,s,i){if(!t)throw Error("Invalid event type");var a,o=I(s)?!!s.capture:!!s,h=Se(e);if(h||(e[ve]=h=new me(e)),(n=h.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(Ie(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(Ie(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 Ie(e){return e in we?we[e]:we[e]="on"+e}function _e(e,t){var n,r;return e=!!e.ca||(t=new ue(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 Ce(){x.call(this),this.i=new me(this),(this.P=this).I=null}function ke(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 he(t,e):t instanceof he?t.target=t.target||e:(a=t,H(t=new he(r,e),a)),a=!0,n)for(var s=n.length-1;0<=s;s--)var i=t.g=n[s],a=Ne(i,r,!0,t)&&a;if(a=Ne(i=t.g=e,r,!0,t)&&a,a=Ne(i,r,!1,t)&&a,n)for(s=0;s<n.length;s++)a=Ne(i=t.g=n[s],r,!1,t)&&a}function Ne(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var s=!0,i=0;i<t.length;++i){var a,o,h=t[i];h&&!h.ca&&h.capture==n&&(a=h.listener,o=h.ia||h.src,h.fa&&pe(e.i,h),s=!1!==a.call(o,r)&&s)}return s&&!r.defaultPrevented}N(Ce,x),Ce.prototype[le]=!0,Ce.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=I(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)},Ce.prototype.M=function(){if(Ce.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},Ce.prototype.N=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},Ce.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var xe=b.JSON.stringify;var Re,Le=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new Me,e=>e.reset());class Me{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function Oe(e,t){var n;Re||(n=b.Promise.resolve(void 0),Re=function(){n.then(Ve)}),Fe||(Re(),Fe=!0),Pe.add(e,t)}var Fe=!1,Pe=new class{constructor(){this.h=this.g=null}add(e,t){const n=Le.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function Ve(){for(var e;e=function(){var e=Pe;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=Le;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}Fe=!1}function Ue(e,t){Ce.call(this),this.h=e||1,this.g=t||b,this.j=C(this.kb,this),this.l=Date.now()}function qe(e){e.da=!1,e.S&&(e.g.clearTimeout(e.S),e.S=null)}function Be(e,t,n){if("function"==typeof e)n&&(e=C(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=C(e.handleEvent,e)}return 2147483647<Number(t)?-1:b.setTimeout(e,t||0)}N(Ue,Ce),(y=Ue.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),ke(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(){Ue.Z.M.call(this),qe(this),delete this.g};class je extends x{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=Be(()=>{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 Ke(e){x.call(this),this.h=e,this.g={}}N(Ke,x);var $e=[];function Ge(e,t,n,r){Array.isArray(n)||(n&&($e[0]=n.toString()),n=$e);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 He(e){K(e.g,function(e,t){this.g.hasOwnProperty(t)&&Ee(e)},e),e.g={}}function We(){this.g=!0}function ze(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 xe(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}Ke.prototype.M=function(){Ke.Z.M.call(this),He(this)},Ke.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 Je(){return Ye=Ye||new Ce}function Xe(e){he.call(this,Qe.Ma,e)}function Ze(){var e=Je();ke(e,new Xe(e))}function et(e,t){he.call(this,Qe.STAT_EVENT,e),this.stat=t}function tt(e){var t=Je();ke(t,new et(t,e))}function nt(e,t){he.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",N(Xe,he),Qe.STAT_EVENT="statevent",N(et,he),Qe.Na="timingevent",N(nt,he);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 ht(){}at.prototype.h=null;v={OPEN:"a",pb:"b",Ka:"c",Bb:"d"};function ut(){he.call(this,"d")}function ct(){he.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 Ke(this),this.P=mt,this.W=new Ue(e=X?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}N(ut,he),N(ct,he),N(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(Mt(t)),e.s=n,e.U=!0,wt(e,null)}function wt(e,t){e.F=Date.now(),Et(e),e.A=Mt(e.v);var a,o,h,u,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 je(C(e.Ia,e,e.g),e.O)),Ge(e.V,e.g,"readystatechange",e.gb),t=e.H?$(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,h=e.A,u=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 ("+u+") [attempt "+c+"]: "+o+"\n"+h+"\n"+e})}function bt(e){return e.g&&("GET"==e.u&&2!=e.K&&e.l.Ba)}function Tt(e,t,n){let r=!0,s;for(;!e.I&&e.C<n.length;){if(s=(a=n,h=o=void 0,o=(i=e).C,-1==(h=a.indexOf("\n",o))?yt:(o=Number(a.substring(o,h)),isNaN(o)?pt:(h+=1)+o>a.length?yt:(a=a.substr(h,o),i.C=h+o,a))),s==yt){4==t&&(e.o=4,tt(14),r=!1),ze(e.j,e.m,null,"[Incomplete Response]");break}if(s==pt){e.o=4,tt(15),ze(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}ze(e.j,e.m,s,null),Dt(e,s)}var i,a,o,h;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),Hn(t),t.L=!0,tt(11))):(ze(e.j,e.m,n,"[Invalid Chunked Response]"),At(e),St(e))}function Et(e){e.Y=Date.now()+e.P,It(e,e.P)}function It(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=rt(C(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),He(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;zn(n),Pn(n)}Gn(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(C(n.ab,n),6e3));if(an(n.i)<=1&&n.ka){try{n.ka()}catch(e){}n.ka=void 0}}else Jn(n,11)}else if(!e.J&&n.g!=e||zn(n),!P(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 h,u,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&&(!(h=m.g?m.g.getResponseHeader("X-Client-Wire-Protocol"):null)||!(u=r.i).g&&(q(h,"spdy")||q(h,"quic")||q(h,"h2"))&&(u.j=u.l,u.g=new Set,u.h&&(hn(u,u.h),u.h=null)),!r.D||(c=m.g?m.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.sa=c,Ut(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?(un(r.i,g),d=g,(f=r.K)&&d.setTimeout(f),d.B&&(_t(d),Et(d)),r.g=g):$n(r),0<n.l.length&&qn(n)}else"stop"!=i[0]&&"close"!=i[0]||Jn(n,7);else 3==n.G&&("stop"==i[0]||"close"==i[0]?"stop"==i[0]?Jn(n,7):Fn(n):"noop"!=i[0]&&n.j&&n.j.wa(i),n.A=0)}Ze()}catch(e){}}function Ct(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(E(e)||"string"==typeof e)M(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 kt(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 kt)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 Nt(e){if(e.i!=e.g.length){for(var t=0,n=0;t<e.g.length;){var r=e.g[t];xt(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;)xt(s,r=e.g[t])||(s[e.g[n++]=r]=1),t++;e.g.length=n}}function xt(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==xn(e)?t.l():this.Ia(e)},y.Ia=function(e){try{if(e==this.g)e:{var t=xn(this.g),n=this.g.Da();this.g.ba();if(!(t<3)&&(3!=t||X||this.g&&(this.h.h||this.g.ga()||Rn(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=Rn(this.g);e="";var i=s.length,a=4==xn(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 h,u=this.g;if((h=u.g?u.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!P(h)){var c=h;break t}}c=null}if(!(r=c)){this.i=!1,this.o=3,tt(12),At(this),St(this);break e}ze(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.J=!0,Dt(this,r)}this.U?(Tt(this,t,o),X&&this.i&&3==t&&(Ge(this.V,this.W,"tick",this.fb),this.W.start())):(ze(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=xn(this.g),t=this.g.ga(),this.C<t.length&&(_t(this),Tt(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)):It(this,this.Y-n)},(y=kt.prototype).R=function(){Nt(this);for(var e=[],t=0;t<this.g.length;t++)e.push(this.h[this.g[t]]);return e},y.T=function(){return Nt(this),this.g.concat()},y.get=function(e,t){return xt(this.h,e)?this.h[e]:t},y.set=function(e,t){xt(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 Rt=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function Lt(e,t){var n;this.i=this.s=this.j="",this.m=null,this.o=this.l="",this.g=!1,e instanceof Lt?(this.g=void 0!==t?t:e.g,Ot(this,e.j),this.s=e.s,Ft(this,e.i),Pt(this,e.m),this.l=e.l,t=e.h,(n=new Qt).i=t.i,t.g&&(n.g=new kt(t.g),n.h=t.h),Vt(this,n),this.o=e.o):e&&(n=String(e).match(Rt))?(this.g=!!t,Ot(this,n[1]||"",!0),this.s=Bt(n[2]||""),Ft(this,n[3]||"",!0),Pt(this,n[4]),this.l=Bt(n[5]||"",!0),Vt(this,n[6]||"",!0),this.o=Bt(n[7]||"")):(this.g=!!t,this.h=new Qt(null,this.g))}function Mt(e){return new Lt(e)}function Ot(e,t,n){e.j=n?Bt(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Ft(e,t,n){e.i=n?Bt(t,!0):t}function Pt(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 Vt(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&&(Jt(this,t),Zt(this,n,e))},r)),r.j=s):(n||(t=jt(t,Wt)),e.h=new Qt(t,e.g))}function Ut(e,t,n){e.h.set(t,n)}function qt(e){return Ut(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Bt(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function jt(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,Kt),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function Kt(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}Lt.prototype.toString=function(){var e=[],t=this.j;t&&e.push(jt(t,$t,!0),":");var n=this.i;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(jt(t,$t,!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(jt(n,"/"==n.charAt(0)?Ht:Gt,!0))),(n=this.h.toString())&&e.push("?",n),(n=this.o)&&e.push("#",jt(n,zt)),e.join("")};var $t=/[#\/\?@]/g,Gt=/[#\?:]/g,Ht=/[#\?]/g,Wt=/[#\?@]/g,zt=/#/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 kt,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 Jt(e,t){Yt(e),t=en(e,t),xt(e.g.h,t)&&(e.i=null,e.h-=e.g.get(t).length,xt((e=e.g).h,t)&&(delete e.h[t],e.i--,e.g.length>2*e.i&&Nt(e)))}function Xt(e,t){return Yt(e),t=en(e,t),xt(e.g.h,t)}function Zt(e,t,n){Jt(e,t),0<n.length&&(e.i=null,e.g.set(en(e,t),F(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){M(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)Xt(this,e)&&(t=O(t,this.g.get(en(this,e))));else{e=this.g.R();for(var n=0;n<e.length;n++)t=O(t,e[n])}return t},y.set=function(e,t){return Yt(this),this.i=null,Xt(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 hn(e,t){e.g?e.g.add(t):e.h=t}function un(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 F(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){Ce.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)},N(gn,at),gn.prototype.g=function(){return new mn(this.l,this.j)},gn.prototype.i=(rn={},function(){return rn}),N(mn,Ce);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 Tn(e){Ce.call(this),this.headers=new kt,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}N(Tn,Ce);var En="",In=/^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),kn(e)}function Dn(e){e.D||(e.D=!0,ke(e,"complete"),ke(e,"error"))}function Cn(e){if(e.h&&void 0!==w&&(!e.C[1]||4!=xn(e)||2!=e.ba()))if(e.v&&4==xn(e))Be(e.Fa,0,e);else if(ke(e,"readystatechange"),4==xn(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(Rt)[1]||null)&&b.self&&b.self.location&&(s=(r=b.self.location.protocol).substr(0,r.length-1)),n=!In.test(s?s.toLowerCase():"")),t=n),t)ke(e,"complete"),ke(e,"success");else{e.m=6;try{var o=2<xn(e)?e.g.statusText:""}catch(e){o=""}e.j=o+" ["+e.ba()+"]",Dn(e)}}finally{kn(e)}}}function kn(e,t){if(e.g){Nn(e);const n=e.g,r=e.C[0]?T:null;e.g=null,e.C=null,t||ke(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Nn(e){e.g&&e.K&&(e.g.ontimeout=null),e.A&&(b.clearTimeout(e.A),e.A=null)}function xn(e){return e.g?e.g.readyState:0}function Rn(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 Ln(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=function(e){let n="";return K(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):Ut(e,t,n))}function Mn(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function On(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=Mn("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=Mn("baseRetryDelayMs",5e3,e),this.$a=Mn("retryDelaySeedMs",1e4,e),this.Ya=Mn("forwardChannelMaxRetries",2,e),this.ra=Mn("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 Fn(e){var t,n;Vn(e),3==e.G&&(t=e.V++,Ut(n=Mt(e.F),"SID",e.J),Ut(n,"RID",t),Ut(n,"TYPE","terminate"),jn(e,n),(t=new dt(e,e.h,t,void 0)).K=2,t.v=qt(Mt(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)),Xn(e)}function Pn(e){e.g&&(Hn(e),e.g.cancel(),e.g=null)}function Vn(e){Pn(e),e.u&&(b.clearTimeout(e.u),e.u=null),zn(e),e.i.cancel(),e.m&&("number"==typeof e.m&&b.clearTimeout(e.m),e.m=null)}function Un(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,Oe(e.Ha,e),e.C=0)}function Bn(e,t){var n=t?t.m:e.V++,r=Mt(e.F);Ut(r,"SID",e.J),Ut(r,"RID",n),Ut(r,"AID",e.U),jn(e,r),e.o&&e.s&&Ln(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=Kn(e,n,1e3),n.setTimeout(Math.round(.5*e.ra)+Math.round(.5*e.ra*Math.random())),hn(e.i,n),vt(n,r,t)}function jn(e,n){e.j&&Ct({},function(e,t){Ut(n,t,e)})}function Kn(e,t,r){r=Math.min(e.l.length,r);var s=e.j?C(e.j.Oa,e.j,e):null;e:{var i=e.l;let n=-1;for(;;){const h=["count="+r];-1==n?0<r?(n=i[0].h,h.push("ofs="+n)):n=0:h.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{Ct(e,function(e,t){let n=e;I(e)&&(n=xe(e)),r.push(s+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(s+"type="+encodeURIComponent("_badmap")),e}}(o,h,"req"+a+"_")}catch(e){s&&s(o)}}if(e){s=h.join("&");break e}}}return e=e.l.splice(0,r),t.D=e,s}function $n(e){e.g||e.u||(e.Y=1,Oe(e.Ga,e),e.A=0)}function Gn(e){return!(e.g||e.u||3<=e.A)&&(e.Y++,e.u=rt(C(e.Ga,e),Yn(e,e.A)),e.A++,1)}function Hn(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=Mt(e.oa);Ut(t,"RID","rpc"),Ut(t,"SID",e.J),Ut(t,"CI",e.N?"0":"1"),Ut(t,"AID",e.U),jn(e,t),Ut(t,"TYPE","xmlhttp"),e.o&&e.s&&Ln(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(Mt(t)),n.s=null,n.U=!0,wt(n,e)}function zn(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){zn(e),Hn(e),e.g=null;var a=2}else{if(!on(e.i,t))return;i=t.D,un(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,ke(a=Je(),new nt(a,i)),qn(e)):$n(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(C(r.Ha,r,s),Yn(r,r.C)),r.C++,0))))&&(2!=a||!Gn(e)))switch(i&&0<i.length&&(t=e.i,t.i=t.i.concat(i)),n){case 1:Jn(e,5);break;case 4:Jn(e,10);break;case 3:Jn(e,6);break;default:Jn(e,2)}}function Yn(e,t){let n=e.Pa+Math.floor(Math.random()*e.$a);return e.j||(n*=2),n*t}function Jn(e,t){var n,r;e.h.info("Error code "+t),2==t?(n=null,e.j&&(n=null),r=C(e.jb,e),n||(n=new Lt("//www.google.com/images/cleardot.gif"),b.location&&"http"==b.location.protocol||Ot(n,"https"),qt(n)),function(e,t){var n=new We;if(b.Image){const r=new Image;r.onload=k(fn,n,r,"TestLoadImage: loaded",!0,t),r.onerror=k(fn,n,r,"TestLoadImage: error",!1,t),r.onabort=k(fn,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=k(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),Xn(e),Vn(e)}function Xn(e){e.G=0,e.I=-1,e.j&&(0==cn(e.i).length&&0==e.l.length||(e.i.i.length=0,F(e.l),e.l.length=0),e.j.ua())}function Zn(e,t,n){let r=(o=n)instanceof Lt?Mt(o):new Lt(o,void 0);var s,i,a,o,h;return""!=r.i?(t&&Ft(r,t+"."+r.i),Pt(r,r.m)):(h=b.location,r=(s=h.protocol,i=t?t+"."+h.hostname:h.hostname,a=+h.port,o=n,h=new Lt(null,void 0),s&&Ot(h,s),i&&Ft(h,i),a&&Pt(h,a),o&&(h.l=o),h)),e.aa&&K(e.aa,function(e,t){Ut(r,t,e)}),t=e.D,n=e.sa,t&&n&&Ut(r,t,n),Ut(r,"VER",e.ma),jn(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 Tn(new gn({ib:!0})):new Tn(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){Ce.call(this),this.g=new On(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)&&!P(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!P(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){ut.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=Tn.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=C(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 kt(this.headers);r&&Ct(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<=L(_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{Nn(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=C(this.pa,this)):this.A=Be(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,ke(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,ke(this,"complete"),ke(this,"abort"),kn(this))},y.M=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),kn(this,!0)),Tn.Z.M.call(this)},y.Fa=function(){this.s||(this.F||this.v||this.l?Cn(this):this.cb())},y.cb=function(){Cn(this)},y.ba=function(){try{return 2<xn(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=On.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=$(e),H(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=Kn(this,i,n),Ut(r=Mt(this.F),"RID",t),Ut(r,"CVER",22),this.D&&Ut(r,"X-HTTP-Session-Id",this.D),jn(this,r),this.o&&e&&Ln(r,this.o,e),hn(this.i,i),this.Ra&&Ut(r,"TYPE","init"),this.ja?(Ut(r,"$req",n),Ut(r,"SID","null"),i.$=!0,vt(i,r,null)):vt(i,r,n),this.G=2}}else 3==this.G&&(t?Bn(this,t):0==this.l.length||sn(this.i)||Bn(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(C(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),Pn(this),Wn(this))},y.ab=function(){null!=this.v&&(this.v=null,Pn(this),Gn(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)},N(rr,Ce),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."),Oe(C(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(){Fn(this.g)},rr.prototype.u=function(e){var t;"string"==typeof e?((t={}).__data__=e,Un(this.g,t)):this.v?((t={}).__data__=xe(e),Un(this.g,t)):Un(this.g,e)},rr.prototype.M=function(){this.g.j=null,delete this.j,Fn(this.g),delete this.g,rr.Z.M.call(this)},N(sr,ut),N(ir,ct),N(ar,tr),ar.prototype.xa=function(){ke(this.g,"a")},ar.prototype.wa=function(e){ke(this.g,new sr(e))},ar.prototype.va=function(e){ke(this.g,new ir)},ar.prototype.ua=function(){ke(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",(ht.EventType=v).OPEN="a",v.CLOSE="b",v.ERROR="c",v.MESSAGE="d",Ce.prototype.listen=Ce.prototype.N,Tn.prototype.listenOnce=Tn.prototype.O,Tn.prototype.getLastError=Tn.prototype.La,Tn.prototype.getLastErrorCode=Tn.prototype.Da,Tn.prototype.getStatus=Tn.prototype.ba,Tn.prototype.getResponseJson=Tn.prototype.Qa,Tn.prototype.getResponseText=Tn.prototype.ga,Tn.prototype.send=Tn.prototype.ea;var or,hr=Je,ur=st,cr=it,lr=Qe,dr=10,fr=11,gr=gn,mr=ht,pr=Tn;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.2";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 Tr(){return br.logLevel}function Er(e,...t){var n;br.logLevel<=l.DEBUG&&(n=t.map(Sr),br.debug(`Firestore (${wr}): ${e}`,...n))}function Ir(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 Ir(t),new Error(t)}function Dr(e){e||Ar()}const Cr={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 kr extends o{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class Nr{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class xr{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Rr{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(vr.UNAUTHENTICATED))}shutdown(){}}class Lr{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 Mr{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 Nr;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new Nr,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 Nr))},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 xr(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return Dr(null===e||"string"==typeof e),new vr(e)}}class Or{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 Fr{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new Or(this.h,this.l,this.m))}start(e,t){e.enqueueRetryable(()=>t(vr.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Pr{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 Vr{constructor(e){this.g=e,this.forceRefresh=!1,this.appCheck=null}start(t,n){this.o=e=>{t.enqueueRetryable(()=>(e=>(null!=e.error&&Er("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`),n(e.token)))(e))};const r=e=>{Er("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.g.onInit(e=>r(e)),setTimeout(()=>{var e;this.appCheck||((e=this.g.getImmediate({optional:!0}))?r(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),new Pr(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class Ur{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.p(e),this.T=e=>t.writeSequenceNumber(e))}p(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.T&&this.T(e),e}}Ur.I=-1;class qr{static A(){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 Br(e,t){return e<t?-1:t<e?1:0}function jr(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function Kr(e){return e+"\0"}class $r{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new kr(Cr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new kr(Cr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new kr(Cr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new kr(Cr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return $r.fromMillis(Date.now())}static fromDate(e){return $r.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new $r(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Br(this.nanoseconds,e.nanoseconds):Br(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 Gr{constructor(e){this.timestamp=e}static fromTimestamp(e){return new Gr(e)}static min(){return new Gr(new $r(0,0))}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 Hr(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 zr(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 kr(Cr.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 Jr=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Xr extends Qr{construct(e,t,n){return new Xr(e,t,n)}static isValidIdentifier(e){return Jr.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!Xr.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new Xr(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var s=()=>{if(0===n.length)throw new kr(Cr.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 kr(Cr.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new kr(Cr.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 kr(Cr.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Xr(t)}static emptyPath(){return new Xr([])}}class Zr{constructor(e){(this.fields=e).sort(Xr.comparator)}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return jr(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class 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 Br(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 $r(t.seconds,t.nanos)}function os(e){return null==e}function hs(e){return 0===e&&1/e==-1/0}function us(e){return"number"==typeof e&&Number.isInteger(e)&&!hs(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}class cs{constructor(e){this.path=e}static fromPath(e){return new cs(Yr.fromString(e))}static fromName(e){return new cs(Yr.fromString(e).popFirst(5))}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}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 cs(new Yr(e.slice()))}}function ls(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?is(e)?4:10:Ar()}function ds(r,s){if(r===s)return!0;var e,t,n=ls(r);if(n!==ls(s))return!1;switch(n){case 0: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?hs(n)===hs(r):isNaN(n)&&isNaN(r)}return!1}(r,s);case 9:return jr(r.arrayValue.values||[],s.arrayValue.values||[],ds);case 10:return function(e){const t=e.mapValue.fields||{},n=s.mapValue.fields||{};if(Hr(t)!==Hr(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!ds(t[e],n[e])))return!1;return!0}(r);default:return Ar()}}function fs(e,t){return void 0!==(e.values||[]).find(e=>ds(e,t))}function gs(e,t){if(e===t)return 0;var n,r,s,i,a=ls(e),o=ls(t);if(a!==o)return Br(a,o);switch(a){case 0:return 0;case 1:return Br(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 ms(e.timestampValue,t.timestampValue);case 4:return ms(as(e),as(t));case 5:return Br(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=Br(n[s],r[s]);if(0!==t)return t}return Br(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(i=Br(rs(n.latitude),rs(r.latitude)))?i:Br(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=gs(n[s],r[s]);if(t)return t}return Br(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=Br(r[o],i[o]);if(0!==t)return t;var a=gs(n[r[o]],s[i[o]]);if(0!==a)return a}return Br(r.length,i.length)}(e.mapValue,t.mapValue);default:throw Ar()}}function ms(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Br(e,t);var n=ns(e),r=ns(t),s=Br(n.seconds,r.seconds);return 0!==s?s:Br(n.nanos,r.nanos)}function ps(e){return function i(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=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,cs.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 ys(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function vs(e){return e&&"integerValue"in e}function ws(e){return!!e&&"arrayValue"in e}function bs(e){return e&&"nullValue"in e}function Ts(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Es(e){return e&&"mapValue"in e}function Is(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]=Is(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Is(t.arrayValue.values[e]);return r}return Object.assign({},t)}class _s{constructor(e){this.value=e}static empty(){return new _s({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)],!Es(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Is(t)}setAll(e){let n=Xr.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()]=Is(e):s.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,s)}delete(e){const t=this.field(e.popLast());Es(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return ds(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)];Es(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 _s(Is(this.value))}}class Ss{constructor(e,t,n,r,s){this.key=e,this.documentType=t,this.version=n,this.data=r,this.documentState=s}static newInvalidDocument(e){return new Ss(e,0,Gr.min(),_s.empty(),0)}static newFoundDocument(e,t,n){return new Ss(e,1,t,n,0)}static newNoDocument(e,t){return new Ss(e,2,t,_s.empty(),0)}static newUnknownDocument(e,t){return new Ss(e,3,t,_s.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=_s.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=_s.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,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 Ss&&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 Ss(this.key,this.documentType,this.version,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class As{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.R=null}}function Ds(e,t=null,n=[],r=[],s=null,i=null,a=null){return new As(e,t,n,r,s,i,a)}function Cs(e){const t=e;if(null===t.R){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>function(e){return e.field.canonicalString()+e.op.toString()+ps(e.value)}(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),os(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=Bs(t.startAt)),t.endAt&&(e+="|ub:",e+=Bs(t.endAt)),t.R=e}return t.R}function ks(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)||!ds(s.value,i.value))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!$s(e.startAt,t.startAt)&&$s(e.endAt,t.endAt)}function Ns(e){return cs.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}class xs 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.P(e,t,n):new Rs(e,t,n):"array-contains"===t?new Fs(e,n):"in"===t?new Ps(e,n):"not-in"===t?new Vs(e,n):"array-contains-any"===t?new Us(e,n):new xs(e,t,n)}static P(e,t,n){return new("in"===t?Ls:Ms)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.v(gs(t,this.value)):null!==t&&ls(this.value)===ls(t)&&this.v(gs(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()}}V(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}}class Rs extends xs{constructor(e,t,n){super(e,t,n),this.key=cs.fromName(n.referenceValue)}matches(e){var t=cs.comparator(e.key,this.key);return this.v(t)}}class Ls extends xs{constructor(e,t){super(e,"in",t),this.keys=Os(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class Ms extends xs{constructor(e,t){super(e,"not-in",t),this.keys=Os(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function Os(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>cs.fromName(e.referenceValue))}class Fs extends xs{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return ws(t)&&fs(t.arrayValue,this.value)}}class Ps extends xs{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&fs(this.value.arrayValue,t)}}class Vs extends xs{constructor(e,t){super(e,"not-in",t)}matches(e){if(fs(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!fs(this.value.arrayValue,t)}}class Us extends xs{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!ws(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>fs(this.value.arrayValue,e))}}class qs{constructor(e,t){this.position=e,this.before=t}}function Bs(e){return`${e.before?"b":"a"}:${e.position.map(e=>ps(e)).join(",")}`}class js{constructor(e,t="asc"){this.field=e,this.dir=t}}function Ks(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()?cs.comparator(cs.fromName(a.referenceValue),n.key):gs(a,n.data.field(i.field)),"desc"===i.dir&&(r*=-1),0!==r)break}return e.before?r<=0:r<0}function $s(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.before!==t.before||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!ds(e.position[n],t.position[n]))return!1;return!0}class Gs{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.S=null,this.D=null,this.startAt,this.endAt}}function Hs(e,t,n,r,s,i,a,o){return new Gs(e,t,n,r,s,i,a,o)}function Ws(e){return new Gs(e)}function zs(e){return!os(e.limit)&&"F"===e.limitType}function Qs(e){return!os(e.limit)&&"L"===e.limitType}function Ys(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function Js(e){for(const t of e.filters)if(t.V())return t.field;return null}function Xs(e){return null!==e.collectionGroup}function Zs(t){const n=t;if(null===n.S){n.S=[];const t=Js(n),e=Ys(n);if(null!==t&&null===e)t.isKeyField()||n.S.push(new js(t)),n.S.push(new js(Xr.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.S.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.S.push(new js(Xr.keyField(),t))}}}return n.S}function ei(e){const t=e;if(!t.D)if("F"===t.limitType)t.D=Ds(t.path,t.collectionGroup,Zs(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const s of Zs(t)){const t="desc"===s.dir?"asc":"desc";e.push(new js(s.field,t))}var n=t.endAt?new qs(t.endAt.position,!t.endAt.before):null,r=t.startAt?new qs(t.startAt.position,!t.startAt.before):null;t.D=Ds(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.D}function ti(e,t,n){return new Gs(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function ni(e,t){return ks(ei(e),ei(t))&&e.limitType===t.limitType}function ri(e){return`${Cs(ei(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} ${ps(t.value)}`;var t}).join(", ")}]`),os(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: "+Bs(e.startAt)),e.endAt&&(t+=", endAt: "+Bs(e.endAt)),`Target(${t})`}(ei(e))}; limitType=${e.limitType})`}function ii(n,e){return e.isFoundDocument()&&(t=n,s=(r=e).key.path,null!==t.collectionGroup?r.key.hasCollectionId(t.collectionGroup)&&t.path.isPrefixOf(s):cs.isDocumentKey(t.path)?t.path.isEqual(s):t.path.isImmediateParentOf(s))&&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)&&(t=e,(!(e=n).startAt||Ks(e.startAt,Zs(e),t))&&(!e.endAt||!Ks(e.endAt,Zs(e),t)));var t,r,s}function ai(s){return(e,t)=>{let n=!1;for(const r of Zs(s)){const s=function(e,s,t){var n=e.field.isKeyField()?cs.comparator(s.key,t.key):function(e,t){var n=s.data.field(e),r=t.data.field(e);return null!==n&&null!==r?gs(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 oi(e,t){if(e.C){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:hs(t)?"-0":t}}function hi(e){return{integerValue:""+e}}function ui(e,t){return us(t)?hi(t):oi(e,t)}class ci{constructor(){this._=void 0}}function li(e,t){return e instanceof yi?vs(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class di extends ci{}class fi extends ci{constructor(e){super(),this.elements=e}}function gi(e,t){const n=wi(t);for(const t of e.elements)n.some(e=>ds(e,t))||n.push(t);return{arrayValue:{values:n}}}class mi extends ci{constructor(e){super(),this.elements=e}}function pi(e,t){let n=wi(t);for(const t of e.elements)n=n.filter(e=>!ds(e,t));return{arrayValue:{values:n}}}class yi extends ci{constructor(e,t){super(),this.k=e,this.N=t}}function vi(e){return rs(e.integerValue||e.doubleValue)}function wi(e){return ws(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class bi{constructor(e,t){this.field=e,this.transform=t}}class Ti{constructor(e,t){this.version=e,this.transformResults=t}}class Ei{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Ei}static exists(e){return new Ei(void 0,e)}static updateTime(e){return new Ei(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 Ii(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class _i{}function Si(e,t,n){e instanceof ki?function(e,t,n){const r=e.value.clone(),s=Ri(e.fieldTransforms,t,n.transformResults);r.setAll(s),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Ni?function(e,t,n){if(!Ii(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=Ri(e.fieldTransforms,t,n.transformResults),s=t.data;s.setAll(xi(e)),s.setAll(r),t.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function Ai(e,t,n){e instanceof ki?function(e,t,n){if(Ii(e.precondition,t)){const r=e.value.clone(),s=Li(e.fieldTransforms,n,t);r.setAll(s),t.convertToFoundDocument(Ci(t),r).setHasLocalMutations()}}(e,t,n):e instanceof Ni?function(e,t,n){if(Ii(e.precondition,t)){const r=Li(e.fieldTransforms,n,t),s=t.data;s.setAll(xi(e)),s.setAll(r),t.convertToFoundDocument(Ci(t),s).setHasLocalMutations()}}(e,t,n):(t=t,Ii(e.precondition,t)&&t.convertToNoDocument(Gr.min()))}function Di(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&jr(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof fi&&t instanceof fi||e instanceof mi&&t instanceof mi?jr(e.elements,t.elements,ds):e instanceof yi&&t instanceof yi?ds(e.N,t.N):e instanceof di&&t instanceof di)}(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 Ci(e){return e.isFoundDocument()?e.version:Gr.min()}class ki extends _i{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}}class Ni extends _i{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 xi(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 Ri(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,h=a,u=n[c],o instanceof fi?gi(o,h):o instanceof mi?pi(o,h):u))}var o,h,u;return r}function Li(e,t,n){const r=new Map;for(const u of e){const e=u.transform,c=n.data.field(u.field);r.set(u.field,(s=e,i=c,a=t,h=o=void 0,s instanceof di?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 fi?gi(s,i):s instanceof mi?pi(s,i):(o=li(s=s,i),h=vi(o)+vi(s.N),vs(o)&&vs(s.N)?hi(h):oi(s.k,h))))}var s,i,a,o,h;return r}class Mi extends _i{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}}class Oi extends _i{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}}class Fi{constructor(e){this.count=e}}function Pi(e){switch(e){default:return Ar(),0;case Cr.CANCELLED:case Cr.UNKNOWN:case Cr.DEADLINE_EXCEEDED:case Cr.RESOURCE_EXHAUSTED:case Cr.INTERNAL:case Cr.UNAVAILABLE:case Cr.UNAUTHENTICATED:return;case Cr.INVALID_ARGUMENT:case Cr.NOT_FOUND:case Cr.ALREADY_EXISTS:case Cr.PERMISSION_DENIED:case Cr.FAILED_PRECONDITION:case Cr.ABORTED:case Cr.OUT_OF_RANGE:case Cr.UNIMPLEMENTED:case Cr.DATA_LOSS:return 1}}function Vi(e){if(void 0===e)return Ir("GRPC error has no .code"),Cr.UNKNOWN;switch(e){case or.OK:return Cr.OK;case or.CANCELLED:return Cr.CANCELLED;case or.UNKNOWN:return Cr.UNKNOWN;case or.DEADLINE_EXCEEDED:return Cr.DEADLINE_EXCEEDED;case or.RESOURCE_EXHAUSTED:return Cr.RESOURCE_EXHAUSTED;case or.INTERNAL:return Cr.INTERNAL;case or.UNAVAILABLE:return Cr.UNAVAILABLE;case or.UNAUTHENTICATED:return Cr.UNAUTHENTICATED;case or.INVALID_ARGUMENT:return Cr.INVALID_ARGUMENT;case or.NOT_FOUND:return Cr.NOT_FOUND;case or.ALREADY_EXISTS:return Cr.ALREADY_EXISTS;case or.PERMISSION_DENIED:return Cr.PERMISSION_DENIED;case or.FAILED_PRECONDITION:return Cr.FAILED_PRECONDITION;case or.ABORTED:return Cr.ABORTED;case or.OUT_OF_RANGE:return Cr.OUT_OF_RANGE;case or.UNIMPLEMENTED:return Cr.UNIMPLEMENTED;case or.DATA_LOSS:return Cr.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 Ui{constructor(e,t){this.comparator=e,this.root=t||Bi.EMPTY}insert(e,t){return new Ui(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,Bi.BLACK,null,null))}remove(e){return new Ui(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Bi.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 qi(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new qi(this.root,e,this.comparator,!1)}getReverseIterator(){return new qi(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new qi(this.root,e,this.comparator,!0)}}class qi{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,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 Bi{constructor(e,t,n,r,s){this.key=e,this.value=t,this.color=null!=n?n:Bi.RED,this.left=null!=r?r:Bi.EMPTY,this.right=null!=s?s:Bi.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,s){return new Bi(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 Bi.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 Bi.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,Bi.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,Bi.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)}}Bi.EMPTY=null,Bi.RED=!0,Bi.BLACK=!1,Bi.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 Bi(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 ji{constructor(e){this.comparator=e,this.data=new Ui(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 Ki(this.data.getIterator())}getIteratorFrom(e){return new Ki(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 ji))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 ji(this.comparator);return t.data=e,t}}class Ki{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}const $i=new Ui(cs.comparator);const Gi=new Ui(cs.comparator);const Hi=new Ui(cs.comparator);const Wi=new ji(cs.comparator);function zi(...e){let t=Wi;for(const n of e)t=t.add(n);return t}const Qi=new ji(Br);class Yi{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,Ji.createSynthesizedTargetChangeForCurrentChange(e,t)),new Yi(Gr.min(),n,Qi,$i,zi())}}class Ji{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 Ji(es.EMPTY_BYTE_STRING,t,zi(),zi(),zi())}}class Xi{constructor(e,t,n,r){this.$=e,this.removedTargetIds=t,this.key=n,this.O=r}}class Zi{constructor(e,t){this.targetId=e,this.F=t}}class ea{constructor(e,t,n=es.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class ta{constructor(){this.M=0,this.L=sa(),this.B=es.EMPTY_BYTE_STRING,this.U=!1,this.q=!0}get current(){return this.U}get resumeToken(){return this.B}get K(){return 0!==this.M}get j(){return this.q}W(e){0<e.approximateByteSize()&&(this.q=!0,this.B=e)}G(){let n=zi(),r=zi(),s=zi();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 Ji(this.B,this.U,n,r,s)}H(){this.q=!1,this.L=sa()}J(e,t){this.q=!0,this.L=this.L.insert(e,t)}Y(e){this.q=!0,this.L=this.L.remove(e)}X(){this.M+=1}Z(){--this.M}tt(){this.q=!0,this.U=!0}}class na{constructor(e){this.et=e,this.nt=new Map,this.st=$i,this.it=ra(),this.rt=new ji(Br)}ot(e){for(const t of e.$)e.O&&e.O.isFoundDocument()?this.at(t,e.O):this.ct(t,e.key,e.O);for(const n of e.removedTargetIds)this.ct(n,e.key,e.O)}ut(n){this.forEachTarget(n,e=>{const t=this.ht(e);switch(n.state){case 0:this.lt(e)&&t.W(n.resumeToken);break;case 1:t.Z(),t.K||t.H(),t.W(n.resumeToken);break;case 2:t.Z(),t.K||this.removeTarget(e);break;case 3:this.lt(e)&&(t.tt(),t.W(n.resumeToken));break;case 4:this.lt(e)&&(this.ft(e),t.W(n.resumeToken));break;default:Ar()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.nt.forEach((e,t)=>{this.lt(t)&&n(t)})}dt(e){const t=e.targetId,n=e.F.count,r=this.wt(t);if(r){const e=r.target;if(Ns(e))if(0===n){const n=new cs(e.path);this.ct(t,n,Ss.newNoDocument(n,Gr.min()))}else Dr(1===n);else this._t(t)!==n&&(this.ft(t),this.rt=this.rt.add(t))}}gt(r){const s=new Map;this.nt.forEach((e,t)=>{var n=this.wt(t);if(n){if(e.current&&Ns(n.target)){const s=new cs(n.target.path);null!==this.st.get(s)||this.yt(t,s)||this.ct(t,s,Ss.newNoDocument(s,r))}e.j&&(s.set(t,e.G()),e.H())}});let i=zi();this.it.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))});var e=new Yi(r,s,this.rt,this.st,i);return this.st=$i,this.it=ra(),this.rt=new ji(Br),e}at(e,t){var n;this.lt(e)&&(n=this.yt(e,t.key)?2:0,this.ht(e).J(t.key,n),this.st=this.st.insert(t.key,t),this.it=this.it.insert(t.key,this.Tt(t.key).add(e)))}ct(e,t,n){if(this.lt(e)){const r=this.ht(e);this.yt(e,t)?r.J(t,1):r.Y(t),this.it=this.it.insert(t,this.Tt(t).delete(e)),n&&(this.st=this.st.insert(t,n))}}removeTarget(e){this.nt.delete(e)}_t(e){var t=this.ht(e).G();return this.et.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}X(e){this.ht(e).X()}ht(e){let t=this.nt.get(e);return t||(t=new ta,this.nt.set(e,t)),t}Tt(e){let t=this.it.get(e);return t||(t=new ji(Br),this.it=this.it.insert(e,t)),t}lt(e){var t=null!==this.wt(e);return t||Er("WatchChangeAggregator","Detected inactive target",e),t}wt(e){var t=this.nt.get(e);return t&&t.K?null:this.et.Et(e)}ft(t){this.nt.set(t,new ta),this.et.getRemoteKeysForTarget(t).forEach(e=>{this.ct(t,e,null)})}yt(e,t){return this.et.getRemoteKeysForTarget(e).has(t)}}function ra(){return new Ui(cs.comparator)}function sa(){return new Ui(cs.comparator)}const ia={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 oa{constructor(e,t){this.databaseId=e,this.C=t}}function ha(e,t){return e.C?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function ua(e,t){return e.C?t.toBase64():t.toUint8Array()}function ca(e){return Dr(!!e),Gr.fromTimestamp((t=ns(e),new $r(t.seconds,t.nanos)));var t}function la(e,t){return e=e,new Yr(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function da(e){var t=Yr.fromString(e);return Dr(Ra(t)),t}function fa(e,t){return la(e.databaseId,t.path)}function ga(e,t){const n=da(t);if(n.get(1)!==e.databaseId.projectId)throw new kr(Cr.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 kr(Cr.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new cs(va(n))}function ma(e,t){return la(e.databaseId,t)}function pa(e){var t=da(e);return 4===t.length?Yr.emptyPath():va(t)}function ya(e){return new Yr(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function va(e){return Dr(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function wa(e,t,n){return{name:fa(e,t),fields:n.value.mapValue.fields}}function ba(e,t,n){const r=ga(e,t.name),s=ca(t.updateTime),i=new _s({mapValue:{fields:t.fields}}),a=Ss.newFoundDocument(r,s,i);return n&&a.setHasCommittedMutations(),n?a.setHasCommittedMutations():a}function Ta(e,t){let n;if(t instanceof ki)n={update:wa(e,t.key,t.value)};else if(t instanceof Mi)n={delete:fa(e,t.key)};else if(t instanceof Ni)n={update:wa(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 Oi))return Ar();n={verify:fa(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof di)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof fi)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 yi)return{fieldPath:e.field.canonicalString(),increment:t.N};throw Ar()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,ha(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:Ar()),n;var r}function Ea(t,n){const e=n.currentDocument?void 0!==(s=n.currentDocument).updateTime?Ei.updateTime(ca(s.updateTime)):void 0!==s.exists?Ei.exists(s.exists):Ei.none():Ei.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 di;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new fi(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new mi(e)}else"increment"in t?n=new yi(e,t.increment):Ar();var r=Xr.fromServerFormat(t.fieldPath);return new bi(r,n)}(t,e)):[];var s;if(n.update){n.update.name;var i=ga(t,n.update.name),a=new _s({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new Zr(e.map(e=>Xr.fromServerFormat(e)))}();return new Ni(i,a,t,e,r)}return new ki(i,a,e,r)}if(n.delete){const r=ga(t,n.delete);return new Mi(r,e)}if(n.verify){const r=ga(t,n.verify);return new Oi(r,e)}return Ar()}function Ia(e,t){return{documents:[ma(e,t.path)]}}function _a(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=ma(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=ma(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(Ts(e.value))return{unaryFilter:{field:Ca(e.field),op:"IS_NAN"}};if(bs(e.value))return{unaryFilter:{field:Ca(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Ts(e.value))return{unaryFilter:{field:Ca(e.field),op:"IS_NOT_NAN"}};if(bs(e.value))return{unaryFilter:{field:Ca(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Ca(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:Ca(e.field),direction:(e=e.dir,ia[e])}}(e))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);var i,s=(i=t.limit,e.C||os(i)?i:{value:i});return null!==s&&(n.structuredQuery.limit=s),t.startAt&&(n.structuredQuery.startAt=Aa(t.startAt)),t.endAt&&(n.structuredQuery.endAt=Aa(t.endAt)),n}function Sa(e){let t=pa(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let s=null;if(0<r){Dr(1===r);const l=n.from[0];l.allDescendants?s=l.collectionId:t=t.child(l.collectionId)}let i=[];n.where&&(i=function t(e){return e?void 0!==e.unaryFilter?[xa(e)]:void 0!==e.fieldFilter?[Na(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 js(ka(e.field),function(){switch(e.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(e)));let o=null;var h;n.limit&&(o=(e=n.limit,os(h="object"==typeof e?e.value:e)?null:h));let u=null;n.startAt&&(u=Da(n.startAt));let c=null;return n.endAt&&(c=Da(n.endAt)),Hs(t,s,a,i,o,"F",u,c)}function Aa(e){return{before:e.before,values:e.position}}function Da(e){var t=!!e.before,n=e.values||[];return new qs(n,t)}function Ca(e){return{fieldPath:e.canonicalString()}}function ka(e){return Xr.fromServerFormat(e.fieldPath)}function Na(e){return xs.create(ka(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 xa(e){switch(e.unaryFilter.op){case"IS_NAN":var t=ka(e.unaryFilter.field);return xs.create(t,"==",{doubleValue:NaN});case"IS_NULL":t=ka(e.unaryFilter.field);return xs.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=ka(e.unaryFilter.field);return xs.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=ka(e.unaryFilter.field);return xs.create(n,"!=",{nullValue:"NULL_VALUE"});default:return Ar()}}function Ra(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function La(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=Ma(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 Ma(t)}function Ma(e){return e+""}function Oa(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)}class Fa{constructor(e,t){this.seconds=e,this.nanoseconds=t}}class Pa{constructor(e,t,n){this.ownerId=e,this.allowTabSynchronization=t,this.leaseTimestampMs=n}}Pa.store="owner",Pa.key="owner";class Va{constructor(e,t,n){this.userId=e,this.lastAcknowledgedBatchId=t,this.lastStreamToken=n}}Va.store="mutationQueues",Va.keyPath="userId";class Ua{constructor(e,t,n,r,s){this.userId=e,this.batchId=t,this.localWriteTimeMs=n,this.baseMutations=r,this.mutations=s}}Ua.store="mutations",Ua.keyPath="batchId",Ua.userMutationsIndex="userMutationsIndex",Ua.userMutationsKeyPath=["userId","batchId"];class qa{constructor(){}static prefixForUser(e){return[e]}static prefixForPath(e,t){return[e,La(t)]}static key(e,t,n){return[e,La(t),n]}}qa.store="documentMutations",qa.PLACEHOLDER=new qa;class Ba{constructor(e,t){this.path=e,this.readTime=t}}class ja{constructor(e,t){this.path=e,this.version=t}}class Ka{constructor(e,t,n,r,s,i){this.unknownDocument=e,this.noDocument=t,this.document=n,this.hasCommittedMutations=r,this.readTime=s,this.parentPath=i}}Ka.store="remoteDocuments",Ka.readTimeIndex="readTimeIndex",Ka.readTimeIndexPath="readTime",Ka.collectionReadTimeIndex="collectionReadTimeIndex",Ka.collectionReadTimeIndexPath=["parentPath","readTime"];class $a{constructor(e){this.byteSize=e}}$a.store="remoteDocumentGlobal",$a.key="remoteDocumentGlobalKey";class Ga{constructor(e,t,n,r,s,i,a){this.targetId=e,this.canonicalId=t,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=s,this.lastLimboFreeSnapshotVersion=i,this.query=a}}Ga.store="targets",Ga.keyPath="targetId",Ga.queryTargetsIndexName="queryTargetsIndex",Ga.queryTargetsKeyPath=["canonicalId","targetId"];class Ha{constructor(e,t,n){this.targetId=e,this.path=t,this.sequenceNumber=n}}Ha.store="targetDocuments",Ha.keyPath=["targetId","path"],Ha.documentTargetsIndex="documentTargetsIndex",Ha.documentTargetsKeyPath=["path","targetId"];class Wa{constructor(e,t,n,r){this.highestTargetId=e,this.highestListenSequenceNumber=t,this.lastRemoteSnapshotVersion=n,this.targetCount=r}}Wa.key="targetGlobalKey",Wa.store="targetGlobal";class za{constructor(e,t){this.collectionId=e,this.parent=t}}za.store="collectionParents",za.keyPath=["collectionId","parent"];class Qa{constructor(e,t,n,r){this.clientId=e,this.updateTimeMs=t,this.networkEnabled=n,this.inForeground=r}}Qa.store="clientMetadata",Qa.keyPath="clientId";class Ya{constructor(e,t,n){this.bundleId=e,this.createTime=t,this.version=n}}Ya.store="bundles",Ya.keyPath="bundleId";class Ja{constructor(e,t,n){this.name=e,this.readTime=t,this.bundledQuery=n}}Ja.store="namedQueries",Ja.keyPath="name";const Xa=[Va.store,Ua.store,qa.store,Ka.store,Ga.store,Pa.store,Wa.store,Ha.store,Qa.store,$a.store,za.store,Ya.store,Ja.store],Za="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class eo{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}class to{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 to((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 to?t:to.resolve(t)}catch(e){return to.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):to.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):to.reject(t)}static resolve(n){return new to((e,t)=>{e(n)})}static reject(n){return new to((e,t)=>{t(n)})}static waitFor(e){return new to((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=to.resolve(!1);for(const n of e)t=t.next(e=>e?to.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 no{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.It=new Nr,this.transaction.oncomplete=()=>{this.It.resolve()},this.transaction.onabort=()=>{e.error?this.It.reject(new io(n,e.error)):this.It.resolve()},this.transaction.onerror=e=>{var t=co(e.target.error);this.It.reject(new io(n,t))}}static open(e,t,n,r){try{return new no(t,e.transaction(r,n))}catch(e){throw new io(t,e)}}get At(){return this.It.promise}abort(e){e&&this.It.reject(e),this.aborted||(Er("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}store(e){var t=this.transaction.objectStore(e);return new oo(t)}}class ro{constructor(e,t,n){this.name=e,this.version=t,this.Rt=n,12.2===ro.bt(f())&&Ir("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),ho(window.indexedDB.deleteDatabase(e)).toPromise()}static Pt(){if("object"!=typeof indexedDB)return!1;if(ro.vt())return!0;const e=f(),t=ro.bt(e),n=0<t&&t<10,r=ro.Vt(e),s=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||s)}static vt(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.St)}static Dt(e,t){return e.store(t)}static bt(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 Vt(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async Ct(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 io(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 kr(Cr.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 kr(Cr.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 io(i,t))},s.onupgradeneeded=e=>{Er("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.Rt.Nt(t,s.transaction,e.oldVersion,this.version).next(()=>{Er("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.kt&&(this.db.onversionchange=e=>this.kt(e)),this.db}xt(t){this.kt=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.Ct(e);const t=no.open(this.db,e,s?"readonly":"readwrite",n),i=r(t).catch(e=>(t.abort(e),to.reject(e))).toPromise();return i.catch(()=>{}),await t.At,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 so{constructor(e){this.$t=e,this.Ot=!1,this.Ft=null}get isDone(){return this.Ot}get Mt(){return this.Ft}set cursor(e){this.$t=e}done(){this.Ot=!0}Lt(e){this.Ft=e}delete(){return ho(this.$t.delete())}}class io extends kr{constructor(e,t){super(Cr.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function ao(e){return"IndexedDbTransactionError"===e.name}class oo{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)),ho(n)}add(e){return Er("SimpleDb","ADD",this.store.name,e,e),ho(this.store.add(e))}get(t){return ho(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),ho(this.store.delete(e))}count(){return Er("SimpleDb","COUNT",this.store.name),ho(this.store.count())}Bt(e,t){const n=this.cursor(this.options(e,t)),r=[];return this.Ut(n,(e,t)=>{r.push(t)}).next(()=>r)}qt(e,t){Er("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.Kt=!1;var r=this.cursor(n);return this.Ut(r,(e,t,n)=>n.delete())}jt(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.Ut(r,t)}Qt(s){const e=this.cursor({});return new to((n,r)=>{e.onerror=e=>{var t=co(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()}})}Ut(e,i){const a=[];return new to((s,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new so(t),r=i(t.primaryKey,t.value,n);if(r instanceof to){const e=r.catch(e=>(n.done(),to.reject(e)));a.push(e)}n.isDone?s():null===n.Mt?t.continue():t.continue(n.Mt)}else s()}}).next(()=>to.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.Kt?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function ho(e){return new to((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=co(e.target.error);r(t)}})}let uo=!1;function co(e){const t=ro.bt(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 kr("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 uo||(uo=!0,setTimeout(()=>{throw e},0)),e}}return e}class lo extends eo{constructor(e,t){super(),this.Wt=e,this.currentSequenceNumber=t}}function fo(e,t){var n=e;return ro.Dt(n.Wt,t)}class go{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)&&Si(s,e,n[r])}}applyToLocalView(e){for(const t of this.baseMutations)t.key.isEqual(e.key)&&Ai(t,e,this.localWriteTime);for(const n of this.mutations)n.key.isEqual(e.key)&&Ai(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(Gr.min())})}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),zi())}isEqual(e){return this.batchId===e.batchId&&jr(this.mutations,e.mutations,(e,t)=>Di(e,t))&&jr(this.baseMutations,e.baseMutations,(e,t)=>Di(e,t))}}class mo{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=Hi;var s=e.mutations;for(let i=0;i<s.length;i++)r=r.insert(s[i].key,n[i].version);return new mo(e,t,n,r)}}class po{constructor(e,t,n,r,s=Gr.min(),i=Gr.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 po(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new po(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new po(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class yo{constructor(e){this.Gt=e}}function vo(e,t){if(t.document)return ba(e.Gt,t.document,!!t.hasCommittedMutations);if(t.noDocument){const e=cs.fromSegments(t.noDocument.path),n=Io(t.noDocument.readTime),r=Ss.newNoDocument(e,n);return t.hasCommittedMutations?r.setHasCommittedMutations():r}if(t.unknownDocument){const e=cs.fromSegments(t.unknownDocument.path),s=Io(t.unknownDocument.version);return Ss.newUnknownDocument(e,s)}return Ar()}function wo(e,t,n){var r=bo(n),s=t.key.path.popLast().toArray();if(t.isFoundDocument()){const i={name:fa(n=e.Gt,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:ha(n,e.version.toTimestamp())},a=t.hasCommittedMutations;return new Ka(null,null,i,a,r,s)}if(t.isNoDocument()){const o=t.key.path.toArray(),i=Eo(t.version),h=t.hasCommittedMutations;return new Ka(null,new Ba(o,i),null,h,r,s)}if(t.isUnknownDocument()){const o=t.key.path.toArray(),i=Eo(t.version);return new Ka(new ja(o,i),null,null,!0,r,s)}return Ar()}function bo(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function To(e){var t=new $r(e[0],e[1]);return Gr.fromTimestamp(t)}function Eo(e){var t=e.toTimestamp();return new Fa(t.seconds,t.nanoseconds)}function Io(e){var t=new $r(e.seconds,e.nanoseconds);return Gr.fromTimestamp(t)}function _o(t,e){const n=(e.baseMutations||[]).map(e=>Ea(t.Gt,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=>Ea(t.Gt,e)),s=$r.fromMillis(e.localWriteTimeMs);return new go(e.batchId,s,n,r)}function So(e){var t,n=Io(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?Io(e.lastLimboFreeSnapshotVersion):Gr.min();let s;return s=void 0!==e.query.documents?(Dr(1===(t=e.query).documents.length),ei(Ws(pa(t.documents[0])))):ei(Sa(e.query)),new po(s,e.targetId,0,e.lastListenSequenceNumber,n,r,es.fromBase64String(e.resumeToken))}function Ao(e,t){var n=Eo(t.snapshotVersion),r=Eo(t.lastLimboFreeSnapshotVersion),s=(Ns(t.target)?Ia:_a)(e.Gt,t.target),i=t.resumeToken.toBase64();return new Ga(t.targetId,Cs(t.target),n,i,t.sequenceNumber,r,s)}function Do(e){var t=Sa({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?ti(t,t.limit,"L"):t}class Co{getBundleMetadata(e,t){return ko(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:Io(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return ko(e).put({bundleId:(n=t).id,createTime:Eo(ca(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return No(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:Do(t.bundledQuery),readTime:Io(t.readTime)};var t})}saveNamedQuery(e,t){return No(e).put({name:(t=t).name,readTime:Eo(ca(t.readTime)),bundledQuery:t.bundledQuery})}}function ko(e){return fo(e,Ya.store)}function No(e){return fo(e,Ja.store)}class xo{constructor(){this.zt=new Ro}addToCollectionParentIndex(e,t){return this.zt.add(t),to.resolve()}getCollectionParents(e,t){return to.resolve(this.zt.getEntries(t))}}class Ro{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new ji(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 ji(Yr.comparator)).toArray()}}class Lo{constructor(){this.Ht=new Ro}addToCollectionParentIndex(e,t){if(this.Ht.has(t))return to.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Ht.add(t)});r={collectionId:n,parent:La(r)};return Mo(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[Kr(n),""],!1,!0);return Mo(e).Bt(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(Oa(t.parent))}return r})}}function Mo(e){return fo(e,za.store)}const Oo={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class Fo{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Fo(e,Fo.DEFAULT_COLLECTION_PERCENTILE,Fo.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function Po(e,t,n){const r=e.store(Ua.store),s=e.store(qa.store),i=[],a=IDBKeyRange.only(n.batchId);let o=0;const h=r.jt({range:a},(e,t,n)=>(o++,n.delete()));i.push(h.next(()=>{Dr(1===o)}));const u=[];for(const e of n.mutations){const r=qa.key(t,e.key.path,n.batchId);i.push(s.delete(r)),u.push(e.key)}return to.waitFor(i).next(()=>u)}function Vo(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}Fo.DEFAULT_COLLECTION_PERCENTILE=10,Fo.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Fo.DEFAULT=new Fo(41943040,Fo.DEFAULT_COLLECTION_PERCENTILE,Fo.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Fo.DISABLED=new Fo(-1,0,0);class Uo{constructor(e,t,n,r){this.userId=e,this.k=t,this.Jt=n,this.referenceDelegate=r,this.Yt={}}static Xt(e,t,n,r){Dr(""!==e.uid);var s=e.isAuthenticated()?e.uid:"";return new Uo(s,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Bo(e).jt({index:Ua.userMutationsIndex,range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(c,l,d,f){const g=jo(c),m=Bo(c);return m.add({}).next(e=>{Dr("number"==typeof e);const t=new go(e,l,d,f),n=(s=this.k,i=this.userId,a=t,o=a.baseMutations.map(e=>Ta(s.Gt,e)),h=a.mutations.map(e=>Ta(s.Gt,e)),new Ua(i,a.batchId,a.localWriteTime.toMillis(),o,h)),r=[];var s,i,a,o,h;let u=new ji((e,t)=>Br(e.canonicalString(),t.canonicalString()));for(const c of f){const l=qa.key(this.userId,c.key.path,e);u=u.add(c.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,qa.PLACEHOLDER))}return u.forEach(e=>{r.push(this.Jt.addToCollectionParentIndex(c,e))}),c.addOnCommittedListener(()=>{this.Yt[e]=t.keys()}),to.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return Bo(e).get(t).next(e=>e?(Dr(e.userId===this.userId),_o(this.k,e)):null)}Zt(e,n){return this.Yt[n]?to.resolve(this.Yt[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.Yt[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let s=null;return Bo(e).jt({index:Ua.userMutationsIndex,range:n},(e,t,n)=>{t.userId===this.userId&&(Dr(t.batchId>=r),s=_o(this.k,t)),n.done()}).next(()=>s)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return Bo(e).jt({index:Ua.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 Bo(e).Bt(Ua.userMutationsIndex,t).next(e=>e.map(e=>_o(this.k,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=qa.prefixForPath(this.userId,o.path),t=IDBKeyRange.lowerBound(e),h=[];return jo(a).jt({range:t},(e,t,n)=>{var[r,s,i]=e,s=Oa(s);if(r===this.userId&&o.path.isEqual(s))return Bo(a).get(i).next(e=>{if(!e)throw Ar();Dr(e.userId===this.userId),h.push(_o(this.k,e))});n.done()}).next(()=>h)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new ji(Br);const n=[];return e.forEach(a=>{var e=qa.prefixForPath(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=jo(t).jt({range:e},(e,t,n)=>{var[r,s,i]=e,s=Oa(s);r===this.userId&&a.path.isEqual(s)?o=o.add(i):n.done()});n.push(e)}),to.waitFor(n).next(()=>this.te(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=qa.prefixForPath(this.userId,a),r=IDBKeyRange.lowerBound(n);let h=new ji(Br);return jo(e).jt({range:r},(e,t,n)=>{var[r,s,i]=e,s=Oa(s);r===this.userId&&a.isPrefixOf(s)?s.length===o&&(h=h.add(i)):n.done()}).next(()=>this.te(e,h))}te(t,e){const n=[],r=[];return e.forEach(e=>{r.push(Bo(t).get(e).next(e=>{if(null===e)throw Ar();Dr(e.userId===this.userId),n.push(_o(this.k,e))}))}),to.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return Po(t.Wt,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.ee(n.batchId)}),to.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}ee(e){delete this.Yt[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return to.resolve();const t=IDBKeyRange.lowerBound(qa.prefixForUser(this.userId)),r=[];return jo(n).jt({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=Oa(e[1]);r.push(t)}else n.done()}).next(()=>{Dr(0===r.length)})})}containsKey(e,t){return qo(e,this.userId,t)}ne(e){return Ko(e).get(this.userId).next(e=>e||new Va(this.userId,-1,""))}}function qo(e,i,t){const n=qa.prefixForPath(i,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return jo(e).jt({range:r,Kt:!0},(e,t,n)=>{var[r,s]=e;r===i&&s===a&&(o=!0),n.done()}).next(()=>o)}function Bo(e){return fo(e,Ua.store)}function jo(e){return fo(e,qa.store)}function Ko(e){return fo(e,Va.store)}class $o{constructor(e){this.se=e}next(){return this.se+=2,this.se}static ie(){return new $o(0)}static re(){return new $o(-1)}}class Go{constructor(e,t){this.referenceDelegate=e,this.k=t}allocateTargetId(n){return this.oe(n).next(e=>{const t=new $o(e.highestTargetId);return e.highestTargetId=t.next(),this.ae(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.oe(e).next(e=>Gr.fromTimestamp(new $r(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.oe(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.oe(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.ae(t,e)))}addTargetData(t,n){return this.ce(t,n).next(()=>this.oe(t).next(e=>(e.targetCount+=1,this.ue(n,e),this.ae(t,e))))}updateTargetData(e,t){return this.ce(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>Ho(t).delete(e.targetId)).next(()=>this.oe(t)).next(e=>(Dr(0<e.targetCount),--e.targetCount,this.ae(t,e)))}removeTargets(r,s,i){let a=0;const o=[];return Ho(r).jt((e,t)=>{var n=So(t);n.sequenceNumber<=s&&null===i.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>to.waitFor(o)).next(()=>a)}forEachTarget(e,r){return Ho(e).jt((e,t)=>{var n=So(t);r(n)})}oe(e){return Wo(e).get(Wa.key).next(e=>(Dr(null!==e),e))}ae(e,t){return Wo(e).put(Wa.key,t)}ce(e,t){return Ho(e).put(Ao(this.k,t))}ue(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.oe(e).next(e=>e.targetCount)}getTargetData(e,s){var t=Cs(s),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let i=null;return Ho(e).jt({range:t,index:Ga.queryTargetsIndexName},(e,t,n)=>{var r=So(t);ks(s,r.target)&&(i=r,n.done())}).next(()=>i)}addMatchingKeys(n,e,r){const s=[],i=zo(n);return e.forEach(e=>{var t=La(e.path);s.push(i.put(new Ha(r,t))),s.push(this.referenceDelegate.addReference(n,r,e))}),to.waitFor(s)}removeMatchingKeys(n,e,r){const s=zo(n);return to.forEach(e,e=>{var t=La(e.path);return to.waitFor([s.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=zo(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=zo(e);let s=zi();return r.jt({range:n,Kt:!0},(e,t,n)=>{var r=Oa(e[1]),r=new cs(r);s=s.add(r)}).next(()=>s)}containsKey(e,t){var n=La(t.path),n=IDBKeyRange.bound([n],[Kr(n)],!1,!0);let r=0;return zo(e).jt({index:Ha.documentTargetsIndex,Kt:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}Et(e,t){return Ho(e).get(t).next(e=>e?So(e):null)}}function Ho(e){return fo(e,Ga.store)}function Wo(e){return fo(e,Wa.store)}function zo(e){return fo(e,Ha.store)}async function Qo(e){if(e.code!==Cr.FAILED_PRECONDITION||e.message!==Za)throw e;Er("LocalStore","Unexpectedly lost primary lease")}function Yo([e,t],[n,r]){var s=Br(e,n);return 0===s?Br(t,r):s}class Jo{constructor(e){this.he=e,this.buffer=new ji(Yo),this.le=0}fe(){return++this.le}de(e){var t=[e,this.fe()];if(this.buffer.size<this.he)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();Yo(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class Xo{constructor(e,t){this.garbageCollector=e,this.asyncQueue=t,this.we=!1,this._e=null}start(e){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.me(e)}stop(){this._e&&(this._e.cancel(),this._e=null)}get started(){return null!==this._e}me(e){var t=this.we?3e5:6e4;Er("LruGarbageCollector",`Garbage collection scheduled in ${t}ms`),this._e=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",t,async()=>{this._e=null,this.we=!0;try{await e.collectGarbage(this.garbageCollector)}catch(e){ao(e)?Er("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await Qo(e)}await this.me(e)})}}class Zo{constructor(e,t){this.ge=e,this.params=t}calculateTargetCount(e,t){return this.ge.ye(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return to.resolve(Ur.I);const n=new Jo(t);return this.ge.forEachTarget(e,e=>n.de(e.sequenceNumber)).next(()=>this.ge.pe(e,e=>n.de(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.ge.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.ge.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(Er("LruGarbageCollector","Garbage collection skipped; disabled"),to.resolve(Oo)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(Er("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),Oo):this.Te(t,n))}getCacheSize(e){return this.ge.getCacheSize(e)}Te(t,n){let r,s,i,a,o,h,u;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,h=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(u=Date.now(),Tr()<=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 `+(h-o)+"ms\n"+`\tRemoved ${e} documents in `+(u-h)+"ms\n"+`Total Duration: ${u-c}ms`),to.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:e})))}}class eh{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new Zo(e,t))}ye(e){const n=this.Ee(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Ee(e){let t=0;return this.pe(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}pe(e,n){return this.Ie(e,(e,t)=>n(t))}addReference(e,t,n){return th(e,n)}removeReference(e,t,n){return th(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return th(e,t)}Ae(t,n){let r=!1;return Ko(t).Qt(e=>qo(t,e,n).next(e=>(e&&(r=!0),to.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const s=this.db.getRemoteDocumentCache().newChangeBuffer(),i=[];let a=0;return this.Ie(n,(t,e)=>{if(e<=r){const r=this.Ae(n,t).next(e=>{if(!e)return a++,s.getEntry(n,t).next(()=>(s.removeEntry(t),zo(n).delete([0,La(t.path)])))});i.push(r)}}).next(()=>to.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 th(e,t)}Ie(e,r){const t=zo(e);let s,i=Ur.I;return t.jt({index:Ha.documentTargetsIndex},([e],{path:t,sequenceNumber:n})=>{0===e?(i!==Ur.I&&r(new cs(Oa(s)),i),i=n,s=t):i=Ur.I}).next(()=>{i!==Ur.I&&r(new cs(Oa(s)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function th(e,t){return zo(e).put((t=t,e=e.currentSequenceNumber,new Ha(0,La(t.path),e)))}class nh{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={}}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(t,n){const e=this.mapKeyFn(t),r=this.inner[e];if(void 0!==r){for(let e=0;e<r.length;e++)if(this.equalsFn(r[e][0],t))return void(r[e]=[t,n]);r.push([t,n])}else this.inner[e]=[[t,n]]}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),!0;return!1}forEach(r){Wr(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return zr(this.inner)}}class rh{constructor(){this.changes=new nh(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}getReadTime(e){var t=this.changes.get(e);return t?t.readTime:Gr.min()}addEntry(e,t){this.assertNotApplied(),this.changes.set(e.key,{document:e,readTime:t})}removeEntry(e,t=null){this.assertNotApplied(),this.changes.set(e,{document:Ss.newInvalidDocument(e),readTime:t})}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?to.resolve(n.document):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 sh{constructor(e,t){this.k=e,this.Jt=t}addEntry(e,t,n){return oh(e).put(hh(t),n)}removeEntry(e,t){const n=oh(e),r=hh(t);return n.delete(r)}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Re(t,e)))}getEntry(e,t){return oh(e).get(hh(t)).next(e=>this.be(t,e))}Pe(e,t){return oh(e).get(hh(t)).next(e=>({document:this.be(t,e),size:Vo(e)}))}getEntries(e,t){let r=$i;return this.ve(e,t,(e,t)=>{var n=this.be(e,t);r=r.insert(e,n)}).next(()=>r)}Ve(e,t){let r=$i,s=new Ui(cs.comparator);return this.ve(e,t,(e,t)=>{var n=this.be(e,t);r=r.insert(e,n),s=s.insert(e,Vo(t))}).next(()=>({documents:r,Se:s}))}ve(e,t,s){if(t.isEmpty())return to.resolve();const n=IDBKeyRange.bound(t.first().path.toArray(),t.last().path.toArray()),i=t.getIterator();let a=i.getNext();return oh(e).jt({range:n},(e,t,n)=>{for(var r=cs.fromSegments(e);a&&cs.comparator(a,r)<0;)s(a,null),a=i.getNext();a&&a.isEqual(r)&&(s(a,t),a=i.hasNext()?i.getNext():null),a?n.Lt(a.path.toArray()):n.done()}).next(()=>{for(;a;)s(a,null),a=i.hasNext()?i.getNext():null})}getDocumentsMatchingQuery(e,s,t){let i=$i;const a=s.path.length+1,n={};if(t.isEqual(Gr.min())){const e=s.path.toArray();n.range=IDBKeyRange.lowerBound(e)}else{const e=s.path.toArray(),i=bo(t);n.range=IDBKeyRange.lowerBound([e,i],!0),n.index=Ka.collectionReadTimeIndex}return oh(e).jt(n,(e,t,n)=>{var r;e.length===a&&(r=vo(this.k,t),s.path.isPrefixOf(r.key.path)?ii(s,r)&&(i=i.insert(r.key,r)):n.done())}).next(()=>i)}newChangeBuffer(e){return new ih(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return ah(e).get($a.key).next(e=>(Dr(!!e),e))}Re(e,t){return ah(e).put($a.key,t)}be(e,t){if(t){const e=vo(this.k,t);if(!e.isNoDocument()||!e.version.isEqual(Gr.min()))return e}return Ss.newInvalidDocument(e)}}class ih extends rh{constructor(e,t){super(),this.De=e,this.trackRemovals=t,this.Ce=new nh(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(i){const a=[];let o=0,h=new ji((e,t)=>Br(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.Ce.get(e);if(t.document.isValidDocument()){var r=wo(this.De.k,t.document,this.getReadTime(e));h=h.add(e.path.popLast());var s=Vo(r);o+=s-n,a.push(this.De.addEntry(i,e,r))}else if(o-=n,this.trackRemovals){const o=wo(this.De.k,Ss.newNoDocument(e,Gr.min()),this.getReadTime(e));a.push(this.De.addEntry(i,e,o))}else a.push(this.De.removeEntry(i,e))}),h.forEach(e=>{a.push(this.De.Jt.addToCollectionParentIndex(i,e))}),a.push(this.De.updateMetadata(i,o)),to.waitFor(a)}getFromCache(e,t){return this.De.Pe(e,t).next(e=>(this.Ce.set(t,e.size),e.document))}getAllFromCache(e,t){return this.De.Ve(e,t).next(({documents:e,Se:t})=>(t.forEach((e,t)=>{this.Ce.set(e,t)}),e))}}function ah(e){return fo(e,$a.store)}function oh(e){return fo(e,Ka.store)}function hh(e){return e.path.toArray()}class uh{constructor(e){this.k=e}Nt(t,n,e,r){Dr(e<r&&0<=e&&r<=11);const s=new no("createOrUpgrade",n);var i;e<1&&1<=r&&(t.createObjectStore(Pa.store),(i=t).createObjectStore(Va.store,{keyPath:Va.keyPath}),i.createObjectStore(Ua.store,{keyPath:Ua.keyPath,autoIncrement:!0}).createIndex(Ua.userMutationsIndex,Ua.userMutationsKeyPath,{unique:!0}),i.createObjectStore(qa.store),ch(t),t.createObjectStore(Ka.store));let a=to.resolve();return e<3&&3<=r&&(0!==e&&((i=t).deleteObjectStore(Ha.store),i.deleteObjectStore(Ga.store),i.deleteObjectStore(Wa.store),ch(t)),a=a.next(()=>function(){const e=s.store(Wa.store),t=new Wa(0,0,Gr.min().toTimestamp(),0);return e.put(Wa.key,t)}())),e<4&&4<=r&&(0!==e&&(a=a.next(()=>function(r,s){return s.store(Ua.store).Bt().next(e=>{r.deleteObjectStore(Ua.store),r.createObjectStore(Ua.store,{keyPath:Ua.keyPath,autoIncrement:!0}).createIndex(Ua.userMutationsIndex,Ua.userMutationsKeyPath,{unique:!0});const t=s.store(Ua.store),n=e.map(e=>t.put(e));return to.waitFor(n)})}(t,s))),a=a.next(()=>{t.createObjectStore(Qa.store,{keyPath:Qa.keyPath})})),e<5&&5<=r&&(a=a.next(()=>this.Ne(s))),e<6&&6<=r&&(a=a.next(()=>(t.createObjectStore($a.store),this.ke(s)))),e<7&&7<=r&&(a=a.next(()=>this.xe(s))),e<8&&8<=r&&(a=a.next(()=>this.$e(t,s))),e<9&&9<=r&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges"),function(){const e=n.objectStore(Ka.store);e.createIndex(Ka.readTimeIndex,Ka.readTimeIndexPath,{unique:!1}),e.createIndex(Ka.collectionReadTimeIndex,Ka.collectionReadTimeIndexPath,{unique:!1})}()})),e<10&&10<=r&&(a=a.next(()=>this.Oe(s))),e<11&&11<=r&&(a=a.next(()=>{t.createObjectStore(Ya.store,{keyPath:Ya.keyPath}),t.createObjectStore(Ja.store,{keyPath:Ja.keyPath})})),a}ke(t){let n=0;return t.store(Ka.store).jt((e,t)=>{n+=Vo(t)}).next(()=>{var e=new $a(n);return t.store($a.store).put($a.key,e)})}Ne(r){const e=r.store(Va.store),t=r.store(Ua.store);return e.Bt().next(e=>to.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.Bt(Ua.userMutationsIndex,e).next(e=>to.forEach(e,e=>{Dr(e.userId===n.userId);var t=_o(this.k,e);return Po(r,n.userId,t).next(()=>{})}))}))}xe(e){const a=e.store(Ha.store),t=e.store(Ka.store);return e.store(Wa.store).get(Wa.key).next(s=>{const i=[];return t.jt((e,t)=>{const n=new Yr(e),r=[0,La(n)];i.push(a.get(r).next(e=>e?to.resolve():(e=>a.put(new Ha(0,La(e),s.highestListenSequenceNumber)))(n)))}).next(()=>to.waitFor(i))})}$e(e,t){e.createObjectStore(za.store,{keyPath:za.keyPath});const n=t.store(za.store),r=new Ro,s=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:La(r)})}};return t.store(Ka.store).jt({Kt:!0},(e,t)=>{const n=new Yr(e);return s(n.popLast())}).next(()=>t.store(qa.store).jt({Kt:!0},([,e],t)=>{const n=Oa(e);return s(n.popLast())}))}Oe(e){const r=e.store(Ga.store);return r.jt((e,t)=>{var n=So(t),n=Ao(this.k,n);return r.put(n)})}}function ch(e){e.createObjectStore(Ha.store,{keyPath:Ha.keyPath}).createIndex(Ha.documentTargetsIndex,Ha.documentTargetsKeyPath,{unique:!0}),e.createObjectStore(Ga.store,{keyPath:Ga.keyPath}).createIndex(Ga.queryTargetsIndexName,Ga.queryTargetsKeyPath,{unique:!0}),e.createObjectStore(Wa.store)}const lh="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 dh{constructor(e,t,n,r,s,i,a,o,h,u){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Fe=s,this.window=i,this.document=a,this.Me=h,this.Le=u,this.Be=null,this.Ue=!1,this.isPrimary=!1,this.networkEnabled=!0,this.qe=null,this.inForeground=!1,this.Ke=null,this.je=null,this.Qe=Number.NEGATIVE_INFINITY,this.We=e=>Promise.resolve(),!dh.Pt())throw new kr(Cr.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new eh(this,r),this.Ge=t+"main",this.k=new yo(o),this.ze=new ro(this.Ge,11,new uh(this.k)),this.He=new Go(this.referenceDelegate,this.k),this.Jt=new Lo,this.Je=(t=this.k,o=this.Jt,new sh(t,o)),this.Ye=new Co,this.window&&this.window.localStorage?this.Xe=this.window.localStorage:(this.Xe=null,!1===u&&Ir("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.Ze().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new kr(Cr.FAILED_PRECONDITION,lh);return this.tn(),this.en(),this.nn(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.He.getHighestSequenceNumber(e))}).then(e=>{this.Be=new Ur(e,this.Me)}).then(()=>{this.Ue=!0}).catch(e=>(this.ze&&this.ze.close(),Promise.reject(e)))}sn(t){return this.We=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.ze.xt(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Fe.enqueueAndForget(async()=>{this.started&&await this.Ze()}))}Ze(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>gh(t).put(new Qa(this.clientId,Date.now(),this.networkEnabled,this.inForeground)).next(()=>{if(this.isPrimary)return this.rn(t).next(e=>{e||(this.isPrimary=!1,this.Fe.enqueueRetryable(()=>this.We(!1)))})}).next(()=>this.on(t)).next(e=>this.isPrimary&&!e?this.an(t).next(()=>!1):!!e&&this.cn(t).next(()=>!0))).catch(e=>{if(ao(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.Fe.enqueueRetryable(()=>this.We(e)),this.isPrimary=e})}rn(e){return fh(e).get(Pa.key).next(e=>to.resolve(this.un(e)))}hn(e){return gh(e).delete(this.clientId)}async ln(){if(this.isPrimary&&!this.fn(this.Qe,18e5)){this.Qe=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=fo(e,Qa.store);return r.Bt().next(e=>{const t=this.dn(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return to.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.Xe)for(const t of e)this.Xe.removeItem(this.wn(t.clientId))}}nn(){this.je=this.Fe.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Ze().then(()=>this.ln()).then(()=>this.nn()))}un(e){return!!e&&e.ownerId===this.clientId}on(t){return this.Le?to.resolve(!0):fh(t).get(Pa.key).next(e=>{if(null!==e&&this.fn(e.leaseTimestampMs,5e3)&&!this._n(e.ownerId)){if(this.un(e)&&this.networkEnabled)return!0;if(!this.un(e)){if(!e.allowTabSynchronization)throw new kr(Cr.FAILED_PRECONDITION,lh);return!1}}return!(!this.networkEnabled||!this.inForeground)||gh(t).Bt().next(e=>void 0===this.dn(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.Ue=!1,this.mn(),this.je&&(this.je.cancel(),this.je=null),this.gn(),this.yn(),await this.ze.runTransaction("shutdown","readwrite",[Pa.store,Qa.store],e=>{const t=new lo(e,Ur.I);return this.an(t).next(()=>this.hn(t))}),this.ze.close(),this.pn()}dn(e,t){return e.filter(e=>this.fn(e.updateTimeMs,t)&&!this._n(e.clientId))}Tn(){return this.runTransaction("getActiveClients","readonly",e=>gh(e).Bt().next(e=>this.dn(e,18e5).map(e=>e.clientId)))}get started(){return this.Ue}getMutationQueue(e){return Uo.Xt(e,this.k,this.Jt,this.referenceDelegate)}getTargetCache(){return this.He}getRemoteDocumentCache(){return this.Je}getIndexManager(){return this.Jt}getBundleCache(){return this.Ye}runTransaction(t,n,r){Er("IndexedDbPersistence","Starting transaction:",t);let s;return this.ze.runTransaction(t,"readonly"===n?"readonly":"readwrite",Xa,e=>(s=new lo(e,this.Be?this.Be.next():Ur.I),"readwrite-primary"===n?this.rn(s).next(e=>!!e||this.on(s)).next(e=>{if(!e)throw Ir(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Fe.enqueueRetryable(()=>this.We(!1)),new kr(Cr.FAILED_PRECONDITION,Za);return r(s)}).next(e=>this.cn(s).next(()=>e)):this.En(s).next(()=>r(s)))).then(e=>(s.raiseOnCommittedEvent(),e))}En(e){return fh(e).get(Pa.key).next(e=>{if(null!==e&&this.fn(e.leaseTimestampMs,5e3)&&!this._n(e.ownerId)&&!this.un(e)&&!(this.Le||this.allowTabSynchronization&&e.allowTabSynchronization))throw new kr(Cr.FAILED_PRECONDITION,lh)})}cn(e){var t=new Pa(this.clientId,this.allowTabSynchronization,Date.now());return fh(e).put(Pa.key,t)}static Pt(){return ro.Pt()}an(e){const t=fh(e);return t.get(Pa.key).next(e=>this.un(e)?(Er("IndexedDbPersistence","Releasing primary lease."),t.delete(Pa.key)):to.resolve())}fn(e,t){var n=Date.now();return!(e<n-t||n<e&&(Ir(`Detected an update time that is in the future: ${e} > ${n}`),1))}tn(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Ke=()=>{this.Fe.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Ze()))},this.document.addEventListener("visibilitychange",this.Ke),this.inForeground="visible"===this.document.visibilityState)}gn(){this.Ke&&(this.document.removeEventListener("visibilitychange",this.Ke),this.Ke=null)}en(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.qe=()=>{this.mn(),s()&&navigator.appVersion.match(/Version\/1[45]/)&&this.Fe.enterRestrictedMode(!0),this.Fe.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.qe))}yn(){this.qe&&(this.window.removeEventListener("pagehide",this.qe),this.qe=null)}_n(e){var t;try{var n=null!==(null===(t=this.Xe)||void 0===t?void 0:t.getItem(this.wn(e)));return Er("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return Ir("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}mn(){if(this.Xe)try{this.Xe.setItem(this.wn(this.clientId),String(Date.now()))}catch(e){Ir("Failed to set zombie client id.",e)}}pn(){if(this.Xe)try{this.Xe.removeItem(this.wn(this.clientId))}catch(e){}}wn(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function fh(e){return fo(e,Pa.store)}function gh(e){return fo(e,Qa.store)}function mh(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class ph{constructor(e,t){this.progress=e,this.In=t}}class yh{constructor(e,t,n){this.Je=e,this.An=t,this.Jt=n}Rn(t,n){return this.An.getAllMutationBatchesAffectingDocumentKey(t,n).next(e=>this.bn(t,n,e))}bn(e,t,n){return this.Je.getEntry(e,t).next(e=>{for(const t of n)t.applyToLocalView(e);return e})}Pn(e,n){e.forEach((e,t)=>{for(const e of n)e.applyToLocalView(t)})}vn(t,e){return this.Je.getEntries(t,e).next(e=>this.Vn(t,e).next(()=>e))}Vn(e,t){return this.An.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>this.Pn(t,e))}getDocumentsMatchingQuery(e,t,n){return r=t,cs.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.Sn(e,t.path):Xs(t)?this.Dn(e,t,n):this.Cn(e,t,n);var r}Sn(e,t){return this.Rn(e,new cs(t)).next(e=>{let t=Gi;return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}Dn(r,s,i){const a=s.collectionGroup;let o=Gi;return this.Jt.getCollectionParents(r,a).next(e=>to.forEach(e,e=>{var t,n=(t=s,e=e.child(a),new Gs(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.Cn(r,n,i).next(e=>{e.forEach((e,t)=>{o=o.insert(e,t)})})}).next(()=>o))}Cn(t,n,e){let s,i;return this.Je.getDocumentsMatchingQuery(t,n,e).next(e=>(s=e,this.An.getAllMutationBatchesAffectingQuery(t,n))).next(e=>(i=e,this.Nn(t,i,s).next(t=>{s=t;for(const t of i)for(const r of t.mutations){var n=r.key;let e=s.get(n);null==e&&(e=Ss.newInvalidDocument(n),s=s.insert(n,e)),Ai(r,e,t.localWriteTime),e.isFoundDocument()||(s=s.remove(n))}}))).next(()=>(s.forEach((e,t)=>{ii(n,t)||(s=s.remove(e))}),s))}Nn(e,t,n){let r=zi();for(const e of t)for(const t of e.mutations)t instanceof Ni&&null===n.get(t.key)&&(r=r.add(t.key));let s=n;return this.Je.getEntries(e,r).next(e=>(e.forEach((e,t)=>{t.isFoundDocument()&&(s=s.insert(e,t))}),s))}}class vh{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.kn=n,this.xn=r}static $n(e,t){let n=zi(),r=zi();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 vh(e,t.fromCache,n,r)}}class wh{On(e){this.Fn=e}getDocumentsMatchingQuery(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(Gr.min())?this.Mn(t,r):this.Fn.vn(t,i).next(e=>{const n=this.Ln(r,e);return(zs(r)||Qs(r))&&this.Bn(r.limitType,n,i,s)?this.Mn(t,r):(Tr()<=l.DEBUG&&Er("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),si(r)),this.Fn.getDocumentsMatchingQuery(t,r,s).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t)))});var e}Ln(n,e){let r=new ji(ai(n));return e.forEach((e,t)=>{ii(n,t)&&(r=r.add(t))}),r}Bn(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))}Mn(e,t){return Tr()<=l.DEBUG&&Er("QueryEngine","Using full collection scan to execute query:",si(t)),this.Fn.getDocumentsMatchingQuery(e,t,Gr.min())}}class bh{constructor(e,t,n,r){this.persistence=e,this.Un=t,this.k=r,this.qn=new Ui(Br),this.Kn=new nh(e=>Cs(e),ks),this.jn=Gr.min(),this.An=e.getMutationQueue(n),this.Qn=e.getRemoteDocumentCache(),this.He=e.getTargetCache(),this.Wn=new yh(this.Qn,this.An,this.persistence.getIndexManager()),this.Ye=e.getBundleCache(),this.Un.On(this.Wn)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.qn))}}function Th(e,t,n,r){return new bh(e,t,n,r)}async function Eh(e,t){const n=e;let r=n.An,a=n.Wn;var s=await n.persistence.runTransaction("Handle user change","readonly",s=>{let i;return n.An.getAllMutationBatches(s).next(e=>(i=e,r=n.persistence.getMutationQueue(t),a=new yh(n.Qn,r,n.persistence.getIndexManager()),r.getAllMutationBatches(s))).next(e=>{const t=[],n=[];let r=zi();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.vn(s,r).next(e=>({Gn:e,removedBatchIds:t,addedBatchIds:n}))})});return n.An=r,n.Wn=a,n.Un.On(n.Wn),s}function Ih(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.He.getLastRemoteSnapshotVersion(e))}function _h(e,u){const c=e,l=u.snapshotVersion;let d=c.qn;return c.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=c.Qn.newChangeBuffer({trackRemovals:!0});d=c.qn;const h=[];u.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){h.push(c.He.removeMatchingKeys(o,t.removedDocuments,n).next(()=>c.He.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var s,i,a;u.targetMismatches.has(n)?e=e.withResumeToken(es.EMPTY_BYTE_STRING,Gr.min()).withLastLimboFreeSnapshotVersion(Gr.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)||h.push(c.He.updateTargetData(o,e))}});let t=$i;if(u.documentUpdates.forEach((e,t)=>{u.resolvedLimboDocuments.has(e)&&h.push(c.persistence.referenceDelegate.updateLimboDocument(o,e))}),h.push(Sh(o,e,u.documentUpdates,l,void 0).next(e=>{t=e})),!l.isEqual(Gr.min())){const u=c.He.getLastRemoteSnapshotVersion(o).next(e=>c.He.setTargetsMetadata(o,o.currentSequenceNumber,l));h.push(u)}return to.waitFor(h).next(()=>e.apply(o)).next(()=>c.Wn.Vn(o,t)).next(()=>t)}).then(e=>(c.qn=d,e))}function Sh(e,a,t,o,h){let n=zi();return t.forEach(e=>n=n.add(e)),a.getEntries(e,n).next(s=>{let i=$i;return t.forEach((e,t)=>{const n=s.get(e),r=(null==h?void 0:h.get(e))||o;t.isNoDocument()&&t.version.isEqual(Gr.min())?(a.removeEntry(e,r),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(a.addEntry(t,r),i=i.insert(e,t)):Er("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),i})}function Ah(e,r){const s=e;return s.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return s.He.getTargetData(t,r).next(e=>e?(n=e,to.resolve(n)):s.He.allocateTargetId(t).next(e=>(n=new po(r,e,0,t.currentSequenceNumber),s.He.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=s.qn.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(s.qn=s.qn.insert(e.targetId,e),s.Kn.set(r,e.targetId)),e})}async function Dh(e,t,n){const r=e,s=r.qn.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(!ao(e))throw e;Er("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.qn=r.qn.remove(t),r.Kn.delete(s.target)}function Ch(e,n,r){const s=e;let i=Gr.min(),a=zi();return s.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,s=r.Kn.get(n);return void 0!==s?to.resolve(r.qn.get(s)):r.He.getTargetData(t,n)}(s,t,ei(n)).next(e=>{if(e)return i=e.lastLimboFreeSnapshotVersion,s.He.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>s.Un.getDocumentsMatchingQuery(t,n,r?i:Gr.min(),r?a:zi())).next(e=>({documents:e,zn:a})))}function kh(e,t){const n=e,r=n.He,s=n.qn.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 Nh(e){const n=e;return n.persistence.runTransaction("Get new document changes","readonly",e=>function(e,t,n){const r=e;let s=$i,i=bo(n);const a=oh(t),o=IDBKeyRange.lowerBound(i,!0);return a.jt({index:Ka.readTimeIndex,range:o},(e,t)=>{var n=vo(r.k,t);s=s.insert(n.key,n),i=t.readTime}).next(()=>({In:s,readTime:To(i)}))}(n.Qn,e,n.jn)).then(({In:e,readTime:t})=>(n.jn=t,e))}class xh{constructor(e){this.k=e,this.Xn=new Map,this.Zn=new Map}getBundleMetadata(e,t){return to.resolve(this.Xn.get(t))}saveBundleMetadata(e,t){return this.Xn.set(t.id,{id:t.id,version:t.version,createTime:ca(t.createTime)}),to.resolve()}getNamedQuery(e,t){return to.resolve(this.Zn.get(t))}saveNamedQuery(e,t){return this.Zn.set(t.name,{name:(t=t).name,query:Do(t.bundledQuery),readTime:ca(t.readTime)}),to.resolve()}}class Rh{constructor(){this.ts=new ji(Lh.es),this.ns=new ji(Lh.ss)}isEmpty(){return this.ts.isEmpty()}addReference(e,t){var n=new Lh(e,t);this.ts=this.ts.add(n),this.ns=this.ns.add(n)}rs(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.os(new Lh(e,t))}cs(e,t){e.forEach(e=>this.removeReference(e,t))}us(e){const t=new cs(new Yr([])),n=new Lh(t,e),r=new Lh(t,e+1),s=[];return this.ns.forEachInRange([n,r],e=>{this.os(e),s.push(e.key)}),s}hs(){this.ts.forEach(e=>this.os(e))}os(e){this.ts=this.ts.delete(e),this.ns=this.ns.delete(e)}ls(e){var t=new cs(new Yr([])),n=new Lh(t,e),t=new Lh(t,e+1);let r=zi();return this.ns.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new Lh(e,0),t=this.ts.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class Lh{constructor(e,t){this.key=e,this.fs=t}static es(e,t){return cs.comparator(e.key,t.key)||Br(e.fs,t.fs)}static ss(e,t){return Br(e.fs,t.fs)||cs.comparator(e.key,t.key)}}class Mh{constructor(e,t){this.Jt=e,this.referenceDelegate=t,this.An=[],this.ds=1,this.ws=new ji(Lh.es)}checkEmpty(e){return to.resolve(0===this.An.length)}addMutationBatch(e,t,n,r){var s=this.ds;this.ds++,0<this.An.length&&this.An[this.An.length-1];var i=new go(s,t,n,r);this.An.push(i);for(const t of r)this.ws=this.ws.add(new Lh(t.key,s)),this.Jt.addToCollectionParentIndex(e,t.key.path.popLast());return to.resolve(i)}lookupMutationBatch(e,t){return to.resolve(this._s(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.gs(t+1),n=n<0?0:n;return to.resolve(this.An.length>n?this.An[n]:null)}getHighestUnacknowledgedBatchId(){return to.resolve(0===this.An.length?-1:this.ds-1)}getAllMutationBatches(e){return to.resolve(this.An.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Lh(t,0),r=new Lh(t,Number.POSITIVE_INFINITY),s=[];return this.ws.forEachInRange([n,r],e=>{var t=this._s(e.fs);s.push(t)}),to.resolve(s)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new ji(Br);return t.forEach(e=>{var t=new Lh(e,0),n=new Lh(e,Number.POSITIVE_INFINITY);this.ws.forEachInRange([t,n],e=>{r=r.add(e.fs)})}),to.resolve(this.ys(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let s=n;cs.isDocumentKey(s)||(s=s.child(""));var i=new Lh(new cs(s),0);let a=new ji(Br);return this.ws.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.fs)),!0)},i),to.resolve(this.ys(a))}ys(e){const n=[];return e.forEach(e=>{var t=this._s(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){Dr(0===this.ps(r.batchId,"removed")),this.An.shift();let s=this.ws;return to.forEach(r.mutations,e=>{var t=new Lh(e.key,r.batchId);return s=s.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.ws=s})}ee(e){}containsKey(e,t){var n=new Lh(t,0),n=this.ws.firstAfterOrEqual(n);return to.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.An.length,to.resolve()}ps(e,t){return this.gs(e)}gs(e){return 0===this.An.length?0:e-this.An[0].batchId}_s(e){var t=this.gs(e);return t<0||t>=this.An.length?null:this.An[t]}}class Oh{constructor(e,t){this.Jt=e,this.Ts=t,this.docs=new Ui(cs.comparator),this.size=0}addEntry(e,t,n){const r=t.key,s=this.docs.get(r),i=s?s.size:0,a=this.Ts(t);return this.docs=this.docs.insert(r,{document:t.mutableCopy(),size:a,readTime:n}),this.size+=a-i,this.Jt.addToCollectionParentIndex(e,r.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 to.resolve(n?n.document.mutableCopy():Ss.newInvalidDocument(t))}getEntries(e,t){let n=$i;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Ss.newInvalidDocument(e))}),to.resolve(n)}getDocumentsMatchingQuery(e,t,n){let r=$i;const s=new cs(t.path.child("")),i=this.docs.getIteratorFrom(s);for(;i.hasNext();){const{key:e,value:{document:s,readTime:a}}=i.getNext();if(!t.path.isPrefixOf(e.path))break;a.compareTo(n)<=0||ii(t,s)&&(r=r.insert(s.key,s.mutableCopy()))}return to.resolve(r)}Es(e,t){return to.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new Fh(this)}getSize(e){return to.resolve(this.size)}}class Fh extends rh{constructor(e){super(),this.De=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.document.isValidDocument()?r.push(this.De.addEntry(n,t.document,this.getReadTime(e))):this.De.removeEntry(e)}),to.waitFor(r)}getFromCache(e,t){return this.De.getEntry(e,t)}getAllFromCache(e,t){return this.De.getEntries(e,t)}}class Ph{constructor(e){this.persistence=e,this.Is=new nh(e=>Cs(e),ks),this.lastRemoteSnapshotVersion=Gr.min(),this.highestTargetId=0,this.As=0,this.Rs=new Rh,this.targetCount=0,this.bs=$o.ie()}forEachTarget(e,n){return this.Is.forEach((e,t)=>n(t)),to.resolve()}getLastRemoteSnapshotVersion(e){return to.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return to.resolve(this.As)}allocateTargetId(e){return this.highestTargetId=this.bs.next(),to.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.As&&(this.As=t),to.resolve()}ce(e){this.Is.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.bs=new $o(t),this.highestTargetId=t),e.sequenceNumber>this.As&&(this.As=e.sequenceNumber)}addTargetData(e,t){return this.ce(t),this.targetCount+=1,to.resolve()}updateTargetData(e,t){return this.ce(t),to.resolve()}removeTargetData(e,t){return this.Is.delete(t.target),this.Rs.us(t.targetId),--this.targetCount,to.resolve()}removeTargets(n,r,s){let i=0;const a=[];return this.Is.forEach((e,t)=>{t.sequenceNumber<=r&&null===s.get(t.targetId)&&(this.Is.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),i++)}),to.waitFor(a).next(()=>i)}getTargetCount(e){return to.resolve(this.targetCount)}getTargetData(e,t){var n=this.Is.get(t)||null;return to.resolve(n)}addMatchingKeys(e,t,n){return this.Rs.rs(t,n),to.resolve()}removeMatchingKeys(t,e,n){this.Rs.cs(e,n);const r=this.persistence.referenceDelegate,s=[];return r&&e.forEach(e=>{s.push(r.markPotentiallyOrphaned(t,e))}),to.waitFor(s)}removeMatchingKeysForTargetId(e,t){return this.Rs.us(t),to.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Rs.ls(t);return to.resolve(n)}containsKey(e,t){return to.resolve(this.Rs.containsKey(t))}}class Vh{constructor(e,t){var n;this.Ps={},this.Be=new Ur(0),this.Ue=!1,this.Ue=!0,this.referenceDelegate=e(this),this.He=new Ph(this),this.Jt=new xo,this.Je=(n=this.Jt,e=e=>this.referenceDelegate.vs(e),new Oh(n,e)),this.k=new yo(t),this.Ye=new xh(this.k)}start(){return Promise.resolve()}shutdown(){return this.Ue=!1,Promise.resolve()}get started(){return this.Ue}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(){return this.Jt}getMutationQueue(e){let t=this.Ps[e.toKey()];return t||(t=new Mh(this.Jt,this.referenceDelegate),this.Ps[e.toKey()]=t),t}getTargetCache(){return this.He}getRemoteDocumentCache(){return this.Je}getBundleCache(){return this.Ye}runTransaction(e,t,n){Er("MemoryPersistence","Starting transaction:",e);const r=new Uh(this.Be.next());return this.referenceDelegate.Vs(),n(r).next(e=>this.referenceDelegate.Ss(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ds(t,n){return to.or(Object.values(this.Ps).map(e=>()=>e.containsKey(t,n)))}}class Uh extends eo{constructor(e){super(),this.currentSequenceNumber=e}}class qh{constructor(e){this.persistence=e,this.Cs=new Rh,this.Ns=null}static ks(e){return new qh(e)}get xs(){if(this.Ns)return this.Ns;throw Ar()}addReference(e,t,n){return this.Cs.addReference(n,t),this.xs.delete(n.toString()),to.resolve()}removeReference(e,t,n){return this.Cs.removeReference(n,t),this.xs.add(n.toString()),to.resolve()}markPotentiallyOrphaned(e,t){return this.xs.add(t.toString()),to.resolve()}removeTarget(e,t){this.Cs.us(t.targetId).forEach(e=>this.xs.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.xs.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Vs(){this.Ns=new Set}Ss(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return to.forEach(this.xs,e=>{const t=cs.fromPath(e);return this.$s(n,t).next(e=>{e||r.removeEntry(t)})}).next(()=>(this.Ns=null,r.apply(n)))}updateLimboDocument(e,t){return this.$s(e,t).next(e=>{e?this.xs.delete(t.toString()):this.xs.add(t.toString())})}vs(e){return 0}$s(e,t){return to.or([()=>to.resolve(this.Cs.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ds(e,t)])}}function Bh(e,t){return`firestore_clients_${e}_${t}`}function jh(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 $h{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Os(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 kr(r.error.code,r.error.message))),i?new $h(e,t,r.state,s):(Ir("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}Fs(){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 Gh{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Os(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 kr(n.error.code,n.error.message))),s?new Gh(e,n.state,r):(Ir("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}Fs(){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 Hh{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Os(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,s=Qi;for(let i=0;r&&i<n.activeTargetIds.length;++i)r=us(n.activeTargetIds[i]),s=s.add(n.activeTargetIds[i]);return r?new Hh(e,s):(Ir("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class Wh{constructor(e,t){this.clientId=e,this.onlineState=t}static Os(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new Wh(t.clientId,t.onlineState):(Ir("SharedClientState",`Failed to parse online state: ${e}`),null)}}class zh{constructor(){this.activeTargetIds=Qi}Ms(e){this.activeTargetIds=this.activeTargetIds.add(e)}Ls(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Fs(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class Qh{constructor(e,t,n,r,s){this.window=e,this.Fe=t,this.persistenceKey=n,this.Bs=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Us=this.qs.bind(this),this.Ks=new Ui(Br),this.started=!1,this.js=[];var i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=s,this.Qs=Bh(this.persistenceKey,this.Bs),this.Ws=`firestore_sequence_number_${this.persistenceKey}`,this.Ks=this.Ks.insert(this.Bs,new zh),this.Gs=new RegExp(`^firestore_clients_${i}_([^_]*)$`),this.zs=new RegExp(`^firestore_mutations_${i}_(\\d+)(?:_(.*))?$`),this.Hs=new RegExp(`^firestore_targets_${i}_(\\d+)$`),this.Js=`firestore_online_state_${this.persistenceKey}`,this.Ys=`firestore_bundle_loaded_${this.persistenceKey}`,this.window.addEventListener("storage",this.Us)}static Pt(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.Tn();for(const n of e)if(n!==this.Bs){const e=this.getItem(Bh(this.persistenceKey,n));var t;!e||(t=Hh.Os(n,e))&&(this.Ks=this.Ks.insert(t.clientId,t))}this.Xs();const n=this.storage.getItem(this.Js);if(n){const e=this.Zs(n);e&&this.ti(e)}for(const e of this.js)this.qs(e);this.js=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Ws,JSON.stringify(e))}getAllActiveQueryTargets(){return this.ei(this.Ks)}isActiveQueryTarget(n){let r=!1;return this.Ks.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.ni(e,"pending")}updateMutationState(e,t,n){this.ni(e,t,n),this.si(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(Kh(this.persistenceKey,e)))||(n=Gh.Os(e,n))&&(t=n.state)),this.ii.Ms(e),this.Xs(),t}removeLocalQueryTarget(e){this.ii.Ls(e),this.Xs()}isLocalQueryTarget(e){return this.ii.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(Kh(this.persistenceKey,e))}updateQueryState(e,t,n){this.ri(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.si(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.oi(e)}notifyBundleLoaded(){this.ai()}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Us),this.removeItem(this.Qs),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)}qs(e){const r=e;r.storageArea===this.storage&&(Er("SharedClientState","EVENT",r.key,r.newValue),r.key!==this.Qs?this.Fe.enqueueRetryable(async()=>{if(this.started){if(null!==r.key)if(this.Gs.test(r.key)){if(null==r.newValue){var e=this.ci(r.key);return this.ui(e,null)}e=this.hi(r.key,r.newValue);if(e)return this.ui(e.clientId,e)}else if(this.zs.test(r.key)){if(null!==r.newValue){var t=this.li(r.key,r.newValue);if(t)return this.fi(t)}}else if(this.Hs.test(r.key)){if(null!==r.newValue){t=this.di(r.key,r.newValue);if(t)return this.wi(t)}}else if(r.key===this.Js){if(null!==r.newValue){var n=this.Zs(r.newValue);if(n)return this.ti(n)}}else if(r.key===this.Ws){n=function(e){let t=Ur.I;if(null!=e)try{var n=JSON.parse(e);Dr("number"==typeof n),t=n}catch(e){Ir("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(r.newValue);n!==Ur.I&&this.sequenceNumberHandler(n)}else if(r.key===this.Ys)return this.syncEngine._i()}else this.js.push(r)}):Ir("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get ii(){return this.Ks.get(this.Bs)}Xs(){this.setItem(this.Qs,this.ii.Fs())}ni(e,t,n){const r=new $h(this.currentUser,e,t,n),s=jh(this.persistenceKey,this.currentUser,e);this.setItem(s,r.Fs())}si(e){var t=jh(this.persistenceKey,this.currentUser,e);this.removeItem(t)}oi(e){var t={clientId:this.Bs,onlineState:e};this.storage.setItem(this.Js,JSON.stringify(t))}ri(e,t,n){const r=Kh(this.persistenceKey,e),s=new Gh(e,t,n);this.setItem(r,s.Fs())}ai(){this.setItem(this.Ys,"value-not-used")}ci(e){var t=this.Gs.exec(e);return t?t[1]:null}hi(e,t){var n=this.ci(e);return Hh.Os(n,t)}li(e,t){var n=this.zs.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return $h.Os(new vr(n),r,t)}di(e,t){var n=this.Hs.exec(e),n=Number(n[1]);return Gh.Os(n,t)}Zs(e){return Wh.Os(e)}async fi(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.mi(e.batchId,e.state,e.error);Er("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}wi(e){return this.syncEngine.gi(e.targetId,e.state,e.error)}ui(e,t){const n=t?this.Ks.insert(e,t):this.Ks.remove(e),r=this.ei(this.Ks),s=this.ei(n),i=[],a=[];return s.forEach(e=>{r.has(e)||i.push(e)}),r.forEach(e=>{s.has(e)||a.push(e)}),this.syncEngine.yi(i,a).then(()=>{this.Ks=n})}ti(e){this.Ks.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}ei(e){let n=Qi;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class Yh{constructor(){this.pi=new zh,this.Ti={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.pi.Ms(e),this.Ti[e]||"not-current"}updateQueryState(e,t,n){this.Ti[e]=t}removeLocalQueryTarget(e){this.pi.Ls(e)}isLocalQueryTarget(e){return this.pi.activeTargetIds.has(e)}clearQueryState(e){delete this.Ti[e]}getAllActiveQueryTargets(){return this.pi.activeTargetIds}isActiveQueryTarget(e){return this.pi.activeTargetIds.has(e)}start(){return this.pi=new zh,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(){}}class Jh{Ei(e){}shutdown(){}}class Xh{constructor(){this.Ii=()=>this.Ai(),this.Ri=()=>this.bi(),this.Pi=[],this.vi()}Ei(e){this.Pi.push(e)}shutdown(){window.removeEventListener("online",this.Ii),window.removeEventListener("offline",this.Ri)}vi(){window.addEventListener("online",this.Ii),window.addEventListener("offline",this.Ri)}Ai(){Er("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.Pi)e(0)}bi(){Er("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.Pi)e(1)}static Pt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const Zh={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class eu{constructor(e){this.Vi=e.Vi,this.Si=e.Si}Di(e){this.Ci=e}Ni(e){this.ki=e}onMessage(e){this.xi=e}close(){this.Si()}send(e){this.Vi(e)}$i(){this.Ci()}Oi(e){this.ki(e)}Fi(e){this.xi(e)}}class tu extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.Mi=t+"://"+e.host,this.Li="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}Bi(t,e,n,r,s){const i=this.Ui(t,e);Er("RestConnection","Sending: ",i,n);var a={};return this.qi(a,r,s),this.Ki(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})}ji(e,t,n,r,s){return this.Bi(e,t,n,r,s)}qi(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)}Ui(e,t){var n=Zh[e];return`${this.Mi}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}Ki(o,t,n,r){return new Promise((s,i)=>{const a=new pr;a.listenOnce(cr.COMPLETE,()=>{try{switch(a.getLastErrorCode()){case ur.NO_ERROR:var e=a.getResponseJson();Er("Connection","XHR received:",JSON.stringify(e)),s(e);break;case ur.TIMEOUT:Er("Connection",'RPC "'+o+'" timed out'),i(new kr(Cr.DEADLINE_EXCEEDED,"Request time out"));break;case ur.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(Cr).indexOf(r)?r:Cr.UNKNOWN,i(new kr(t,o.message))):i(new kr(Cr.UNKNOWN,"Server responded with status "+a.getStatus()))}else i(new kr(Cr.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)})}Qi(e,t,n){const r=[this.Mi,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=new nr,i=hr(),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.qi(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 h=s.createWebChannel(o,a);let u=!1,c=!1;const l=new eu({Vi:e=>{c?Er("Connection","Not sending because WebChannel is closed:",e):(u||(Er("Connection","Opening WebChannel transport."),h.open(),u=!0),Er("Connection","WebChannel sending:",e),h.send(e))},Si:()=>h.close()}),d=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return d(h,mr.EventType.OPEN,()=>{c||Er("Connection","WebChannel transport opened.")}),d(h,mr.EventType.CLOSE,()=>{c||(c=!0,Er("Connection","WebChannel transport closed"),l.Oi())}),d(h,mr.EventType.ERROR,e=>{c||(c=!0,_r("Connection","WebChannel transport errored:",e),l.Oi(new kr(Cr.UNAVAILABLE,"The operation could not be completed")))}),d(h,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 Vi(t)}(n),t=r.message;void 0===e&&(e=Cr.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),c=!0,l.Oi(new kr(e,t)),h.close()}else Er("Connection","WebChannel received:",e),l.Fi(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.$i()},0),l}}function nu(){return"undefined"!=typeof window?window:null}function ru(){return"undefined"!=typeof document?document:null}function su(e){return new oa(e,!0)}class iu{constructor(e,t,n=1e3,r=1.5,s=6e4){this.Fe=e,this.timerId=t,this.Wi=n,this.Gi=r,this.zi=s,this.Hi=0,this.Ji=null,this.Yi=Date.now(),this.reset()}reset(){this.Hi=0}Xi(){this.Hi=this.zi}Zi(e){this.cancel();var t=Math.floor(this.Hi+this.tr()),n=Math.max(0,Date.now()-this.Yi),r=Math.max(0,t-n);0<r&&Er("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Hi} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Ji=this.Fe.enqueueAfterDelay(this.timerId,r,()=>(this.Yi=Date.now(),e())),this.Hi*=this.Gi,this.Hi<this.Wi&&(this.Hi=this.Wi),this.Hi>this.zi&&(this.Hi=this.zi)}er(){null!==this.Ji&&(this.Ji.skipDelay(),this.Ji=null)}cancel(){null!==this.Ji&&(this.Ji.cancel(),this.Ji=null)}tr(){return(Math.random()-.5)*this.Hi}}class au{constructor(e,t,n,r,s,i,a,o){this.Fe=e,this.nr=n,this.sr=r,this.ir=s,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.rr=0,this.ar=null,this.cr=null,this.stream=null,this.ur=new iu(e,t)}hr(){return 1===this.state||5===this.state||this.lr()}lr(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.dr()}async stop(){this.hr()&&await this.close(0)}wr(){this.state=0,this.ur.reset()}_r(){this.lr()&&null===this.ar&&(this.ar=this.Fe.enqueueAfterDelay(this.nr,6e4,()=>this.mr()))}gr(e){this.yr(),this.stream.send(e)}async mr(){if(this.lr())return this.close(0)}yr(){this.ar&&(this.ar.cancel(),this.ar=null)}pr(){this.cr&&(this.cr.cancel(),this.cr=null)}async close(e,t){this.yr(),this.pr(),this.ur.cancel(),this.rr++,4!==e?this.ur.reset():t&&t.code===Cr.RESOURCE_EXHAUSTED?(Ir(t.toString()),Ir("Using maximum backoff delay to prevent overloading the backend."),this.ur.Xi()):t&&t.code===Cr.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Tr(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Ni(t)}Tr(){}auth(){this.state=1;const e=this.Er(this.rr),n=this.rr;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.rr===n&&this.Ir(e,t)},t=>{e(()=>{var e=new kr(Cr.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Ar(e)})})}Ir(e,t){const n=this.Er(this.rr);this.stream=this.Rr(e,t),this.stream.Di(()=>{n(()=>(this.state=2,this.cr=this.Fe.enqueueAfterDelay(this.sr,1e4,()=>(this.lr()&&(this.state=3),Promise.resolve())),this.listener.Di()))}),this.stream.Ni(e=>{n(()=>this.Ar(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}dr(){this.state=5,this.ur.Zi(async()=>{this.state=0,this.start()})}Ar(e){return Er("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Er(t){return e=>{this.Fe.enqueueAndForget(()=>this.rr===t?e():(Er("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class ou extends au{constructor(e,t,n,r,s,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,i),this.k=s}Rr(e,t){return this.ir.Qi("Listen",e,t)}onMessage(e){this.ur.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.C?(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?Cr.UNKNOWN:Vi(f.code),new kr(o,f.message||""));n=new ea(r,s,i,o||null)}else if("documentChange"in t){t.documentChange;var h=t.documentChange;h.document,h.document.name,h.document.updateTime;var o=ga(e,h.document.name),u=ca(h.document.updateTime),c=new _s({mapValue:{fields:h.document.fields}}),u=Ss.newFoundDocument(o,u,c),c=h.targetIds||[],h=h.removedTargetIds||[];n=new Xi(c,h,u.key,u)}else if("documentDelete"in t){t.documentDelete;c=t.documentDelete;c.document;h=ga(e,c.document),u=c.readTime?ca(c.readTime):Gr.min(),u=Ss.newNoDocument(h,u),c=c.removedTargetIds||[];n=new Xi([],c,u.key,u)}else if("documentRemove"in t){t.documentRemove;var l=t.documentRemove;l.document;var d=ga(e,l.document),l=l.removedTargetIds||[];n=new Xi([],l,d,null)}else{if(!("filter"in t))return Ar();{t.filter;const e=t.filter;e.targetId;l=e.count||0,d=new Fi(l),l=e.targetId;n=new Zi(l,d)}}var o,f;return n}(this.k,e),n=function(e){if(!("targetChange"in e))return Gr.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?ca(t.readTime):Gr.min()}(e);return this.listener.br(t,n)}Pr(e){const t={};t.database=ya(this.k),t.addTarget=function(e,t){let n;var r=t.target;return n=Ns(r)?{documents:Ia(e,r)}:{query:_a(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()?n.resumeToken=ua(e,t.resumeToken):0<t.snapshotVersion.compareTo(Gr.min())&&(n.readTime=ha(e,t.snapshotVersion.toTimestamp())),n}(this.k,e);var n,r,r=(this.k,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.gr(t)}vr(e){const t={};t.database=ya(this.k),t.removeTarget=e,this.gr(t)}}class hu extends au{constructor(e,t,n,r,s,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,i),this.k=s,this.Vr=!1}get Sr(){return this.Vr}start(){this.Vr=!1,this.lastStreamToken=void 0,super.start()}Tr(){this.Vr&&this.Dr([])}Rr(e,t){return this.ir.Qi("Write",e,t)}onMessage(e){if(Dr(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Vr){this.ur.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(Gr.min())&&(n=ca(t)),new Ti(n,e.transformResults||[])}(e,s))):[]),n=ca(e.commitTime);return this.listener.Cr(n,t)}var r,s;return Dr(!e.writeResults||0===e.writeResults.length),this.Vr=!0,this.listener.Nr()}kr(){const e={};e.database=ya(this.k),this.gr(e)}Dr(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>Ta(this.k,e))};this.gr(t)}}class uu extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.ir=n,this.k=r,this.$r=!1}Or(){if(this.$r)throw new kr(Cr.FAILED_PRECONDITION,"The client has already been terminated.")}Bi(n,r,s){return this.Or(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.ir.Bi(n,r,s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Cr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new kr(Cr.UNKNOWN,e.toString())})}ji(n,r,s){return this.Or(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.ir.ji(n,r,s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Cr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new kr(Cr.UNKNOWN,e.toString())})}terminate(){this.$r=!0}}class cu{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.Fr=0,this.Mr=null,this.Lr=!0}Br(){0===this.Fr&&(this.Ur("Unknown"),this.Mr=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.Mr=null,this.qr("Backend didn't respond within 10 seconds."),this.Ur("Offline"),Promise.resolve())))}Kr(e){"Online"===this.state?this.Ur("Unknown"):(this.Fr++,1<=this.Fr&&(this.jr(),this.qr(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.Ur("Offline")))}set(e){this.jr(),this.Fr=0,"Online"===e&&(this.Lr=!1),this.Ur(e)}Ur(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}qr(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.Lr?(Ir(t),this.Lr=!1):Er("OnlineStateTracker",t)}jr(){null!==this.Mr&&(this.Mr.cancel(),this.Mr=null)}}class lu{constructor(e,t,n,r,s){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Qr=[],this.Wr=new Map,this.Gr=new Set,this.zr=[],this.Hr=s,this.Hr.Ei(e=>{n.enqueueAndForget(async()=>{bu(this)&&(Er("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.Gr.add(4),await fu(t),t.Jr.set("Unknown"),t.Gr.delete(4),await du(t)}(this))})}),this.Jr=new cu(n,r)}}async function du(e){if(bu(e))for(const t of e.zr)await t(!0)}async function fu(e){for(const t of e.zr)await t(!1)}function gu(e,t){const n=e;n.Wr.has(t.targetId)||(n.Wr.set(t.targetId,t),wu(n)?vu(n):Cu(n).lr()&&pu(n,t))}function mu(e,t){const n=e,r=Cu(n);n.Wr.delete(t),r.lr()&&yu(n,t),0===n.Wr.size&&(r.lr()?r._r():bu(n)&&n.Jr.set("Unknown"))}function pu(e,t){e.Yr.X(t.targetId),Cu(e).Pr(t)}function yu(e,t){e.Yr.X(t),Cu(e).vr(t)}function vu(t){t.Yr=new na({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),Et:e=>t.Wr.get(e)||null}),Cu(t).start(),t.Jr.Br()}function wu(e){return bu(e)&&!Cu(e).hr()&&0<e.Wr.size}function bu(e){return 0===e.Gr.size}function Tu(e){e.Yr=void 0}async function Eu(e,t,n){if(!ao(t))throw t;e.Gr.add(1),await fu(e),e.Jr.set("Offline"),n=n||(()=>Ih(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{Er("RemoteStore","Retrying IndexedDB access"),await n(),e.Gr.delete(1),await du(e)})}function Iu(t,n){return n().catch(e=>Eu(t,e,n))}async function _u(e){const t=e,n=ku(t);let r=0<t.Qr.length?t.Qr[t.Qr.length-1].batchId:-1;for(;bu(s=t)&&s.Qr.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.An.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.Qr.length&&n._r();break}r=e.batchId,function(e,t){e.Qr.push(t);const n=ku(e);n.lr()&&n.Sr&&n.Dr(t.mutations)}(t,e)}catch(e){await Eu(t,e)}var s;Su(t)&&Au(t)}function Su(e){return bu(e)&&!ku(e).hr()&&0<e.Qr.length}function Au(e){ku(e).start()}async function Du(e,t){const n=e;t?(n.Gr.delete(2),await du(n)):(n.Gr.add(2),await fu(n),n.Jr.set("Unknown"))}function Cu(t){return t.Xr||(t.Xr=function(e,t,n){const r=e;return r.Or(),new ou(t,r.ir,r.authCredentials,r.appCheckCredentials,r.k,n)}(t.datastore,t.asyncQueue,{Di:(async function(n){n.Wr.forEach((e,t)=>{pu(n,e)})}).bind(null,t),Ni:(async function(e,t){Tu(e),wu(e)?(e.Jr.Kr(t),vu(e)):e.Jr.set("Unknown")}).bind(null,t),br:(async function(e,r,t){if(e.Jr.set("Online"),r instanceof ea&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e.Wr.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e.Wr.delete(n),e.Yr.removeTarget(n))}(e)}catch(t){Er("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await Eu(e,t)}else if(r instanceof Xi?e.Yr.ot(r):r instanceof Zi?e.Yr.dt(r):e.Yr.ut(r),!t.isEqual(Gr.min()))try{const r=await Ih(e.localStore);0<=t.compareTo(r)&&await function(r,s){const e=r.Yr.gt(s);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=r.Wr.get(t);n&&r.Wr.set(t,n.withResumeToken(e.resumeToken,s))}}),e.targetMismatches.forEach(e=>{const t=r.Wr.get(e);var n;t&&(r.Wr.set(e,t.withResumeToken(es.EMPTY_BYTE_STRING,t.snapshotVersion)),yu(r,e),n=new po(t.target,e,1,t.sequenceNumber),pu(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){Er("RemoteStore","Failed to raise snapshot:",r),await Eu(e,r)}}).bind(null,t)}),t.zr.push(async e=>{e?(t.Xr.wr(),wu(t)?vu(t):t.Jr.set("Unknown")):(await t.Xr.stop(),Tu(t))})),t.Xr}function ku(t){return t.Zr||(t.Zr=function(e,t,n){const r=e;return r.Or(),new hu(t,r.ir,r.authCredentials,r.appCheckCredentials,r.k,n)}(t.datastore,t.asyncQueue,{Di:(async function(e){ku(e).kr()}).bind(null,t),Ni:(async function(e,t){t&&ku(e).Sr&&await async function(e,t){if(Pi(n=t.code)&&n!==Cr.ABORTED){const n=e.Qr.shift();ku(e).wr(),await Iu(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await _u(e)}var n}(e,t),Su(e)&&Au(e)}).bind(null,t),Nr:(async function(e){const t=ku(e);for(const n of e.Qr)t.Dr(n.mutations)}).bind(null,t),Cr:(async function(e,t,n){const r=e.Qr.shift(),s=mo.from(r,t,n);await Iu(e,()=>e.remoteSyncer.applySuccessfulWrite(s)),await _u(e)}).bind(null,t)}),t.zr.push(async e=>{e?(t.Zr.wr(),await _u(t)):(await t.Zr.stop(),0<t.Qr.length&&(Er("RemoteStore",`Stopping write stream with ${t.Qr.length} pending writes`),t.Qr=[]))})),t.Zr}class Nu{constructor(e,t,n,r,s){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=s,this.deferred=new Nr,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 Nu(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 kr(Cr.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 xu(e,t){if(Ir("AsyncQueue",`${t}: ${e}`),ao(e))return new kr(Cr.UNAVAILABLE,`${t}: ${e}`);throw e}class Ru{constructor(n){this.comparator=n?(e,t)=>n(e,t)||cs.comparator(e.key,t.key):(e,t)=>cs.comparator(e.key,t.key),this.keyedMap=Gi,this.sortedSet=new Ui(this.comparator)}static emptySet(e){return new Ru(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 Ru))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 Ru;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class Lu{constructor(){this.eo=new Ui(cs.comparator)}track(e){var t=e.doc.key,n=this.eo.get(t);!n||0!==e.type&&3===n.type?this.eo=this.eo.insert(t,e):3===e.type&&1!==n.type?this.eo=this.eo.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.eo=this.eo.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.eo=this.eo.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.eo=this.eo.remove(t):1===e.type&&2===n.type?this.eo=this.eo.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.eo=this.eo.insert(t,{type:2,doc:e.doc}):Ar()}no(){const n=[];return this.eo.inorderTraversal((e,t)=>{n.push(t)}),n}}class Mu{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 Mu(e,t,Ru.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)&&ni(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 Ou{constructor(){this.so=void 0,this.listeners=[]}}class Fu{constructor(){this.queries=new nh(e=>ri(e),ni),this.onlineState="Unknown",this.io=new Set}}async function Pu(e,t){const n=e,r=t.query;let s=!1,i=n.queries.get(r);if(i||(s=!0,i=new Ou),s)try{i.so=await n.onListen(r)}catch(e){const n=xu(e,`Initialization of query '${si(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,i),i.listeners.push(t),t.ro(n.onlineState),!i.so||t.oo(i.so)&&Uu(n)}async function Vu(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 Uu(e){e.io.forEach(e=>{e.next()})}class qu{constructor(e,t,n){this.query=e,this.ao=t,this.co=!1,this.uo=null,this.onlineState="Unknown",this.options=n||{}}oo(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new Mu(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}let t=!1;return this.co?this.ho(e)&&(this.ao.next(e),t=!0):this.lo(e,this.onlineState)&&(this.fo(e),t=!0),this.uo=e,t}onError(e){this.ao.error(e)}ro(e){this.onlineState=e;let t=!1;return this.uo&&!this.co&&this.lo(this.uo,e)&&(this.fo(this.uo),t=!0),t}lo(e,t){return!e.fromCache||!(this.options.wo&&"Offline"!==t||e.docs.isEmpty()&&"Offline"!==t)}ho(e){if(0<e.docChanges.length)return!0;var t=this.uo&&this.uo.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}fo(e){e=Mu.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.co=!0,this.ao.next(e)}}class Bu{constructor(e,t){this.payload=e,this.byteLength=t}_o(){return"metadata"in this.payload}}class ju{constructor(e){this.k=e}Hn(e){return ga(this.k,e)}Jn(e){return e.metadata.exists?ba(this.k,e.document,!1):Ss.newNoDocument(this.Hn(e.metadata.name),this.Yn(e.metadata.readTime))}Yn(e){return ca(e)}}class Ku{constructor(e,t,n){this.mo=e,this.localStore=t,this.k=n,this.queries=[],this.documents=[],this.progress=$u(e)}yo(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;return e.payload.namedQuery?this.queries.push(e.payload.namedQuery):e.payload.documentMetadata?(this.documents.push({metadata:e.payload.documentMetadata}),e.payload.documentMetadata.exists||++t):e.payload.document&&(this.documents[this.documents.length-1].document=e.payload.document,++t),t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}po(e){const t=new Map,n=new ju(this.k);for(const s of e)if(s.metadata.queries){const e=n.Hn(s.metadata.name);for(const n of s.metadata.queries){var r=(t.get(n)||zi()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const s=e;let i=zi(),a=$i,o=Hi;for(const e of n){const n=t.Hn(e.metadata.name);e.document&&(i=i.add(n)),a=a.insert(n,t.Jn(e)),o=o.insert(n,t.Yn(e.metadata.readTime))}const h=s.Qn.newChangeBuffer({trackRemovals:!0}),u=await Ah(s,(r=r,ei(Ws(Yr.fromString(`__bundle__/docs/${r}`)))));return s.persistence.runTransaction("Apply bundle documents","readwrite",t=>Sh(t,h,a,Gr.min(),o).next(e=>(h.apply(t),e)).next(e=>s.He.removeMatchingKeysForTargetId(t,u.targetId).next(()=>s.He.addMatchingKeys(t,i,u.targetId)).next(()=>s.Wn.Vn(t,e)).next(()=>e)))}(this.localStore,new ju(this.k),this.documents,this.mo.id),t=this.po(this.documents);for(const e of this.queries)await async function(e,n,r=zi()){const s=await Ah(e,ei(Do(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.Ye.saveNamedQuery(e,n);t=s.withResumeToken(es.EMPTY_BYTE_STRING,t);return i.qn=i.qn.insert(t.targetId,t),i.He.updateTargetData(e,t).next(()=>i.He.removeMatchingKeysForTargetId(e,s.targetId)).next(()=>i.He.addMatchingKeys(e,r,s.targetId)).next(()=>i.Ye.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",new ph(Object.assign({},this.progress),e)}}function $u(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class Gu{constructor(e){this.key=e}}class Hu{constructor(e){this.key=e}}class Wu{constructor(e,t){this.query=e,this.To=t,this.Eo=null,this.current=!1,this.Io=zi(),this.mutatedKeys=zi(),this.Ao=ai(e),this.Ro=new Ru(this.Ao)}get bo(){return this.To}Po(e,t){const o=t?t.vo:new Lu,h=(t||this).Ro;let u=(t||this).mutatedKeys,c=h,l=!1;const d=zs(this.query)&&h.size===this.query.limit?h.last():null,f=Qs(this.query)&&h.size===this.query.limit?h.first():null;if(e.inorderTraversal((e,t)=>{const n=h.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.Vo(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.Ao(r,d)||f&&this.Ao(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&&(u=r?(c=c.add(r),i?u.add(e):u.delete(e)):(c=c.delete(e),u.delete(e)))}),zs(this.query)||Qs(this.query))for(;c.size>this.query.limit;){const e=zs(this.query)?c.last():c.first();c=c.delete(e.key),u=u.delete(e.key),o.track({type:1,doc:e})}return{Ro:c,vo:o,Bn:l,mutatedKeys:u}}Vo(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.Ro;this.Ro=e.Ro,this.mutatedKeys=e.mutatedKeys;const s=e.vo.no();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.Ao(e.doc,t.doc)),this.So(n);var i=t?this.Do():[],a=0===this.Io.size&&this.current?1:0,o=a!==this.Eo;return this.Eo=a,0!==s.length||o?{snapshot:new Mu(this.query,e.Ro,r,s,e.mutatedKeys,0==a,o,!1),Co:i}:{Co:i}}ro(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ro:this.Ro,vo:new Lu,mutatedKeys:this.mutatedKeys,Bn:!1},!1)):{Co:[]}}No(e){return!this.To.has(e)&&!!this.Ro.has(e)&&!this.Ro.get(e).hasLocalMutations}So(e){e&&(e.addedDocuments.forEach(e=>this.To=this.To.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.To=this.To.delete(e)),this.current=e.current)}Do(){if(!this.current)return[];const t=this.Io;this.Io=zi(),this.Ro.forEach(e=>{this.No(e.key)&&(this.Io=this.Io.add(e.key))});const n=[];return t.forEach(e=>{this.Io.has(e)||n.push(new Hu(e))}),this.Io.forEach(e=>{t.has(e)||n.push(new Gu(e))}),n}ko(e){this.To=e.zn,this.Io=zi();var t=this.Po(e.documents);return this.applyChanges(t,!0)}xo(){return Mu.fromInitialDocuments(this.query,this.Ro,this.mutatedKeys,0===this.Eo)}}class zu{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Qu{constructor(e){this.key=e,this.$o=!1}}class Yu{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.Oo={},this.Fo=new nh(e=>ri(e),ni),this.Mo=new Map,this.Lo=new Set,this.Bo=new Ui(cs.comparator),this.Uo=new Map,this.qo=new Rh,this.Ko={},this.jo=new Map,this.Qo=$o.re(),this.onlineState="Unknown",this.Wo=void 0}get isPrimaryClient(){return!0===this.Wo}}async function Ju(n,e,t,r){n.Go=(e,i,t)=>async function(e,t,n){let r=t.view.Po(i);r.Bn&&(r=await Ch(e.localStore,t.query,!1).then(({documents:e})=>t.view.Po(e,r)));var s=n&&n.targetChanges.get(t.targetId),s=t.view.applyChanges(r,e.isPrimaryClient,s);return ac(e,t.targetId,s.Co),s.snapshot}(n,e,t);const s=await Ch(n.localStore,e,!0),i=new Wu(e,s.zn),a=i.Po(s.documents),o=Ji.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState),h=i.applyChanges(a,n.isPrimaryClient,o);ac(n,t,h.Co);var u=new zu(e,t,i);return n.Fo.set(e,u),n.Mo.has(t)?n.Mo.get(t).push(e):n.Mo.set(t,[e]),h.snapshot}async function Xu(e,t,n){const r=fc(e);try{const e=await function(e,r){const s=e,i=$r.now(),t=r.reduce((e,t)=>e.add(t.key),zi());let a;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>s.Wn.vn(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=li(r.transform,e||null);null!=s&&(null==n&&(n=_s.empty()),n.set(r.field,s))}return n||null}(n,a.get(n.key));null!=r&&t.push(new Ni(n.key,r,function r(e){const s=[];return Wr(e.fields,(e,t)=>{const n=new Xr([e]);if(Es(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),Ei.exists(!0)))}return s.An.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.Ko[e.currentUser.toKey()];r=r||new Ui(Br),r=r.insert(t,n),e.Ko[e.currentUser.toKey()]=r}(r,e.batchId,n),await hc(r,e.changes),await _u(r.remoteStore)}catch(e){const t=xu(e,"Failed to persist write");n.reject(t)}}async function Zu(e,t){const r=e;try{const e=await _h(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.Uo.get(t);n&&(Dr(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.$o=!0:0<e.modifiedDocuments.size?Dr(n.$o):0<e.removedDocuments.size&&(Dr(n.$o),n.$o=!1))}),await hc(r,e,t)}catch(e){await Qo(e)}}function ec(r,s,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.Fo.forEach((e,t)=>{var n=t.view.ro(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.ro(n)&&(r=!0)}),r&&Uu(t)}(t.eventManager,s),r.length&&t.Oo.br(r),t.onlineState=s,t.isPrimaryClient&&t.sharedClientState.setOnlineState(s)}}async function tc(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.Qn.newChangeBuffer({trackRemovals:!0});return function(e,t,r,s){const i=r.batch,n=i.keys();let a=to.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()&&s.addEntry(e,r.commitVersion))})}),a.next(()=>e.An.removeMutationBatch(t,i))}(s,e,r,n).next(()=>n.apply(e)).next(()=>s.An.performConsistencyCheck(e)).next(()=>s.Wn.vn(e,t))})}(n.localStore,t);rc(n,r,null),nc(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await hc(n,e)}catch(e){await Qo(e)}}function nc(e,t){(e.jo.get(t)||[]).forEach(e=>{e.resolve()}),e.jo.delete(t)}function rc(e,t,n){const r=e;let s=r.Ko[r.currentUser.toKey()];if(s){const e=s.get(t);e&&(n?e.reject(n):e.resolve(),s=s.remove(t)),r.Ko[r.currentUser.toKey()]=s}}function sc(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.Mo.get(e))t.Fo.delete(r),n&&t.Oo.zo(r,n);t.Mo.delete(e),t.isPrimaryClient&&t.qo.us(e).forEach(e=>{t.qo.containsKey(e)||ic(t,e)})}function ic(e,t){e.Lo.delete(t.path.canonicalString());var n=e.Bo.get(t);null!==n&&(mu(e.remoteStore,n),e.Bo=e.Bo.remove(t),e.Uo.delete(n),oc(e))}function ac(e,t,n){for(const r of n)r instanceof Gu?(e.qo.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.Bo.get(n)||e.Lo.has(r)||(Er("SyncEngine","New document in limbo: "+n),e.Lo.add(r),oc(e))}(e,r)):r instanceof Hu?(Er("SyncEngine","Document no longer in limbo: "+r.key),e.qo.removeReference(r.key,t),e.qo.containsKey(r.key)||ic(e,r.key)):Ar()}function oc(e){for(;0<e.Lo.size&&e.Bo.size<e.maxConcurrentLimboResolutions;){var t=e.Lo.values().next().value;e.Lo.delete(t);var n=new cs(Yr.fromString(t)),t=e.Qo.next();e.Uo.set(t,new Qu(n)),e.Bo=e.Bo.insert(n,t),gu(e.remoteStore,new po(ei(Ws(n.path)),t,2,Ur.I))}}async function hc(e,t,r){const s=e,i=[],a=[],o=[];s.Fo.isEmpty()||(s.Fo.forEach((e,n)=>{o.push(s.Go(n,t,r).then(e=>{var t;e&&(s.isPrimaryClient&&s.sharedClientState.updateQueryState(n.targetId,e.fromCache?"not-current":"current"),i.push(e),t=vh.$n(n.targetId,e),a.push(t))}))}),await Promise.all(o),s.Oo.br(i),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>to.forEach(t,t=>to.forEach(t.kn,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>to.forEach(t.xn,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!ao(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.qn.get(t),n=e.snapshotVersion,s=e.withLastLimboFreeSnapshotVersion(n);r.qn=r.qn.insert(t,s)}}}(s.localStore,a))}async function uc(r,e){const s=r;if(dc(s),fc(s),!0===e&&!0!==s.Wo){const r=s.sharedClientState.getAllActiveQueryTargets(),e=await cc(s,r.toArray());s.Wo=!0,await Du(s.remoteStore,!0);for(const r of e)gu(s.remoteStore,r)}else if(!1===e&&!1!==s.Wo){const r=[];let n=Promise.resolve();s.Mo.forEach((e,t)=>{s.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(sc(s,t),Dh(s.localStore,t,!0))),mu(s.remoteStore,t)}),await n,await cc(s,r),function(){const n=s;n.Uo.forEach((e,t)=>{mu(n.remoteStore,t)}),n.qo.hs(),n.Uo=new Map,n.Bo=new Ui(cs.comparator)}(),s.Wo=!1,await Du(s.remoteStore,!1)}}async function cc(t,n){const r=t,s=[],i=[];for(const t of n){let e;const c=r.Mo.get(t);if(c&&0!==c.length){e=await Ah(r.localStore,ei(c[0]));for(const t of c){const n=r.Fo.get(t),c=(a=r,o=n,u=h=void 0,u=await Ch((h=a).localStore,o.query,!0),u=o.view.ko(u),h.isPrimaryClient&&ac(h,o.targetId,u.Co),await u);c.snapshot&&i.push(c.snapshot)}}else{const c=await kh(r.localStore,t);e=await Ah(r.localStore,c),await Ju(r,lc(c),t,!1)}s.push(e)}var a,o,h,u;return r.Oo.br(i),s}function lc(e){return Hs(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function dc(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=Zu.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.Uo.get(t);if(r&&r.$o)return zi().add(r.key);{let e=zi();const r=n.Mo.get(t);if(!r)return e;for(const t of r){const r=n.Fo.get(t);e=e.unionWith(r.view.bo)}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.Uo.get(t),i=s&&s.key;if(i){let e=new Ui(cs.comparator);e=e.insert(i,Ss.newNoDocument(i,Gr.min()));const n=zi().add(i),s=new Yi(Gr.min(),new Map,new ji(Br),e,n);await Zu(r,s),r.Bo=r.Bo.remove(i),r.Uo.delete(t),oc(r)}else await Dh(r.localStore,t,!1).then(()=>sc(r,t,n)).catch(Qo)}).bind(null,t),t.Oo.br=(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.oo(e)&&(r=!0);s.so=e}}r&&Uu(n)}).bind(null,t.eventManager),t.Oo.zo=(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 fc(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=tc.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.An.lookupMutationBatch(t,r).next(e=>(Dr(null!==e),n=e.keys(),s.An.removeMutationBatch(t,e))).next(()=>s.An.performConsistencyCheck(t)).next(()=>s.Wn.vn(t,n))})}(r.localStore,t);rc(r,t,n),nc(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await hc(r,e)}catch(n){await Qo(n)}}).bind(null,t),t}class gc{constructor(){this.synchronizeTabs=!1}async initialize(e){this.k=su(e.databaseInfo.databaseId),this.sharedClientState=this.Jo(e),this.persistence=this.Yo(e),await this.persistence.start(),this.gcScheduler=this.Xo(e),this.localStore=this.Zo(e)}Xo(e){return null}Zo(e){return Th(this.persistence,new wh,e.initialUser,this.k)}Yo(e){return new Vh(qh.ks,this.k)}Jo(e){return new Yh}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class mc extends gc{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 async function(e){const t=e;return t.persistence.runTransaction("Synchronize last document change read time","readonly",t=>function(){const e=oh(t);let r=Gr.min();return e.jt({index:Ka.readTimeIndex,reverse:!0},(e,t,n)=>{t.readTime&&(r=To(t.readTime)),n.done()}).next(()=>r)}()).then(e=>{t.jn=e})}(this.localStore),await this.ta.initialize(this,e),await fc(this.ta.syncEngine),await _u(this.ta.remoteStore),await this.persistence.sn(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(this.localStore),Promise.resolve()))}Zo(e){return Th(this.persistence,new wh,e.initialUser,this.k)}Xo(e){var t=this.persistence.referenceDelegate.garbageCollector;return new Xo(t,e.asyncQueue)}Yo(e){var t=mh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?Fo.withCacheSize(this.cacheSizeBytes):Fo.DEFAULT;return new dh(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,nu(),ru(),this.k,this.sharedClientState,!!this.forceOwnership)}Jo(e){return new Yh}}class pc extends mc{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 Qh&&(this.sharedClientState.syncEngine={mi:(async function(e,t,n,r){var s=e,i=await function(e,n){const r=e,s=r.An;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>s.Zt(t,n).next(e=>e?r.Wn.vn(t,e):to.resolve(null)))}(s.localStore,t);null!==i?("pending"===n?await _u(s.remoteStore):"acknowledged"===n||"rejected"===n?(rc(s,t,r||null),nc(s,t),s.localStore.An.ee(t)):Ar(),await hc(s,i)):Er("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),gi:(async function(e,t,n,r){const s=e;if(s.Wo)Er("SyncEngine","Ignoring unexpected query state notification.");else if(s.Mo.has(t))switch(n){case"current":case"not-current":{const e=await Nh(s.localStore),r=Yi.createSynthesizedRemoteEventForCurrentChange(t,"current"===n);await hc(s,e,r);break}case"rejected":await Dh(s.localStore,t,!0),sc(s,t,r);break;default:Ar()}}).bind(null,t),yi:(async function(e,t,n){const r=dc(e);if(r.Wo){for(const e of t)if(r.Mo.has(e))Er("SyncEngine","Adding an already active target "+e);else{const t=await kh(r.localStore,e),n=await Ah(r.localStore,t);await Ju(r,lc(t),n.targetId,!1),gu(r.remoteStore,n)}for(const e of n)r.Mo.has(e)&&await Dh(r.localStore,e,!1).then(()=>{mu(r.remoteStore,e),sc(r,e)}).catch(Qo)}}).bind(null,t),Tn:(function(e){return e.localStore.persistence.Tn()}).bind(null,t),_i:(async function(e){const t=e;return Nh(t.localStore).then(e=>hc(t,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.sn(async e=>{await uc(this.ta.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start(this.localStore):e||this.gcScheduler.stop())})}Jo(e){var t=nu();if(!Qh.Pt(t))throw new kr(Cr.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=mh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new Qh(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class yc{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=>ec(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 Eh(n.localStore,t);n.currentUser=t,(e=n).jo.forEach(e=>{e.forEach(e=>{e.reject(new kr(Cr.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.jo.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await hc(n,r.Gn)}}).bind(null,this.syncEngine),await Du(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Fu}createDatastore(e){var t,n,r,s,i=su(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new tu(t));return n=e.authCredentials,r=e.appCheckCredentials,s=t,e=i,new uu(n,r,s,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,s=e=>ec(this.syncEngine,e,0),i=new(Xh.Pt()?Xh:Jh),new lu(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 Yu(e,t,n,r,s,i);return a&&(o.Wo=!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.Gr.add(5),await fu(t),t.Hr.shutdown(),t.Jr.set("Unknown")}(this.remoteStore)}}function vc(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 wc{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)}na(){this.muted=!0}ea(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class bc{constructor(e,t){this.sa=e,this.k=t,this.metadata=new Nr,this.buffer=new Uint8Array,this.ia=new TextDecoder("utf-8"),this.ra().then(e=>{e&&e._o()?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.sa.cancel()}async getMetadata(){return this.metadata.promise}async Ho(){return await this.getMetadata(),this.ra()}async ra(){var e=await this.oa();if(null===e)return null;var t=this.ia.decode(e),n=Number(t);isNaN(n)&&this.aa(`length string (${t}) is not valid number`);t=await this.ca(n);return new Bu(JSON.parse(t),e.length+n)}ua(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async oa(){for(;this.ua()<0&&!await this.ha(););if(0===this.buffer.length)return null;var e=this.ua();e<0&&this.aa("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 ca(e){for(;this.buffer.length<e;)await this.ha()&&this.aa("Reached the end of bundle when more is expected.");var t=this.ia.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}aa(e){throw this.sa.cancel(),new Error(`Invalid bundle format: ${e}`)}async ha(){var e=await this.sa.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 Tc{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 kr(Cr.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=ya(r.k)+"/documents",s={documents:t.map(e=>fa(r.k,e))},i=await r.ji("BatchGetDocuments",n,s),a=new Map;i.forEach(e=>{const t=(n=r.k,"found"in(e=e)?function(e,t){Dr(!!t.found),t.found.name,t.found.updateTime;var n=ga(e,t.found.name),r=ca(t.found.updateTime),s=new _s({mapValue:{fields:t.found.fields}});return Ss.newFoundDocument(n,r,s)}(n,e):"missing"in e?function(e,t){Dr(!!t.missing),Dr(!!t.readTime);var n=ga(e,t.missing),r=ca(t.readTime);return Ss.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 Mi(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=cs.fromPath(t);this.mutations.push(new Oi(n,this.precondition(n)))}),await async function(e,t){const n=e,r=ya(n.k)+"/documents",s={writes:t.map(e=>Ta(n.k,e))};await n.Bi("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=Gr.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new kr(Cr.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?Ei.updateTime(t):Ei.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return Ei.exists(!0);if(t.isEqual(Gr.min()))throw new kr(Cr.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Ei.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class Ec{constructor(e,t,n,r){this.asyncQueue=e,this.datastore=t,this.updateFunction=n,this.deferred=r,this.la=5,this.ur=new iu(this.asyncQueue,"transaction_retry")}run(){--this.la,this.fa()}fa(){this.ur.Zi(async()=>{const t=new Tc(this.datastore),e=this.da(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.wa(e)}))}).catch(e=>{this.wa(e)})})}da(e){try{var t=this.updateFunction(e);return!os(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}wa(e){0<this.la&&this._a(e)?(--this.la,this.asyncQueue.enqueueAndForget(()=>(this.fa(),Promise.resolve()))):this.deferred.reject(e)}_a(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||!Pi(t)}}class Ic{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=vr.UNAUTHENTICATED,this.clientId=qr.A(),this.authCredentialListener=()=>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,()=>Promise.resolve())}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}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new kr(Cr.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new Nr;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=xu(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function _c(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 Eh(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function Sc(e,t){e.asyncQueue.verifyOperationInProgress();var n=await Ac(e);Er("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await t.initialize(n,r),e.setCredentialChangeListener(e=>async function(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),Er("RemoteStore","RemoteStore received new credentials");var r=bu(n);n.Gr.add(3),await fu(n),r&&n.Jr.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.Gr.delete(3),await du(n)}(t.remoteStore,e)),e.onlineComponents=t}async function Ac(e){return e.offlineComponents||(Er("FirestoreClient","Using default OfflineComponentProvider"),await _c(e,new gc)),e.offlineComponents}async function Dc(e){return e.onlineComponents||(Er("FirestoreClient","Using default OnlineComponentProvider"),await Sc(e,new yc)),e.onlineComponents}function Cc(e){return Ac(e).then(e=>e.persistence)}function kc(e){return Ac(e).then(e=>e.localStore)}function Nc(e){return Dc(e).then(e=>e.remoteStore)}function xc(e){return Dc(e).then(e=>e.syncEngine)}async function Rc(e){const t=await Dc(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=dc(e);let r,s;const i=n.Fo.get(t);if(i)r=i.targetId,n.sharedClientState.addLocalQueryTarget(r),s=i.view.xo();else{const e=await Ah(n.localStore,ei(t)),i=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,s=await Ju(n,t,r,"current"===i),n.isPrimaryClient&&gu(n.remoteStore,e)}return s}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.Fo.get(t),s=n.Mo.get(r.targetId);if(1<s.length)return n.Mo.set(r.targetId,s.filter(e=>!ni(e,t))),void n.Fo.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await Dh(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),mu(n.remoteStore,r.targetId),sc(n,r.targetId)}).catch(Qo)):(sc(n,r.targetId),await Dh(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function Lc(e,t,n={}){const r=new Nr;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,s,i,a){const e=new wc({next:e=>{r.enqueueAndForget(()=>Vu(n,o));var t=e.docs.has(s);!t&&e.fromCache?a.reject(new kr(Cr.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&i&&"server"===i.source?a.reject(new kr(Cr.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 qu(Ws(s.path),e,{includeMetadataChanges:!0,wo:!0});return Pu(n,o)}(await Rc(e),e.asyncQueue,t,n,r)),r.promise}function Mc(e,t,n={}){const r=new Nr;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,s){const i=new wc({next:e=>{n.enqueueAndForget(()=>Vu(t,a)),e.fromCache&&"server"===r.source?s.reject(new kr(Cr.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 qu(e,i,{includeMetadataChanges:!0,wo:!0});return Pu(t,a)}(await Rc(e),e.asyncQueue,t,n,r)),r.promise}function Oc(e,t,n,r){const s=(n=n,t=su(t),i="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return vc(e,void 0);if(e instanceof ArrayBuffer)return vc(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 bc(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.Ye.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,s))return await n.close(),void r._completeWith({taskState:"Success",documentsLoaded:s.totalDocuments,bytesLoaded:s.totalBytes,totalDocuments:s.totalDocuments,totalBytes:s.totalBytes});r._updateProgress($u(s));const a=new Ku(s,t.localStore,n.k);let e=await n.Ho();for(;e;){const t=await a.yo(e);t&&r._updateProgress(t),e=await n.Ho()}var i=await a.complete();await hc(t,i.In,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.Ye.saveBundleMetadata(e,t))}(t.localStore,s),r._completeWith(i.progress)}catch(t){_r("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t)}}(r,t,n).then(()=>{r.sharedClientState.notifyBundleLoaded()})}(await xc(e),s,r)})}class Fc{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 Pc{constructor(e,t){this.projectId=e,this.database=t||"(default)"}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Pc&&e.projectId===this.projectId&&e.database===this.database}}const Vc=new Map;function Uc(e,t,n){if(!n)throw new kr(Cr.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function qc(e,t,n,r){if(!0===t&&!0===r)throw new kr(Cr.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Bc(e){if(!cs.isDocumentKey(e))throw new kr(Cr.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function jc(e){if(cs.isDocumentKey(e))throw new kr(Cr.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Kc(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 $c(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new kr(Cr.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=Kc(e);throw new kr(Cr.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function Gc(e,t){if(t<=0)throw new kr(Cr.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Hc{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new kr(Cr.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 kr(Cr.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,qc("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 Wc{constructor(e,t,n){this._authCredentials=t,this._appCheckCredentials=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Hc({}),this._settingsFrozen=!1,e instanceof Pc?this._databaseId=e:(this._app=e,this._databaseId=function(e){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new kr(Cr.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Pc(e.options.projectId)}(e))}get app(){if(!this._app)throw new kr(Cr.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 kr(Cr.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 Hc(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new Rr;switch(e.type){case"gapi":var t=e.client;return Dr(!("object"!=typeof t||null===t||!t.auth||!t.auth.getAuthHeaderValueForFirstParty)),new Fr(t,e.sessionIndex||"0",e.iamToken||null);case"provider":return e.client;default:throw new kr(Cr.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=Vc.get(e);t&&(Er("ComponentProvider","Removing Datastore"),Vc.delete(e),t.terminate())}(this),Promise.resolve()}}function zc(n,e,t,r={}){var s;const i=(n=$c(n,Wc))._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 kr(Cr.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new vr(i)}n._authCredentials=new Lr(new xr(e,t))}}class Qc{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 Jc(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Qc(this.firestore,e,this._key)}}class Yc{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Yc(this.firestore,e,this._query)}}class Jc extends Yc{constructor(e,t,n){super(e,t,Ws(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 Qc(this.firestore,null,new cs(e))}withConverter(e){return new Jc(this.firestore,e,this._path)}}function Xc(e,t,...n){if(e=m(e),Uc("collection","path",t),e instanceof Wc){var r=Yr.fromString(t,...n);return jc(r),new Jc(e,null,r)}if(!(e instanceof Qc||e instanceof Jc))throw new kr(Cr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(Yr.fromString(t,...n));return jc(r),new Jc(e.firestore,null,r)}function Zc(e,t,...n){if(e=m(e),Uc("doc","path",t=1===arguments.length?qr.A():t),e instanceof Wc){var r=Yr.fromString(t,...n);return Bc(r),new Qc(e,null,new cs(r))}if(!(e instanceof Qc||e instanceof Jc))throw new kr(Cr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(Yr.fromString(t,...n));return Bc(r),new Qc(e.firestore,e instanceof Jc?e.converter:null,new cs(r))}function el(e,t){return e=m(e),t=m(t),(e instanceof Qc||e instanceof Jc)&&(t instanceof Qc||t instanceof Jc)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function tl(e,t){return e=m(e),t=m(t),e instanceof Yc&&t instanceof Yc&&e.firestore===t.firestore&&ni(e._query,t._query)&&e.converter===t.converter}class nl{constructor(){this.ma=Promise.resolve(),this.ga=[],this.ya=!1,this.pa=[],this.Ta=null,this.Ea=!1,this.Ia=!1,this.Aa=[],this.ur=new iu(this,"async_queue_retry"),this.Ra=()=>{var e=ru();e&&Er("AsyncQueue","Visibility state changed to "+e.visibilityState),this.ur.er()};const e=ru();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Ra)}get isShuttingDown(){return this.ya}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.ba(),this.Pa(e)}enterRestrictedMode(e){if(!this.ya){this.ya=!0,this.Ia=e||!1;const t=ru();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Ra)}}enqueue(e){if(this.ba(),this.ya)return new Promise(()=>{});const t=new Nr;return this.Pa(()=>this.ya&&this.Ia?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.ga.push(e),this.va()))}async va(){if(0!==this.ga.length){try{await this.ga[0](),this.ga.shift(),this.ur.reset()}catch(e){if(!ao(e))throw e;Er("AsyncQueue","Operation failed with retryable error: "+e)}0<this.ga.length&&this.ur.Zi(()=>this.va())}}Pa(e){var t=this.ma.then(()=>(this.Ea=!0,e().catch(e=>{throw this.Ta=e,this.Ea=!1,Ir("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.Ea=!1,e))));return this.ma=t}enqueueAfterDelay(e,t,n){this.ba(),-1<this.Aa.indexOf(e)&&(t=0);var r=Nu.createAndSchedule(this,e,t,n,e=>this.Va(e));return this.pa.push(r),r}ba(){this.Ta&&Ar()}verifyOperationInProgress(){}async Sa(){for(var e;await(e=this.ma),e!==this.ma;);}Da(e){for(const t of this.pa)if(t.timerId===e)return!0;return!1}Ca(t){return this.Sa().then(()=>{this.pa.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.pa)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Sa()})}Na(e){this.Aa.push(e)}Va(e){var t=this.pa.indexOf(e);this.pa.splice(t,1)}}function rl(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 sl{constructor(){this._progressObserver={},this._taskCompletionResolver=new Nr,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 il,al,ol;class hl extends Wc{constructor(e,t,n){super(e,t,n),this.type="firestore",this._queue=new nl,this._persistenceKey="name"in e?e.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||cl(this),this._firestoreClient.terminate()}}function ul(e){return e._firestoreClient||cl(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function cl(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 Fc(n,r,s,i.host,i.ssl,i.experimentalForceLongPolling,i.experimentalAutoDetectLongPolling,i.useFetchStreams));e._firestoreClient=new Ic(e._authCredentials,e._appCheckCredentials,e._queue,a)}function ll(e,n,r){const s=new Nr;return e.asyncQueue.enqueue(async()=>{try{await _c(e,r),await Sc(e,n),s.resolve()}catch(e){if(!("FirebaseError"===(t=e).name?t.code===Cr.FAILED_PRECONDITION||t.code===Cr.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 dl(e){return function(e){const t=new Nr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;bu(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.An.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.jo.get(e)||[];r.push(t),n.jo.set(e,r)}catch(e){const n=xu(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await xc(e),t)),t.promise}(ul(e=$c(e,hl)))}function fl(e){return(n=ul(e=$c(e,hl))).asyncQueue.enqueue(async()=>{const e=await Cc(n),t=await Nc(n);return e.setNetworkEnabled(!0),function(){const e=t;return e.Gr.delete(0),du(e)}()});var n}function gl(e){return(n=ul(e=$c(e,hl))).asyncQueue.enqueue(async()=>{const e=await Cc(n),t=await Nc(n);return e.setNetworkEnabled(!1),async function(){const e=t;e.Gr.add(0),await fu(e),e.Jr.set("Offline")}()});var n}function ml(t,e){return n=ul(t=$c(t,hl)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.Ye.getNamedQuery(e,t))}(await kc(n),r)).then(e=>e?new Yc(t,null,e.query):null);var n,r}function pl(e){if(e._initialized||e._terminated)throw new kr(Cr.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 yl{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new kr(Cr.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Xr(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class vl{constructor(e){this._byteString=e}static fromBase64String(e){try{return new vl(es.fromBase64String(e))}catch(e){throw new kr(Cr.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new vl(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 wl{constructor(e){this._methodName=e}}class bl{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new kr(Cr.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new kr(Cr.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 Br(this._lat,e._lat)||Br(this._long,e._long)}}const Tl=/^__.*__$/;class El{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Ni(e,this.data,this.fieldMask,t,this.fieldTransforms):new ki(e,this.data,t,this.fieldTransforms)}}class Il{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Ni(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function _l(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw Ar()}}class Sl{constructor(e,t,n,r,s,i){this.settings=e,this.databaseId=t,this.k=n,this.ignoreUndefinedProperties=r,void 0===s&&this.ka(),this.fieldTransforms=s||[],this.fieldMask=i||[]}get path(){return this.settings.path}get xa(){return this.settings.xa}$a(e){return new Sl(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.k,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Oa(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.$a({path:n,Fa:!1});return r.Ma(e),r}La(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.$a({path:n,Fa:!1});return r.ka(),r}Ba(e){return this.$a({path:void 0,Fa:!0})}Ua(e){return Gl(e,this.settings.methodName,this.settings.qa||!1,this.path,this.settings.Ka)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}ka(){if(this.path)for(let e=0;e<this.path.length;e++)this.Ma(this.path.get(e))}Ma(e){if(0===e.length)throw this.Ua("Document fields must not be empty");if(_l(this.xa)&&Tl.test(e))throw this.Ua('Document fields cannot begin and end with "__"')}}class Al{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.k=n||su(e)}ja(e,t,n,r=!1){return new Sl({xa:e,methodName:t,Ka:n,path:Xr.emptyPath(),Fa:!1,qa:r},this.databaseId,this.k,this.ignoreUndefinedProperties)}}function Dl(e){var t=e._freezeSettings(),n=su(e._databaseId);return new Al(e._databaseId,!!t.ignoreUndefinedProperties,n)}function Cl(e,t,n,r,s,i={}){const a=e.ja(i.merge||i.mergeFields?2:0,t,n,s);Bl("Data must be an object, but it was:",a,r);var o=Ul(r,a);let h,u;if(i.merge)h=new Zr(a.fieldMask),u=a.fieldTransforms;else if(i.mergeFields){const e=[];for(const r of i.mergeFields){const s=jl(t,r,n);if(!a.contains(s))throw new kr(Cr.INVALID_ARGUMENT,`Field '${s}' is specified in your field mask but missing from your input data.`);Hl(e,s)||e.push(s)}h=new Zr(e),u=a.fieldTransforms.filter(e=>h.covers(e.field))}else h=null,u=a.fieldTransforms;return new El(new _s(o),h,u)}class kl extends wl{_toFieldTransform(e){if(2!==e.xa)throw 1===e.xa?e.Ua(`${this._methodName}() can only appear at the top level of your update data`):e.Ua(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof kl}}function Nl(e,t,n){return new Sl({xa:3,Ka:t.settings.Ka,methodName:e._methodName,Fa:n},t.databaseId,t.k,t.ignoreUndefinedProperties)}class xl extends wl{_toFieldTransform(e){return new bi(e.path,new di)}isEqual(e){return e instanceof xl}}class Rl extends wl{constructor(e,t){super(e),this.Qa=t}_toFieldTransform(e){const t=Nl(this,e,!0),n=this.Qa.map(e=>Vl(e,t)),r=new fi(n);return new bi(e.path,r)}isEqual(e){return this===e}}class Ll extends wl{constructor(e,t){super(e),this.Qa=t}_toFieldTransform(e){const t=Nl(this,e,!0),n=this.Qa.map(e=>Vl(e,t)),r=new mi(n);return new bi(e.path,r)}isEqual(e){return this===e}}class Ml extends wl{constructor(e,t){super(e),this.Wa=t}_toFieldTransform(e){var t=new yi(e.k,ui(e.k,this.Wa));return new bi(e.path,t)}isEqual(e){return this===e}}function Ol(e,s,i,t){const a=e.ja(1,s,i);Bl("Data must be an object, but it was:",a,t);const o=[],h=_s.empty();Wr(t,(e,t)=>{var n=$l(s,e,i);t=m(t);var r=a.La(n);if(t instanceof kl)o.push(n);else{const e=Vl(t,r);null!=e&&(o.push(n),h.set(n,e))}});var n=new Zr(o);return new Il(h,n,a.fieldTransforms)}function Fl(e,t,n,r,s,i){const a=e.ja(1,t,n),o=[jl(t,r,n)],h=[s];if(i.length%2!=0)throw new kr(Cr.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(jl(t,i[f])),h.push(i[f+1]);const u=[],c=_s.empty();for(let g=o.length-1;0<=g;--g)if(!Hl(u,o[g])){const t=o[g];var l=m(l=h[g]);const r=a.La(t);if(l instanceof kl)u.push(t);else{const e=Vl(l,r);null!=e&&(u.push(t),c.set(t,e))}}var d=new Zr(u);return new Il(c,d,a.fieldTransforms)}function Pl(e,t,n,r=!1){return Vl(n,e.ja(r?4:3,t))}function Vl(i,e){if(ql(i=m(i)))return Bl("Unsupported field value:",e,i),Ul(i,e);if(i instanceof wl)return function(e,t){if(!_l(t.xa))throw t.Ua(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.Ua(`${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.Fa&&4!==e.xa)throw e.Ua("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const s of i){let e=Vl(s,t.Ba(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 ui(t.k,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=$r.fromDate(e);return{timestampValue:ha(t.k,n)}}if(e instanceof $r){n=new $r(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:ha(t.k,n)}}if(e instanceof bl)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof vl)return{bytesValue:ua(t.k,e._byteString)};if(e instanceof Qc){const r=t.databaseId,s=e.firestore._databaseId;if(!s.isEqual(r))throw t.Ua(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:la(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.Ua(`Unsupported field value: ${Kc(e)}`)}(0,e)}function Ul(e,r){const s={};return zr(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):Wr(e,(e,t)=>{var n=Vl(t,r.Oa(e));null!=n&&(s[e]=n)}),{mapValue:{fields:s}}}function ql(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof $r||e instanceof bl||e instanceof vl||e instanceof Qc||e instanceof wl)}function Bl(e,t,n){if(!ql(n)||("object"!=typeof(s=n)||null===s||Object.getPrototypeOf(s)!==Object.prototype&&null!==Object.getPrototypeOf(s))){var r=Kc(n);throw"an object"===r?t.Ua(e+" a custom object"):t.Ua(e+" "+r)}var s}function jl(e,t,n){if((t=m(t))instanceof yl)return t._internalPath;if("string"==typeof t)return $l(e,t);throw Gl("Field path arguments must be of type string or FieldPath.",e,!1,void 0,n)}const Kl=new RegExp("[~\\*/\\[\\]]");function $l(t,n,r){if(0<=n.search(Kl))throw Gl(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new yl(...n.split("."))._internalPath}catch(e){throw Gl(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function Gl(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 h="";return(i||a)&&(h+=" (found",i&&(h+=` in field ${r}`),a&&(h+=` in document ${s}`),h+=")"),new kr(Cr.INVALID_ARGUMENT,o+e+h)}function Hl(e,t){return e.some(e=>e.isEqual(t))}class Wl{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 Qc(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new zl(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(Ql("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class zl extends Wl{data(){return super.data()}}function Ql(e,t){return"string"==typeof t?$l(e,t):(t instanceof yl?t:t._delegate)._internalPath}class Yl{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Jl extends Wl{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 Xl(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(Ql("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Xl extends Jl{data(e={}){return super.data(e)}}class Zl{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new Yl(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 Xl(this._firestore,this._userDataWriter,e.key,e,new Yl(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 kr(Cr.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 Xl(i._firestore,i._userDataWriter,e.doc.key,e.doc,new Yl(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 Xl(i._firestore,i._userDataWriter,e.doc.key,e.doc,new Yl(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 ed(e,t){return e instanceof Jl&&t instanceof Jl?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 Zl&&t instanceof Zl&&e._firestore===t._firestore&&tl(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function td(e){if(Qs(e)&&0===e.explicitOrderBy.length)throw new kr(Cr.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class nd{}function rd(e,...t){for(const n of t)e=n._apply(e);return e}class sd extends nd{constructor(e,t,n){super(),this.Ga=e,this.za=t,this.Ha=n,this.type="where"}_apply(e){var t=Dl(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 kr(Cr.INVALID_ARGUMENT,`Invalid Query. You can't perform '${i}' queries on FieldPath.documentId().`);if("in"===i||"not-in"===i){ld(a,i);const t=[];for(const n of a)t.push(cd(r,e,n));o={arrayValue:{values:t}}}else o=cd(r,e,a)}else"in"!==i&&"not-in"!==i&&"array-contains-any"!==i||ld(a,i),o=Pl(n,t,a,"in"===i||"not-in"===i);var h=xs.create(s,i,o);return function(e,t){if(t.V()){const r=Js(e);if(null!==r&&!r.isEqual(t.field))throw new kr(Cr.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=Ys(e);null!==n&&dd(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 kr(Cr.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new kr(Cr.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}(e,h),h}(e._query,"where",t,e.firestore._databaseId,this.Ga,this.za,this.Ha);return new Yc(e.firestore,e.converter,(e=e._query,t=e.filters.concat([t]),new Gs(e.path,e.collectionGroup,e.explicitOrderBy.slice(),t,e.limit,e.limitType,e.startAt,e.endAt)))}}class id extends nd{constructor(e,t){super(),this.Ga=e,this.Ja=t,this.type="orderBy"}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new kr(Cr.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new kr(Cr.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,s=new js(t,n);return n=s,null!==Ys(e=e)||null!==(r=Js(e))&&dd(0,r,n.field),s}(e._query,this.Ga,this.Ja);return new Yc(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new Gs(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class ad extends nd{constructor(e,t,n){super(),this.type=e,this.Ya=t,this.Xa=n}_apply(e){return new Yc(e.firestore,e.converter,ti(e._query,this.Ya,this.Xa))}}class od extends nd{constructor(e,t,n){super(),this.type=e,this.Za=t,this.tc=n}_apply(e){var t,n=ud(e,this.type,this.Za,this.tc);return new Yc(e.firestore,e.converter,(t=e._query,e=n,new Gs(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class hd extends nd{constructor(e,t,n){super(),this.type=e,this.Za=t,this.tc=n}_apply(e){var t,n=ud(e,this.type,this.Za,this.tc);return new Yc(e.firestore,e.converter,(t=e._query,e=n,new Gs(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function ud(e,t,n,r){if(n[0]=m(n[0]),n[0]instanceof Wl)return function(e,t,n,r,s){if(!r)throw new kr(Cr.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const i=[];for(const n of Zs(e))if(n.field.isKeyField())i.push(ys(t,r.key));else{const e=r.data.field(n.field);if(is(e))throw new kr(Cr.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 kr(Cr.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 qs(i,s)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var s=Dl(e.firestore);return function(e,t,n,r,s,i){const a=e.explicitOrderBy;if(s.length>a.length)throw new kr(Cr.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 h=0;h<s.length;h++){const u=s[h];if(a[h].field.isKeyField()){if("string"!=typeof u)throw new kr(Cr.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof u}`);if(!Xs(e)&&-1!==u.indexOf("/"))throw new kr(Cr.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by FieldPath.documentId(), the value passed to ${r}() must be a plain document ID, but '${u}' contains a slash.`);const n=e.path.child(Yr.fromString(u));if(!cs.isDocumentKey(n))throw new kr(Cr.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by FieldPath.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 cs(n);o.push(ys(t,s))}else{const e=Pl(n,r,u);o.push(e)}}return new qs(o,i)}(e._query,e.firestore._databaseId,s,t,n,r)}function cd(e,t,n){if("string"==typeof(n=m(n))){if(""===n)throw new kr(Cr.INVALID_ARGUMENT,"Invalid query. When querying with FieldPath.documentId(), you must provide a valid document ID, but it was an empty string.");if(!Xs(t)&&-1!==n.indexOf("/"))throw new kr(Cr.INVALID_ARGUMENT,`Invalid query. When querying a collection by FieldPath.documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(Yr.fromString(n));if(!cs.isDocumentKey(r))throw new kr(Cr.INVALID_ARGUMENT,`Invalid query. When querying a collection group by FieldPath.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 ys(e,new cs(r))}if(n instanceof Qc)return ys(e,n._key);throw new kr(Cr.INVALID_ARGUMENT,`Invalid query. When querying with FieldPath.documentId(), you must provide a valid string or a DocumentReference, but it was: ${Kc(n)}.`)}function ld(e,t){if(!Array.isArray(e)||0===e.length)throw new kr(Cr.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);if(10<e.length)throw new kr(Cr.INVALID_ARGUMENT,`Invalid Query. '${t.toString()}' filters support a maximum of 10 elements in the value array.`)}function dd(e,t,n){if(!n.isEqual(t))throw new kr(Cr.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 fd{convertValue(e,t="none"){switch(ls(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 bl(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 $r(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=Yr.fromString(e);Dr(Ra(n));const r=new Pc(n.get(1),n.get(3)),s=new cs(n.popFirst(5));return r.isEqual(t)||Ir(`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 gd(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class md extends fd{constructor(e){super(),this.firestore=e}convertBytes(e){return new vl(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Qc(this.firestore,null,t)}}class pd{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=Dl(e)}set(e,t,n){this._verifyNotCommitted();const r=yd(e,this._firestore),s=gd(r.converter,t,n),i=Cl(this._dataReader,"WriteBatch.set",r._key,s,null!==r.converter,n);return this._mutations.push(i.toMutation(r._key,Ei.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var s=yd(e,this._firestore);let i;return i="string"==typeof(t=m(t))||t instanceof yl?Fl(this._dataReader,"WriteBatch.update",s._key,t,n,r):Ol(this._dataReader,"WriteBatch.update",s._key,t),this._mutations.push(i.toMutation(s._key,Ei.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=yd(e,this._firestore);return this._mutations=this._mutations.concat(new Mi(t._key,Ei.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 kr(Cr.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function yd(e,t){if((e=m(e)).firestore!==t)throw new kr(Cr.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class vd extends fd{constructor(e){super(),this.firestore=e}convertBytes(e){return new vl(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Qc(this.firestore,null,t)}}function wd(t){t=$c(t,Qc);const n=$c(t.firestore,hl),e=ul(n),r=new vd(n);return function(e,t){const n=new Nr;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.Wn.Rn(e,t))}(t);s.isFoundDocument()?n.resolve(s):s.isNoDocument()?n.resolve(null):n.reject(new kr(Cr.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=xu(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await kc(e),t,n)),n.promise}(e,t._key).then(e=>new Jl(n,r,t._key,e,new Yl(null!==e&&e.hasLocalMutations,!0),t.converter))}function bd(t){t=$c(t,Yc);const n=$c(t.firestore,hl),e=ul(n),r=new vd(n);return function(e,t){const n=new Nr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const s=await Ch(e,t,!0),i=new Wu(t,s.zn),a=i.Po(s.documents),o=i.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=xu(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await kc(e),t,n)),n.promise}(e,t._query).then(e=>new Zl(n,r,t,e))}function Td(e,t,n){e=$c(e,Qc);var r=$c(e.firestore,hl),s=gd(e.converter,t,n);return Sd(r,[Cl(Dl(r),"setDoc",e._key,s,null!==e.converter,n).toMutation(e._key,Ei.none())])}function Ed(e,t,n,...r){e=$c(e,Qc);var s=$c(e.firestore,hl),i=Dl(s);let a;return a="string"==typeof(t=m(t))||t instanceof yl?Fl(i,"updateDoc",e._key,t,n,r):Ol(i,"updateDoc",e._key,t),Sd(s,[a.toMutation(e._key,Ei.exists(!0))])}function Id(t,...n){var e;t=m(t);let r={includeMetadataChanges:!1},s=0;"object"!=typeof n[s]||rl(n[s])||(r=n[s],s++);var i={includeMetadataChanges:r.includeMetadataChanges};if(rl(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,h;if(t instanceof Qc)o=$c(t.firestore,hl),h=Ws(t._key.path),a={next:e=>{n[s]&&n[s](Ad(o,t,e))},error:n[s+1],complete:n[s+2]};else{const u=$c(t,Yc);o=$c(u.firestore,hl),h=u._query;const c=new vd(o);a={next:e=>{n[s]&&n[s](new Zl(o,c,u,e))},error:n[s+1],complete:n[s+2]},td(t._query)}return function(e,t,n,r){const s=new wc(r),i=new qu(t,s,n);return e.asyncQueue.enqueueAndForget(async()=>Pu(await Rc(e),i)),()=>{s.na(),e.asyncQueue.enqueueAndForget(async()=>Vu(await Rc(e),i))}}(ul(o),h,i,a)}function _d(e,t){return function(e,t){const n=new wc(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.io.add(t),t.next()}(await Rc(e),n)),()=>{n.na(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.io.delete(t)}(await Rc(e),n))}}(ul(e=$c(e,hl)),rl(t)?t:{next:t})}function Sd(e,t){return function(e,t){const n=new Nr;return e.asyncQueue.enqueueAndForget(async()=>Xu(await xc(e),t,n)),n.promise}(ul(e),t)}function Ad(e,t,n){var r=n.docs.get(t._key),s=new vd(e);return new Jl(e,s,t._key,r,new Yl(n.hasPendingWrites,n.fromCache),t.converter)}class Dd extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=Dl(e)}get(e){const n=yd(e,this._firestore),r=new md(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 Wl(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new Wl(this._firestore,r,n._key,null,n.converter);throw Ar()})}set(e,t,n){var r=yd(e,this._firestore),s=gd(r.converter,t,n),s=Cl(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=yd(e,this._firestore),i="string"==typeof(t=m(t))||t instanceof yl?Fl(this._dataReader,"Transaction.update",s._key,t,n,r):Ol(this._dataReader,"Transaction.update",s._key,t);return this._transaction.update(s._key,i),this}delete(e){var t=yd(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=yd(e,this._firestore),n=new vd(this._firestore);return super.get(e).then(e=>new Jl(this._firestore,n,t._key,e._document,new Yl(!1,!1),t.converter))}}function Cd(t,n){return function(t,n){const r=new Nr;return t.asyncQueue.enqueueAndForget(async()=>{var e=await Dc(t).then(e=>e.datastore);new Ec(t.asyncQueue,e,n,r).run()}),r.promise}(ul(t=$c(t,hl)),e=>n(new Dd(t,e)))}il=tf.SDK_VERSION,wr=il,tf._registerComponent(new u("firestore",(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=new hl(n,new Mr(e.getProvider("auth-internal")),new Vr(e.getProvider("app-check-internal")));return t=Object.assign({useFetchStreams:!0},t),r._setSettings(t),r},"PUBLIC")),tf.registerVersion(yr,"3.4.2",void 0),tf.registerVersion(yr,"3.4.2","esm2017");function kd(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new kr("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function Nd(){if("undefined"==typeof Uint8Array)throw new kr("unimplemented","Uint8Arrays are not available in this environment.")}function xd(){if("undefined"==typeof atob)throw new kr("unimplemented","Blobs are unavailable in Firestore in this environment.")}class Rd{constructor(e){this._delegate=e}static fromBase64String(e){return xd(),new Rd(vl.fromBase64String(e))}static fromUint8Array(e){return Nd(),new Rd(vl.fromUint8Array(e))}toBase64(){return xd(),this._delegate.toBase64()}toUint8Array(){return Nd(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function Ld(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 Md{enableIndexedDbPersistence(e,t){return function(e,t){pl(e=$c(e,hl));var n=ul(e),r=e._freezeSettings(),s=new yc;return ll(n,s,new mc(s,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){pl(e=$c(e,hl));var t=ul(e),n=e._freezeSettings(),r=new yc;return ll(t,r,new pc(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new kr(Cr.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new Nr;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!ro.Pt())return Promise.resolve();var t=e+"main";await ro.delete(t)}(mh(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class Od{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Pc||(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={}){zc(this._delegate,e,t,n)}enableNetwork(){return fl(this._delegate)}disableNetwork(){return gl(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,qc("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 dl(this._delegate)}onSnapshotsInSync(e){return _d(this._delegate,e)}get app(){if(!this._appCompat)throw new kr("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new Qd(this,Xc(this._delegate,e))}catch(e){throw Bd(e,"collection()","Firestore.collection()")}}doc(e){try{return new qd(this,Zc(this._delegate,e))}catch(e){throw Bd(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new Hd(this,function(e,t){if(e=$c(e,Wc),Uc("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new kr(Cr.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Yc(e,null,(t=t,new Gs(Yr.emptyPath(),t)))}(this._delegate,e))}catch(e){throw Bd(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return Cd(this._delegate,e=>t(new Pd(this,e)))}batch(){return ul(this._delegate),new Vd(new pd(this._delegate,e=>Sd(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=ul(t=$c(t,hl)),r=new sl,Oc(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return ml(this._delegate,e).then(e=>e?new Hd(this,e):null)}}class Fd extends fd{constructor(e){super(),this.firestore=e}convertBytes(e){return new Rd(new vl(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return qd.forKey(t,this.firestore,null)}}class Pd{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Fd(e)}get(e){const t=Yd(e);return this._delegate.get(t).then(e=>new $d(this._firestore,new Jl(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=Yd(e);return n?(kd("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var s=Yd(e);return 2===arguments.length?this._delegate.update(s,t):this._delegate.update(s,t,n,...r),this}delete(e){var t=Yd(e);return this._delegate.delete(t),this}}class Vd{constructor(e){this._delegate=e}set(e,t,n){var r=Yd(e);return n?(kd("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var s=Yd(e);return 2===arguments.length?this._delegate.update(s,t):this._delegate.update(s,t,n,...r),this}delete(e){var t=Yd(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Ud{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new Xl(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new Gd(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=Ud.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let s=r.get(t);return s||(s=new Ud(e,new Fd(e),t),r.set(t,s)),s}}Ud.INSTANCES=new WeakMap;class qd{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Fd(e)}static forPath(e,t,n){if(e.length%2!=0)throw new kr("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new qd(t,new Qc(t._delegate,n,new cs(e)))}static forKey(e,t,n){return new qd(t,new Qc(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new Qd(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new Qd(this.firestore,Xc(this._delegate,e))}catch(e){throw Bd(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=m(e))instanceof Qc&&el(this._delegate,e)}set(e,t){t=kd("DocumentReference.set",t);try{return t?Td(this._delegate,e,t):Td(this._delegate,e)}catch(e){throw Bd(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?Ed(this._delegate,e):Ed(this._delegate,e,t,...n)}catch(e){throw Bd(e,"updateDoc()","DocumentReference.update()")}}delete(){return Sd($c((e=this._delegate).firestore,hl),[new Mi(e._key,Ei.none())]);var e}onSnapshot(...e){var t=jd(e),n=Kd(e,e=>new $d(this.firestore,new Jl(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return Id(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?wd:"server"===(null==e?void 0:e.source)?function(t){t=$c(t,Qc);const n=$c(t.firestore,hl);return Lc(ul(n),t._key,{source:"server"}).then(e=>Ad(n,t,e))}:function(t){t=$c(t,Qc);const n=$c(t.firestore,hl);return Lc(ul(n),t._key).then(e=>Ad(n,t,e))})(this._delegate),t.then(e=>new $d(this.firestore,new Jl(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new qd(this.firestore,e?this._delegate.withConverter(Ud.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Bd(e,t,n){return e.message=e.message.replace(t,n),e}function jd(e){for(const t of e)if("object"==typeof t&&!Ld(t))return t;return{}}function Kd(e,t){var n;let r;return r=Ld(e[0])?e[0]:Ld(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 $d{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new qd(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 ed(this._delegate,e._delegate)}}class Gd extends $d{data(e){var t=this._delegate.data(e);return void 0!==t||Ar(),t}}class Hd{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Fd(e)}where(e,t,n){try{return new Hd(this.firestore,rd(this._delegate,(r=n,s=t,i=Ql("where",e),new sd(i,s,r))))}catch(e){throw Bd(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,s,i}orderBy(e,t){try{return new Hd(this.firestore,rd(this._delegate,([n,r="asc"]=[e,t],s=r,i=Ql("orderBy",n),new id(i,s))))}catch(e){throw Bd(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,s,i}limit(e){try{return new Hd(this.firestore,rd(this._delegate,(Gc("limit",t=e),new ad("limit",t,"F"))))}catch(e){throw Bd(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new Hd(this.firestore,rd(this._delegate,(Gc("limitToLast",t=e),new ad("limitToLast",t,"L"))))}catch(e){throw Bd(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new Hd(this.firestore,rd(this._delegate,function(...e){return new od("startAt",e,!0)}(...e)))}catch(e){throw Bd(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new Hd(this.firestore,rd(this._delegate,function(...e){return new od("startAfter",e,!1)}(...e)))}catch(e){throw Bd(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new Hd(this.firestore,rd(this._delegate,function(...e){return new hd("endBefore",e,!0)}(...e)))}catch(e){throw Bd(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new Hd(this.firestore,rd(this._delegate,function(...e){return new hd("endAt",e,!1)}(...e)))}catch(e){throw Bd(e,"endAt()","Query.endAt()")}}isEqual(e){return tl(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?bd:"server"===(null==e?void 0:e.source)?function(t){t=$c(t,Yc);const n=$c(t.firestore,hl),e=ul(n),r=new vd(n);return Mc(e,t._query,{source:"server"}).then(e=>new Zl(n,r,t,e))}:function(t){t=$c(t,Yc);const n=$c(t.firestore,hl),e=ul(n),r=new vd(n);return td(t._query),Mc(e,t._query).then(e=>new Zl(n,r,t,e))})(this._delegate),t.then(e=>new zd(this.firestore,new Zl(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=jd(e),n=Kd(e,e=>new zd(this.firestore,new Zl(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return Id(this._delegate,t,n)}withConverter(e){return new Hd(this.firestore,e?this._delegate.withConverter(Ud.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class Wd{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new Gd(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class zd{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new Hd(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 Gd(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new Wd(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new Gd(this._firestore,e))})}isEqual(e){return ed(this._delegate,e._delegate)}}class Qd extends Hd{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 qd(this.firestore,e):null}doc(e){try{return void 0===e?new qd(this.firestore,Zc(this._delegate)):new qd(this.firestore,Zc(this._delegate,e))}catch(e){throw Bd(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=$c(e.firestore,hl),r=Zc(e),s=gd(e.converter,t);return Sd(n,[Cl(Dl(e.firestore),"addDoc",r._key,s,null!==e.converter,{}).toMutation(r._key,Ei.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new qd(this.firestore,e))}isEqual(e){return el(this._delegate,e._delegate)}withConverter(e){return new Qd(this.firestore,e?this._delegate.withConverter(Ud.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Yd(e){return $c(e,Qc)}const Jd={Firestore:Od,GeoPoint:bl,Timestamp:$r,Blob:Rd,Transaction:Pd,WriteBatch:Vd,DocumentReference:qd,DocumentSnapshot:$d,Query:Hd,QueryDocumentSnapshot:Gd,QuerySnapshot:zd,CollectionReference:Qd,FieldPath:class Xd{constructor(...e){this._delegate=new yl(...e)}static documentId(){return new Xd(Xr.keyField().canonicalString())}isEqual(e){return(e=m(e))instanceof yl&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class Zd{constructor(e){this._delegate=e}static serverTimestamp(){const e=new xl("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new Zd(e)}static delete(){const e=new kl("deleteField");return e._methodName="FieldValue.delete",new Zd(e)}static arrayUnion(...e){const t=function(...e){return new Rl("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new Zd(t)}static arrayRemove(...e){const t=function(...e){return new Ll("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new Zd(t)}static increment(e){const t=new Ml("increment",e);return t._methodName="FieldValue.increment",new Zd(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,br.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};al=t.default,ol=(e,t)=>new Od(e,t,new Md),al.INTERNAL.registerComponent(new u("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return ol(t,n)},"PUBLIC").setServiceProps(Object.assign({},Jd))),al.registerVersion("@firebase/firestore-compat","0.1.11")}).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(ef,tf){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l,t=e(ef);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 u=0;u<n.length;u+=3){var i=n[u],o=u+1<n.length,a=o?n[u+1]:0,h=u+2<n.length,c=h?n[u+2]:0;let e=(15&a)<<2|c>>6,t=63&c;h||(t=64,o||(e=64)),s.push(r[i>>2],r[(3&i)<<4|a>>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,o=e[n++];o<128?t[r++]=String.fromCharCode(o):191<o&&o<224?(s=e[n++],t[r++]=String.fromCharCode((31&o)<<6|63&s)):239<o&&o<365?(i=((7&o)<<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&o)<<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 h=0;h<e.length;){var s=n[e.charAt(h++)],i=h<e.length?n[e.charAt(h)]:0;++h;var o=h<e.length?n[e.charAt(h)]:64;++h;var a=h<e.length?n[e.charAt(h)]:64;if(++h,null==s||null==i||null==o||null==a)throw Error();r.push(s<<2|i>>4),64!==o&&(r.push(i<<4&240|o>>2),64!==a&&r.push(o<<6&192|a))}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)}}},o=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 a extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,a.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(h,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",i=`${this.serviceName}: ${i} (${s}).`;return new a(s,i,n)}}const h=/\{\$([^}]+)}/g;function m(e){return e&&e._delegate?e._delegate:e}class c{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}}(il=l=l||{})[il.DEBUG=0]="DEBUG",il[il.VERBOSE=1]="VERBOSE",il[il.INFO=2]="INFO",il[il.WARN=3]="WARN",il[il.ERROR=4]="ERROR",il[il.SILENT=5]="SILENT";const u={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 T(){}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 I(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 C(e,t,n){return(C=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?A:D).apply(null,arguments)}function k(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 N(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 x(){this.s=this.s,this.o=this.o}var R={};x.prototype.s=!1,x.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 R[e])},x.prototype.M=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const L=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},M=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 O(){return Array.prototype.concat.apply([],arguments)}function P(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 V,q=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]};function U(e,t){return-1!=e.indexOf(t)}function B(e,t){return e<t?-1:t<e?1:0}e:{var j=b.navigator;if(j){j=j.userAgent;if(j){V=j;break e}}V=""}function K(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function $(e){const t={};for(const n in e)t[n]=e[n];return t}var G="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function H(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<G.length;e++)n=G[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function W(e){return W[" "](e),e}W[" "]=T;var z,Q=U(V,"Opera"),Y=U(V,"Trident")||U(V,"MSIE"),J=U(V,"Edge"),X=J||Y,Z=U(V,"Gecko")&&!(U(V.toLowerCase(),"webkit")&&!U(V,"Edge"))&&!(U(V,"Trident")||U(V,"MSIE"))&&!U(V,"Edge"),ee=U(V.toLowerCase(),"webkit")&&!U(V,"Edge");function te(){var e=b.document;return e?e.documentMode:void 0}e:{var ne="",re=(re=V,Z?/rv:([^\);]+)(\)|;)/.exec(re):J?/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)){z=String(re);break e}}z=ne}var se={};function ie(){return e=function(){let e=0;var t=q(String(z)).split("."),n=q("9").split("."),r=Math.max(t.length,n.length);for(let o=0;0==e&&o<r;o++)for(var s=t[o]||"",i=n[o]||"";s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],i=/(\d*)(\D*)(.*)/.exec(i)||["","","",""],(0!=s[0].length||0!=i[0].length)&&(e=B(0==s[1].length?0:parseInt(s[1],10),0==i[1].length?0:parseInt(i[1],10))||B(0==s[2].length,0==i[2].length)||B(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 oe=b.document&&Y&&(te()||parseInt(z,10))||void 0,ae=function(){if(!b.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{b.addEventListener("test",T,t),b.removeEventListener("test",T,t)}catch(e){}return e}();function he(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}function ce(e,t){if(he.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:ue[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&ce.Z.h.call(this)}}he.prototype.h=function(){this.defaultPrevented=!0},N(ce,he);var ue={2:"touch",3:"pen",4:"mouse"};ce.prototype.h=function(){ce.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=L(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 o=ye(e,t,r,s);return-1<o?(t=e[o],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 o=0;o<n.length;o++)e(t,n[o],r,s,i);return null}r=De(r);return t&&t[le]?t.O(n,r,I(s)?!!s.capture:!!s,i):Te(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,I(r)?!!r.capture:!!r,s):Te(e,t,n,!1,r,s)}function Te(e,t,n,r,s,i){if(!t)throw Error("Invalid event type");var o,a=I(s)?!!s.capture:!!s,h=Se(e);if(h||(e[ve]=h=new me(e)),(n=h.add(t,n,r,a,i)).proxy)return n;if(o=_e,r=function e(t){return o.call(e.src,e.listener,t)},(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(s=!ae?a:s)&&(s=!1),e.addEventListener(t.toString(),r,s);else if(e.attachEvent)e.attachEvent(Ie(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(Ie(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 Ie(e){return e in we?we[e]:we[e]="on"+e}function _e(e,t){var n,r;return e=!!e.ca||(t=new ce(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 Ce(){x.call(this),this.i=new me(this),(this.P=this).I=null}function ke(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 he(t,e):t instanceof he?t.target=t.target||e:(o=t,H(t=new he(r,e),o)),o=!0,n)for(var s=n.length-1;0<=s;s--)var i=t.g=n[s],o=Ne(i,r,!0,t)&&o;if(o=Ne(i=t.g=e,r,!0,t)&&o,o=Ne(i,r,!1,t)&&o,n)for(s=0;s<n.length;s++)o=Ne(i=t.g=n[s],r,!1,t)&&o}function Ne(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var s=!0,i=0;i<t.length;++i){var o,a,h=t[i];h&&!h.ca&&h.capture==n&&(o=h.listener,a=h.ia||h.src,h.fa&&pe(e.i,h),s=!1!==o.call(a,r)&&s)}return s&&!r.defaultPrevented}N(Ce,x),Ce.prototype[le]=!0,Ce.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,s,i){if(Array.isArray(n))for(var o=0;o<n.length;o++)e(t,n[o],r,s,i);else s=I(s)?!!s.capture:!!s,r=De(r),t&&t[le]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=ye(o=t.g[n],r,s,i))&&(ge(o[r]),Array.prototype.splice.call(o,r,1),0==o.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)},Ce.prototype.M=function(){if(Ce.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},Ce.prototype.N=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},Ce.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var xe=b.JSON.stringify;var Re,Le=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new Me,e=>e.reset());class Me{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function Oe(e,t){var n;Re||(n=b.Promise.resolve(void 0),Re=function(){n.then(Ve)}),Pe||(Re(),Pe=!0),Fe.add(e,t)}var Pe=!1,Fe=new class{constructor(){this.h=this.g=null}add(e,t){const n=Le.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function Ve(){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=Le;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}Pe=!1}function qe(e,t){Ce.call(this),this.h=e||1,this.g=t||b,this.j=C(this.kb,this),this.l=Date.now()}function Ue(e){e.da=!1,e.S&&(e.g.clearTimeout(e.S),e.S=null)}function Be(e,t,n){if("function"==typeof e)n&&(e=C(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=C(e.handleEvent,e)}return 2147483647<Number(t)?-1:b.setTimeout(e,t||0)}N(qe,Ce),(y=qe.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),ke(this,"tick"),this.da&&(Ue(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(){qe.Z.M.call(this),Ue(this),delete this.g};class je extends x{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=Be(()=>{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 Ke(e){x.call(this),this.h=e,this.g={}}N(Ke,x);var $e=[];function Ge(e,t,n,r){Array.isArray(n)||(n&&($e[0]=n.toString()),n=$e);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 He(e){K(e.g,function(e,t){this.g.hasOwnProperty(t)&&Ee(e)},e),e.g={}}function We(){this.g=!0}function ze(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 o=1;o<s.length;o++)s[o]=""}}}return xe(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}Ke.prototype.M=function(){Ke.Z.M.call(this),He(this)},Ke.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 Je(){return Ye=Ye||new Ce}function Xe(e){he.call(this,Qe.Ma,e)}function Ze(){var e=Je();ke(e,new Xe(e))}function et(e,t){he.call(this,Qe.STAT_EVENT,e),this.stat=t}function tt(e){var t=Je();ke(t,new et(t,e))}function nt(e,t){he.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",N(Xe,he),Qe.STAT_EVENT="statevent",N(et,he),Qe.Na="timingevent",N(nt,he);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 ot(){}function at(e){return e.h||(e.h=e.i())}function ht(){}ot.prototype.h=null;v={OPEN:"a",pb:"b",Ka:"c",Bb:"d"};function ct(){he.call(this,"d")}function ut(){he.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 Ke(this),this.P=mt,this.W=new qe(e=X?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}N(ct,he),N(ut,he),N(lt,ot),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=Ut(Mt(t)),e.s=n,e.U=!0,wt(e,null)}function wt(e,t){e.F=Date.now(),Et(e),e.A=Mt(e.v);var o,a,h,c,u,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 je(C(e.Ia,e,e.g),e.O)),Ge(e.V,e.g,"readystatechange",e.gb),t=e.H?$(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(),o=e.j,a=e.u,h=e.A,c=e.m,u=e.X,l=e.s,o.info(function(){if(o.g)if(l)for(var e="",t=l.split("&"),n=0;n<t.length;n++){var r,s,i=t[n].split("=");1<i.length&&(r=i[0],i=i[1],e=2<=(s=r.split("_")).length&&"type"==s[1]?e+(r+"=")+i+"&":e+(r+"=redacted&"))}else e=null;else e=l;return"XMLHTTP REQ ("+c+") [attempt "+u+"]: "+a+"\n"+h+"\n"+e})}function bt(e){return e.g&&("GET"==e.u&&2!=e.K&&e.l.Ba)}function Tt(e,t,n){let r=!0,s;for(;!e.I&&e.C<n.length;){if(s=(o=n,h=a=void 0,a=(i=e).C,-1==(h=o.indexOf("\n",a))?yt:(a=Number(o.substring(a,h)),isNaN(a)?pt:(h+=1)+a>o.length?yt:(o=o.substr(h,a),i.C=h+a,o))),s==yt){4==t&&(e.o=4,tt(14),r=!1),ze(e.j,e.m,null,"[Incomplete Response]");break}if(s==pt){e.o=4,tt(15),ze(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}ze(e.j,e.m,s,null),Dt(e,s)}var i,o,a,h;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),Hn(t),t.L=!0,tt(11))):(ze(e.j,e.m,n,"[Invalid Chunked Response]"),At(e),St(e))}function Et(e){e.Y=Date.now()+e.P,It(e,e.P)}function It(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=rt(C(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,Ue(e.W),He(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||an(n.i,e)))if(n.I=e.N,!e.J&&an(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;zn(n),Fn(n)}Gn(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(C(n.ab,n),6e3));if(on(n.i)<=1&&n.ka){try{n.ka()}catch(e){}n.ka=void 0}}else Jn(n,11)}else if(!e.J&&n.g!=e||zn(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 o=i[3];null!=o&&(n.ma=o,n.h.info("VER="+n.ma));var a=i[4];null!=a&&(n.za=a,n.h.info("SVER="+n.za));var h,c,u,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&&(!(h=m.g?m.g.getResponseHeader("X-Client-Wire-Protocol"):null)||!(c=r.i).g&&(U(h,"spdy")||U(h,"quic")||U(h,"h2"))&&(c.j=c.l,c.g=new Set,c.h&&(hn(c,c.h),c.h=null)),!r.D||(u=m.g?m.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.sa=u,qt(r.F,r.D,u))),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?(cn(r.i,g),d=g,(f=r.K)&&d.setTimeout(f),d.B&&(_t(d),Et(d)),r.g=g):$n(r),0<n.l.length&&Un(n)}else"stop"!=i[0]&&"close"!=i[0]||Jn(n,7);else 3==n.G&&("stop"==i[0]||"close"==i[0]?"stop"==i[0]?Jn(n,7):Pn(n):"noop"!=i[0]&&n.j&&n.j.wa(i),n.A=0)}Ze()}catch(e){}}function Ct(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(E(e)||"string"==typeof e)M(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 kt(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 kt)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 Nt(e){if(e.i!=e.g.length){for(var t=0,n=0;t<e.g.length;){var r=e.g[t];xt(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;)xt(s,r=e.g[t])||(s[e.g[n++]=r]=1),t++;e.g.length=n}}function xt(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==xn(e)?t.l():this.Ia(e)},y.Ia=function(e){try{if(e==this.g)e:{var t=xn(this.g),n=this.g.Da();this.g.ba();if(!(t<3)&&(3!=t||X||this.g&&(this.h.h||this.g.ga()||Rn(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=Rn(this.g);e="";var i=s.length,o=4==xn(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){At(this),St(this);var a="";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:o&&n==i-1});s.splice(0,i),this.h.g+=e,this.C=0,a=this.h.g}else a=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 h,c=this.g;if((h=c.g?c.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!F(h)){var u=h;break t}}u=null}if(!(r=u)){this.i=!1,this.o=3,tt(12),At(this),St(this);break e}ze(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.J=!0,Dt(this,r)}this.U?(Tt(this,t,a),X&&this.i&&3==t&&(Ge(this.V,this.W,"tick",this.fb),this.W.start())):(ze(this.j,this.m,a,null),Dt(this,a)),4==t&&At(this),this.i&&!this.I&&(4==t?Qn(this.l,this):(this.i=!1,Et(this)))}else 400==r&&0<a.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=xn(this.g),t=this.g.ga(),this.C<t.length&&(_t(this),Tt(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)):It(this,this.Y-n)},(y=kt.prototype).R=function(){Nt(this);for(var e=[],t=0;t<this.g.length;t++)e.push(this.h[this.g[t]]);return e},y.T=function(){return Nt(this),this.g.concat()},y.get=function(e,t){return xt(this.h,e)?this.h[e]:t},y.set=function(e,t){xt(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 Rt=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function Lt(e,t){var n;this.i=this.s=this.j="",this.m=null,this.o=this.l="",this.g=!1,e instanceof Lt?(this.g=void 0!==t?t:e.g,Ot(this,e.j),this.s=e.s,Pt(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 kt(t.g),n.h=t.h),Vt(this,n),this.o=e.o):e&&(n=String(e).match(Rt))?(this.g=!!t,Ot(this,n[1]||"",!0),this.s=Bt(n[2]||""),Pt(this,n[3]||"",!0),Ft(this,n[4]),this.l=Bt(n[5]||"",!0),Vt(this,n[6]||"",!0),this.o=Bt(n[7]||"")):(this.g=!!t,this.h=new Qt(null,this.g))}function Mt(e){return new Lt(e)}function Ot(e,t,n){e.j=n?Bt(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Pt(e,t,n){e.i=n?Bt(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 Vt(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&&(Jt(this,t),Zt(this,n,e))},r)),r.j=s):(n||(t=jt(t,Wt)),e.h=new Qt(t,e.g))}function qt(e,t,n){e.h.set(t,n)}function Ut(e){return qt(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Bt(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function jt(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,Kt),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function Kt(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}Lt.prototype.toString=function(){var e=[],t=this.j;t&&e.push(jt(t,$t,!0),":");var n=this.i;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(jt(t,$t,!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(jt(n,"/"==n.charAt(0)?Ht:Gt,!0))),(n=this.h.toString())&&e.push("?",n),(n=this.o)&&e.push("#",jt(n,zt)),e.join("")};var $t=/[#\/\?@]/g,Gt=/[#\?:]/g,Ht=/[#\?]/g,Wt=/[#\?@]/g,zt=/#/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 kt,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 Jt(e,t){Yt(e),t=en(e,t),xt(e.g.h,t)&&(e.i=null,e.h-=e.g.get(t).length,xt((e=e.g).h,t)&&(delete e.h[t],e.i--,e.g.length>2*e.i&&Nt(e)))}function Xt(e,t){return Yt(e),t=en(e,t),xt(e.g.h,t)}function Zt(e,t,n){Jt(e,t),0<n.length&&(e.i=null,e.g.set(en(e,t),P(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){M(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)Xt(this,e)&&(t=O(t,this.g.get(en(this,e))));else{e=this.g.R();for(var n=0;n<e.length;n++)t=O(t,e[n])}return t},y.set=function(e,t){return Yt(this),this.i=null,Xt(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 o=s;""!==r[i]&&(o+="="+encodeURIComponent(String(r[i]))),e.push(o)}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 on(e){return e.h?1:e.g?e.g.size:0}function an(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function hn(e,t){e.g?e.g.add(t):e.h=t}function cn(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function un(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return P(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){Ce.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=un(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)},N(gn,ot),gn.prototype.g=function(){return new mn(this.l,this.j)},gn.prototype.i=(rn={},function(){return rn}),N(mn,Ce);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 Tn(e){Ce.call(this),this.headers=new kt,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}N(Tn,Ce);var En="",In=/^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),kn(e)}function Dn(e){e.D||(e.D=!0,ke(e,"complete"),ke(e,"error"))}function Cn(e){if(e.h&&void 0!==w&&(!e.C[1]||4!=xn(e)||2!=e.ba()))if(e.v&&4==xn(e))Be(e.Fa,0,e);else if(ke(e,"readystatechange"),4==xn(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 o=!0;break e;default:o=!1}if((t=o)||((n=0===i)&&(!(s=String(e.H).match(Rt)[1]||null)&&b.self&&b.self.location&&(s=(r=b.self.location.protocol).substr(0,r.length-1)),n=!In.test(s?s.toLowerCase():"")),t=n),t)ke(e,"complete"),ke(e,"success");else{e.m=6;try{var a=2<xn(e)?e.g.statusText:""}catch(e){a=""}e.j=a+" ["+e.ba()+"]",Dn(e)}}finally{kn(e)}}}function kn(e,t){if(e.g){Nn(e);const n=e.g,r=e.C[0]?T:null;e.g=null,e.C=null,t||ke(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Nn(e){e.g&&e.K&&(e.g.ontimeout=null),e.A&&(b.clearTimeout(e.A),e.A=null)}function xn(e){return e.g?e.g.readyState:0}function Rn(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 Ln(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=function(e){let n="";return K(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):qt(e,t,n))}function Mn(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function On(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=Mn("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=Mn("baseRetryDelayMs",5e3,e),this.$a=Mn("retryDelaySeedMs",1e4,e),this.Ya=Mn("forwardChannelMaxRetries",2,e),this.ra=Mn("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 Pn(e){var t,n;Vn(e),3==e.G&&(t=e.V++,qt(n=Mt(e.F),"SID",e.J),qt(n,"RID",t),qt(n,"TYPE","terminate"),jn(e,n),(t=new dt(e,e.h,t,void 0)).K=2,t.v=Ut(Mt(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)),Xn(e)}function Fn(e){e.g&&(Hn(e),e.g.cancel(),e.g=null)}function Vn(e){Fn(e),e.u&&(b.clearTimeout(e.u),e.u=null),zn(e),e.i.cancel(),e.m&&("number"==typeof e.m&&b.clearTimeout(e.m),e.m=null)}function qn(e,t){e.l.push(new tn(e.Za++,t)),3==e.G&&Un(e)}function Un(e){sn(e.i)||e.m||(e.m=!0,Oe(e.Ha,e),e.C=0)}function Bn(e,t){var n=t?t.m:e.V++,r=Mt(e.F);qt(r,"SID",e.J),qt(r,"RID",n),qt(r,"AID",e.U),jn(e,r),e.o&&e.s&&Ln(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=Kn(e,n,1e3),n.setTimeout(Math.round(.5*e.ra)+Math.round(.5*e.ra*Math.random())),hn(e.i,n),vt(n,r,t)}function jn(e,n){e.j&&Ct({},function(e,t){qt(n,t,e)})}function Kn(e,t,r){r=Math.min(e.l.length,r);var s=e.j?C(e.j.Oa,e.j,e):null;e:{var i=e.l;let n=-1;for(;;){const h=["count="+r];-1==n?0<r?(n=i[0].h,h.push("ofs="+n)):n=0:h.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var o=i[t].h,a=i[t].g;if((o-=n)<0)n=Math.max(0,i[t].h-100),e=!1;else try{!function(e,r,t){const s=t||"";try{Ct(e,function(e,t){let n=e;I(e)&&(n=xe(e)),r.push(s+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(s+"type="+encodeURIComponent("_badmap")),e}}(a,h,"req"+o+"_")}catch(e){s&&s(a)}}if(e){s=h.join("&");break e}}}return e=e.l.splice(0,r),t.D=e,s}function $n(e){e.g||e.u||(e.Y=1,Oe(e.Ga,e),e.A=0)}function Gn(e){return!(e.g||e.u||3<=e.A)&&(e.Y++,e.u=rt(C(e.Ga,e),Yn(e,e.A)),e.A++,1)}function Hn(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=Mt(e.oa);qt(t,"RID","rpc"),qt(t,"SID",e.J),qt(t,"CI",e.N?"0":"1"),qt(t,"AID",e.U),jn(e,t),qt(t,"TYPE","xmlhttp"),e.o&&e.s&&Ln(t,e.o,e.s),e.K&&e.g.setTimeout(e.K);var n=e.g;e=e.la,n.K=1,n.v=Ut(Mt(t)),n.s=null,n.U=!0,wt(n,e)}function zn(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){zn(e),Hn(e),e.g=null;var o=2}else{if(!an(e.i,t))return;i=t.D,cn(e.i,t),o=1}if(e.I=t.N,0!=e.G)if(t.i)1==o?(i=t.s?t.s.length:0,t=Date.now()-t.F,n=e.C,ke(o=Je(),new nt(o,i)),Un(e)):$n(e);else if(3==(n=t.o)||0==n&&0<e.I||(1!=o||(s=t,on((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(C(r.Ha,r,s),Yn(r,r.C)),r.C++,0))))&&(2!=o||!Gn(e)))switch(i&&0<i.length&&(t=e.i,t.i=t.i.concat(i)),n){case 1:Jn(e,5);break;case 4:Jn(e,10);break;case 3:Jn(e,6);break;default:Jn(e,2)}}function Yn(e,t){let n=e.Pa+Math.floor(Math.random()*e.$a);return e.j||(n*=2),n*t}function Jn(e,t){var n,r;e.h.info("Error code "+t),2==t?(n=null,e.j&&(n=null),r=C(e.jb,e),n||(n=new Lt("//www.google.com/images/cleardot.gif"),b.location&&"http"==b.location.protocol||Ot(n,"https"),Ut(n)),function(e,t){var n=new We;if(b.Image){const r=new Image;r.onload=k(fn,n,r,"TestLoadImage: loaded",!0,t),r.onerror=k(fn,n,r,"TestLoadImage: error",!1,t),r.onabort=k(fn,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=k(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),Xn(e),Vn(e)}function Xn(e){e.G=0,e.I=-1,e.j&&(0==un(e.i).length&&0==e.l.length||(e.i.i.length=0,P(e.l),e.l.length=0),e.j.ua())}function Zn(e,t,n){let r=(a=n)instanceof Lt?Mt(a):new Lt(a,void 0);var s,i,o,a,h;return""!=r.i?(t&&Pt(r,t+"."+r.i),Ft(r,r.m)):(h=b.location,r=(s=h.protocol,i=t?t+"."+h.hostname:h.hostname,o=+h.port,a=n,h=new Lt(null,void 0),s&&Ot(h,s),i&&Pt(h,i),o&&Ft(h,o),a&&(h.l=a),h)),e.aa&&K(e.aa,function(e,t){qt(r,t,e)}),t=e.D,n=e.sa,t&&n&&qt(r,t,n),qt(r,"VER",e.ma),jn(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 Tn(new gn({ib:!0})):new Tn(e.qa)).L=e.H,t}function tr(){}function nr(){if(Y&&!(10<=Number(oe)))throw Error("Environmental error: no available transport.")}function rr(e,t){Ce.call(this),this.g=new On(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 or(this)}function sr(e){ct.call(this);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function ir(){ut.call(this),this.status=1}function or(e){this.g=e}(y=Tn.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?at(this.u):at(gt),this.g.onreadystatechange=C(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 kt(this.headers);r&&Ct(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<=L(_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{Nn(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=C(this.pa,this)):this.A=Be(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,ke(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,ke(this,"complete"),ke(this,"abort"),kn(this))},y.M=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),kn(this,!0)),Tn.Z.M.call(this)},y.Fa=function(){this.s||(this.F||this.v||this.l?Cn(this):this.cb())},y.cb=function(){Cn(this)},y.ba=function(){try{return 2<xn(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=On.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=$(e),H(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=Kn(this,i,n),qt(r=Mt(this.F),"RID",t),qt(r,"CVER",22),this.D&&qt(r,"X-HTTP-Session-Id",this.D),jn(this,r),this.o&&e&&Ln(r,this.o,e),hn(this.i,i),this.Ra&&qt(r,"TYPE","init"),this.ja?(qt(r,"$req",n),qt(r,"SID","null"),i.$=!0,vt(i,r,null)):vt(i,r,n),this.G=2}}else 3==this.G&&(t?Bn(this,t):0==this.l.length||sn(this.i)||Bn(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(C(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),Gn(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)},N(rr,Ce),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."),Oe(C(e.hb,e,t))),tt(0),e.W=t,e.aa=n||{},e.N=e.X,e.F=Zn(e,null,e.W),Un(e)},rr.prototype.close=function(){Pn(this.g)},rr.prototype.u=function(e){var t;"string"==typeof e?((t={}).__data__=e,qn(this.g,t)):this.v?((t={}).__data__=xe(e),qn(this.g,t)):qn(this.g,e)},rr.prototype.M=function(){this.g.j=null,delete this.j,Pn(this.g),delete this.g,rr.Z.M.call(this)},N(sr,ct),N(ir,ut),N(or,tr),or.prototype.xa=function(){ke(this.g,"a")},or.prototype.wa=function(e){ke(this.g,new sr(e))},or.prototype.va=function(e){ke(this.g,new ir)},or.prototype.ua=function(){ke(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",(ht.EventType=v).OPEN="a",v.CLOSE="b",v.ERROR="c",v.MESSAGE="d",Ce.prototype.listen=Ce.prototype.N,Tn.prototype.listenOnce=Tn.prototype.O,Tn.prototype.getLastError=Tn.prototype.La,Tn.prototype.getLastErrorCode=Tn.prototype.Da,Tn.prototype.getStatus=Tn.prototype.ba,Tn.prototype.getResponseJson=Tn.prototype.Qa,Tn.prototype.getResponseText=Tn.prototype.ga,Tn.prototype.send=Tn.prototype.ea;var ar,hr=Je,cr=st,ur=it,lr=Qe,dr=10,fr=11,gr=gn,mr=ht,pr=Tn;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.3";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?u[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 Tr(){return br.logLevel}function Er(e,...t){var n;br.logLevel<=l.DEBUG&&(n=t.map(Sr),br.debug(`Firestore (${wr}): ${e}`,...n))}function Ir(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 Ir(t),new Error(t)}function Dr(e){e||Ar()}const Cr={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 kr extends a{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class Nr{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class xr{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Rr{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(vr.UNAUTHENTICATED))}shutdown(){}}class Lr{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 Mr{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 Nr;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new Nr,t.enqueueRetryable(()=>s(this.currentUser))};const o=()=>{const e=i;t.enqueueRetryable(async()=>{await e.promise,await s(this.currentUser)})},a=e=>{Er("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),o()};this.t.onInit(e=>a(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?a(e):(Er("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new Nr))},0),o()}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 xr(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return Dr(null===e||"string"==typeof e),new vr(e)}}class Or{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 Pr{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new Or(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 Vr{constructor(e){this.g=e,this.forceRefresh=!1,this.appCheck=null}start(t,n){this.o=e=>{t.enqueueRetryable(()=>(e=>(null!=e.error&&Er("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`),n(e.token)))(e))};const r=e=>{Er("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.g.onInit(e=>r(e)),setTimeout(()=>{var e;this.appCheck||((e=this.g.getImmediate({optional:!0}))?r(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),new Fr(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class qr{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.p(e),this.T=e=>t.writeSequenceNumber(e))}p(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.T&&this.T(e),e}}qr.I=-1;class Ur{static A(){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 Br(e,t){return e<t?-1:t<e?1:0}function jr(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function Kr(e){return e+"\0"}class $r{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new kr(Cr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new kr(Cr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new kr(Cr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new kr(Cr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return $r.fromMillis(Date.now())}static fromDate(e){return $r.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new $r(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Br(this.nanoseconds,e.nanoseconds):Br(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 Gr{constructor(e){this.timestamp=e}static fromTimestamp(e){return new Gr(e)}static min(){return new Gr(new $r(0,0))}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 Hr(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 zr(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 kr(Cr.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 Jr=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Xr extends Qr{construct(e,t,n){return new Xr(e,t,n)}static isValidIdentifier(e){return Jr.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!Xr.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new Xr(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var s=()=>{if(0===n.length)throw new kr(Cr.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 kr(Cr.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new kr(Cr.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 kr(Cr.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Xr(t)}static emptyPath(){return new Xr([])}}class Zr{constructor(e){(this.fields=e).sort(Xr.comparator)}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return jr(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class 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 Br(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 os(e){var t=ns(e.mapValue.fields.__local_write_time__.timestampValue);return new $r(t.seconds,t.nanos)}function as(e){return null==e}function hs(e){return 0===e&&1/e==-1/0}function cs(e){return"number"==typeof e&&Number.isInteger(e)&&!hs(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}class us{constructor(e){this.path=e}static fromPath(e){return new us(Yr.fromString(e))}static fromName(e){return new us(Yr.fromString(e).popFirst(5))}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}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 us(new Yr(e.slice()))}}function ls(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?is(e)?4:10:Ar()}function ds(r,s){if(r===s)return!0;var e,t,n=ls(r);if(n!==ls(s))return!1;switch(n){case 0:return!0;case 1:return r.booleanValue===s.booleanValue;case 4:return os(r).isEqual(os(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?hs(n)===hs(r):isNaN(n)&&isNaN(r)}return!1}(r,s);case 9:return jr(r.arrayValue.values||[],s.arrayValue.values||[],ds);case 10:return function(e){const t=e.mapValue.fields||{},n=s.mapValue.fields||{};if(Hr(t)!==Hr(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!ds(t[e],n[e])))return!1;return!0}(r);default:return Ar()}}function fs(e,t){return void 0!==(e.values||[]).find(e=>ds(e,t))}function gs(e,t){if(e===t)return 0;var n,r,s,i,o=ls(e),a=ls(t);if(o!==a)return Br(o,a);switch(o){case 0:return 0;case 1:return Br(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 ms(e.timestampValue,t.timestampValue);case 4:return ms(os(e),os(t));case 5:return Br(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=Br(n[s],r[s]);if(0!==t)return t}return Br(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(i=Br(rs(n.latitude),rs(r.latitude)))?i:Br(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=gs(n[s],r[s]);if(t)return t}return Br(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 a=0;a<r.length&&a<i.length;++a){const t=Br(r[a],i[a]);if(0!==t)return t;var o=gs(n[r[a]],s[i[a]]);if(0!==o)return o}return Br(r.length,i.length)}(e.mapValue,t.mapValue);default:throw Ar()}}function ms(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Br(e,t);var n=ns(e),r=ns(t),s=Br(n.seconds,r.seconds);return 0!==s?s:Br(n.nanos,r.nanos)}function ps(e){return function i(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=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,us.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 ys(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function vs(e){return e&&"integerValue"in e}function ws(e){return!!e&&"arrayValue"in e}function bs(e){return e&&"nullValue"in e}function Ts(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Es(e){return e&&"mapValue"in e}function Is(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]=Is(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Is(t.arrayValue.values[e]);return r}return Object.assign({},t)}class _s{constructor(e){this.value=e}static empty(){return new _s({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)],!Es(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Is(t)}setAll(e){let n=Xr.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()]=Is(e):s.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,s)}delete(e){const t=this.field(e.popLast());Es(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return ds(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)];Es(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 _s(Is(this.value))}}class Ss{constructor(e,t,n,r,s){this.key=e,this.documentType=t,this.version=n,this.data=r,this.documentState=s}static newInvalidDocument(e){return new Ss(e,0,Gr.min(),_s.empty(),0)}static newFoundDocument(e,t,n){return new Ss(e,1,t,n,0)}static newNoDocument(e,t){return new Ss(e,2,t,_s.empty(),0)}static newUnknownDocument(e,t){return new Ss(e,3,t,_s.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=_s.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=_s.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,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 Ss&&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 Ss(this.key,this.documentType,this.version,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class As{constructor(e,t=null,n=[],r=[],s=null,i=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=s,this.startAt=i,this.endAt=o,this.R=null}}function Ds(e,t=null,n=[],r=[],s=null,i=null,o=null){return new As(e,t,n,r,s,i,o)}function Cs(e){const t=e;if(null===t.R){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>function(e){return e.field.canonicalString()+e.op.toString()+ps(e.value)}(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),as(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=Bs(t.startAt)),t.endAt&&(e+="|ub:",e+=Bs(t.endAt)),t.R=e}return t.R}function ks(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let o=0;o<e.orderBy.length;o++)if(n=e.orderBy[o],r=t.orderBy[o],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 a=0;a<e.filters.length;a++)if(s=e.filters[a],i=t.filters[a],s.op!==i.op||!s.field.isEqual(i.field)||!ds(s.value,i.value))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!$s(e.startAt,t.startAt)&&$s(e.endAt,t.endAt)}function Ns(e){return us.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}class xs 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.P(e,t,n):new Rs(e,t,n):"array-contains"===t?new Ps(e,n):"in"===t?new Fs(e,n):"not-in"===t?new Vs(e,n):"array-contains-any"===t?new qs(e,n):new xs(e,t,n)}static P(e,t,n){return new("in"===t?Ls:Ms)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.v(gs(t,this.value)):null!==t&&ls(this.value)===ls(t)&&this.v(gs(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()}}V(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}}class Rs extends xs{constructor(e,t,n){super(e,t,n),this.key=us.fromName(n.referenceValue)}matches(e){var t=us.comparator(e.key,this.key);return this.v(t)}}class Ls extends xs{constructor(e,t){super(e,"in",t),this.keys=Os(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class Ms extends xs{constructor(e,t){super(e,"not-in",t),this.keys=Os(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function Os(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>us.fromName(e.referenceValue))}class Ps extends xs{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return ws(t)&&fs(t.arrayValue,this.value)}}class Fs extends xs{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&fs(this.value.arrayValue,t)}}class Vs extends xs{constructor(e,t){super(e,"not-in",t)}matches(e){if(fs(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!fs(this.value.arrayValue,t)}}class qs extends xs{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!ws(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>fs(this.value.arrayValue,e))}}class Us{constructor(e,t){this.position=e,this.before=t}}function Bs(e){return`${e.before?"b":"a"}:${e.position.map(e=>ps(e)).join(",")}`}class js{constructor(e,t="asc"){this.field=e,this.dir=t}}function Ks(e,t,n){let r=0;for(let s=0;s<e.position.length;s++){const i=t[s],o=e.position[s];if(r=i.field.isKeyField()?us.comparator(us.fromName(o.referenceValue),n.key):gs(o,n.data.field(i.field)),"desc"===i.dir&&(r*=-1),0!==r)break}return e.before?r<=0:r<0}function $s(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.before!==t.before||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!ds(e.position[n],t.position[n]))return!1;return!0}class Gs{constructor(e,t=null,n=[],r=[],s=null,i="F",o=null,a=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=s,this.limitType=i,this.startAt=o,this.endAt=a,this.S=null,this.D=null,this.startAt,this.endAt}}function Hs(e,t,n,r,s,i,o,a){return new Gs(e,t,n,r,s,i,o,a)}function Ws(e){return new Gs(e)}function zs(e){return!as(e.limit)&&"F"===e.limitType}function Qs(e){return!as(e.limit)&&"L"===e.limitType}function Ys(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function Js(e){for(const t of e.filters)if(t.V())return t.field;return null}function Xs(e){return null!==e.collectionGroup}function Zs(t){const n=t;if(null===n.S){n.S=[];const t=Js(n),e=Ys(n);if(null!==t&&null===e)t.isKeyField()||n.S.push(new js(t)),n.S.push(new js(Xr.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.S.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.S.push(new js(Xr.keyField(),t))}}}return n.S}function ei(e){const t=e;if(!t.D)if("F"===t.limitType)t.D=Ds(t.path,t.collectionGroup,Zs(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const s of Zs(t)){const t="desc"===s.dir?"asc":"desc";e.push(new js(s.field,t))}var n=t.endAt?new Us(t.endAt.position,!t.endAt.before):null,r=t.startAt?new Us(t.startAt.position,!t.startAt.before):null;t.D=Ds(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.D}function ti(e,t,n){return new Gs(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function ni(e,t){return ks(ei(e),ei(t))&&e.limitType===t.limitType}function ri(e){return`${Cs(ei(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} ${ps(t.value)}`;var t}).join(", ")}]`),as(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: "+Bs(e.startAt)),e.endAt&&(t+=", endAt: "+Bs(e.endAt)),`Target(${t})`}(ei(e))}; limitType=${e.limitType})`}function ii(n,e){return e.isFoundDocument()&&(t=n,s=(r=e).key.path,null!==t.collectionGroup?r.key.hasCollectionId(t.collectionGroup)&&t.path.isPrefixOf(s):us.isDocumentKey(t.path)?t.path.isEqual(s):t.path.isImmediateParentOf(s))&&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)&&(t=e,(!(e=n).startAt||Ks(e.startAt,Zs(e),t))&&(!e.endAt||!Ks(e.endAt,Zs(e),t)));var t,r,s}function oi(s){return(e,t)=>{let n=!1;for(const r of Zs(s)){const s=function(e,s,t){var n=e.field.isKeyField()?us.comparator(s.key,t.key):function(e,t){var n=s.data.field(e),r=t.data.field(e);return null!==n&&null!==r?gs(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 ai(e,t){if(e.C){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:hs(t)?"-0":t}}function hi(e){return{integerValue:""+e}}function ci(e,t){return cs(t)?hi(t):ai(e,t)}class ui{constructor(){this._=void 0}}function li(e,t){return e instanceof yi?vs(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class di extends ui{}class fi extends ui{constructor(e){super(),this.elements=e}}function gi(e,t){const n=wi(t);for(const t of e.elements)n.some(e=>ds(e,t))||n.push(t);return{arrayValue:{values:n}}}class mi extends ui{constructor(e){super(),this.elements=e}}function pi(e,t){let n=wi(t);for(const t of e.elements)n=n.filter(e=>!ds(e,t));return{arrayValue:{values:n}}}class yi extends ui{constructor(e,t){super(),this.k=e,this.N=t}}function vi(e){return rs(e.integerValue||e.doubleValue)}function wi(e){return ws(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class bi{constructor(e,t){this.field=e,this.transform=t}}class Ti{constructor(e,t){this.version=e,this.transformResults=t}}class Ei{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Ei}static exists(e){return new Ei(void 0,e)}static updateTime(e){return new Ei(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 Ii(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class _i{}function Si(e,t,n){e instanceof ki?function(e,t,n){const r=e.value.clone(),s=Ri(e.fieldTransforms,t,n.transformResults);r.setAll(s),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Ni?function(e,t,n){if(!Ii(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=Ri(e.fieldTransforms,t,n.transformResults),s=t.data;s.setAll(xi(e)),s.setAll(r),t.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function Ai(e,t,n){e instanceof ki?function(e,t,n){if(Ii(e.precondition,t)){const r=e.value.clone(),s=Li(e.fieldTransforms,n,t);r.setAll(s),t.convertToFoundDocument(Ci(t),r).setHasLocalMutations()}}(e,t,n):e instanceof Ni?function(e,t,n){if(Ii(e.precondition,t)){const r=Li(e.fieldTransforms,n,t),s=t.data;s.setAll(xi(e)),s.setAll(r),t.convertToFoundDocument(Ci(t),s).setHasLocalMutations()}}(e,t,n):(t=t,Ii(e.precondition,t)&&t.convertToNoDocument(Gr.min()))}function Di(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&jr(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof fi&&t instanceof fi||e instanceof mi&&t instanceof mi?jr(e.elements,t.elements,ds):e instanceof yi&&t instanceof yi?ds(e.N,t.N):e instanceof di&&t instanceof di)}(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 Ci(e){return e.isFoundDocument()?e.version:Gr.min()}class ki extends _i{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}}class Ni extends _i{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 xi(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 Ri(e,t,n){const r=new Map;Dr(e.length===n.length);for(let u=0;u<n.length;u++){var s=e[u],i=s.transform,o=t.data.field(s.field);r.set(s.field,(a=i,h=o,c=n[u],a instanceof fi?gi(a,h):a instanceof mi?pi(a,h):c))}var a,h,c;return r}function Li(e,t,n){const r=new Map;for(const c of e){const e=c.transform,u=n.data.field(c.field);r.set(c.field,(s=e,i=u,o=t,h=a=void 0,s instanceof di?function(){const e={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:o.seconds,nanos:o.nanoseconds}}}};return i&&(e.fields.__previous_value__=i),{mapValue:e}}():s instanceof fi?gi(s,i):s instanceof mi?pi(s,i):(a=li(s=s,i),h=vi(a)+vi(s.N),vs(a)&&vs(s.N)?hi(h):ai(s.k,h))))}var s,i,o,a,h;return r}class Mi extends _i{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}}class Oi extends _i{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}}class Pi{constructor(e){this.count=e}}function Fi(e){switch(e){default:return Ar(),0;case Cr.CANCELLED:case Cr.UNKNOWN:case Cr.DEADLINE_EXCEEDED:case Cr.RESOURCE_EXHAUSTED:case Cr.INTERNAL:case Cr.UNAVAILABLE:case Cr.UNAUTHENTICATED:return;case Cr.INVALID_ARGUMENT:case Cr.NOT_FOUND:case Cr.ALREADY_EXISTS:case Cr.PERMISSION_DENIED:case Cr.FAILED_PRECONDITION:case Cr.ABORTED:case Cr.OUT_OF_RANGE:case Cr.UNIMPLEMENTED:case Cr.DATA_LOSS:return 1}}function Vi(e){if(void 0===e)return Ir("GRPC error has no .code"),Cr.UNKNOWN;switch(e){case ar.OK:return Cr.OK;case ar.CANCELLED:return Cr.CANCELLED;case ar.UNKNOWN:return Cr.UNKNOWN;case ar.DEADLINE_EXCEEDED:return Cr.DEADLINE_EXCEEDED;case ar.RESOURCE_EXHAUSTED:return Cr.RESOURCE_EXHAUSTED;case ar.INTERNAL:return Cr.INTERNAL;case ar.UNAVAILABLE:return Cr.UNAVAILABLE;case ar.UNAUTHENTICATED:return Cr.UNAUTHENTICATED;case ar.INVALID_ARGUMENT:return Cr.INVALID_ARGUMENT;case ar.NOT_FOUND:return Cr.NOT_FOUND;case ar.ALREADY_EXISTS:return Cr.ALREADY_EXISTS;case ar.PERMISSION_DENIED:return Cr.PERMISSION_DENIED;case ar.FAILED_PRECONDITION:return Cr.FAILED_PRECONDITION;case ar.ABORTED:return Cr.ABORTED;case ar.OUT_OF_RANGE:return Cr.OUT_OF_RANGE;case ar.UNIMPLEMENTED:return Cr.UNIMPLEMENTED;case ar.DATA_LOSS:return Cr.DATA_LOSS;default:return Ar()}}(it=ar=ar||{})[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 qi{constructor(e,t){this.comparator=e,this.root=t||Bi.EMPTY}insert(e,t){return new qi(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,Bi.BLACK,null,null))}remove(e){return new qi(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Bi.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 Ui(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new Ui(this.root,e,this.comparator,!1)}getReverseIterator(){return new Ui(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new Ui(this.root,e,this.comparator,!0)}}class Ui{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,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 Bi{constructor(e,t,n,r,s){this.key=e,this.value=t,this.color=null!=n?n:Bi.RED,this.left=null!=r?r:Bi.EMPTY,this.right=null!=s?s:Bi.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,s){return new Bi(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 Bi.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 Bi.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,Bi.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,Bi.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)}}Bi.EMPTY=null,Bi.RED=!0,Bi.BLACK=!1,Bi.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 Bi(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 ji{constructor(e){this.comparator=e,this.data=new qi(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 Ki(this.data.getIterator())}getIteratorFrom(e){return new Ki(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 ji))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 ji(this.comparator);return t.data=e,t}}class Ki{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}const $i=new qi(us.comparator);const Gi=new qi(us.comparator);const Hi=new qi(us.comparator);const Wi=new ji(us.comparator);function zi(...e){let t=Wi;for(const n of e)t=t.add(n);return t}const Qi=new ji(Br);class Yi{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,Ji.createSynthesizedTargetChangeForCurrentChange(e,t)),new Yi(Gr.min(),n,Qi,$i,zi())}}class Ji{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 Ji(es.EMPTY_BYTE_STRING,t,zi(),zi(),zi())}}class Xi{constructor(e,t,n,r){this.$=e,this.removedTargetIds=t,this.key=n,this.O=r}}class Zi{constructor(e,t){this.targetId=e,this.M=t}}class eo{constructor(e,t,n=es.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class to{constructor(){this.F=0,this.L=so(),this.B=es.EMPTY_BYTE_STRING,this.U=!1,this.q=!0}get current(){return this.U}get resumeToken(){return this.B}get K(){return 0!==this.F}get j(){return this.q}W(e){0<e.approximateByteSize()&&(this.q=!0,this.B=e)}G(){let n=zi(),r=zi(),s=zi();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 Ji(this.B,this.U,n,r,s)}H(){this.q=!1,this.L=so()}J(e,t){this.q=!0,this.L=this.L.insert(e,t)}Y(e){this.q=!0,this.L=this.L.remove(e)}X(){this.F+=1}Z(){--this.F}tt(){this.q=!0,this.U=!0}}class no{constructor(e){this.et=e,this.nt=new Map,this.st=$i,this.it=ro(),this.rt=new ji(Br)}ot(e){for(const t of e.$)e.O&&e.O.isFoundDocument()?this.ct(t,e.O):this.at(t,e.key,e.O);for(const n of e.removedTargetIds)this.at(n,e.key,e.O)}ut(n){this.forEachTarget(n,e=>{const t=this.ht(e);switch(n.state){case 0:this.lt(e)&&t.W(n.resumeToken);break;case 1:t.Z(),t.K||t.H(),t.W(n.resumeToken);break;case 2:t.Z(),t.K||this.removeTarget(e);break;case 3:this.lt(e)&&(t.tt(),t.W(n.resumeToken));break;case 4:this.lt(e)&&(this.ft(e),t.W(n.resumeToken));break;default:Ar()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.nt.forEach((e,t)=>{this.lt(t)&&n(t)})}dt(e){const t=e.targetId,n=e.M.count,r=this.wt(t);if(r){const e=r.target;if(Ns(e))if(0===n){const n=new us(e.path);this.at(t,n,Ss.newNoDocument(n,Gr.min()))}else Dr(1===n);else this._t(t)!==n&&(this.ft(t),this.rt=this.rt.add(t))}}gt(r){const s=new Map;this.nt.forEach((e,t)=>{var n=this.wt(t);if(n){if(e.current&&Ns(n.target)){const s=new us(n.target.path);null!==this.st.get(s)||this.yt(t,s)||this.at(t,s,Ss.newNoDocument(s,r))}e.j&&(s.set(t,e.G()),e.H())}});let i=zi();this.it.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))});var e=new Yi(r,s,this.rt,this.st,i);return this.st=$i,this.it=ro(),this.rt=new ji(Br),e}ct(e,t){var n;this.lt(e)&&(n=this.yt(e,t.key)?2:0,this.ht(e).J(t.key,n),this.st=this.st.insert(t.key,t),this.it=this.it.insert(t.key,this.Tt(t.key).add(e)))}at(e,t,n){if(this.lt(e)){const r=this.ht(e);this.yt(e,t)?r.J(t,1):r.Y(t),this.it=this.it.insert(t,this.Tt(t).delete(e)),n&&(this.st=this.st.insert(t,n))}}removeTarget(e){this.nt.delete(e)}_t(e){var t=this.ht(e).G();return this.et.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}X(e){this.ht(e).X()}ht(e){let t=this.nt.get(e);return t||(t=new to,this.nt.set(e,t)),t}Tt(e){let t=this.it.get(e);return t||(t=new ji(Br),this.it=this.it.insert(e,t)),t}lt(e){var t=null!==this.wt(e);return t||Er("WatchChangeAggregator","Detected inactive target",e),t}wt(e){var t=this.nt.get(e);return t&&t.K?null:this.et.Et(e)}ft(t){this.nt.set(t,new to),this.et.getRemoteKeysForTarget(t).forEach(e=>{this.at(t,e,null)})}yt(e,t){return this.et.getRemoteKeysForTarget(e).has(t)}}function ro(){return new qi(us.comparator)}function so(){return new qi(us.comparator)}const io={asc:"ASCENDING",desc:"DESCENDING"},oo={"<":"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 ao{constructor(e,t){this.databaseId=e,this.C=t}}function ho(e,t){return e.C?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function co(e,t){return e.C?t.toBase64():t.toUint8Array()}function uo(e){return Dr(!!e),Gr.fromTimestamp((t=ns(e),new $r(t.seconds,t.nanos)));var t}function lo(e,t){return e=e,new Yr(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function fo(e){var t=Yr.fromString(e);return Dr(Lo(t)),t}function go(e,t){return lo(e.databaseId,t.path)}function mo(e,t){const n=fo(t);if(n.get(1)!==e.databaseId.projectId)throw new kr(Cr.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 kr(Cr.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new us(wo(n))}function po(e,t){return lo(e.databaseId,t)}function yo(e){var t=fo(e);return 4===t.length?Yr.emptyPath():wo(t)}function vo(e){return new Yr(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function wo(e){return Dr(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function bo(e,t,n){return{name:go(e,t),fields:n.value.mapValue.fields}}function To(e,t,n){const r=mo(e,t.name),s=uo(t.updateTime),i=new _s({mapValue:{fields:t.fields}}),o=Ss.newFoundDocument(r,s,i);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function Eo(e,t){let n;if(t instanceof ki)n={update:bo(e,t.key,t.value)};else if(t instanceof Mi)n={delete:go(e,t.key)};else if(t instanceof Ni)n={update:bo(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 Oi))return Ar();n={verify:go(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof di)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof fi)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 yi)return{fieldPath:e.field.canonicalString(),increment:t.N};throw Ar()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,ho(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:Ar()),n;var r}function Io(t,n){const e=n.currentDocument?void 0!==(s=n.currentDocument).updateTime?Ei.updateTime(uo(s.updateTime)):void 0!==s.exists?Ei.exists(s.exists):Ei.none():Ei.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 di;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new fi(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new mi(e)}else"increment"in t?n=new yi(e,t.increment):Ar();var r=Xr.fromServerFormat(t.fieldPath);return new bi(r,n)}(t,e)):[];var s;if(n.update){n.update.name;var i=mo(t,n.update.name),o=new _s({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new Zr(e.map(e=>Xr.fromServerFormat(e)))}();return new Ni(i,o,t,e,r)}return new ki(i,o,e,r)}if(n.delete){const r=mo(t,n.delete);return new Mi(r,e)}if(n.verify){const r=mo(t,n.verify);return new Oi(r,e)}return Ar()}function _o(e,t){return{documents:[po(e,t.path)]}}function So(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=po(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=po(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(Ts(e.value))return{unaryFilter:{field:ko(e.field),op:"IS_NAN"}};if(bs(e.value))return{unaryFilter:{field:ko(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Ts(e.value))return{unaryFilter:{field:ko(e.field),op:"IS_NOT_NAN"}};if(bs(e.value))return{unaryFilter:{field:ko(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:ko(e.field),op:(t=e.op,oo[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:ko(e.field),direction:(e=e.dir,io[e])}}(e))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);var i,s=(i=t.limit,e.C||as(i)?i:{value:i});return null!==s&&(n.structuredQuery.limit=s),t.startAt&&(n.structuredQuery.startAt=Do(t.startAt)),t.endAt&&(n.structuredQuery.endAt=Do(t.endAt)),n}function Ao(e){let t=yo(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let s=null;if(0<r){Dr(1===r);const l=n.from[0];l.allDescendants?s=l.collectionId:t=t.child(l.collectionId)}let i=[];n.where&&(i=function t(e){return e?void 0!==e.unaryFilter?[Ro(e)]:void 0!==e.fieldFilter?[xo(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map(e=>t(e)).reduce((e,t)=>e.concat(t)):Ar():[]}(n.where));let o=[];n.orderBy&&(o=n.orderBy.map(e=>function(e){return new js(No(e.field),function(){switch(e.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(e)));let a=null;var h;n.limit&&(a=(e=n.limit,as(h="object"==typeof e?e.value:e)?null:h));let c=null;n.startAt&&(c=Co(n.startAt));let u=null;return n.endAt&&(u=Co(n.endAt)),Hs(t,s,o,i,a,"F",c,u)}function Do(e){return{before:e.before,values:e.position}}function Co(e){var t=!!e.before,n=e.values||[];return new Us(n,t)}function ko(e){return{fieldPath:e.canonicalString()}}function No(e){return Xr.fromServerFormat(e.fieldPath)}function xo(e){return xs.create(No(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 Ro(e){switch(e.unaryFilter.op){case"IS_NAN":var t=No(e.unaryFilter.field);return xs.create(t,"==",{doubleValue:NaN});case"IS_NULL":t=No(e.unaryFilter.field);return xs.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=No(e.unaryFilter.field);return xs.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=No(e.unaryFilter.field);return xs.create(n,"!=",{nullValue:"NULL_VALUE"});default:return Ar()}}function Lo(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function Mo(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=Oo(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 Oo(t)}function Oo(e){return e+""}function Po(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 o=0;o<n;){const n=t.indexOf("",o);switch((n<0||n>r)&&Ar(),t.charAt(n+1)){case"":const r=t.substring(o,n);let e;0===i.length?e=r:(i+=r,e=i,i=""),s.push(e);break;case"":i+=t.substring(o,n),i+="\0";break;case"":i+=t.substring(o,n+1);break;default:Ar()}o=n+2}return new Yr(s)}class Fo{constructor(e,t){this.seconds=e,this.nanoseconds=t}}class Vo{constructor(e,t,n){this.ownerId=e,this.allowTabSynchronization=t,this.leaseTimestampMs=n}}Vo.store="owner",Vo.key="owner";class qo{constructor(e,t,n){this.userId=e,this.lastAcknowledgedBatchId=t,this.lastStreamToken=n}}qo.store="mutationQueues",qo.keyPath="userId";class Uo{constructor(e,t,n,r,s){this.userId=e,this.batchId=t,this.localWriteTimeMs=n,this.baseMutations=r,this.mutations=s}}Uo.store="mutations",Uo.keyPath="batchId",Uo.userMutationsIndex="userMutationsIndex",Uo.userMutationsKeyPath=["userId","batchId"];class Bo{constructor(){}static prefixForUser(e){return[e]}static prefixForPath(e,t){return[e,Mo(t)]}static key(e,t,n){return[e,Mo(t),n]}}Bo.store="documentMutations",Bo.PLACEHOLDER=new Bo;class jo{constructor(e,t){this.path=e,this.readTime=t}}class Ko{constructor(e,t){this.path=e,this.version=t}}class $o{constructor(e,t,n,r,s,i){this.unknownDocument=e,this.noDocument=t,this.document=n,this.hasCommittedMutations=r,this.readTime=s,this.parentPath=i}}$o.store="remoteDocuments",$o.readTimeIndex="readTimeIndex",$o.readTimeIndexPath="readTime",$o.collectionReadTimeIndex="collectionReadTimeIndex",$o.collectionReadTimeIndexPath=["parentPath","readTime"];class Go{constructor(e){this.byteSize=e}}Go.store="remoteDocumentGlobal",Go.key="remoteDocumentGlobalKey";class Ho{constructor(e,t,n,r,s,i,o){this.targetId=e,this.canonicalId=t,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=s,this.lastLimboFreeSnapshotVersion=i,this.query=o}}Ho.store="targets",Ho.keyPath="targetId",Ho.queryTargetsIndexName="queryTargetsIndex",Ho.queryTargetsKeyPath=["canonicalId","targetId"];class Wo{constructor(e,t,n){this.targetId=e,this.path=t,this.sequenceNumber=n}}Wo.store="targetDocuments",Wo.keyPath=["targetId","path"],Wo.documentTargetsIndex="documentTargetsIndex",Wo.documentTargetsKeyPath=["path","targetId"];class zo{constructor(e,t,n,r){this.highestTargetId=e,this.highestListenSequenceNumber=t,this.lastRemoteSnapshotVersion=n,this.targetCount=r}}zo.key="targetGlobalKey",zo.store="targetGlobal";class Qo{constructor(e,t){this.collectionId=e,this.parent=t}}Qo.store="collectionParents",Qo.keyPath=["collectionId","parent"];class Yo{constructor(e,t,n,r){this.clientId=e,this.updateTimeMs=t,this.networkEnabled=n,this.inForeground=r}}Yo.store="clientMetadata",Yo.keyPath="clientId";class Jo{constructor(e,t,n){this.bundleId=e,this.createTime=t,this.version=n}}Jo.store="bundles",Jo.keyPath="bundleId";class Xo{constructor(e,t,n){this.name=e,this.readTime=t,this.bundledQuery=n}}Xo.store="namedQueries",Xo.keyPath="name";const Zo=[qo.store,Uo.store,Bo.store,$o.store,Ho.store,Vo.store,zo.store,Wo.store,Yo.store,Go.store,Qo.store,Jo.store,Xo.store],ea="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class ta{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}class na{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 na((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 na?t:na.resolve(t)}catch(e){return na.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):na.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):na.reject(t)}static resolve(n){return new na((e,t)=>{e(n)})}static reject(n){return new na((e,t)=>{t(n)})}static waitFor(e){return new na((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=na.resolve(!1);for(const n of e)t=t.next(e=>e?na.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 ra{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.It=new Nr,this.transaction.oncomplete=()=>{this.It.resolve()},this.transaction.onabort=()=>{e.error?this.It.reject(new oa(n,e.error)):this.It.resolve()},this.transaction.onerror=e=>{var t=la(e.target.error);this.It.reject(new oa(n,t))}}static open(e,t,n,r){try{return new ra(t,e.transaction(r,n))}catch(e){throw new oa(t,e)}}get At(){return this.It.promise}abort(e){e&&this.It.reject(e),this.aborted||(Er("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}store(e){var t=this.transaction.objectStore(e);return new ha(t)}}class sa{constructor(e,t,n){this.name=e,this.version=t,this.Rt=n,12.2===sa.bt(f())&&Ir("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),ca(window.indexedDB.deleteDatabase(e)).toPromise()}static Pt(){if("object"!=typeof indexedDB)return!1;if(sa.vt())return!0;const e=f(),t=sa.bt(e),n=0<t&&t<10,r=sa.Vt(e),s=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||s)}static vt(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.St)}static Dt(e,t){return e.store(t)}static bt(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 Vt(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async Ct(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 oa(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 kr(Cr.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 kr(Cr.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 oa(i,t))},s.onupgradeneeded=e=>{Er("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.Rt.Nt(t,s.transaction,e.oldVersion,this.version).next(()=>{Er("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.kt&&(this.db.onversionchange=e=>this.kt(e)),this.db}xt(t){this.kt=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.Ct(e);const t=ra.open(this.db,e,s?"readonly":"readwrite",n),i=r(t).catch(e=>(t.abort(e),na.reject(e))).toPromise();return i.catch(()=>{}),await t.At,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 ia{constructor(e){this.$t=e,this.Ot=!1,this.Mt=null}get isDone(){return this.Ot}get Ft(){return this.Mt}set cursor(e){this.$t=e}done(){this.Ot=!0}Lt(e){this.Mt=e}delete(){return ca(this.$t.delete())}}class oa extends kr{constructor(e,t){super(Cr.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function aa(e){return"IndexedDbTransactionError"===e.name}class ha{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)),ca(n)}add(e){return Er("SimpleDb","ADD",this.store.name,e,e),ca(this.store.add(e))}get(t){return ca(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),ca(this.store.delete(e))}count(){return Er("SimpleDb","COUNT",this.store.name),ca(this.store.count())}Bt(e,t){const n=this.cursor(this.options(e,t)),r=[];return this.Ut(n,(e,t)=>{r.push(t)}).next(()=>r)}qt(e,t){Er("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.Kt=!1;var r=this.cursor(n);return this.Ut(r,(e,t,n)=>n.delete())}jt(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.Ut(r,t)}Qt(s){const e=this.cursor({});return new na((n,r)=>{e.onerror=e=>{var t=la(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()}})}Ut(e,i){const o=[];return new na((s,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new ia(t),r=i(t.primaryKey,t.value,n);if(r instanceof na){const e=r.catch(e=>(n.done(),na.reject(e)));o.push(e)}n.isDone?s():null===n.Ft?t.continue():t.continue(n.Ft)}else s()}}).next(()=>na.waitFor(o))}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.Kt?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function ca(e){return new na((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=la(e.target.error);r(t)}})}let ua=!1;function la(e){const t=sa.bt(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 kr("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 ua||(ua=!0,setTimeout(()=>{throw e},0)),e}}return e}class da extends ta{constructor(e,t){super(),this.Wt=e,this.currentSequenceNumber=t}}function fa(e,t){var n=e;return sa.Dt(n.Wt,t)}class ga{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)&&Si(s,e,n[r])}}applyToLocalView(e){for(const t of this.baseMutations)t.key.isEqual(e.key)&&Ai(t,e,this.localWriteTime);for(const n of this.mutations)n.key.isEqual(e.key)&&Ai(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(Gr.min())})}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),zi())}isEqual(e){return this.batchId===e.batchId&&jr(this.mutations,e.mutations,(e,t)=>Di(e,t))&&jr(this.baseMutations,e.baseMutations,(e,t)=>Di(e,t))}}class ma{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=Hi;var s=e.mutations;for(let i=0;i<s.length;i++)r=r.insert(s[i].key,n[i].version);return new ma(e,t,n,r)}}class pa{constructor(e,t,n,r,s=Gr.min(),i=Gr.min(),o=es.EMPTY_BYTE_STRING){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=s,this.lastLimboFreeSnapshotVersion=i,this.resumeToken=o}withSequenceNumber(e){return new pa(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new pa(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new pa(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class ya{constructor(e){this.Gt=e}}function va(e,t){if(t.document)return To(e.Gt,t.document,!!t.hasCommittedMutations);if(t.noDocument){const e=us.fromSegments(t.noDocument.path),n=Ia(t.noDocument.readTime),r=Ss.newNoDocument(e,n);return t.hasCommittedMutations?r.setHasCommittedMutations():r}if(t.unknownDocument){const e=us.fromSegments(t.unknownDocument.path),s=Ia(t.unknownDocument.version);return Ss.newUnknownDocument(e,s)}return Ar()}function wa(e,t,n){var r=ba(n),s=t.key.path.popLast().toArray();if(t.isFoundDocument()){const i={name:go(n=e.Gt,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:ho(n,e.version.toTimestamp())},o=t.hasCommittedMutations;return new $o(null,null,i,o,r,s)}if(t.isNoDocument()){const a=t.key.path.toArray(),i=Ea(t.version),h=t.hasCommittedMutations;return new $o(null,new jo(a,i),null,h,r,s)}if(t.isUnknownDocument()){const a=t.key.path.toArray(),i=Ea(t.version);return new $o(new Ko(a,i),null,null,!0,r,s)}return Ar()}function ba(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Ta(e){var t=new $r(e[0],e[1]);return Gr.fromTimestamp(t)}function Ea(e){var t=e.toTimestamp();return new Fo(t.seconds,t.nanoseconds)}function Ia(e){var t=new $r(e.seconds,e.nanoseconds);return Gr.fromTimestamp(t)}function _a(t,e){const n=(e.baseMutations||[]).map(e=>Io(t.Gt,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=>Io(t.Gt,e)),s=$r.fromMillis(e.localWriteTimeMs);return new ga(e.batchId,s,n,r)}function Sa(e){var t,n=Ia(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?Ia(e.lastLimboFreeSnapshotVersion):Gr.min();let s;return s=void 0!==e.query.documents?(Dr(1===(t=e.query).documents.length),ei(Ws(yo(t.documents[0])))):ei(Ao(e.query)),new pa(s,e.targetId,0,e.lastListenSequenceNumber,n,r,es.fromBase64String(e.resumeToken))}function Aa(e,t){var n=Ea(t.snapshotVersion),r=Ea(t.lastLimboFreeSnapshotVersion),s=(Ns(t.target)?_o:So)(e.Gt,t.target),i=t.resumeToken.toBase64();return new Ho(t.targetId,Cs(t.target),n,i,t.sequenceNumber,r,s)}function Da(e){var t=Ao({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?ti(t,t.limit,"L"):t}class Ca{getBundleMetadata(e,t){return ka(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:Ia(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return ka(e).put({bundleId:(n=t).id,createTime:Ea(uo(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return Na(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:Da(t.bundledQuery),readTime:Ia(t.readTime)};var t})}saveNamedQuery(e,t){return Na(e).put({name:(t=t).name,readTime:Ea(uo(t.readTime)),bundledQuery:t.bundledQuery})}}function ka(e){return fa(e,Jo.store)}function Na(e){return fa(e,Xo.store)}class xa{constructor(){this.zt=new Ra}addToCollectionParentIndex(e,t){return this.zt.add(t),na.resolve()}getCollectionParents(e,t){return na.resolve(this.zt.getEntries(t))}}class Ra{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new ji(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 ji(Yr.comparator)).toArray()}}class La{constructor(){this.Ht=new Ra}addToCollectionParentIndex(e,t){if(this.Ht.has(t))return na.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Ht.add(t)});r={collectionId:n,parent:Mo(r)};return Ma(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[Kr(n),""],!1,!0);return Ma(e).Bt(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(Po(t.parent))}return r})}}function Ma(e){return fa(e,Qo.store)}const Oa={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class Pa{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Pa(e,Pa.DEFAULT_COLLECTION_PERCENTILE,Pa.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function Fa(e,t,n){const r=e.store(Uo.store),s=e.store(Bo.store),i=[],o=IDBKeyRange.only(n.batchId);let a=0;const h=r.jt({range:o},(e,t,n)=>(a++,n.delete()));i.push(h.next(()=>{Dr(1===a)}));const c=[];for(const e of n.mutations){const r=Bo.key(t,e.key.path,n.batchId);i.push(s.delete(r)),c.push(e.key)}return na.waitFor(i).next(()=>c)}function Va(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}Pa.DEFAULT_COLLECTION_PERCENTILE=10,Pa.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Pa.DEFAULT=new Pa(41943040,Pa.DEFAULT_COLLECTION_PERCENTILE,Pa.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Pa.DISABLED=new Pa(-1,0,0);class qa{constructor(e,t,n,r){this.userId=e,this.k=t,this.Jt=n,this.referenceDelegate=r,this.Yt={}}static Xt(e,t,n,r){Dr(""!==e.uid);var s=e.isAuthenticated()?e.uid:"";return new qa(s,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Ba(e).jt({index:Uo.userMutationsIndex,range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(u,l,d,f){const g=ja(u),m=Ba(u);return m.add({}).next(e=>{Dr("number"==typeof e);const t=new ga(e,l,d,f),n=(s=this.k,i=this.userId,o=t,a=o.baseMutations.map(e=>Eo(s.Gt,e)),h=o.mutations.map(e=>Eo(s.Gt,e)),new Uo(i,o.batchId,o.localWriteTime.toMillis(),a,h)),r=[];var s,i,o,a,h;let c=new ji((e,t)=>Br(e.canonicalString(),t.canonicalString()));for(const u of f){const l=Bo.key(this.userId,u.key.path,e);c=c.add(u.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,Bo.PLACEHOLDER))}return c.forEach(e=>{r.push(this.Jt.addToCollectionParentIndex(u,e))}),u.addOnCommittedListener(()=>{this.Yt[e]=t.keys()}),na.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return Ba(e).get(t).next(e=>e?(Dr(e.userId===this.userId),_a(this.k,e)):null)}Zt(e,n){return this.Yt[n]?na.resolve(this.Yt[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.Yt[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let s=null;return Ba(e).jt({index:Uo.userMutationsIndex,range:n},(e,t,n)=>{t.userId===this.userId&&(Dr(t.batchId>=r),s=_a(this.k,t)),n.done()}).next(()=>s)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return Ba(e).jt({index:Uo.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 Ba(e).Bt(Uo.userMutationsIndex,t).next(e=>e.map(e=>_a(this.k,e)))}getAllMutationBatchesAffectingDocumentKey(o,a){const e=Bo.prefixForPath(this.userId,a.path),t=IDBKeyRange.lowerBound(e),h=[];return ja(o).jt({range:t},(e,t,n)=>{var[r,s,i]=e,s=Po(s);if(r===this.userId&&a.path.isEqual(s))return Ba(o).get(i).next(e=>{if(!e)throw Ar();Dr(e.userId===this.userId),h.push(_a(this.k,e))});n.done()}).next(()=>h)}getAllMutationBatchesAffectingDocumentKeys(t,e){let a=new ji(Br);const n=[];return e.forEach(o=>{var e=Bo.prefixForPath(this.userId,o.path),e=IDBKeyRange.lowerBound(e),e=ja(t).jt({range:e},(e,t,n)=>{var[r,s,i]=e,s=Po(s);r===this.userId&&o.path.isEqual(s)?a=a.add(i):n.done()});n.push(e)}),na.waitFor(n).next(()=>this.te(t,a))}getAllMutationBatchesAffectingQuery(e,t){const o=t.path,a=o.length+1,n=Bo.prefixForPath(this.userId,o),r=IDBKeyRange.lowerBound(n);let h=new ji(Br);return ja(e).jt({range:r},(e,t,n)=>{var[r,s,i]=e,s=Po(s);r===this.userId&&o.isPrefixOf(s)?s.length===a&&(h=h.add(i)):n.done()}).next(()=>this.te(e,h))}te(t,e){const n=[],r=[];return e.forEach(e=>{r.push(Ba(t).get(e).next(e=>{if(null===e)throw Ar();Dr(e.userId===this.userId),n.push(_a(this.k,e))}))}),na.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return Fa(t.Wt,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.ee(n.batchId)}),na.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}ee(e){delete this.Yt[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return na.resolve();const t=IDBKeyRange.lowerBound(Bo.prefixForUser(this.userId)),r=[];return ja(n).jt({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=Po(e[1]);r.push(t)}else n.done()}).next(()=>{Dr(0===r.length)})})}containsKey(e,t){return Ua(e,this.userId,t)}ne(e){return Ka(e).get(this.userId).next(e=>e||new qo(this.userId,-1,""))}}function Ua(e,i,t){const n=Bo.prefixForPath(i,t.path),o=n[1],r=IDBKeyRange.lowerBound(n);let a=!1;return ja(e).jt({range:r,Kt:!0},(e,t,n)=>{var[r,s]=e;r===i&&s===o&&(a=!0),n.done()}).next(()=>a)}function Ba(e){return fa(e,Uo.store)}function ja(e){return fa(e,Bo.store)}function Ka(e){return fa(e,qo.store)}class $a{constructor(e){this.se=e}next(){return this.se+=2,this.se}static ie(){return new $a(0)}static re(){return new $a(-1)}}class Ga{constructor(e,t){this.referenceDelegate=e,this.k=t}allocateTargetId(n){return this.oe(n).next(e=>{const t=new $a(e.highestTargetId);return e.highestTargetId=t.next(),this.ce(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.oe(e).next(e=>Gr.fromTimestamp(new $r(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.oe(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.oe(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.ce(t,e)))}addTargetData(t,n){return this.ae(t,n).next(()=>this.oe(t).next(e=>(e.targetCount+=1,this.ue(n,e),this.ce(t,e))))}updateTargetData(e,t){return this.ae(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>Ha(t).delete(e.targetId)).next(()=>this.oe(t)).next(e=>(Dr(0<e.targetCount),--e.targetCount,this.ce(t,e)))}removeTargets(r,s,i){let o=0;const a=[];return Ha(r).jt((e,t)=>{var n=Sa(t);n.sequenceNumber<=s&&null===i.get(n.targetId)&&(o++,a.push(this.removeTargetData(r,n)))}).next(()=>na.waitFor(a)).next(()=>o)}forEachTarget(e,r){return Ha(e).jt((e,t)=>{var n=Sa(t);r(n)})}oe(e){return Wa(e).get(zo.key).next(e=>(Dr(null!==e),e))}ce(e,t){return Wa(e).put(zo.key,t)}ae(e,t){return Ha(e).put(Aa(this.k,t))}ue(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.oe(e).next(e=>e.targetCount)}getTargetData(e,s){var t=Cs(s),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let i=null;return Ha(e).jt({range:t,index:Ho.queryTargetsIndexName},(e,t,n)=>{var r=Sa(t);ks(s,r.target)&&(i=r,n.done())}).next(()=>i)}addMatchingKeys(n,e,r){const s=[],i=za(n);return e.forEach(e=>{var t=Mo(e.path);s.push(i.put(new Wo(r,t))),s.push(this.referenceDelegate.addReference(n,r,e))}),na.waitFor(s)}removeMatchingKeys(n,e,r){const s=za(n);return na.forEach(e,e=>{var t=Mo(e.path);return na.waitFor([s.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=za(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=za(e);let s=zi();return r.jt({range:n,Kt:!0},(e,t,n)=>{var r=Po(e[1]),r=new us(r);s=s.add(r)}).next(()=>s)}containsKey(e,t){var n=Mo(t.path),n=IDBKeyRange.bound([n],[Kr(n)],!1,!0);let r=0;return za(e).jt({index:Wo.documentTargetsIndex,Kt:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}Et(e,t){return Ha(e).get(t).next(e=>e?Sa(e):null)}}function Ha(e){return fa(e,Ho.store)}function Wa(e){return fa(e,zo.store)}function za(e){return fa(e,Wo.store)}async function Qa(e){if(e.code!==Cr.FAILED_PRECONDITION||e.message!==ea)throw e;Er("LocalStore","Unexpectedly lost primary lease")}function Ya([e,t],[n,r]){var s=Br(e,n);return 0===s?Br(t,r):s}class Ja{constructor(e){this.he=e,this.buffer=new ji(Ya),this.le=0}fe(){return++this.le}de(e){var t=[e,this.fe()];if(this.buffer.size<this.he)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();Ya(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class Xa{constructor(e,t){this.garbageCollector=e,this.asyncQueue=t,this.we=!1,this._e=null}start(e){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.me(e)}stop(){this._e&&(this._e.cancel(),this._e=null)}get started(){return null!==this._e}me(e){var t=this.we?3e5:6e4;Er("LruGarbageCollector",`Garbage collection scheduled in ${t}ms`),this._e=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",t,async()=>{this._e=null,this.we=!0;try{await e.collectGarbage(this.garbageCollector)}catch(e){aa(e)?Er("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await Qa(e)}await this.me(e)})}}class Za{constructor(e,t){this.ge=e,this.params=t}calculateTargetCount(e,t){return this.ge.ye(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return na.resolve(qr.I);const n=new Ja(t);return this.ge.forEachTarget(e,e=>n.de(e.sequenceNumber)).next(()=>this.ge.pe(e,e=>n.de(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.ge.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.ge.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(Er("LruGarbageCollector","Garbage collection skipped; disabled"),na.resolve(Oa)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(Er("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),Oa):this.Te(t,n))}getCacheSize(e){return this.ge.getCacheSize(e)}Te(t,n){let r,s,i,o,a,h,c;const u=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,o=Date.now(),this.nthSequenceNumber(t,s))).next(e=>(r=e,a=Date.now(),this.removeTargets(t,r,n))).next(e=>(i=e,h=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(c=Date.now(),Tr()<=l.DEBUG&&Er("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${o-u}ms\n\tDetermined least recently used ${s} in `+(a-o)+"ms\n"+`\tRemoved ${i} targets in `+(h-a)+"ms\n"+`\tRemoved ${e} documents in `+(c-h)+"ms\n"+`Total Duration: ${c-u}ms`),na.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:e})))}}class eh{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new Za(e,t))}ye(e){const n=this.Ee(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Ee(e){let t=0;return this.pe(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}pe(e,n){return this.Ie(e,(e,t)=>n(t))}addReference(e,t,n){return th(e,n)}removeReference(e,t,n){return th(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return th(e,t)}Ae(t,n){let r=!1;return Ka(t).Qt(e=>Ua(t,e,n).next(e=>(e&&(r=!0),na.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const s=this.db.getRemoteDocumentCache().newChangeBuffer(),i=[];let o=0;return this.Ie(n,(t,e)=>{if(e<=r){const r=this.Ae(n,t).next(e=>{if(!e)return o++,s.getEntry(n,t).next(()=>(s.removeEntry(t),za(n).delete([0,Mo(t.path)])))});i.push(r)}}).next(()=>na.waitFor(i)).next(()=>s.apply(n)).next(()=>o)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return th(e,t)}Ie(e,r){const t=za(e);let s,i=qr.I;return t.jt({index:Wo.documentTargetsIndex},([e],{path:t,sequenceNumber:n})=>{0===e?(i!==qr.I&&r(new us(Po(s)),i),i=n,s=t):i=qr.I}).next(()=>{i!==qr.I&&r(new us(Po(s)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function th(e,t){return za(e).put((t=t,e=e.currentSequenceNumber,new Wo(0,Mo(t.path),e)))}class nh{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={}}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(t,n){const e=this.mapKeyFn(t),r=this.inner[e];if(void 0!==r){for(let e=0;e<r.length;e++)if(this.equalsFn(r[e][0],t))return void(r[e]=[t,n]);r.push([t,n])}else this.inner[e]=[[t,n]]}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),!0;return!1}forEach(r){Wr(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return zr(this.inner)}}class rh{constructor(){this.changes=new nh(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}getReadTime(e){var t=this.changes.get(e);return t?t.readTime:Gr.min()}addEntry(e,t){this.assertNotApplied(),this.changes.set(e.key,{document:e,readTime:t})}removeEntry(e,t=null){this.assertNotApplied(),this.changes.set(e,{document:Ss.newInvalidDocument(e),readTime:t})}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?na.resolve(n.document):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 sh{constructor(e,t){this.k=e,this.Jt=t}addEntry(e,t,n){return ah(e).put(hh(t),n)}removeEntry(e,t){const n=ah(e),r=hh(t);return n.delete(r)}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Re(t,e)))}getEntry(e,t){return ah(e).get(hh(t)).next(e=>this.be(t,e))}Pe(e,t){return ah(e).get(hh(t)).next(e=>({document:this.be(t,e),size:Va(e)}))}getEntries(e,t){let r=$i;return this.ve(e,t,(e,t)=>{var n=this.be(e,t);r=r.insert(e,n)}).next(()=>r)}Ve(e,t){let r=$i,s=new qi(us.comparator);return this.ve(e,t,(e,t)=>{var n=this.be(e,t);r=r.insert(e,n),s=s.insert(e,Va(t))}).next(()=>({documents:r,Se:s}))}ve(e,t,s){if(t.isEmpty())return na.resolve();const n=IDBKeyRange.bound(t.first().path.toArray(),t.last().path.toArray()),i=t.getIterator();let o=i.getNext();return ah(e).jt({range:n},(e,t,n)=>{for(var r=us.fromSegments(e);o&&us.comparator(o,r)<0;)s(o,null),o=i.getNext();o&&o.isEqual(r)&&(s(o,t),o=i.hasNext()?i.getNext():null),o?n.Lt(o.path.toArray()):n.done()}).next(()=>{for(;o;)s(o,null),o=i.hasNext()?i.getNext():null})}getDocumentsMatchingQuery(e,s,t){let i=$i;const o=s.path.length+1,n={};if(t.isEqual(Gr.min())){const e=s.path.toArray();n.range=IDBKeyRange.lowerBound(e)}else{const e=s.path.toArray(),i=ba(t);n.range=IDBKeyRange.lowerBound([e,i],!0),n.index=$o.collectionReadTimeIndex}return ah(e).jt(n,(e,t,n)=>{var r;e.length===o&&(r=va(this.k,t),s.path.isPrefixOf(r.key.path)?ii(s,r)&&(i=i.insert(r.key,r)):n.done())}).next(()=>i)}newChangeBuffer(e){return new ih(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return oh(e).get(Go.key).next(e=>(Dr(!!e),e))}Re(e,t){return oh(e).put(Go.key,t)}be(e,t){if(t){const e=va(this.k,t);if(!e.isNoDocument()||!e.version.isEqual(Gr.min()))return e}return Ss.newInvalidDocument(e)}}class ih extends rh{constructor(e,t){super(),this.De=e,this.trackRemovals=t,this.Ce=new nh(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(i){const o=[];let a=0,h=new ji((e,t)=>Br(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.Ce.get(e);if(t.document.isValidDocument()){var r=wa(this.De.k,t.document,this.getReadTime(e));h=h.add(e.path.popLast());var s=Va(r);a+=s-n,o.push(this.De.addEntry(i,e,r))}else if(a-=n,this.trackRemovals){const a=wa(this.De.k,Ss.newNoDocument(e,Gr.min()),this.getReadTime(e));o.push(this.De.addEntry(i,e,a))}else o.push(this.De.removeEntry(i,e))}),h.forEach(e=>{o.push(this.De.Jt.addToCollectionParentIndex(i,e))}),o.push(this.De.updateMetadata(i,a)),na.waitFor(o)}getFromCache(e,t){return this.De.Pe(e,t).next(e=>(this.Ce.set(t,e.size),e.document))}getAllFromCache(e,t){return this.De.Ve(e,t).next(({documents:e,Se:t})=>(t.forEach((e,t)=>{this.Ce.set(e,t)}),e))}}function oh(e){return fa(e,Go.store)}function ah(e){return fa(e,$o.store)}function hh(e){return e.path.toArray()}class ch{constructor(e){this.k=e}Nt(t,n,e,r){Dr(e<r&&0<=e&&r<=11);const s=new ra("createOrUpgrade",n);var i;e<1&&1<=r&&(t.createObjectStore(Vo.store),(i=t).createObjectStore(qo.store,{keyPath:qo.keyPath}),i.createObjectStore(Uo.store,{keyPath:Uo.keyPath,autoIncrement:!0}).createIndex(Uo.userMutationsIndex,Uo.userMutationsKeyPath,{unique:!0}),i.createObjectStore(Bo.store),uh(t),t.createObjectStore($o.store));let o=na.resolve();return e<3&&3<=r&&(0!==e&&((i=t).deleteObjectStore(Wo.store),i.deleteObjectStore(Ho.store),i.deleteObjectStore(zo.store),uh(t)),o=o.next(()=>function(){const e=s.store(zo.store),t=new zo(0,0,Gr.min().toTimestamp(),0);return e.put(zo.key,t)}())),e<4&&4<=r&&(0!==e&&(o=o.next(()=>function(r,s){return s.store(Uo.store).Bt().next(e=>{r.deleteObjectStore(Uo.store),r.createObjectStore(Uo.store,{keyPath:Uo.keyPath,autoIncrement:!0}).createIndex(Uo.userMutationsIndex,Uo.userMutationsKeyPath,{unique:!0});const t=s.store(Uo.store),n=e.map(e=>t.put(e));return na.waitFor(n)})}(t,s))),o=o.next(()=>{t.createObjectStore(Yo.store,{keyPath:Yo.keyPath})})),e<5&&5<=r&&(o=o.next(()=>this.Ne(s))),e<6&&6<=r&&(o=o.next(()=>(t.createObjectStore(Go.store),this.ke(s)))),e<7&&7<=r&&(o=o.next(()=>this.xe(s))),e<8&&8<=r&&(o=o.next(()=>this.$e(t,s))),e<9&&9<=r&&(o=o.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges"),function(){const e=n.objectStore($o.store);e.createIndex($o.readTimeIndex,$o.readTimeIndexPath,{unique:!1}),e.createIndex($o.collectionReadTimeIndex,$o.collectionReadTimeIndexPath,{unique:!1})}()})),e<10&&10<=r&&(o=o.next(()=>this.Oe(s))),e<11&&11<=r&&(o=o.next(()=>{t.createObjectStore(Jo.store,{keyPath:Jo.keyPath}),t.createObjectStore(Xo.store,{keyPath:Xo.keyPath})})),o}ke(t){let n=0;return t.store($o.store).jt((e,t)=>{n+=Va(t)}).next(()=>{var e=new Go(n);return t.store(Go.store).put(Go.key,e)})}Ne(r){const e=r.store(qo.store),t=r.store(Uo.store);return e.Bt().next(e=>na.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.Bt(Uo.userMutationsIndex,e).next(e=>na.forEach(e,e=>{Dr(e.userId===n.userId);var t=_a(this.k,e);return Fa(r,n.userId,t).next(()=>{})}))}))}xe(e){const o=e.store(Wo.store),t=e.store($o.store);return e.store(zo.store).get(zo.key).next(s=>{const i=[];return t.jt((e,t)=>{const n=new Yr(e),r=[0,Mo(n)];i.push(o.get(r).next(e=>e?na.resolve():(e=>o.put(new Wo(0,Mo(e),s.highestListenSequenceNumber)))(n)))}).next(()=>na.waitFor(i))})}$e(e,t){e.createObjectStore(Qo.store,{keyPath:Qo.keyPath});const n=t.store(Qo.store),r=new Ra,s=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Mo(r)})}};return t.store($o.store).jt({Kt:!0},(e,t)=>{const n=new Yr(e);return s(n.popLast())}).next(()=>t.store(Bo.store).jt({Kt:!0},([,e],t)=>{const n=Po(e);return s(n.popLast())}))}Oe(e){const r=e.store(Ho.store);return r.jt((e,t)=>{var n=Sa(t),n=Aa(this.k,n);return r.put(n)})}}function uh(e){e.createObjectStore(Wo.store,{keyPath:Wo.keyPath}).createIndex(Wo.documentTargetsIndex,Wo.documentTargetsKeyPath,{unique:!0}),e.createObjectStore(Ho.store,{keyPath:Ho.keyPath}).createIndex(Ho.queryTargetsIndexName,Ho.queryTargetsKeyPath,{unique:!0}),e.createObjectStore(zo.store)}const lh="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 dh{constructor(e,t,n,r,s,i,o,a,h,c){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Me=s,this.window=i,this.document=o,this.Fe=h,this.Le=c,this.Be=null,this.Ue=!1,this.isPrimary=!1,this.networkEnabled=!0,this.qe=null,this.inForeground=!1,this.Ke=null,this.je=null,this.Qe=Number.NEGATIVE_INFINITY,this.We=e=>Promise.resolve(),!dh.Pt())throw new kr(Cr.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new eh(this,r),this.Ge=t+"main",this.k=new ya(a),this.ze=new sa(this.Ge,11,new ch(this.k)),this.He=new Ga(this.referenceDelegate,this.k),this.Jt=new La,this.Je=(t=this.k,a=this.Jt,new sh(t,a)),this.Ye=new Ca,this.window&&this.window.localStorage?this.Xe=this.window.localStorage:(this.Xe=null,!1===c&&Ir("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.Ze().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new kr(Cr.FAILED_PRECONDITION,lh);return this.tn(),this.en(),this.nn(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.He.getHighestSequenceNumber(e))}).then(e=>{this.Be=new qr(e,this.Fe)}).then(()=>{this.Ue=!0}).catch(e=>(this.ze&&this.ze.close(),Promise.reject(e)))}sn(t){return this.We=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.ze.xt(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Me.enqueueAndForget(async()=>{this.started&&await this.Ze()}))}Ze(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>gh(t).put(new Yo(this.clientId,Date.now(),this.networkEnabled,this.inForeground)).next(()=>{if(this.isPrimary)return this.rn(t).next(e=>{e||(this.isPrimary=!1,this.Me.enqueueRetryable(()=>this.We(!1)))})}).next(()=>this.on(t)).next(e=>this.isPrimary&&!e?this.cn(t).next(()=>!1):!!e&&this.an(t).next(()=>!0))).catch(e=>{if(aa(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.Me.enqueueRetryable(()=>this.We(e)),this.isPrimary=e})}rn(e){return fh(e).get(Vo.key).next(e=>na.resolve(this.un(e)))}hn(e){return gh(e).delete(this.clientId)}async ln(){if(this.isPrimary&&!this.fn(this.Qe,18e5)){this.Qe=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=fa(e,Yo.store);return r.Bt().next(e=>{const t=this.dn(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return na.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.Xe)for(const t of e)this.Xe.removeItem(this.wn(t.clientId))}}nn(){this.je=this.Me.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Ze().then(()=>this.ln()).then(()=>this.nn()))}un(e){return!!e&&e.ownerId===this.clientId}on(t){return this.Le?na.resolve(!0):fh(t).get(Vo.key).next(e=>{if(null!==e&&this.fn(e.leaseTimestampMs,5e3)&&!this._n(e.ownerId)){if(this.un(e)&&this.networkEnabled)return!0;if(!this.un(e)){if(!e.allowTabSynchronization)throw new kr(Cr.FAILED_PRECONDITION,lh);return!1}}return!(!this.networkEnabled||!this.inForeground)||gh(t).Bt().next(e=>void 0===this.dn(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.Ue=!1,this.mn(),this.je&&(this.je.cancel(),this.je=null),this.gn(),this.yn(),await this.ze.runTransaction("shutdown","readwrite",[Vo.store,Yo.store],e=>{const t=new da(e,qr.I);return this.cn(t).next(()=>this.hn(t))}),this.ze.close(),this.pn()}dn(e,t){return e.filter(e=>this.fn(e.updateTimeMs,t)&&!this._n(e.clientId))}Tn(){return this.runTransaction("getActiveClients","readonly",e=>gh(e).Bt().next(e=>this.dn(e,18e5).map(e=>e.clientId)))}get started(){return this.Ue}getMutationQueue(e){return qa.Xt(e,this.k,this.Jt,this.referenceDelegate)}getTargetCache(){return this.He}getRemoteDocumentCache(){return this.Je}getIndexManager(){return this.Jt}getBundleCache(){return this.Ye}runTransaction(t,n,r){Er("IndexedDbPersistence","Starting transaction:",t);let s;return this.ze.runTransaction(t,"readonly"===n?"readonly":"readwrite",Zo,e=>(s=new da(e,this.Be?this.Be.next():qr.I),"readwrite-primary"===n?this.rn(s).next(e=>!!e||this.on(s)).next(e=>{if(!e)throw Ir(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Me.enqueueRetryable(()=>this.We(!1)),new kr(Cr.FAILED_PRECONDITION,ea);return r(s)}).next(e=>this.an(s).next(()=>e)):this.En(s).next(()=>r(s)))).then(e=>(s.raiseOnCommittedEvent(),e))}En(e){return fh(e).get(Vo.key).next(e=>{if(null!==e&&this.fn(e.leaseTimestampMs,5e3)&&!this._n(e.ownerId)&&!this.un(e)&&!(this.Le||this.allowTabSynchronization&&e.allowTabSynchronization))throw new kr(Cr.FAILED_PRECONDITION,lh)})}an(e){var t=new Vo(this.clientId,this.allowTabSynchronization,Date.now());return fh(e).put(Vo.key,t)}static Pt(){return sa.Pt()}cn(e){const t=fh(e);return t.get(Vo.key).next(e=>this.un(e)?(Er("IndexedDbPersistence","Releasing primary lease."),t.delete(Vo.key)):na.resolve())}fn(e,t){var n=Date.now();return!(e<n-t||n<e&&(Ir(`Detected an update time that is in the future: ${e} > ${n}`),1))}tn(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Ke=()=>{this.Me.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Ze()))},this.document.addEventListener("visibilitychange",this.Ke),this.inForeground="visible"===this.document.visibilityState)}gn(){this.Ke&&(this.document.removeEventListener("visibilitychange",this.Ke),this.Ke=null)}en(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.qe=()=>{this.mn(),s()&&navigator.appVersion.match(/Version\/1[45]/)&&this.Me.enterRestrictedMode(!0),this.Me.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.qe))}yn(){this.qe&&(this.window.removeEventListener("pagehide",this.qe),this.qe=null)}_n(e){var t;try{var n=null!==(null===(t=this.Xe)||void 0===t?void 0:t.getItem(this.wn(e)));return Er("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return Ir("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}mn(){if(this.Xe)try{this.Xe.setItem(this.wn(this.clientId),String(Date.now()))}catch(e){Ir("Failed to set zombie client id.",e)}}pn(){if(this.Xe)try{this.Xe.removeItem(this.wn(this.clientId))}catch(e){}}wn(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function fh(e){return fa(e,Vo.store)}function gh(e){return fa(e,Yo.store)}function mh(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class ph{constructor(e,t){this.progress=e,this.In=t}}class yh{constructor(e,t,n){this.Je=e,this.An=t,this.Jt=n}Rn(t,n){return this.An.getAllMutationBatchesAffectingDocumentKey(t,n).next(e=>this.bn(t,n,e))}bn(e,t,n){return this.Je.getEntry(e,t).next(e=>{for(const t of n)t.applyToLocalView(e);return e})}Pn(e,n){e.forEach((e,t)=>{for(const e of n)e.applyToLocalView(t)})}vn(t,e){return this.Je.getEntries(t,e).next(e=>this.Vn(t,e).next(()=>e))}Vn(e,t){return this.An.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>this.Pn(t,e))}getDocumentsMatchingQuery(e,t,n){return r=t,us.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.Sn(e,t.path):Xs(t)?this.Dn(e,t,n):this.Cn(e,t,n);var r}Sn(e,t){return this.Rn(e,new us(t)).next(e=>{let t=Gi;return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}Dn(r,s,i){const o=s.collectionGroup;let a=Gi;return this.Jt.getCollectionParents(r,o).next(e=>na.forEach(e,e=>{var t,n=(t=s,e=e.child(o),new Gs(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.Cn(r,n,i).next(e=>{e.forEach((e,t)=>{a=a.insert(e,t)})})}).next(()=>a))}Cn(t,n,e){let s,i;return this.Je.getDocumentsMatchingQuery(t,n,e).next(e=>(s=e,this.An.getAllMutationBatchesAffectingQuery(t,n))).next(e=>(i=e,this.Nn(t,i,s).next(t=>{s=t;for(const t of i)for(const r of t.mutations){var n=r.key;let e=s.get(n);null==e&&(e=Ss.newInvalidDocument(n),s=s.insert(n,e)),Ai(r,e,t.localWriteTime),e.isFoundDocument()||(s=s.remove(n))}}))).next(()=>(s.forEach((e,t)=>{ii(n,t)||(s=s.remove(e))}),s))}Nn(e,t,n){let r=zi();for(const e of t)for(const t of e.mutations)t instanceof Ni&&null===n.get(t.key)&&(r=r.add(t.key));let s=n;return this.Je.getEntries(e,r).next(e=>(e.forEach((e,t)=>{t.isFoundDocument()&&(s=s.insert(e,t))}),s))}}class vh{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.kn=n,this.xn=r}static $n(e,t){let n=zi(),r=zi();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 vh(e,t.fromCache,n,r)}}class wh{On(e){this.Mn=e}getDocumentsMatchingQuery(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(Gr.min())?this.Fn(t,r):this.Mn.vn(t,i).next(e=>{const n=this.Ln(r,e);return(zs(r)||Qs(r))&&this.Bn(r.limitType,n,i,s)?this.Fn(t,r):(Tr()<=l.DEBUG&&Er("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),si(r)),this.Mn.getDocumentsMatchingQuery(t,r,s).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t)))});var e}Ln(n,e){let r=new ji(oi(n));return e.forEach((e,t)=>{ii(n,t)&&(r=r.add(t))}),r}Bn(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))}Fn(e,t){return Tr()<=l.DEBUG&&Er("QueryEngine","Using full collection scan to execute query:",si(t)),this.Mn.getDocumentsMatchingQuery(e,t,Gr.min())}}class bh{constructor(e,t,n,r){this.persistence=e,this.Un=t,this.k=r,this.qn=new qi(Br),this.Kn=new nh(e=>Cs(e),ks),this.jn=Gr.min(),this.An=e.getMutationQueue(n),this.Qn=e.getRemoteDocumentCache(),this.He=e.getTargetCache(),this.Wn=new yh(this.Qn,this.An,this.persistence.getIndexManager()),this.Ye=e.getBundleCache(),this.Un.On(this.Wn)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.qn))}}function Th(e,t,n,r){return new bh(e,t,n,r)}async function Eh(e,t){const n=e;let r=n.An,o=n.Wn;var s=await n.persistence.runTransaction("Handle user change","readonly",s=>{let i;return n.An.getAllMutationBatches(s).next(e=>(i=e,r=n.persistence.getMutationQueue(t),o=new yh(n.Qn,r,n.persistence.getIndexManager()),r.getAllMutationBatches(s))).next(e=>{const t=[],n=[];let r=zi();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 o.vn(s,r).next(e=>({Gn:e,removedBatchIds:t,addedBatchIds:n}))})});return n.An=r,n.Wn=o,n.Un.On(n.Wn),s}function Ih(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.He.getLastRemoteSnapshotVersion(e))}function _h(e,c){const u=e,l=c.snapshotVersion;let d=u.qn;return u.persistence.runTransaction("Apply remote event","readwrite-primary",a=>{const e=u.Qn.newChangeBuffer({trackRemovals:!0});d=u.qn;const h=[];c.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){h.push(u.He.removeMatchingKeys(a,t.removedDocuments,n).next(()=>u.He.addMatchingKeys(a,t.addedDocuments,n)));let e=r.withSequenceNumber(a.currentSequenceNumber);var s,i,o;c.targetMismatches.has(n)?e=e.withResumeToken(es.EMPTY_BYTE_STRING,Gr.min()).withLastLimboFreeSnapshotVersion(Gr.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,l)),d=d.insert(n,e),s=r,i=e,o=t,0!==s.resumeToken.approximateByteSize()&&!(3e8<=i.snapshotVersion.toMicroseconds()-s.snapshotVersion.toMicroseconds()||0<o.addedDocuments.size+o.modifiedDocuments.size+o.removedDocuments.size)||h.push(u.He.updateTargetData(a,e))}});let t=$i;if(c.documentUpdates.forEach((e,t)=>{c.resolvedLimboDocuments.has(e)&&h.push(u.persistence.referenceDelegate.updateLimboDocument(a,e))}),h.push(Sh(a,e,c.documentUpdates,l,void 0).next(e=>{t=e})),!l.isEqual(Gr.min())){const c=u.He.getLastRemoteSnapshotVersion(a).next(e=>u.He.setTargetsMetadata(a,a.currentSequenceNumber,l));h.push(c)}return na.waitFor(h).next(()=>e.apply(a)).next(()=>u.Wn.Vn(a,t)).next(()=>t)}).then(e=>(u.qn=d,e))}function Sh(e,o,t,a,h){let n=zi();return t.forEach(e=>n=n.add(e)),o.getEntries(e,n).next(s=>{let i=$i;return t.forEach((e,t)=>{const n=s.get(e),r=(null==h?void 0:h.get(e))||a;t.isNoDocument()&&t.version.isEqual(Gr.min())?(o.removeEntry(e,r),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(o.addEntry(t,r),i=i.insert(e,t)):Er("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),i})}function Ah(e,r){const s=e;return s.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return s.He.getTargetData(t,r).next(e=>e?(n=e,na.resolve(n)):s.He.allocateTargetId(t).next(e=>(n=new pa(r,e,0,t.currentSequenceNumber),s.He.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=s.qn.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(s.qn=s.qn.insert(e.targetId,e),s.Kn.set(r,e.targetId)),e})}async function Dh(e,t,n){const r=e,s=r.qn.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(!aa(e))throw e;Er("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.qn=r.qn.remove(t),r.Kn.delete(s.target)}function Ch(e,n,r){const s=e;let i=Gr.min(),o=zi();return s.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,s=r.Kn.get(n);return void 0!==s?na.resolve(r.qn.get(s)):r.He.getTargetData(t,n)}(s,t,ei(n)).next(e=>{if(e)return i=e.lastLimboFreeSnapshotVersion,s.He.getMatchingKeysForTargetId(t,e.targetId).next(e=>{o=e})}).next(()=>s.Un.getDocumentsMatchingQuery(t,n,r?i:Gr.min(),r?o:zi())).next(e=>({documents:e,zn:o})))}function kh(e,t){const n=e,r=n.He,s=n.qn.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 Nh(e){const n=e;return n.persistence.runTransaction("Get new document changes","readonly",e=>function(e,t,n){const r=e;let s=$i,i=ba(n);const o=ah(t),a=IDBKeyRange.lowerBound(i,!0);return o.jt({index:$o.readTimeIndex,range:a},(e,t)=>{var n=va(r.k,t);s=s.insert(n.key,n),i=t.readTime}).next(()=>({In:s,readTime:Ta(i)}))}(n.Qn,e,n.jn)).then(({In:e,readTime:t})=>(n.jn=t,e))}class xh{constructor(e){this.k=e,this.Xn=new Map,this.Zn=new Map}getBundleMetadata(e,t){return na.resolve(this.Xn.get(t))}saveBundleMetadata(e,t){return this.Xn.set(t.id,{id:t.id,version:t.version,createTime:uo(t.createTime)}),na.resolve()}getNamedQuery(e,t){return na.resolve(this.Zn.get(t))}saveNamedQuery(e,t){return this.Zn.set(t.name,{name:(t=t).name,query:Da(t.bundledQuery),readTime:uo(t.readTime)}),na.resolve()}}class Rh{constructor(){this.ts=new ji(Lh.es),this.ns=new ji(Lh.ss)}isEmpty(){return this.ts.isEmpty()}addReference(e,t){var n=new Lh(e,t);this.ts=this.ts.add(n),this.ns=this.ns.add(n)}rs(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.os(new Lh(e,t))}cs(e,t){e.forEach(e=>this.removeReference(e,t))}us(e){const t=new us(new Yr([])),n=new Lh(t,e),r=new Lh(t,e+1),s=[];return this.ns.forEachInRange([n,r],e=>{this.os(e),s.push(e.key)}),s}hs(){this.ts.forEach(e=>this.os(e))}os(e){this.ts=this.ts.delete(e),this.ns=this.ns.delete(e)}ls(e){var t=new us(new Yr([])),n=new Lh(t,e),t=new Lh(t,e+1);let r=zi();return this.ns.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new Lh(e,0),t=this.ts.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class Lh{constructor(e,t){this.key=e,this.fs=t}static es(e,t){return us.comparator(e.key,t.key)||Br(e.fs,t.fs)}static ss(e,t){return Br(e.fs,t.fs)||us.comparator(e.key,t.key)}}class Mh{constructor(e,t){this.Jt=e,this.referenceDelegate=t,this.An=[],this.ds=1,this.ws=new ji(Lh.es)}checkEmpty(e){return na.resolve(0===this.An.length)}addMutationBatch(e,t,n,r){var s=this.ds;this.ds++,0<this.An.length&&this.An[this.An.length-1];var i=new ga(s,t,n,r);this.An.push(i);for(const t of r)this.ws=this.ws.add(new Lh(t.key,s)),this.Jt.addToCollectionParentIndex(e,t.key.path.popLast());return na.resolve(i)}lookupMutationBatch(e,t){return na.resolve(this._s(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.gs(t+1),n=n<0?0:n;return na.resolve(this.An.length>n?this.An[n]:null)}getHighestUnacknowledgedBatchId(){return na.resolve(0===this.An.length?-1:this.ds-1)}getAllMutationBatches(e){return na.resolve(this.An.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Lh(t,0),r=new Lh(t,Number.POSITIVE_INFINITY),s=[];return this.ws.forEachInRange([n,r],e=>{var t=this._s(e.fs);s.push(t)}),na.resolve(s)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new ji(Br);return t.forEach(e=>{var t=new Lh(e,0),n=new Lh(e,Number.POSITIVE_INFINITY);this.ws.forEachInRange([t,n],e=>{r=r.add(e.fs)})}),na.resolve(this.ys(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let s=n;us.isDocumentKey(s)||(s=s.child(""));var i=new Lh(new us(s),0);let o=new ji(Br);return this.ws.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.fs)),!0)},i),na.resolve(this.ys(o))}ys(e){const n=[];return e.forEach(e=>{var t=this._s(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){Dr(0===this.ps(r.batchId,"removed")),this.An.shift();let s=this.ws;return na.forEach(r.mutations,e=>{var t=new Lh(e.key,r.batchId);return s=s.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.ws=s})}ee(e){}containsKey(e,t){var n=new Lh(t,0),n=this.ws.firstAfterOrEqual(n);return na.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.An.length,na.resolve()}ps(e,t){return this.gs(e)}gs(e){return 0===this.An.length?0:e-this.An[0].batchId}_s(e){var t=this.gs(e);return t<0||t>=this.An.length?null:this.An[t]}}class Oh{constructor(e,t){this.Jt=e,this.Ts=t,this.docs=new qi(us.comparator),this.size=0}addEntry(e,t,n){const r=t.key,s=this.docs.get(r),i=s?s.size:0,o=this.Ts(t);return this.docs=this.docs.insert(r,{document:t.mutableCopy(),size:o,readTime:n}),this.size+=o-i,this.Jt.addToCollectionParentIndex(e,r.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 na.resolve(n?n.document.mutableCopy():Ss.newInvalidDocument(t))}getEntries(e,t){let n=$i;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Ss.newInvalidDocument(e))}),na.resolve(n)}getDocumentsMatchingQuery(e,t,n){let r=$i;const s=new us(t.path.child("")),i=this.docs.getIteratorFrom(s);for(;i.hasNext();){const{key:e,value:{document:s,readTime:o}}=i.getNext();if(!t.path.isPrefixOf(e.path))break;o.compareTo(n)<=0||ii(t,s)&&(r=r.insert(s.key,s.mutableCopy()))}return na.resolve(r)}Es(e,t){return na.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new Ph(this)}getSize(e){return na.resolve(this.size)}}class Ph extends rh{constructor(e){super(),this.De=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.document.isValidDocument()?r.push(this.De.addEntry(n,t.document,this.getReadTime(e))):this.De.removeEntry(e)}),na.waitFor(r)}getFromCache(e,t){return this.De.getEntry(e,t)}getAllFromCache(e,t){return this.De.getEntries(e,t)}}class Fh{constructor(e){this.persistence=e,this.Is=new nh(e=>Cs(e),ks),this.lastRemoteSnapshotVersion=Gr.min(),this.highestTargetId=0,this.As=0,this.Rs=new Rh,this.targetCount=0,this.bs=$a.ie()}forEachTarget(e,n){return this.Is.forEach((e,t)=>n(t)),na.resolve()}getLastRemoteSnapshotVersion(e){return na.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return na.resolve(this.As)}allocateTargetId(e){return this.highestTargetId=this.bs.next(),na.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.As&&(this.As=t),na.resolve()}ae(e){this.Is.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.bs=new $a(t),this.highestTargetId=t),e.sequenceNumber>this.As&&(this.As=e.sequenceNumber)}addTargetData(e,t){return this.ae(t),this.targetCount+=1,na.resolve()}updateTargetData(e,t){return this.ae(t),na.resolve()}removeTargetData(e,t){return this.Is.delete(t.target),this.Rs.us(t.targetId),--this.targetCount,na.resolve()}removeTargets(n,r,s){let i=0;const o=[];return this.Is.forEach((e,t)=>{t.sequenceNumber<=r&&null===s.get(t.targetId)&&(this.Is.delete(e),o.push(this.removeMatchingKeysForTargetId(n,t.targetId)),i++)}),na.waitFor(o).next(()=>i)}getTargetCount(e){return na.resolve(this.targetCount)}getTargetData(e,t){var n=this.Is.get(t)||null;return na.resolve(n)}addMatchingKeys(e,t,n){return this.Rs.rs(t,n),na.resolve()}removeMatchingKeys(t,e,n){this.Rs.cs(e,n);const r=this.persistence.referenceDelegate,s=[];return r&&e.forEach(e=>{s.push(r.markPotentiallyOrphaned(t,e))}),na.waitFor(s)}removeMatchingKeysForTargetId(e,t){return this.Rs.us(t),na.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Rs.ls(t);return na.resolve(n)}containsKey(e,t){return na.resolve(this.Rs.containsKey(t))}}class Vh{constructor(e,t){var n;this.Ps={},this.Be=new qr(0),this.Ue=!1,this.Ue=!0,this.referenceDelegate=e(this),this.He=new Fh(this),this.Jt=new xa,this.Je=(n=this.Jt,e=e=>this.referenceDelegate.vs(e),new Oh(n,e)),this.k=new ya(t),this.Ye=new xh(this.k)}start(){return Promise.resolve()}shutdown(){return this.Ue=!1,Promise.resolve()}get started(){return this.Ue}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(){return this.Jt}getMutationQueue(e){let t=this.Ps[e.toKey()];return t||(t=new Mh(this.Jt,this.referenceDelegate),this.Ps[e.toKey()]=t),t}getTargetCache(){return this.He}getRemoteDocumentCache(){return this.Je}getBundleCache(){return this.Ye}runTransaction(e,t,n){Er("MemoryPersistence","Starting transaction:",e);const r=new qh(this.Be.next());return this.referenceDelegate.Vs(),n(r).next(e=>this.referenceDelegate.Ss(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ds(t,n){return na.or(Object.values(this.Ps).map(e=>()=>e.containsKey(t,n)))}}class qh extends ta{constructor(e){super(),this.currentSequenceNumber=e}}class Uh{constructor(e){this.persistence=e,this.Cs=new Rh,this.Ns=null}static ks(e){return new Uh(e)}get xs(){if(this.Ns)return this.Ns;throw Ar()}addReference(e,t,n){return this.Cs.addReference(n,t),this.xs.delete(n.toString()),na.resolve()}removeReference(e,t,n){return this.Cs.removeReference(n,t),this.xs.add(n.toString()),na.resolve()}markPotentiallyOrphaned(e,t){return this.xs.add(t.toString()),na.resolve()}removeTarget(e,t){this.Cs.us(t.targetId).forEach(e=>this.xs.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.xs.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Vs(){this.Ns=new Set}Ss(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return na.forEach(this.xs,e=>{const t=us.fromPath(e);return this.$s(n,t).next(e=>{e||r.removeEntry(t)})}).next(()=>(this.Ns=null,r.apply(n)))}updateLimboDocument(e,t){return this.$s(e,t).next(e=>{e?this.xs.delete(t.toString()):this.xs.add(t.toString())})}vs(e){return 0}$s(e,t){return na.or([()=>na.resolve(this.Cs.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ds(e,t)])}}function Bh(e,t){return`firestore_clients_${e}_${t}`}function jh(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 $h{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Os(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 kr(r.error.code,r.error.message))),i?new $h(e,t,r.state,s):(Ir("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}Ms(){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 Gh{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Os(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 kr(n.error.code,n.error.message))),s?new Gh(e,n.state,r):(Ir("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}Ms(){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 Hh{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Os(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,s=Qi;for(let i=0;r&&i<n.activeTargetIds.length;++i)r=cs(n.activeTargetIds[i]),s=s.add(n.activeTargetIds[i]);return r?new Hh(e,s):(Ir("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class Wh{constructor(e,t){this.clientId=e,this.onlineState=t}static Os(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new Wh(t.clientId,t.onlineState):(Ir("SharedClientState",`Failed to parse online state: ${e}`),null)}}class zh{constructor(){this.activeTargetIds=Qi}Fs(e){this.activeTargetIds=this.activeTargetIds.add(e)}Ls(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Ms(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class Qh{constructor(e,t,n,r,s){this.window=e,this.Me=t,this.persistenceKey=n,this.Bs=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Us=this.qs.bind(this),this.Ks=new qi(Br),this.started=!1,this.js=[];var i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=s,this.Qs=Bh(this.persistenceKey,this.Bs),this.Ws=`firestore_sequence_number_${this.persistenceKey}`,this.Ks=this.Ks.insert(this.Bs,new zh),this.Gs=new RegExp(`^firestore_clients_${i}_([^_]*)$`),this.zs=new RegExp(`^firestore_mutations_${i}_(\\d+)(?:_(.*))?$`),this.Hs=new RegExp(`^firestore_targets_${i}_(\\d+)$`),this.Js=`firestore_online_state_${this.persistenceKey}`,this.Ys=`firestore_bundle_loaded_${this.persistenceKey}`,this.window.addEventListener("storage",this.Us)}static Pt(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.Tn();for(const n of e)if(n!==this.Bs){const e=this.getItem(Bh(this.persistenceKey,n));var t;!e||(t=Hh.Os(n,e))&&(this.Ks=this.Ks.insert(t.clientId,t))}this.Xs();const n=this.storage.getItem(this.Js);if(n){const e=this.Zs(n);e&&this.ti(e)}for(const e of this.js)this.qs(e);this.js=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Ws,JSON.stringify(e))}getAllActiveQueryTargets(){return this.ei(this.Ks)}isActiveQueryTarget(n){let r=!1;return this.Ks.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.ni(e,"pending")}updateMutationState(e,t,n){this.ni(e,t,n),this.si(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(Kh(this.persistenceKey,e)))||(n=Gh.Os(e,n))&&(t=n.state)),this.ii.Fs(e),this.Xs(),t}removeLocalQueryTarget(e){this.ii.Ls(e),this.Xs()}isLocalQueryTarget(e){return this.ii.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(Kh(this.persistenceKey,e))}updateQueryState(e,t,n){this.ri(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.si(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.oi(e)}notifyBundleLoaded(){this.ci()}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Us),this.removeItem(this.Qs),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)}qs(e){const r=e;r.storageArea===this.storage&&(Er("SharedClientState","EVENT",r.key,r.newValue),r.key!==this.Qs?this.Me.enqueueRetryable(async()=>{if(this.started){if(null!==r.key)if(this.Gs.test(r.key)){if(null==r.newValue){var e=this.ai(r.key);return this.ui(e,null)}e=this.hi(r.key,r.newValue);if(e)return this.ui(e.clientId,e)}else if(this.zs.test(r.key)){if(null!==r.newValue){var t=this.li(r.key,r.newValue);if(t)return this.fi(t)}}else if(this.Hs.test(r.key)){if(null!==r.newValue){t=this.di(r.key,r.newValue);if(t)return this.wi(t)}}else if(r.key===this.Js){if(null!==r.newValue){var n=this.Zs(r.newValue);if(n)return this.ti(n)}}else if(r.key===this.Ws){n=function(e){let t=qr.I;if(null!=e)try{var n=JSON.parse(e);Dr("number"==typeof n),t=n}catch(e){Ir("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(r.newValue);n!==qr.I&&this.sequenceNumberHandler(n)}else if(r.key===this.Ys)return this.syncEngine._i()}else this.js.push(r)}):Ir("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get ii(){return this.Ks.get(this.Bs)}Xs(){this.setItem(this.Qs,this.ii.Ms())}ni(e,t,n){const r=new $h(this.currentUser,e,t,n),s=jh(this.persistenceKey,this.currentUser,e);this.setItem(s,r.Ms())}si(e){var t=jh(this.persistenceKey,this.currentUser,e);this.removeItem(t)}oi(e){var t={clientId:this.Bs,onlineState:e};this.storage.setItem(this.Js,JSON.stringify(t))}ri(e,t,n){const r=Kh(this.persistenceKey,e),s=new Gh(e,t,n);this.setItem(r,s.Ms())}ci(){this.setItem(this.Ys,"value-not-used")}ai(e){var t=this.Gs.exec(e);return t?t[1]:null}hi(e,t){var n=this.ai(e);return Hh.Os(n,t)}li(e,t){var n=this.zs.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return $h.Os(new vr(n),r,t)}di(e,t){var n=this.Hs.exec(e),n=Number(n[1]);return Gh.Os(n,t)}Zs(e){return Wh.Os(e)}async fi(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.mi(e.batchId,e.state,e.error);Er("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}wi(e){return this.syncEngine.gi(e.targetId,e.state,e.error)}ui(e,t){const n=t?this.Ks.insert(e,t):this.Ks.remove(e),r=this.ei(this.Ks),s=this.ei(n),i=[],o=[];return s.forEach(e=>{r.has(e)||i.push(e)}),r.forEach(e=>{s.has(e)||o.push(e)}),this.syncEngine.yi(i,o).then(()=>{this.Ks=n})}ti(e){this.Ks.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}ei(e){let n=Qi;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class Yh{constructor(){this.pi=new zh,this.Ti={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.pi.Fs(e),this.Ti[e]||"not-current"}updateQueryState(e,t,n){this.Ti[e]=t}removeLocalQueryTarget(e){this.pi.Ls(e)}isLocalQueryTarget(e){return this.pi.activeTargetIds.has(e)}clearQueryState(e){delete this.Ti[e]}getAllActiveQueryTargets(){return this.pi.activeTargetIds}isActiveQueryTarget(e){return this.pi.activeTargetIds.has(e)}start(){return this.pi=new zh,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(){}}class Jh{Ei(e){}shutdown(){}}class Xh{constructor(){this.Ii=()=>this.Ai(),this.Ri=()=>this.bi(),this.Pi=[],this.vi()}Ei(e){this.Pi.push(e)}shutdown(){window.removeEventListener("online",this.Ii),window.removeEventListener("offline",this.Ri)}vi(){window.addEventListener("online",this.Ii),window.addEventListener("offline",this.Ri)}Ai(){Er("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.Pi)e(0)}bi(){Er("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.Pi)e(1)}static Pt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const Zh={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class ec{constructor(e){this.Vi=e.Vi,this.Si=e.Si}Di(e){this.Ci=e}Ni(e){this.ki=e}onMessage(e){this.xi=e}close(){this.Si()}send(e){this.Vi(e)}$i(){this.Ci()}Oi(e){this.ki(e)}Mi(e){this.xi(e)}}class tc extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.Fi=t+"://"+e.host,this.Li="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}Bi(t,e,n,r,s){const i=this.Ui(t,e);Er("RestConnection","Sending: ",i,n);var o={};return this.qi(o,r,s),this.Ki(t,i,o,n).then(e=>(Er("RestConnection","Received: ",e),e),e=>{throw _r("RestConnection",`${t} failed with error: `,e,"url: ",i,"request:",n),e})}ji(e,t,n,r,s){return this.Bi(e,t,n,r,s)}qi(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)}Ui(e,t){var n=Zh[e];return`${this.Fi}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}Ki(a,t,n,r){return new Promise((s,i)=>{const o=new pr;o.listenOnce(ur.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case cr.NO_ERROR:var e=o.getResponseJson();Er("Connection","XHR received:",JSON.stringify(e)),s(e);break;case cr.TIMEOUT:Er("Connection",'RPC "'+a+'" timed out'),i(new kr(Cr.DEADLINE_EXCEEDED,"Request time out"));break;case cr.HTTP_ERROR:var t,n=o.getStatus();if(Er("Connection",'RPC "'+a+'" failed with status:',n,"response text:",o.getResponseText()),0<n){const a=o.getResponseJson().error;a&&a.status&&a.message?(r=a.status.toLowerCase().replace(/_/g,"-"),t=0<=Object.values(Cr).indexOf(r)?r:Cr.UNKNOWN,i(new kr(t,a.message))):i(new kr(Cr.UNKNOWN,"Server responded with status "+o.getStatus()))}else i(new kr(Cr.UNAVAILABLE,"Connection failed."));break;default:Ar()}}finally{Er("Connection",'RPC "'+a+'" completed.')}var r});var e=JSON.stringify(r);o.send(t,"POST",e,n,15)})}Qi(e,t,n){const r=[this.Fi,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=new nr,i=hr(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(o.xmlHttpFactory=new gr({})),this.qi(o.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(a="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0)&&void 0!==a.id||(o.httpHeadersOverwriteParam="$httpHeaders");var a=r.join("");Er("Connection","Creating WebChannel: "+a,o);const h=s.createWebChannel(a,o);let c=!1,u=!1;const l=new ec({Vi:e=>{u?Er("Connection","Not sending because WebChannel is closed:",e):(c||(Er("Connection","Opening WebChannel transport."),h.open(),c=!0),Er("Connection","WebChannel sending:",e),h.send(e))},Si:()=>h.close()}),d=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return d(h,mr.EventType.OPEN,()=>{u||Er("Connection","WebChannel transport opened.")}),d(h,mr.EventType.CLOSE,()=>{u||(u=!0,Er("Connection","WebChannel transport closed"),l.Oi())}),d(h,mr.EventType.ERROR,e=>{u||(u=!0,_r("Connection","WebChannel transport errored:",e),l.Oi(new kr(Cr.UNAVAILABLE,"The operation could not be completed")))}),d(h,mr.EventType.MESSAGE,n=>{if(!u){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=ar[e];if(void 0!==t)return Vi(t)}(n),t=r.message;void 0===e&&(e=Cr.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),u=!0,l.Oi(new kr(e,t)),h.close()}else Er("Connection","WebChannel received:",e),l.Mi(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.$i()},0),l}}function nc(){return"undefined"!=typeof window?window:null}function rc(){return"undefined"!=typeof document?document:null}function sc(e){return new ao(e,!0)}class ic{constructor(e,t,n=1e3,r=1.5,s=6e4){this.Me=e,this.timerId=t,this.Wi=n,this.Gi=r,this.zi=s,this.Hi=0,this.Ji=null,this.Yi=Date.now(),this.reset()}reset(){this.Hi=0}Xi(){this.Hi=this.zi}Zi(e){this.cancel();var t=Math.floor(this.Hi+this.tr()),n=Math.max(0,Date.now()-this.Yi),r=Math.max(0,t-n);0<r&&Er("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Hi} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Ji=this.Me.enqueueAfterDelay(this.timerId,r,()=>(this.Yi=Date.now(),e())),this.Hi*=this.Gi,this.Hi<this.Wi&&(this.Hi=this.Wi),this.Hi>this.zi&&(this.Hi=this.zi)}er(){null!==this.Ji&&(this.Ji.skipDelay(),this.Ji=null)}cancel(){null!==this.Ji&&(this.Ji.cancel(),this.Ji=null)}tr(){return(Math.random()-.5)*this.Hi}}class oc{constructor(e,t,n,r,s,i,o,a){this.Me=e,this.nr=n,this.sr=r,this.ir=s,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.rr=0,this.cr=null,this.ar=null,this.stream=null,this.ur=new ic(e,t)}hr(){return 1===this.state||5===this.state||this.lr()}lr(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.dr()}async stop(){this.hr()&&await this.close(0)}wr(){this.state=0,this.ur.reset()}_r(){this.lr()&&null===this.cr&&(this.cr=this.Me.enqueueAfterDelay(this.nr,6e4,()=>this.mr()))}gr(e){this.yr(),this.stream.send(e)}async mr(){if(this.lr())return this.close(0)}yr(){this.cr&&(this.cr.cancel(),this.cr=null)}pr(){this.ar&&(this.ar.cancel(),this.ar=null)}async close(e,t){this.yr(),this.pr(),this.ur.cancel(),this.rr++,4!==e?this.ur.reset():t&&t.code===Cr.RESOURCE_EXHAUSTED?(Ir(t.toString()),Ir("Using maximum backoff delay to prevent overloading the backend."),this.ur.Xi()):t&&t.code===Cr.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Tr(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Ni(t)}Tr(){}auth(){this.state=1;const e=this.Er(this.rr),n=this.rr;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.rr===n&&this.Ir(e,t)},t=>{e(()=>{var e=new kr(Cr.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Ar(e)})})}Ir(e,t){const n=this.Er(this.rr);this.stream=this.Rr(e,t),this.stream.Di(()=>{n(()=>(this.state=2,this.ar=this.Me.enqueueAfterDelay(this.sr,1e4,()=>(this.lr()&&(this.state=3),Promise.resolve())),this.listener.Di()))}),this.stream.Ni(e=>{n(()=>this.Ar(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}dr(){this.state=5,this.ur.Zi(async()=>{this.state=0,this.start()})}Ar(e){return Er("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Er(t){return e=>{this.Me.enqueueAndForget(()=>this.rr===t?e():(Er("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class ac extends oc{constructor(e,t,n,r,s,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,i),this.k=s}Rr(e,t){return this.ir.Qi("Listen",e,t)}onMessage(e){this.ur.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.C?(Dr(void 0===f||"string"==typeof f),es.fromBase64String(f||"")):(Dr(void 0===f||f instanceof Uint8Array),es.fromUint8Array(f||new Uint8Array))),o=t.targetChange.cause,a=o&&(a=void 0===(f=o).code?Cr.UNKNOWN:Vi(f.code),new kr(a,f.message||""));n=new eo(r,s,i,a||null)}else if("documentChange"in t){t.documentChange;var h=t.documentChange;h.document,h.document.name,h.document.updateTime;var a=mo(e,h.document.name),c=uo(h.document.updateTime),u=new _s({mapValue:{fields:h.document.fields}}),c=Ss.newFoundDocument(a,c,u),u=h.targetIds||[],h=h.removedTargetIds||[];n=new Xi(u,h,c.key,c)}else if("documentDelete"in t){t.documentDelete;u=t.documentDelete;u.document;h=mo(e,u.document),c=u.readTime?uo(u.readTime):Gr.min(),c=Ss.newNoDocument(h,c),u=u.removedTargetIds||[];n=new Xi([],u,c.key,c)}else if("documentRemove"in t){t.documentRemove;var l=t.documentRemove;l.document;var d=mo(e,l.document),l=l.removedTargetIds||[];n=new Xi([],l,d,null)}else{if(!("filter"in t))return Ar();{t.filter;const e=t.filter;e.targetId;l=e.count||0,d=new Pi(l),l=e.targetId;n=new Zi(l,d)}}var a,f;return n}(this.k,e),n=function(e){if(!("targetChange"in e))return Gr.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?uo(t.readTime):Gr.min()}(e);return this.listener.br(t,n)}Pr(e){const t={};t.database=vo(this.k),t.addTarget=function(e,t){let n;var r=t.target;return n=Ns(r)?{documents:_o(e,r)}:{query:So(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()?n.resumeToken=co(e,t.resumeToken):0<t.snapshotVersion.compareTo(Gr.min())&&(n.readTime=ho(e,t.snapshotVersion.toTimestamp())),n}(this.k,e);var n,r,r=(this.k,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.gr(t)}vr(e){const t={};t.database=vo(this.k),t.removeTarget=e,this.gr(t)}}class hc extends oc{constructor(e,t,n,r,s,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,i),this.k=s,this.Vr=!1}get Sr(){return this.Vr}start(){this.Vr=!1,this.lastStreamToken=void 0,super.start()}Tr(){this.Vr&&this.Dr([])}Rr(e,t){return this.ir.Qi("Write",e,t)}onMessage(e){if(Dr(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Vr){this.ur.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?uo(e.updateTime):uo(t);return n.isEqual(Gr.min())&&(n=uo(t)),new Ti(n,e.transformResults||[])}(e,s))):[]),n=uo(e.commitTime);return this.listener.Cr(n,t)}var r,s;return Dr(!e.writeResults||0===e.writeResults.length),this.Vr=!0,this.listener.Nr()}kr(){const e={};e.database=vo(this.k),this.gr(e)}Dr(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>Eo(this.k,e))};this.gr(t)}}class cc extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.ir=n,this.k=r,this.$r=!1}Or(){if(this.$r)throw new kr(Cr.FAILED_PRECONDITION,"The client has already been terminated.")}Bi(n,r,s){return this.Or(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.ir.Bi(n,r,s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Cr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new kr(Cr.UNKNOWN,e.toString())})}ji(n,r,s){return this.Or(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.ir.ji(n,r,s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Cr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new kr(Cr.UNKNOWN,e.toString())})}terminate(){this.$r=!0}}class uc{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.Mr=0,this.Fr=null,this.Lr=!0}Br(){0===this.Mr&&(this.Ur("Unknown"),this.Fr=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.Fr=null,this.qr("Backend didn't respond within 10 seconds."),this.Ur("Offline"),Promise.resolve())))}Kr(e){"Online"===this.state?this.Ur("Unknown"):(this.Mr++,1<=this.Mr&&(this.jr(),this.qr(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.Ur("Offline")))}set(e){this.jr(),this.Mr=0,"Online"===e&&(this.Lr=!1),this.Ur(e)}Ur(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}qr(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.Lr?(Ir(t),this.Lr=!1):Er("OnlineStateTracker",t)}jr(){null!==this.Fr&&(this.Fr.cancel(),this.Fr=null)}}class lc{constructor(e,t,n,r,s){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Qr=[],this.Wr=new Map,this.Gr=new Set,this.zr=[],this.Hr=s,this.Hr.Ei(e=>{n.enqueueAndForget(async()=>{bc(this)&&(Er("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.Gr.add(4),await fc(t),t.Jr.set("Unknown"),t.Gr.delete(4),await dc(t)}(this))})}),this.Jr=new uc(n,r)}}async function dc(e){if(bc(e))for(const t of e.zr)await t(!0)}async function fc(e){for(const t of e.zr)await t(!1)}function gc(e,t){const n=e;n.Wr.has(t.targetId)||(n.Wr.set(t.targetId,t),wc(n)?vc(n):Cc(n).lr()&&pc(n,t))}function mc(e,t){const n=e,r=Cc(n);n.Wr.delete(t),r.lr()&&yc(n,t),0===n.Wr.size&&(r.lr()?r._r():bc(n)&&n.Jr.set("Unknown"))}function pc(e,t){e.Yr.X(t.targetId),Cc(e).Pr(t)}function yc(e,t){e.Yr.X(t),Cc(e).vr(t)}function vc(t){t.Yr=new no({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),Et:e=>t.Wr.get(e)||null}),Cc(t).start(),t.Jr.Br()}function wc(e){return bc(e)&&!Cc(e).hr()&&0<e.Wr.size}function bc(e){return 0===e.Gr.size}function Tc(e){e.Yr=void 0}async function Ec(e,t,n){if(!aa(t))throw t;e.Gr.add(1),await fc(e),e.Jr.set("Offline"),n=n||(()=>Ih(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{Er("RemoteStore","Retrying IndexedDB access"),await n(),e.Gr.delete(1),await dc(e)})}function Ic(t,n){return n().catch(e=>Ec(t,e,n))}async function _c(e){const t=e,n=kc(t);let r=0<t.Qr.length?t.Qr[t.Qr.length-1].batchId:-1;for(;bc(s=t)&&s.Qr.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.An.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.Qr.length&&n._r();break}r=e.batchId,function(e,t){e.Qr.push(t);const n=kc(e);n.lr()&&n.Sr&&n.Dr(t.mutations)}(t,e)}catch(e){await Ec(t,e)}var s;Sc(t)&&Ac(t)}function Sc(e){return bc(e)&&!kc(e).hr()&&0<e.Qr.length}function Ac(e){kc(e).start()}async function Dc(e,t){const n=e;t?(n.Gr.delete(2),await dc(n)):(n.Gr.add(2),await fc(n),n.Jr.set("Unknown"))}function Cc(t){return t.Xr||(t.Xr=function(e,t,n){const r=e;return r.Or(),new ac(t,r.ir,r.authCredentials,r.appCheckCredentials,r.k,n)}(t.datastore,t.asyncQueue,{Di:(async function(n){n.Wr.forEach((e,t)=>{pc(n,e)})}).bind(null,t),Ni:(async function(e,t){Tc(e),wc(e)?(e.Jr.Kr(t),vc(e)):e.Jr.set("Unknown")}).bind(null,t),br:(async function(e,r,t){if(e.Jr.set("Online"),r instanceof eo&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e.Wr.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e.Wr.delete(n),e.Yr.removeTarget(n))}(e)}catch(t){Er("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await Ec(e,t)}else if(r instanceof Xi?e.Yr.ot(r):r instanceof Zi?e.Yr.dt(r):e.Yr.ut(r),!t.isEqual(Gr.min()))try{const r=await Ih(e.localStore);0<=t.compareTo(r)&&await function(r,s){const e=r.Yr.gt(s);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=r.Wr.get(t);n&&r.Wr.set(t,n.withResumeToken(e.resumeToken,s))}}),e.targetMismatches.forEach(e=>{const t=r.Wr.get(e);var n;t&&(r.Wr.set(e,t.withResumeToken(es.EMPTY_BYTE_STRING,t.snapshotVersion)),yc(r,e),n=new pa(t.target,e,1,t.sequenceNumber),pc(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){Er("RemoteStore","Failed to raise snapshot:",r),await Ec(e,r)}}).bind(null,t)}),t.zr.push(async e=>{e?(t.Xr.wr(),wc(t)?vc(t):t.Jr.set("Unknown")):(await t.Xr.stop(),Tc(t))})),t.Xr}function kc(t){return t.Zr||(t.Zr=function(e,t,n){const r=e;return r.Or(),new hc(t,r.ir,r.authCredentials,r.appCheckCredentials,r.k,n)}(t.datastore,t.asyncQueue,{Di:(async function(e){kc(e).kr()}).bind(null,t),Ni:(async function(e,t){t&&kc(e).Sr&&await async function(e,t){if(Fi(n=t.code)&&n!==Cr.ABORTED){const n=e.Qr.shift();kc(e).wr(),await Ic(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await _c(e)}var n}(e,t),Sc(e)&&Ac(e)}).bind(null,t),Nr:(async function(e){const t=kc(e);for(const n of e.Qr)t.Dr(n.mutations)}).bind(null,t),Cr:(async function(e,t,n){const r=e.Qr.shift(),s=ma.from(r,t,n);await Ic(e,()=>e.remoteSyncer.applySuccessfulWrite(s)),await _c(e)}).bind(null,t)}),t.zr.push(async e=>{e?(t.Zr.wr(),await _c(t)):(await t.Zr.stop(),0<t.Qr.length&&(Er("RemoteStore",`Stopping write stream with ${t.Qr.length} pending writes`),t.Qr=[]))})),t.Zr}class Nc{constructor(e,t,n,r,s){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=s,this.deferred=new Nr,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,o=new Nc(e,t,i,r,s);return o.start(n),o}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new kr(Cr.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 xc(e,t){if(Ir("AsyncQueue",`${t}: ${e}`),aa(e))return new kr(Cr.UNAVAILABLE,`${t}: ${e}`);throw e}class Rc{constructor(n){this.comparator=n?(e,t)=>n(e,t)||us.comparator(e.key,t.key):(e,t)=>us.comparator(e.key,t.key),this.keyedMap=Gi,this.sortedSet=new qi(this.comparator)}static emptySet(e){return new Rc(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 Rc))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 Rc;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class Lc{constructor(){this.eo=new qi(us.comparator)}track(e){var t=e.doc.key,n=this.eo.get(t);!n||0!==e.type&&3===n.type?this.eo=this.eo.insert(t,e):3===e.type&&1!==n.type?this.eo=this.eo.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.eo=this.eo.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.eo=this.eo.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.eo=this.eo.remove(t):1===e.type&&2===n.type?this.eo=this.eo.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.eo=this.eo.insert(t,{type:2,doc:e.doc}):Ar()}no(){const n=[];return this.eo.inorderTraversal((e,t)=>{n.push(t)}),n}}class Mc{constructor(e,t,n,r,s,i,o,a){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=s,this.fromCache=i,this.syncStateChanged=o,this.excludesMetadataChanges=a}static fromInitialDocuments(e,t,n,r){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new Mc(e,t,Rc.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)&&ni(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 Oc{constructor(){this.so=void 0,this.listeners=[]}}class Pc{constructor(){this.queries=new nh(e=>ri(e),ni),this.onlineState="Unknown",this.io=new Set}}async function Fc(e,t){const n=e,r=t.query;let s=!1,i=n.queries.get(r);if(i||(s=!0,i=new Oc),s)try{i.so=await n.onListen(r)}catch(e){const n=xc(e,`Initialization of query '${si(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,i),i.listeners.push(t),t.ro(n.onlineState),!i.so||t.oo(i.so)&&qc(n)}async function Vc(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 qc(e){e.io.forEach(e=>{e.next()})}class Uc{constructor(e,t,n){this.query=e,this.co=t,this.ao=!1,this.uo=null,this.onlineState="Unknown",this.options=n||{}}oo(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new Mc(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}let t=!1;return this.ao?this.ho(e)&&(this.co.next(e),t=!0):this.lo(e,this.onlineState)&&(this.fo(e),t=!0),this.uo=e,t}onError(e){this.co.error(e)}ro(e){this.onlineState=e;let t=!1;return this.uo&&!this.ao&&this.lo(this.uo,e)&&(this.fo(this.uo),t=!0),t}lo(e,t){return!e.fromCache||!(this.options.wo&&"Offline"!==t||e.docs.isEmpty()&&"Offline"!==t)}ho(e){if(0<e.docChanges.length)return!0;var t=this.uo&&this.uo.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}fo(e){e=Mc.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.ao=!0,this.co.next(e)}}class Bc{constructor(e,t){this.payload=e,this.byteLength=t}_o(){return"metadata"in this.payload}}class jc{constructor(e){this.k=e}Hn(e){return mo(this.k,e)}Jn(e){return e.metadata.exists?To(this.k,e.document,!1):Ss.newNoDocument(this.Hn(e.metadata.name),this.Yn(e.metadata.readTime))}Yn(e){return uo(e)}}class Kc{constructor(e,t,n){this.mo=e,this.localStore=t,this.k=n,this.queries=[],this.documents=[],this.progress=$c(e)}yo(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;return e.payload.namedQuery?this.queries.push(e.payload.namedQuery):e.payload.documentMetadata?(this.documents.push({metadata:e.payload.documentMetadata}),e.payload.documentMetadata.exists||++t):e.payload.document&&(this.documents[this.documents.length-1].document=e.payload.document,++t),t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}po(e){const t=new Map,n=new jc(this.k);for(const s of e)if(s.metadata.queries){const e=n.Hn(s.metadata.name);for(const n of s.metadata.queries){var r=(t.get(n)||zi()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const s=e;let i=zi(),o=$i,a=Hi;for(const e of n){const n=t.Hn(e.metadata.name);e.document&&(i=i.add(n)),o=o.insert(n,t.Jn(e)),a=a.insert(n,t.Yn(e.metadata.readTime))}const h=s.Qn.newChangeBuffer({trackRemovals:!0}),c=await Ah(s,(r=r,ei(Ws(Yr.fromString(`__bundle__/docs/${r}`)))));return s.persistence.runTransaction("Apply bundle documents","readwrite",t=>Sh(t,h,o,Gr.min(),a).next(e=>(h.apply(t),e)).next(e=>s.He.removeMatchingKeysForTargetId(t,c.targetId).next(()=>s.He.addMatchingKeys(t,i,c.targetId)).next(()=>s.Wn.Vn(t,e)).next(()=>e)))}(this.localStore,new jc(this.k),this.documents,this.mo.id),t=this.po(this.documents);for(const e of this.queries)await async function(e,n,r=zi()){const s=await Ah(e,ei(Da(n.bundledQuery))),i=e;return i.persistence.runTransaction("Save named query","readwrite",e=>{var t=uo(n.readTime);if(0<=s.snapshotVersion.compareTo(t))return i.Ye.saveNamedQuery(e,n);t=s.withResumeToken(es.EMPTY_BYTE_STRING,t);return i.qn=i.qn.insert(t.targetId,t),i.He.updateTargetData(e,t).next(()=>i.He.removeMatchingKeysForTargetId(e,s.targetId)).next(()=>i.He.addMatchingKeys(e,r,s.targetId)).next(()=>i.Ye.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",new ph(Object.assign({},this.progress),e)}}function $c(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class Gc{constructor(e){this.key=e}}class Hc{constructor(e){this.key=e}}class Wc{constructor(e,t){this.query=e,this.To=t,this.Eo=null,this.current=!1,this.Io=zi(),this.mutatedKeys=zi(),this.Ao=oi(e),this.Ro=new Rc(this.Ao)}get bo(){return this.To}Po(e,t){const a=t?t.vo:new Lc,h=(t||this).Ro;let c=(t||this).mutatedKeys,u=h,l=!1;const d=zs(this.query)&&h.size===this.query.limit?h.last():null,f=Qs(this.query)&&h.size===this.query.limit?h.first():null;if(e.inorderTraversal((e,t)=>{const n=h.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 o=!1;n&&r?n.data.isEqual(r.data)?s!==i&&(a.track({type:3,doc:r}),o=!0):this.Vo(n,r)||(a.track({type:2,doc:r}),o=!0,(d&&0<this.Ao(r,d)||f&&this.Ao(r,f)<0)&&(l=!0)):!n&&r?(a.track({type:0,doc:r}),o=!0):n&&!r&&(a.track({type:1,doc:n}),o=!0,(d||f)&&(l=!0)),o&&(c=r?(u=u.add(r),i?c.add(e):c.delete(e)):(u=u.delete(e),c.delete(e)))}),zs(this.query)||Qs(this.query))for(;u.size>this.query.limit;){const e=zs(this.query)?u.last():u.first();u=u.delete(e.key),c=c.delete(e.key),a.track({type:1,doc:e})}return{Ro:u,vo:a,Bn:l,mutatedKeys:c}}Vo(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.Ro;this.Ro=e.Ro,this.mutatedKeys=e.mutatedKeys;const s=e.vo.no();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.Ao(e.doc,t.doc)),this.So(n);var i=t?this.Do():[],o=0===this.Io.size&&this.current?1:0,a=o!==this.Eo;return this.Eo=o,0!==s.length||a?{snapshot:new Mc(this.query,e.Ro,r,s,e.mutatedKeys,0==o,a,!1),Co:i}:{Co:i}}ro(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ro:this.Ro,vo:new Lc,mutatedKeys:this.mutatedKeys,Bn:!1},!1)):{Co:[]}}No(e){return!this.To.has(e)&&!!this.Ro.has(e)&&!this.Ro.get(e).hasLocalMutations}So(e){e&&(e.addedDocuments.forEach(e=>this.To=this.To.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.To=this.To.delete(e)),this.current=e.current)}Do(){if(!this.current)return[];const t=this.Io;this.Io=zi(),this.Ro.forEach(e=>{this.No(e.key)&&(this.Io=this.Io.add(e.key))});const n=[];return t.forEach(e=>{this.Io.has(e)||n.push(new Hc(e))}),this.Io.forEach(e=>{t.has(e)||n.push(new Gc(e))}),n}ko(e){this.To=e.zn,this.Io=zi();var t=this.Po(e.documents);return this.applyChanges(t,!0)}xo(){return Mc.fromInitialDocuments(this.query,this.Ro,this.mutatedKeys,0===this.Eo)}}class zc{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Qc{constructor(e){this.key=e,this.$o=!1}}class Yc{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.Oo={},this.Mo=new nh(e=>ri(e),ni),this.Fo=new Map,this.Lo=new Set,this.Bo=new qi(us.comparator),this.Uo=new Map,this.qo=new Rh,this.Ko={},this.jo=new Map,this.Qo=$a.re(),this.onlineState="Unknown",this.Wo=void 0}get isPrimaryClient(){return!0===this.Wo}}async function Jc(n,e,t,r){n.Go=(e,i,t)=>async function(e,t,n){let r=t.view.Po(i);r.Bn&&(r=await Ch(e.localStore,t.query,!1).then(({documents:e})=>t.view.Po(e,r)));var s=n&&n.targetChanges.get(t.targetId),s=t.view.applyChanges(r,e.isPrimaryClient,s);return ou(e,t.targetId,s.Co),s.snapshot}(n,e,t);const s=await Ch(n.localStore,e,!0),i=new Wc(e,s.zn),o=i.Po(s.documents),a=Ji.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState),h=i.applyChanges(o,n.isPrimaryClient,a);ou(n,t,h.Co);var c=new zc(e,t,i);return n.Mo.set(e,c),n.Fo.has(t)?n.Fo.get(t).push(e):n.Fo.set(t,[e]),h.snapshot}async function Xc(e,t,n){const r=fu(e);try{const e=await function(e,r){const s=e,i=$r.now(),t=r.reduce((e,t)=>e.add(t.key),zi());let o;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>s.Wn.vn(n,t).next(e=>{o=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=li(r.transform,e||null);null!=s&&(null==n&&(n=_s.empty()),n.set(r.field,s))}return n||null}(n,o.get(n.key));null!=r&&t.push(new Ni(n.key,r,function r(e){const s=[];return Wr(e.fields,(e,t)=>{const n=new Xr([e]);if(Es(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),Ei.exists(!0)))}return s.An.addMutationBatch(n,i,t,r)})).then(e=>(e.applyToLocalDocumentSet(o),{batchId:e.batchId,changes:o}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Ko[e.currentUser.toKey()];r=r||new qi(Br),r=r.insert(t,n),e.Ko[e.currentUser.toKey()]=r}(r,e.batchId,n),await hu(r,e.changes),await _c(r.remoteStore)}catch(e){const t=xc(e,"Failed to persist write");n.reject(t)}}async function Zc(e,t){const r=e;try{const e=await _h(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.Uo.get(t);n&&(Dr(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.$o=!0:0<e.modifiedDocuments.size?Dr(n.$o):0<e.removedDocuments.size&&(Dr(n.$o),n.$o=!1))}),await hu(r,e,t)}catch(e){await Qa(e)}}function eu(r,s,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.Mo.forEach((e,t)=>{var n=t.view.ro(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.ro(n)&&(r=!0)}),r&&qc(t)}(t.eventManager,s),r.length&&t.Oo.br(r),t.onlineState=s,t.isPrimaryClient&&t.sharedClientState.setOnlineState(s)}}async function tu(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.Qn.newChangeBuffer({trackRemovals:!0});return function(e,t,r,s){const i=r.batch,n=i.keys();let o=na.resolve();return n.forEach(n=>{o=o.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()&&s.addEntry(e,r.commitVersion))})}),o.next(()=>e.An.removeMutationBatch(t,i))}(s,e,r,n).next(()=>n.apply(e)).next(()=>s.An.performConsistencyCheck(e)).next(()=>s.Wn.vn(e,t))})}(n.localStore,t);ru(n,r,null),nu(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await hu(n,e)}catch(e){await Qa(e)}}function nu(e,t){(e.jo.get(t)||[]).forEach(e=>{e.resolve()}),e.jo.delete(t)}function ru(e,t,n){const r=e;let s=r.Ko[r.currentUser.toKey()];if(s){const e=s.get(t);e&&(n?e.reject(n):e.resolve(),s=s.remove(t)),r.Ko[r.currentUser.toKey()]=s}}function su(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.Fo.get(e))t.Mo.delete(r),n&&t.Oo.zo(r,n);t.Fo.delete(e),t.isPrimaryClient&&t.qo.us(e).forEach(e=>{t.qo.containsKey(e)||iu(t,e)})}function iu(e,t){e.Lo.delete(t.path.canonicalString());var n=e.Bo.get(t);null!==n&&(mc(e.remoteStore,n),e.Bo=e.Bo.remove(t),e.Uo.delete(n),au(e))}function ou(e,t,n){for(const r of n)r instanceof Gc?(e.qo.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.Bo.get(n)||e.Lo.has(r)||(Er("SyncEngine","New document in limbo: "+n),e.Lo.add(r),au(e))}(e,r)):r instanceof Hc?(Er("SyncEngine","Document no longer in limbo: "+r.key),e.qo.removeReference(r.key,t),e.qo.containsKey(r.key)||iu(e,r.key)):Ar()}function au(e){for(;0<e.Lo.size&&e.Bo.size<e.maxConcurrentLimboResolutions;){var t=e.Lo.values().next().value;e.Lo.delete(t);var n=new us(Yr.fromString(t)),t=e.Qo.next();e.Uo.set(t,new Qc(n)),e.Bo=e.Bo.insert(n,t),gc(e.remoteStore,new pa(ei(Ws(n.path)),t,2,qr.I))}}async function hu(e,t,r){const s=e,i=[],o=[],a=[];s.Mo.isEmpty()||(s.Mo.forEach((e,n)=>{a.push(s.Go(n,t,r).then(e=>{var t;e&&(s.isPrimaryClient&&s.sharedClientState.updateQueryState(n.targetId,e.fromCache?"not-current":"current"),i.push(e),t=vh.$n(n.targetId,e),o.push(t))}))}),await Promise.all(a),s.Oo.br(i),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>na.forEach(t,t=>na.forEach(t.kn,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>na.forEach(t.xn,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!aa(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.qn.get(t),n=e.snapshotVersion,s=e.withLastLimboFreeSnapshotVersion(n);r.qn=r.qn.insert(t,s)}}}(s.localStore,o))}async function cu(r,e){const s=r;if(du(s),fu(s),!0===e&&!0!==s.Wo){const r=s.sharedClientState.getAllActiveQueryTargets(),e=await uu(s,r.toArray());s.Wo=!0,await Dc(s.remoteStore,!0);for(const r of e)gc(s.remoteStore,r)}else if(!1===e&&!1!==s.Wo){const r=[];let n=Promise.resolve();s.Fo.forEach((e,t)=>{s.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(su(s,t),Dh(s.localStore,t,!0))),mc(s.remoteStore,t)}),await n,await uu(s,r),function(){const n=s;n.Uo.forEach((e,t)=>{mc(n.remoteStore,t)}),n.qo.hs(),n.Uo=new Map,n.Bo=new qi(us.comparator)}(),s.Wo=!1,await Dc(s.remoteStore,!1)}}async function uu(t,n){const r=t,s=[],i=[];for(const t of n){let e;const u=r.Fo.get(t);if(u&&0!==u.length){e=await Ah(r.localStore,ei(u[0]));for(const t of u){const n=r.Mo.get(t),u=(o=r,a=n,c=h=void 0,c=await Ch((h=o).localStore,a.query,!0),c=a.view.ko(c),h.isPrimaryClient&&ou(h,a.targetId,c.Co),await c);u.snapshot&&i.push(u.snapshot)}}else{const u=await kh(r.localStore,t);e=await Ah(r.localStore,u),await Jc(r,lu(u),t,!1)}s.push(e)}var o,a,h,c;return r.Oo.br(i),s}function lu(e){return Hs(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function du(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=Zc.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.Uo.get(t);if(r&&r.$o)return zi().add(r.key);{let e=zi();const r=n.Fo.get(t);if(!r)return e;for(const t of r){const r=n.Mo.get(t);e=e.unionWith(r.view.bo)}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.Uo.get(t),i=s&&s.key;if(i){let e=new qi(us.comparator);e=e.insert(i,Ss.newNoDocument(i,Gr.min()));const n=zi().add(i),s=new Yi(Gr.min(),new Map,new ji(Br),e,n);await Zc(r,s),r.Bo=r.Bo.remove(i),r.Uo.delete(t),au(r)}else await Dh(r.localStore,t,!1).then(()=>su(r,t,n)).catch(Qa)}).bind(null,t),t.Oo.br=(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.oo(e)&&(r=!0);s.so=e}}r&&qc(n)}).bind(null,t.eventManager),t.Oo.zo=(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 fu(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=tu.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.An.lookupMutationBatch(t,r).next(e=>(Dr(null!==e),n=e.keys(),s.An.removeMutationBatch(t,e))).next(()=>s.An.performConsistencyCheck(t)).next(()=>s.Wn.vn(t,n))})}(r.localStore,t);ru(r,t,n),nu(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await hu(r,e)}catch(n){await Qa(n)}}).bind(null,t),t}class gu{constructor(){this.synchronizeTabs=!1}async initialize(e){this.k=sc(e.databaseInfo.databaseId),this.sharedClientState=this.Jo(e),this.persistence=this.Yo(e),await this.persistence.start(),this.gcScheduler=this.Xo(e),this.localStore=this.Zo(e)}Xo(e){return null}Zo(e){return Th(this.persistence,new wh,e.initialUser,this.k)}Yo(e){return new Vh(Uh.ks,this.k)}Jo(e){return new Yh}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class mu extends gu{constructor(e,t,n){super(),this.tc=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await async function(e){const t=e;return t.persistence.runTransaction("Synchronize last document change read time","readonly",t=>function(){const e=ah(t);let r=Gr.min();return e.jt({index:$o.readTimeIndex,reverse:!0},(e,t,n)=>{t.readTime&&(r=Ta(t.readTime)),n.done()}).next(()=>r)}()).then(e=>{t.jn=e})}(this.localStore),await this.tc.initialize(this,e),await fu(this.tc.syncEngine),await _c(this.tc.remoteStore),await this.persistence.sn(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(this.localStore),Promise.resolve()))}Zo(e){return Th(this.persistence,new wh,e.initialUser,this.k)}Xo(e){var t=this.persistence.referenceDelegate.garbageCollector;return new Xa(t,e.asyncQueue)}Yo(e){var t=mh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?Pa.withCacheSize(this.cacheSizeBytes):Pa.DEFAULT;return new dh(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,nc(),rc(),this.k,this.sharedClientState,!!this.forceOwnership)}Jo(e){return new Yh}}class pu extends mu{constructor(e,t){super(e,t,!1),this.tc=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.tc.syncEngine;this.sharedClientState instanceof Qh&&(this.sharedClientState.syncEngine={mi:(async function(e,t,n,r){var s=e,i=await function(e,n){const r=e,s=r.An;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>s.Zt(t,n).next(e=>e?r.Wn.vn(t,e):na.resolve(null)))}(s.localStore,t);null!==i?("pending"===n?await _c(s.remoteStore):"acknowledged"===n||"rejected"===n?(ru(s,t,r||null),nu(s,t),s.localStore.An.ee(t)):Ar(),await hu(s,i)):Er("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),gi:(async function(e,t,n,r){const s=e;if(s.Wo)Er("SyncEngine","Ignoring unexpected query state notification.");else if(s.Fo.has(t))switch(n){case"current":case"not-current":{const e=await Nh(s.localStore),r=Yi.createSynthesizedRemoteEventForCurrentChange(t,"current"===n);await hu(s,e,r);break}case"rejected":await Dh(s.localStore,t,!0),su(s,t,r);break;default:Ar()}}).bind(null,t),yi:(async function(e,t,n){const r=du(e);if(r.Wo){for(const e of t)if(r.Fo.has(e))Er("SyncEngine","Adding an already active target "+e);else{const t=await kh(r.localStore,e),n=await Ah(r.localStore,t);await Jc(r,lu(t),n.targetId,!1),gc(r.remoteStore,n)}for(const e of n)r.Fo.has(e)&&await Dh(r.localStore,e,!1).then(()=>{mc(r.remoteStore,e),su(r,e)}).catch(Qa)}}).bind(null,t),Tn:(function(e){return e.localStore.persistence.Tn()}).bind(null,t),_i:(async function(e){const t=e;return Nh(t.localStore).then(e=>hu(t,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.sn(async e=>{await cu(this.tc.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start(this.localStore):e||this.gcScheduler.stop())})}Jo(e){var t=nc();if(!Qh.Pt(t))throw new kr(Cr.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=mh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new Qh(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class yu{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=>eu(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 Eh(n.localStore,t);n.currentUser=t,(e=n).jo.forEach(e=>{e.forEach(e=>{e.reject(new kr(Cr.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.jo.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await hu(n,r.Gn)}}).bind(null,this.syncEngine),await Dc(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Pc}createDatastore(e){var t,n,r,s,i=sc(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new tc(t));return n=e.authCredentials,r=e.appCheckCredentials,s=t,e=i,new cc(n,r,s,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,s=e=>eu(this.syncEngine,e,0),i=new(Xh.Pt()?Xh:Jh),new lc(t,n,r,s,i);var t,n,r,s,i}createSyncEngine(e,t){return function(e,t,n,r,s,i,o){const a=new Yc(e,t,n,r,s,i);return o&&(a.Wo=!0),a}(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.Gr.add(5),await fc(t),t.Hr.shutdown(),t.Jr.set("Unknown")}(this.remoteStore)}}function vu(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 wu{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.ec(this.observer.next,e)}error(e){this.observer.error?this.ec(this.observer.error,e):console.error("Uncaught Error in snapshot listener:",e)}nc(){this.muted=!0}ec(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class bu{constructor(e,t){this.sc=e,this.k=t,this.metadata=new Nr,this.buffer=new Uint8Array,this.ic=new TextDecoder("utf-8"),this.rc().then(e=>{e&&e._o()?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.sc.cancel()}async getMetadata(){return this.metadata.promise}async Ho(){return await this.getMetadata(),this.rc()}async rc(){var e=await this.oc();if(null===e)return null;var t=this.ic.decode(e),n=Number(t);isNaN(n)&&this.cc(`length string (${t}) is not valid number`);t=await this.ac(n);return new Bc(JSON.parse(t),e.length+n)}uc(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async oc(){for(;this.uc()<0&&!await this.hc(););if(0===this.buffer.length)return null;var e=this.uc();e<0&&this.cc("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 ac(e){for(;this.buffer.length<e;)await this.hc()&&this.cc("Reached the end of bundle when more is expected.");var t=this.ic.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}cc(e){throw this.sc.cancel(),new Error(`Invalid bundle format: ${e}`)}async hc(){var e=await this.sc.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 Tu{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 kr(Cr.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=vo(r.k)+"/documents",s={documents:t.map(e=>go(r.k,e))},i=await r.ji("BatchGetDocuments",n,s),o=new Map;i.forEach(e=>{const t=(n=r.k,"found"in(e=e)?function(e,t){Dr(!!t.found),t.found.name,t.found.updateTime;var n=mo(e,t.found.name),r=uo(t.found.updateTime),s=new _s({mapValue:{fields:t.found.fields}});return Ss.newFoundDocument(n,r,s)}(n,e):"missing"in e?function(e,t){Dr(!!t.missing),Dr(!!t.readTime);var n=mo(e,t.missing),r=uo(t.readTime);return Ss.newNoDocument(n,r)}(n,e):Ar());var n;o.set(t.key.toString(),t)});const a=[];return t.forEach(e=>{var t=o.get(e.toString());Dr(!!t),a.push(t)}),a}(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 Mi(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=us.fromPath(t);this.mutations.push(new Oi(n,this.precondition(n)))}),await async function(e,t){const n=e,r=vo(n.k)+"/documents",s={writes:t.map(e=>Eo(n.k,e))};await n.Bi("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=Gr.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new kr(Cr.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?Ei.updateTime(t):Ei.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return Ei.exists(!0);if(t.isEqual(Gr.min()))throw new kr(Cr.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Ei.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class Eu{constructor(e,t,n,r){this.asyncQueue=e,this.datastore=t,this.updateFunction=n,this.deferred=r,this.lc=5,this.ur=new ic(this.asyncQueue,"transaction_retry")}run(){--this.lc,this.fc()}fc(){this.ur.Zi(async()=>{const t=new Tu(this.datastore),e=this.dc(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.wc(e)}))}).catch(e=>{this.wc(e)})})}dc(e){try{var t=this.updateFunction(e);return!as(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}}wc(e){0<this.lc&&this._c(e)?(--this.lc,this.asyncQueue.enqueueAndForget(()=>(this.fc(),Promise.resolve()))):this.deferred.reject(e)}_c(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||!Fi(t)}}class Iu{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=vr.UNAUTHENTICATED,this.clientId=Ur.A(),this.authCredentialListener=()=>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,()=>Promise.resolve())}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}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new kr(Cr.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new Nr;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=xc(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function _u(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 Eh(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function Su(e,t){e.asyncQueue.verifyOperationInProgress();var n=await Au(e);Er("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await t.initialize(n,r),e.setCredentialChangeListener(e=>async function(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),Er("RemoteStore","RemoteStore received new credentials");var r=bc(n);n.Gr.add(3),await fc(n),r&&n.Jr.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.Gr.delete(3),await dc(n)}(t.remoteStore,e)),e.onlineComponents=t}async function Au(e){return e.offlineComponents||(Er("FirestoreClient","Using default OfflineComponentProvider"),await _u(e,new gu)),e.offlineComponents}async function Du(e){return e.onlineComponents||(Er("FirestoreClient","Using default OnlineComponentProvider"),await Su(e,new yu)),e.onlineComponents}function Cu(e){return Au(e).then(e=>e.persistence)}function ku(e){return Au(e).then(e=>e.localStore)}function Nu(e){return Du(e).then(e=>e.remoteStore)}function xu(e){return Du(e).then(e=>e.syncEngine)}async function Ru(e){const t=await Du(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=du(e);let r,s;const i=n.Mo.get(t);if(i)r=i.targetId,n.sharedClientState.addLocalQueryTarget(r),s=i.view.xo();else{const e=await Ah(n.localStore,ei(t)),i=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,s=await Jc(n,t,r,"current"===i),n.isPrimaryClient&&gc(n.remoteStore,e)}return s}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.Mo.get(t),s=n.Fo.get(r.targetId);if(1<s.length)return n.Fo.set(r.targetId,s.filter(e=>!ni(e,t))),void n.Mo.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await Dh(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),mc(n.remoteStore,r.targetId),su(n,r.targetId)}).catch(Qa)):(su(n,r.targetId),await Dh(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function Lu(e,t,n={}){const r=new Nr;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,s,i,o){const e=new wu({next:e=>{r.enqueueAndForget(()=>Vc(n,a));var t=e.docs.has(s);!t&&e.fromCache?o.reject(new kr(Cr.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&i&&"server"===i.source?o.reject(new kr(Cr.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.)')):o.resolve(e)},error:e=>o.reject(e)}),a=new Uc(Ws(s.path),e,{includeMetadataChanges:!0,wo:!0});return Fc(n,a)}(await Ru(e),e.asyncQueue,t,n,r)),r.promise}function Mu(e,t,n={}){const r=new Nr;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,s){const i=new wu({next:e=>{n.enqueueAndForget(()=>Vc(t,o)),e.fromCache&&"server"===r.source?s.reject(new kr(Cr.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)}),o=new Uc(e,i,{includeMetadataChanges:!0,wo:!0});return Fc(t,o)}(await Ru(e),e.asyncQueue,t,n,r)),r.promise}function Ou(e,t,n,r){const s=(n=n,t=sc(t),i="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return vu(e,void 0);if(e instanceof ArrayBuffer)return vu(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 bu(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=uo(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.Ye.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,s))return await n.close(),void r._completeWith({taskState:"Success",documentsLoaded:s.totalDocuments,bytesLoaded:s.totalBytes,totalDocuments:s.totalDocuments,totalBytes:s.totalBytes});r._updateProgress($c(s));const o=new Kc(s,t.localStore,n.k);let e=await n.Ho();for(;e;){const t=await o.yo(e);t&&r._updateProgress(t),e=await n.Ho()}var i=await o.complete();await hu(t,i.In,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.Ye.saveBundleMetadata(e,t))}(t.localStore,s),r._completeWith(i.progress)}catch(t){_r("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t)}}(r,t,n).then(()=>{r.sharedClientState.notifyBundleLoaded()})}(await xu(e),s,r)})}class Pu{constructor(e,t,n,r,s,i,o,a){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=s,this.forceLongPolling=i,this.autoDetectLongPolling=o,this.useFetchStreams=a}}class Fu{constructor(e,t){this.projectId=e,this.database=t||"(default)"}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Fu&&e.projectId===this.projectId&&e.database===this.database}}const Vu=new Map;function qu(e,t,n){if(!n)throw new kr(Cr.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Uu(e,t,n,r){if(!0===t&&!0===r)throw new kr(Cr.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Bu(e){if(!us.isDocumentKey(e))throw new kr(Cr.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function ju(e){if(us.isDocumentKey(e))throw new kr(Cr.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Ku(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 $u(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new kr(Cr.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=Ku(e);throw new kr(Cr.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function Gu(e,t){if(t<=0)throw new kr(Cr.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Hu{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new kr(Cr.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 kr(Cr.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,Uu("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 Wu{constructor(e,t,n){this._authCredentials=t,this._appCheckCredentials=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Hu({}),this._settingsFrozen=!1,e instanceof Fu?this._databaseId=e:(this._app=e,this._databaseId=function(e){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new kr(Cr.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Fu(e.options.projectId)}(e))}get app(){if(!this._app)throw new kr(Cr.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 kr(Cr.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 Hu(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new Rr;switch(e.type){case"gapi":var t=e.client;return Dr(!("object"!=typeof t||null===t||!t.auth||!t.auth.getAuthHeaderValueForFirstParty)),new Pr(t,e.sessionIndex||"0",e.iamToken||null);case"provider":return e.client;default:throw new kr(Cr.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=Vu.get(e);t&&(Er("ComponentProvider","Removing Datastore"),Vu.delete(e),t.terminate())}(this),Promise.resolve()}}function zu(n,e,t,r={}){var s;const i=(n=$u(n,Wu))._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),[o(JSON.stringify({alg:"none",type:"JWT"})),o(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 kr(Cr.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new vr(i)}n._authCredentials=new Lr(new xr(e,t))}}class Qu{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 Ju(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Qu(this.firestore,e,this._key)}}class Yu{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Yu(this.firestore,e,this._query)}}class Ju extends Yu{constructor(e,t,n){super(e,t,Ws(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 Qu(this.firestore,null,new us(e))}withConverter(e){return new Ju(this.firestore,e,this._path)}}function Xu(e,t,...n){if(e=m(e),qu("collection","path",t),e instanceof Wu){var r=Yr.fromString(t,...n);return ju(r),new Ju(e,null,r)}if(!(e instanceof Qu||e instanceof Ju))throw new kr(Cr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(Yr.fromString(t,...n));return ju(r),new Ju(e.firestore,null,r)}function Zu(e,t,...n){if(e=m(e),qu("doc","path",t=1===arguments.length?Ur.A():t),e instanceof Wu){var r=Yr.fromString(t,...n);return Bu(r),new Qu(e,null,new us(r))}if(!(e instanceof Qu||e instanceof Ju))throw new kr(Cr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(Yr.fromString(t,...n));return Bu(r),new Qu(e.firestore,e instanceof Ju?e.converter:null,new us(r))}function el(e,t){return e=m(e),t=m(t),(e instanceof Qu||e instanceof Ju)&&(t instanceof Qu||t instanceof Ju)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function tl(e,t){return e=m(e),t=m(t),e instanceof Yu&&t instanceof Yu&&e.firestore===t.firestore&&ni(e._query,t._query)&&e.converter===t.converter}class nl{constructor(){this.mc=Promise.resolve(),this.gc=[],this.yc=!1,this.Tc=[],this.Ec=null,this.Ic=!1,this.Ac=!1,this.Rc=[],this.ur=new ic(this,"async_queue_retry"),this.bc=()=>{var e=rc();e&&Er("AsyncQueue","Visibility state changed to "+e.visibilityState),this.ur.er()};const e=rc();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.bc)}get isShuttingDown(){return this.yc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Pc(),this.vc(e)}enterRestrictedMode(e){if(!this.yc){this.yc=!0,this.Ac=e||!1;const t=rc();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.bc)}}enqueue(e){if(this.Pc(),this.yc)return new Promise(()=>{});const t=new Nr;return this.vc(()=>this.yc&&this.Ac?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.gc.push(e),this.Vc()))}async Vc(){if(0!==this.gc.length){try{await this.gc[0](),this.gc.shift(),this.ur.reset()}catch(e){if(!aa(e))throw e;Er("AsyncQueue","Operation failed with retryable error: "+e)}0<this.gc.length&&this.ur.Zi(()=>this.Vc())}}vc(e){var t=this.mc.then(()=>(this.Ic=!0,e().catch(e=>{throw this.Ec=e,this.Ic=!1,Ir("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.Ic=!1,e))));return this.mc=t}enqueueAfterDelay(e,t,n){this.Pc(),-1<this.Rc.indexOf(e)&&(t=0);var r=Nc.createAndSchedule(this,e,t,n,e=>this.Sc(e));return this.Tc.push(r),r}Pc(){this.Ec&&Ar()}verifyOperationInProgress(){}async Dc(){for(var e;await(e=this.mc),e!==this.mc;);}Cc(e){for(const t of this.Tc)if(t.timerId===e)return!0;return!1}Nc(t){return this.Dc().then(()=>{this.Tc.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.Tc)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Dc()})}kc(e){this.Rc.push(e)}Sc(e){var t=this.Tc.indexOf(e);this.Tc.splice(t,1)}}function rl(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 sl{constructor(){this._progressObserver={},this._taskCompletionResolver=new Nr,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 il,ol,al;class hl extends Wu{constructor(e,t,n){super(e,t,n),this.type="firestore",this._queue=new nl,this._persistenceKey="name"in e?e.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||ul(this),this._firestoreClient.terminate()}}function cl(e){return e._firestoreClient||ul(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function ul(e){var t,n,r,s,i,o=e._freezeSettings(),o=(n=e._databaseId,r=(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",s=e._persistenceKey,i=o,new Pu(n,r,s,i.host,i.ssl,i.experimentalForceLongPolling,i.experimentalAutoDetectLongPolling,i.useFetchStreams));e._firestoreClient=new Iu(e._authCredentials,e._appCheckCredentials,e._queue,o)}function ll(e,n,r){const s=new Nr;return e.asyncQueue.enqueue(async()=>{try{await _u(e,r),await Su(e,n),s.resolve()}catch(e){if(!("FirebaseError"===(t=e).name?t.code===Cr.FAILED_PRECONDITION||t.code===Cr.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 dl(e){return function(e){const t=new Nr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;bc(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.An.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.jo.get(e)||[];r.push(t),n.jo.set(e,r)}catch(e){const n=xc(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await xu(e),t)),t.promise}(cl(e=$u(e,hl)))}function fl(e){return(n=cl(e=$u(e,hl))).asyncQueue.enqueue(async()=>{const e=await Cu(n),t=await Nu(n);return e.setNetworkEnabled(!0),function(){const e=t;return e.Gr.delete(0),dc(e)}()});var n}function gl(e){return(n=cl(e=$u(e,hl))).asyncQueue.enqueue(async()=>{const e=await Cu(n),t=await Nu(n);return e.setNetworkEnabled(!1),async function(){const e=t;e.Gr.add(0),await fc(e),e.Jr.set("Offline")}()});var n}function ml(t,e){return n=cl(t=$u(t,hl)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.Ye.getNamedQuery(e,t))}(await ku(n),r)).then(e=>e?new Yu(t,null,e.query):null);var n,r}function pl(e){if(e._initialized||e._terminated)throw new kr(Cr.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 yl{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new kr(Cr.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Xr(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class vl{constructor(e){this._byteString=e}static fromBase64String(e){try{return new vl(es.fromBase64String(e))}catch(e){throw new kr(Cr.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new vl(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 wl{constructor(e){this._methodName=e}}class bl{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new kr(Cr.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new kr(Cr.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 Br(this._lat,e._lat)||Br(this._long,e._long)}}const Tl=/^__.*__$/;class El{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Ni(e,this.data,this.fieldMask,t,this.fieldTransforms):new ki(e,this.data,t,this.fieldTransforms)}}class Il{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Ni(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function _l(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw Ar()}}class Sl{constructor(e,t,n,r,s,i){this.settings=e,this.databaseId=t,this.k=n,this.ignoreUndefinedProperties=r,void 0===s&&this.xc(),this.fieldTransforms=s||[],this.fieldMask=i||[]}get path(){return this.settings.path}get $c(){return this.settings.$c}Oc(e){return new Sl(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.k,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Mc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Oc({path:n,Fc:!1});return r.Lc(e),r}Bc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Oc({path:n,Fc:!1});return r.xc(),r}Uc(e){return this.Oc({path:void 0,Fc:!0})}qc(e){return Gl(e,this.settings.methodName,this.settings.Kc||!1,this.path,this.settings.jc)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}xc(){if(this.path)for(let e=0;e<this.path.length;e++)this.Lc(this.path.get(e))}Lc(e){if(0===e.length)throw this.qc("Document fields must not be empty");if(_l(this.$c)&&Tl.test(e))throw this.qc('Document fields cannot begin and end with "__"')}}class Al{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.k=n||sc(e)}Qc(e,t,n,r=!1){return new Sl({$c:e,methodName:t,jc:n,path:Xr.emptyPath(),Fc:!1,Kc:r},this.databaseId,this.k,this.ignoreUndefinedProperties)}}function Dl(e){var t=e._freezeSettings(),n=sc(e._databaseId);return new Al(e._databaseId,!!t.ignoreUndefinedProperties,n)}function Cl(e,t,n,r,s,i={}){const o=e.Qc(i.merge||i.mergeFields?2:0,t,n,s);Bl("Data must be an object, but it was:",o,r);var a=ql(r,o);let h,c;if(i.merge)h=new Zr(o.fieldMask),c=o.fieldTransforms;else if(i.mergeFields){const e=[];for(const r of i.mergeFields){const s=jl(t,r,n);if(!o.contains(s))throw new kr(Cr.INVALID_ARGUMENT,`Field '${s}' is specified in your field mask but missing from your input data.`);Hl(e,s)||e.push(s)}h=new Zr(e),c=o.fieldTransforms.filter(e=>h.covers(e.field))}else h=null,c=o.fieldTransforms;return new El(new _s(a),h,c)}class kl extends wl{_toFieldTransform(e){if(2!==e.$c)throw 1===e.$c?e.qc(`${this._methodName}() can only appear at the top level of your update data`):e.qc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof kl}}function Nl(e,t,n){return new Sl({$c:3,jc:t.settings.jc,methodName:e._methodName,Fc:n},t.databaseId,t.k,t.ignoreUndefinedProperties)}class xl extends wl{_toFieldTransform(e){return new bi(e.path,new di)}isEqual(e){return e instanceof xl}}class Rl extends wl{constructor(e,t){super(e),this.Wc=t}_toFieldTransform(e){const t=Nl(this,e,!0),n=this.Wc.map(e=>Vl(e,t)),r=new fi(n);return new bi(e.path,r)}isEqual(e){return this===e}}class Ll extends wl{constructor(e,t){super(e),this.Wc=t}_toFieldTransform(e){const t=Nl(this,e,!0),n=this.Wc.map(e=>Vl(e,t)),r=new mi(n);return new bi(e.path,r)}isEqual(e){return this===e}}class Ml extends wl{constructor(e,t){super(e),this.Gc=t}_toFieldTransform(e){var t=new yi(e.k,ci(e.k,this.Gc));return new bi(e.path,t)}isEqual(e){return this===e}}function Ol(e,s,i,t){const o=e.Qc(1,s,i);Bl("Data must be an object, but it was:",o,t);const a=[],h=_s.empty();Wr(t,(e,t)=>{var n=$l(s,e,i);t=m(t);var r=o.Bc(n);if(t instanceof kl)a.push(n);else{const e=Vl(t,r);null!=e&&(a.push(n),h.set(n,e))}});var n=new Zr(a);return new Il(h,n,o.fieldTransforms)}function Pl(e,t,n,r,s,i){const o=e.Qc(1,t,n),a=[jl(t,r,n)],h=[s];if(i.length%2!=0)throw new kr(Cr.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)a.push(jl(t,i[f])),h.push(i[f+1]);const c=[],u=_s.empty();for(let g=a.length-1;0<=g;--g)if(!Hl(c,a[g])){const t=a[g];var l=m(l=h[g]);const r=o.Bc(t);if(l instanceof kl)c.push(t);else{const e=Vl(l,r);null!=e&&(c.push(t),u.set(t,e))}}var d=new Zr(c);return new Il(u,d,o.fieldTransforms)}function Fl(e,t,n,r=!1){return Vl(n,e.Qc(r?4:3,t))}function Vl(i,e){if(Ul(i=m(i)))return Bl("Unsupported field value:",e,i),ql(i,e);if(i instanceof wl)return function(e,t){if(!_l(t.$c))throw t.qc(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.qc(`${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.Fc&&4!==e.$c)throw e.qc("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const s of i){let e=Vl(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 ci(t.k,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=$r.fromDate(e);return{timestampValue:ho(t.k,n)}}if(e instanceof $r){n=new $r(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:ho(t.k,n)}}if(e instanceof bl)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof vl)return{bytesValue:co(t.k,e._byteString)};if(e instanceof Qu){const r=t.databaseId,s=e.firestore._databaseId;if(!s.isEqual(r))throw t.qc(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:lo(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.qc(`Unsupported field value: ${Ku(e)}`)}(0,e)}function ql(e,r){const s={};return zr(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):Wr(e,(e,t)=>{var n=Vl(t,r.Mc(e));null!=n&&(s[e]=n)}),{mapValue:{fields:s}}}function Ul(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof $r||e instanceof bl||e instanceof vl||e instanceof Qu||e instanceof wl)}function Bl(e,t,n){if(!Ul(n)||("object"!=typeof(s=n)||null===s||Object.getPrototypeOf(s)!==Object.prototype&&null!==Object.getPrototypeOf(s))){var r=Ku(n);throw"an object"===r?t.qc(e+" a custom object"):t.qc(e+" "+r)}var s}function jl(e,t,n){if((t=m(t))instanceof yl)return t._internalPath;if("string"==typeof t)return $l(e,t);throw Gl("Field path arguments must be of type string or ",e,!1,void 0,n)}const Kl=new RegExp("[~\\*/\\[\\]]");function $l(t,n,r){if(0<=n.search(Kl))throw Gl(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new yl(...n.split("."))._internalPath}catch(e){throw Gl(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function Gl(e,t,n,r,s){var i=r&&!r.isEmpty(),o=void 0!==s;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let h="";return(i||o)&&(h+=" (found",i&&(h+=` in field ${r}`),o&&(h+=` in document ${s}`),h+=")"),new kr(Cr.INVALID_ARGUMENT,a+e+h)}function Hl(e,t){return e.some(e=>e.isEqual(t))}class Wl{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 Qu(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new zl(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(Ql("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class zl extends Wl{data(){return super.data()}}function Ql(e,t){return"string"==typeof t?$l(e,t):(t instanceof yl?t:t._delegate)._internalPath}class Yl{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Jl extends Wl{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 Xl(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(Ql("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Xl extends Jl{data(e={}){return super.data(e)}}class Zl{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new Yl(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 Xl(this._firestore,this._userDataWriter,e.key,e,new Yl(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 kr(Cr.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 Xl(i._firestore,i._userDataWriter,e.doc.key,e.doc,new Yl(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 Xl(i._firestore,i._userDataWriter,e.doc.key,e.doc,new Yl(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 ed(e,t){return e instanceof Jl&&t instanceof Jl?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 Zl&&t instanceof Zl&&e._firestore===t._firestore&&tl(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function td(e){if(Qs(e)&&0===e.explicitOrderBy.length)throw new kr(Cr.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class nd{}function rd(e,...t){for(const n of t)e=n._apply(e);return e}class sd extends nd{constructor(e,t,n){super(),this.zc=e,this.Hc=t,this.Jc=n,this.type="where"}_apply(e){var t=Dl(e.firestore),t=function(e,t,n,r,s,i,o){let a;if(s.isKeyField()){if("array-contains"===i||"array-contains-any"===i)throw new kr(Cr.INVALID_ARGUMENT,`Invalid Query. You can't perform '${i}' queries on documentId().`);if("in"===i||"not-in"===i){ld(o,i);const t=[];for(const n of o)t.push(ud(r,e,n));a={arrayValue:{values:t}}}else a=ud(r,e,o)}else"in"!==i&&"not-in"!==i&&"array-contains-any"!==i||ld(o,i),a=Fl(n,t,o,"in"===i||"not-in"===i);var h=xs.create(s,i,a);return function(e,t){if(t.V()){const r=Js(e);if(null!==r&&!r.isEqual(t.field))throw new kr(Cr.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=Ys(e);null!==n&&dd(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 kr(Cr.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new kr(Cr.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}(e,h),h}(e._query,"where",t,e.firestore._databaseId,this.zc,this.Hc,this.Jc);return new Yu(e.firestore,e.converter,(e=e._query,t=e.filters.concat([t]),new Gs(e.path,e.collectionGroup,e.explicitOrderBy.slice(),t,e.limit,e.limitType,e.startAt,e.endAt)))}}class id extends nd{constructor(e,t){super(),this.zc=e,this.Yc=t,this.type="orderBy"}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new kr(Cr.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new kr(Cr.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,s=new js(t,n);return n=s,null!==Ys(e=e)||null!==(r=Js(e))&&dd(0,r,n.field),s}(e._query,this.zc,this.Yc);return new Yu(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new Gs(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class od extends nd{constructor(e,t,n){super(),this.type=e,this.Xc=t,this.Zc=n}_apply(e){return new Yu(e.firestore,e.converter,ti(e._query,this.Xc,this.Zc))}}class ad extends nd{constructor(e,t,n){super(),this.type=e,this.ta=t,this.ea=n}_apply(e){var t,n=cd(e,this.type,this.ta,this.ea);return new Yu(e.firestore,e.converter,(t=e._query,e=n,new Gs(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class hd extends nd{constructor(e,t,n){super(),this.type=e,this.ta=t,this.ea=n}_apply(e){var t,n=cd(e,this.type,this.ta,this.ea);return new Yu(e.firestore,e.converter,(t=e._query,e=n,new Gs(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function cd(e,t,n,r){if(n[0]=m(n[0]),n[0]instanceof Wl)return function(e,t,n,r,s){if(!r)throw new kr(Cr.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const i=[];for(const n of Zs(e))if(n.field.isKeyField())i.push(ys(t,r.key));else{const e=r.data.field(n.field);if(is(e))throw new kr(Cr.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 kr(Cr.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 Us(i,s)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var s=Dl(e.firestore);return function(e,t,n,r,s,i){const o=e.explicitOrderBy;if(s.length>o.length)throw new kr(Cr.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 a=[];for(let h=0;h<s.length;h++){const c=s[h];if(o[h].field.isKeyField()){if("string"!=typeof c)throw new kr(Cr.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);if(!Xs(e)&&-1!==c.indexOf("/"))throw new kr(Cr.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${c}' contains a slash.`);const n=e.path.child(Yr.fromString(c));if(!us.isDocumentKey(n))throw new kr(Cr.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 us(n);a.push(ys(t,s))}else{const e=Fl(n,r,c);a.push(e)}}return new Us(a,i)}(e._query,e.firestore._databaseId,s,t,n,r)}function ud(e,t,n){if("string"==typeof(n=m(n))){if(""===n)throw new kr(Cr.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!Xs(t)&&-1!==n.indexOf("/"))throw new kr(Cr.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(!us.isDocumentKey(r))throw new kr(Cr.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 ys(e,new us(r))}if(n instanceof Qu)return ys(e,n._key);throw new kr(Cr.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Ku(n)}.`)}function ld(e,t){if(!Array.isArray(e)||0===e.length)throw new kr(Cr.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);if(10<e.length)throw new kr(Cr.INVALID_ARGUMENT,`Invalid Query. '${t.toString()}' filters support a maximum of 10 elements in the value array.`)}function dd(e,t,n){if(!n.isEqual(t))throw new kr(Cr.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 fd{convertValue(e,t="none"){switch(ls(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 bl(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(os(e));default:return null}}convertTimestamp(e){var t=ns(e);return new $r(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=Yr.fromString(e);Dr(Lo(n));const r=new Fu(n.get(1),n.get(3)),s=new us(n.popFirst(5));return r.isEqual(t)||Ir(`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 gd(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class md extends fd{constructor(e){super(),this.firestore=e}convertBytes(e){return new vl(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Qu(this.firestore,null,t)}}class pd{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=Dl(e)}set(e,t,n){this._verifyNotCommitted();const r=yd(e,this._firestore),s=gd(r.converter,t,n),i=Cl(this._dataReader,"WriteBatch.set",r._key,s,null!==r.converter,n);return this._mutations.push(i.toMutation(r._key,Ei.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var s=yd(e,this._firestore);let i;return i="string"==typeof(t=m(t))||t instanceof yl?Pl(this._dataReader,"WriteBatch.update",s._key,t,n,r):Ol(this._dataReader,"WriteBatch.update",s._key,t),this._mutations.push(i.toMutation(s._key,Ei.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=yd(e,this._firestore);return this._mutations=this._mutations.concat(new Mi(t._key,Ei.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 kr(Cr.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function yd(e,t){if((e=m(e)).firestore!==t)throw new kr(Cr.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class vd extends fd{constructor(e){super(),this.firestore=e}convertBytes(e){return new vl(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Qu(this.firestore,null,t)}}function wd(t){t=$u(t,Qu);const n=$u(t.firestore,hl),e=cl(n),r=new vd(n);return function(e,t){const n=new Nr;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.Wn.Rn(e,t))}(t);s.isFoundDocument()?n.resolve(s):s.isNoDocument()?n.resolve(null):n.reject(new kr(Cr.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=xc(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await ku(e),t,n)),n.promise}(e,t._key).then(e=>new Jl(n,r,t._key,e,new Yl(null!==e&&e.hasLocalMutations,!0),t.converter))}function bd(t){t=$u(t,Yu);const n=$u(t.firestore,hl),e=cl(n),r=new vd(n);return function(e,t){const n=new Nr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const s=await Ch(e,t,!0),i=new Wc(t,s.zn),o=i.Po(s.documents),a=i.applyChanges(o,!1);n.resolve(a.snapshot)}catch(e){var r=xc(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await ku(e),t,n)),n.promise}(e,t._query).then(e=>new Zl(n,r,t,e))}function Td(e,t,n){e=$u(e,Qu);var r=$u(e.firestore,hl),s=gd(e.converter,t,n);return Sd(r,[Cl(Dl(r),"setDoc",e._key,s,null!==e.converter,n).toMutation(e._key,Ei.none())])}function Ed(e,t,n,...r){e=$u(e,Qu);var s=$u(e.firestore,hl),i=Dl(s);let o;return o="string"==typeof(t=m(t))||t instanceof yl?Pl(i,"updateDoc",e._key,t,n,r):Ol(i,"updateDoc",e._key,t),Sd(s,[o.toMutation(e._key,Ei.exists(!0))])}function Id(t,...n){var e;t=m(t);let r={includeMetadataChanges:!1},s=0;"object"!=typeof n[s]||rl(n[s])||(r=n[s],s++);var i={includeMetadataChanges:r.includeMetadataChanges};if(rl(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 o,a,h;if(t instanceof Qu)a=$u(t.firestore,hl),h=Ws(t._key.path),o={next:e=>{n[s]&&n[s](Ad(a,t,e))},error:n[s+1],complete:n[s+2]};else{const c=$u(t,Yu);a=$u(c.firestore,hl),h=c._query;const u=new vd(a);o={next:e=>{n[s]&&n[s](new Zl(a,u,c,e))},error:n[s+1],complete:n[s+2]},td(t._query)}return function(e,t,n,r){const s=new wu(r),i=new Uc(t,s,n);return e.asyncQueue.enqueueAndForget(async()=>Fc(await Ru(e),i)),()=>{s.nc(),e.asyncQueue.enqueueAndForget(async()=>Vc(await Ru(e),i))}}(cl(a),h,i,o)}function _d(e,t){return function(e,t){const n=new wu(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.io.add(t),t.next()}(await Ru(e),n)),()=>{n.nc(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.io.delete(t)}(await Ru(e),n))}}(cl(e=$u(e,hl)),rl(t)?t:{next:t})}function Sd(e,t){return function(e,t){const n=new Nr;return e.asyncQueue.enqueueAndForget(async()=>Xc(await xu(e),t,n)),n.promise}(cl(e),t)}function Ad(e,t,n){var r=n.docs.get(t._key),s=new vd(e);return new Jl(e,s,t._key,r,new Yl(n.hasPendingWrites,n.fromCache),t.converter)}class Dd extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=Dl(e)}get(e){const n=yd(e,this._firestore),r=new md(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 Wl(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new Wl(this._firestore,r,n._key,null,n.converter);throw Ar()})}set(e,t,n){var r=yd(e,this._firestore),s=gd(r.converter,t,n),s=Cl(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=yd(e,this._firestore),i="string"==typeof(t=m(t))||t instanceof yl?Pl(this._dataReader,"Transaction.update",s._key,t,n,r):Ol(this._dataReader,"Transaction.update",s._key,t);return this._transaction.update(s._key,i),this}delete(e){var t=yd(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=yd(e,this._firestore),n=new vd(this._firestore);return super.get(e).then(e=>new Jl(this._firestore,n,t._key,e._document,new Yl(!1,!1),t.converter))}}function Cd(t,n){return function(t,n){const r=new Nr;return t.asyncQueue.enqueueAndForget(async()=>{var e=await Du(t).then(e=>e.datastore);new Eu(t.asyncQueue,e,n,r).run()}),r.promise}(cl(t=$u(t,hl)),e=>n(new Dd(t,e)))}il=tf.SDK_VERSION,wr=il,tf._registerComponent(new c("firestore",(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=new hl(n,new Mr(e.getProvider("auth-internal")),new Vr(e.getProvider("app-check-internal")));return t=Object.assign({useFetchStreams:!0},t),r._setSettings(t),r},"PUBLIC")),tf.registerVersion(yr,"3.4.3",void 0),tf.registerVersion(yr,"3.4.3","esm2017");function kd(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new kr("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function Nd(){if("undefined"==typeof Uint8Array)throw new kr("unimplemented","Uint8Arrays are not available in this environment.")}function xd(){if("undefined"==typeof atob)throw new kr("unimplemented","Blobs are unavailable in Firestore in this environment.")}class Rd{constructor(e){this._delegate=e}static fromBase64String(e){return xd(),new Rd(vl.fromBase64String(e))}static fromUint8Array(e){return Nd(),new Rd(vl.fromUint8Array(e))}toBase64(){return xd(),this._delegate.toBase64()}toUint8Array(){return Nd(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function Ld(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 Md{enableIndexedDbPersistence(e,t){return function(e,t){pl(e=$u(e,hl));var n=cl(e),r=e._freezeSettings(),s=new yu;return ll(n,s,new mu(s,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){pl(e=$u(e,hl));var t=cl(e),n=e._freezeSettings(),r=new yu;return ll(t,r,new pu(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new kr(Cr.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new Nr;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!sa.Pt())return Promise.resolve();var t=e+"main";await sa.delete(t)}(mh(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class Od{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Fu||(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={}){zu(this._delegate,e,t,n)}enableNetwork(){return fl(this._delegate)}disableNetwork(){return gl(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,Uu("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 dl(this._delegate)}onSnapshotsInSync(e){return _d(this._delegate,e)}get app(){if(!this._appCompat)throw new kr("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new Qd(this,Xu(this._delegate,e))}catch(e){throw Bd(e,"collection()","Firestore.collection()")}}doc(e){try{return new Ud(this,Zu(this._delegate,e))}catch(e){throw Bd(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new Hd(this,function(e,t){if(e=$u(e,Wu),qu("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new kr(Cr.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Yu(e,null,(t=t,new Gs(Yr.emptyPath(),t)))}(this._delegate,e))}catch(e){throw Bd(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return Cd(this._delegate,e=>t(new Fd(this,e)))}batch(){return cl(this._delegate),new Vd(new pd(this._delegate,e=>Sd(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=cl(t=$u(t,hl)),r=new sl,Ou(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return ml(this._delegate,e).then(e=>e?new Hd(this,e):null)}}class Pd extends fd{constructor(e){super(),this.firestore=e}convertBytes(e){return new Rd(new vl(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return Ud.forKey(t,this.firestore,null)}}class Fd{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Pd(e)}get(e){const t=Yd(e);return this._delegate.get(t).then(e=>new $d(this._firestore,new Jl(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=Yd(e);return n?(kd("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var s=Yd(e);return 2===arguments.length?this._delegate.update(s,t):this._delegate.update(s,t,n,...r),this}delete(e){var t=Yd(e);return this._delegate.delete(t),this}}class Vd{constructor(e){this._delegate=e}set(e,t,n){var r=Yd(e);return n?(kd("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var s=Yd(e);return 2===arguments.length?this._delegate.update(s,t):this._delegate.update(s,t,n,...r),this}delete(e){var t=Yd(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class qd{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new Xl(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new Gd(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=qd.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let s=r.get(t);return s||(s=new qd(e,new Pd(e),t),r.set(t,s)),s}}qd.INSTANCES=new WeakMap;class Ud{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Pd(e)}static forPath(e,t,n){if(e.length%2!=0)throw new kr("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new Ud(t,new Qu(t._delegate,n,new us(e)))}static forKey(e,t,n){return new Ud(t,new Qu(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new Qd(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new Qd(this.firestore,Xu(this._delegate,e))}catch(e){throw Bd(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=m(e))instanceof Qu&&el(this._delegate,e)}set(e,t){t=kd("DocumentReference.set",t);try{return t?Td(this._delegate,e,t):Td(this._delegate,e)}catch(e){throw Bd(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?Ed(this._delegate,e):Ed(this._delegate,e,t,...n)}catch(e){throw Bd(e,"updateDoc()","DocumentReference.update()")}}delete(){return Sd($u((e=this._delegate).firestore,hl),[new Mi(e._key,Ei.none())]);var e}onSnapshot(...e){var t=jd(e),n=Kd(e,e=>new $d(this.firestore,new Jl(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return Id(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?wd:"server"===(null==e?void 0:e.source)?function(t){t=$u(t,Qu);const n=$u(t.firestore,hl);return Lu(cl(n),t._key,{source:"server"}).then(e=>Ad(n,t,e))}:function(t){t=$u(t,Qu);const n=$u(t.firestore,hl);return Lu(cl(n),t._key).then(e=>Ad(n,t,e))})(this._delegate),t.then(e=>new $d(this.firestore,new Jl(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new Ud(this.firestore,e?this._delegate.withConverter(qd.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Bd(e,t,n){return e.message=e.message.replace(t,n),e}function jd(e){for(const t of e)if("object"==typeof t&&!Ld(t))return t;return{}}function Kd(e,t){var n;let r;return r=Ld(e[0])?e[0]:Ld(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 $d{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new Ud(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 ed(this._delegate,e._delegate)}}class Gd extends $d{data(e){var t=this._delegate.data(e);return void 0!==t||Ar(),t}}class Hd{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Pd(e)}where(e,t,n){try{return new Hd(this.firestore,rd(this._delegate,(r=n,s=t,i=Ql("where",e),new sd(i,s,r))))}catch(e){throw Bd(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,s,i}orderBy(e,t){try{return new Hd(this.firestore,rd(this._delegate,([n,r="asc"]=[e,t],s=r,i=Ql("orderBy",n),new id(i,s))))}catch(e){throw Bd(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,s,i}limit(e){try{return new Hd(this.firestore,rd(this._delegate,(Gu("limit",t=e),new od("limit",t,"F"))))}catch(e){throw Bd(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new Hd(this.firestore,rd(this._delegate,(Gu("limitToLast",t=e),new od("limitToLast",t,"L"))))}catch(e){throw Bd(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new Hd(this.firestore,rd(this._delegate,function(...e){return new ad("startAt",e,!0)}(...e)))}catch(e){throw Bd(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new Hd(this.firestore,rd(this._delegate,function(...e){return new ad("startAfter",e,!1)}(...e)))}catch(e){throw Bd(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new Hd(this.firestore,rd(this._delegate,function(...e){return new hd("endBefore",e,!0)}(...e)))}catch(e){throw Bd(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new Hd(this.firestore,rd(this._delegate,function(...e){return new hd("endAt",e,!1)}(...e)))}catch(e){throw Bd(e,"endAt()","Query.endAt()")}}isEqual(e){return tl(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?bd:"server"===(null==e?void 0:e.source)?function(t){t=$u(t,Yu);const n=$u(t.firestore,hl),e=cl(n),r=new vd(n);return Mu(e,t._query,{source:"server"}).then(e=>new Zl(n,r,t,e))}:function(t){t=$u(t,Yu);const n=$u(t.firestore,hl),e=cl(n),r=new vd(n);return td(t._query),Mu(e,t._query).then(e=>new Zl(n,r,t,e))})(this._delegate),t.then(e=>new zd(this.firestore,new Zl(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=jd(e),n=Kd(e,e=>new zd(this.firestore,new Zl(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return Id(this._delegate,t,n)}withConverter(e){return new Hd(this.firestore,e?this._delegate.withConverter(qd.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class Wd{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new Gd(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class zd{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new Hd(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 Gd(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new Wd(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new Gd(this._firestore,e))})}isEqual(e){return ed(this._delegate,e._delegate)}}class Qd extends Hd{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 Ud(this.firestore,e):null}doc(e){try{return void 0===e?new Ud(this.firestore,Zu(this._delegate)):new Ud(this.firestore,Zu(this._delegate,e))}catch(e){throw Bd(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=$u(e.firestore,hl),r=Zu(e),s=gd(e.converter,t);return Sd(n,[Cl(Dl(e.firestore),"addDoc",r._key,s,null!==e.converter,{}).toMutation(r._key,Ei.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new Ud(this.firestore,e))}isEqual(e){return el(this._delegate,e._delegate)}withConverter(e){return new Qd(this.firestore,e?this._delegate.withConverter(qd.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Yd(e){return $u(e,Qu)}const Jd={Firestore:Od,GeoPoint:bl,Timestamp:$r,Blob:Rd,Transaction:Fd,WriteBatch:Vd,DocumentReference:Ud,DocumentSnapshot:$d,Query:Hd,QueryDocumentSnapshot:Gd,QuerySnapshot:zd,CollectionReference:Qd,FieldPath:class Xd{constructor(...e){this._delegate=new yl(...e)}static documentId(){return new Xd(Xr.keyField().canonicalString())}isEqual(e){return(e=m(e))instanceof yl&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class Zd{constructor(e){this._delegate=e}static serverTimestamp(){const e=new xl("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new Zd(e)}static delete(){const e=new kl("deleteField");return e._methodName="FieldValue.delete",new Zd(e)}static arrayUnion(...e){const t=function(...e){return new Rl("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new Zd(t)}static arrayRemove(...e){const t=function(...e){return new Ll("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new Zd(t)}static increment(e){const t=new Ml("increment",e);return t._methodName="FieldValue.increment",new Zd(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,br.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};ol=t.default,al=(e,t)=>new Od(e,t,new Md),ol.INTERNAL.registerComponent(new c("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return al(t,n)},"PUBLIC").setServiceProps(Object.assign({},Jd))),ol.registerVersion("@firebase/firestore-compat","0.1.12")}).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