/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/@theaimegroup/feedback-v2@2.2.125/dist/cjs/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
var e=require("react/jsx-runtime"),t=require("@chakra-ui/react"),n=require("react"),r=require("graphql"),i=require("react-konva"),s=require("lodash"),o=require("use-image"),a=require("@auth0/auth0-react"),c=require("@chakra-ui/icons");function u(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var l=u(n),h="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function d(){throw new Error("setTimeout has not been defined")}function f(){throw new Error("clearTimeout has not been defined")}var p=d,m=f;function g(e){if(p===setTimeout)return setTimeout(e,0);if((p===d||!p)&&setTimeout)return p=setTimeout,setTimeout(e,0);try{return p(e,0)}catch(t){try{return p.call(null,e,0)}catch(t){return p.call(this,e,0)}}}"function"==typeof h.setTimeout&&(p=setTimeout),"function"==typeof h.clearTimeout&&(m=clearTimeout);var y,v=[],_=!1,w=-1;function b(){_&&y&&(_=!1,y.length?v=y.concat(v):w=-1,v.length&&I())}function I(){if(!_){var e=g(b);_=!0;for(var t=v.length;t;){for(y=v,v=[];++w<t;)y&&y[w].run();w=-1,t=v.length}y=null,_=!1,function(e){if(m===clearTimeout)return clearTimeout(e);if((m===f||!m)&&clearTimeout)return m=clearTimeout,clearTimeout(e);try{return m(e)}catch(t){try{return m.call(null,e)}catch(t){return m.call(this,e)}}}(e)}}function E(e,t){this.fun=e,this.array=t}E.prototype.run=function(){this.fun.apply(null,this.array)};function T(){}var S=T,k=T,C=T,x=T,A=T,N=T,D=T;var R=h.performance||{},O=R.now||R.mozNow||R.msNow||R.oNow||R.webkitNow||function(){return(new Date).getTime()};var P=new Date;var M={nextTick:function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];v.push(new E(e,t)),1!==v.length||_||g(I)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:S,addListener:k,once:C,off:x,removeListener:A,removeAllListeners:N,emit:D,binding:function(e){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(e){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(e){var t=.001*O.call(R),n=Math.floor(t),r=Math.floor(t%1*1e9);return e&&(n-=e[0],(r-=e[1])<0&&(n--,r+=1e9)),[n,r]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-P)/1e3}};const L=(()=>{let e=0;return()=>(e+=1,`u${`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4)}${e}`)})();function F(e){const t=[];for(let n=0,r=e.length;n<r;n++)t.push(e[n]);return t}function j(e,t){const n=(e.ownerDocument.defaultView||window).getComputedStyle(e).getPropertyValue(t);return n?parseFloat(n.replace("px","")):0}function q(e,t={}){return{width:t.width||function(e){const t=j(e,"border-left-width"),n=j(e,"border-right-width");return e.clientWidth+t+n}(e),height:t.height||function(e){const t=j(e,"border-top-width"),n=j(e,"border-bottom-width");return e.clientHeight+t+n}(e)}}const V=16384;function U(e){return new Promise(((t,n)=>{const r=new Image;r.decode=()=>t(r),r.onload=()=>t(r),r.onerror=n,r.crossOrigin="anonymous",r.decoding="async",r.src=e}))}async function B(e,t,n){const r="http://www.w3.org/2000/svg",i=document.createElementNS(r,"svg"),s=document.createElementNS(r,"foreignObject");return i.setAttribute("width",`${t}`),i.setAttribute("height",`${n}`),i.setAttribute("viewBox",`0 0 ${t} ${n}`),s.setAttribute("width","100%"),s.setAttribute("height","100%"),s.setAttribute("x","0"),s.setAttribute("y","0"),s.setAttribute("externalResourcesRequired","true"),i.appendChild(s),s.appendChild(e),async function(e){return Promise.resolve().then((()=>(new XMLSerializer).serializeToString(e))).then(encodeURIComponent).then((e=>`data:image/svg+xml;charset=utf-8,${e}`))}(i)}const z=(e,t)=>{if(e instanceof t)return!0;const n=Object.getPrototypeOf(e);return null!==n&&(n.constructor.name===t.name||z(n,t))};function $(e,t,n){const r=`.${e}:${t}`,i=n.cssText?function(e){const t=e.getPropertyValue("content");return`${e.cssText} content: '${t.replace(/'|"/g,"")}';`}(n):function(e){return F(e).map((t=>`${t}: ${e.getPropertyValue(t)}${e.getPropertyPriority(t)?" !important":""};`)).join(" ")}(n);return document.createTextNode(`${r}{${i}}`)}function W(e,t,n){const r=window.getComputedStyle(e,n),i=r.getPropertyValue("content");if(""===i||"none"===i)return;const s=L();try{t.className=`${t.className} ${s}`}catch(e){return}const o=document.createElement("style");o.appendChild($(s,n,r)),t.appendChild(o)}const Q="application/font-woff",H="image/jpeg",G={woff:Q,woff2:Q,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:H,jpeg:H,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function K(e){const t=function(e){const t=/\.([^./]*?)$/g.exec(e);return t?t[1]:""}(e).toLowerCase();return G[t]||""}function Y(e){return-1!==e.search(/^(data:)/)}function J(e,t){return`data:${t};base64,${e}`}async function X(e,t,n){const r=await fetch(e,t);if(404===r.status)throw new Error(`Resource "${r.url}" not found`);const i=await r.blob();return new Promise(((e,t)=>{const s=new FileReader;s.onerror=t,s.onloadend=()=>{try{e(n({res:r,result:s.result}))}catch(e){t(e)}},s.readAsDataURL(i)}))}const Z={};async function ee(e,t,n){const r=function(e,t,n){let r=e.replace(/\?.*/,"");return n&&(r=e),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}(e,t,n.includeQueryParams);if(null!=Z[r])return Z[r];let i;n.cacheBust&&(e+=(/\?/.test(e)?"&":"?")+(new Date).getTime());try{const r=await X(e,n.fetchRequestInit,(({res:e,result:n})=>(t||(t=e.headers.get("Content-Type")||""),function(e){return e.split(/,/)[1]}(n))));i=J(r,t)}catch(t){i=n.imagePlaceholder||"";let r=`Failed to fetch resource: ${e}`;t&&(r="string"==typeof t?t:t.message),r&&console.warn(r)}return Z[r]=i,i}async function te(e,t){return z(e,HTMLCanvasElement)?async function(e){const t=e.toDataURL();return"data:,"===t?e.cloneNode(!1):U(t)}(e):z(e,HTMLVideoElement)?async function(e,t){if(e.currentSrc){const t=document.createElement("canvas"),n=t.getContext("2d");return t.width=e.clientWidth,t.height=e.clientHeight,null==n||n.drawImage(e,0,0,t.width,t.height),U(t.toDataURL())}const n=e.poster,r=K(n);return U(await ee(n,r,t))}(e,t):z(e,HTMLIFrameElement)?async function(e){var t;try{if(null===(t=null==e?void 0:e.contentDocument)||void 0===t?void 0:t.body)return await ie(e.contentDocument.body,{},!0)}catch(e){}return e.cloneNode(!1)}(e):e.cloneNode(!1)}const ne=e=>null!=e.tagName&&"SLOT"===e.tagName.toUpperCase();function re(e,t){return z(t,Element)&&(function(e,t){const n=t.style;if(!n)return;const r=window.getComputedStyle(e);r.cssText?(n.cssText=r.cssText,n.transformOrigin=r.transformOrigin):F(r).forEach((i=>{let s=r.getPropertyValue(i);if("font-size"===i&&s.endsWith("px")){const e=Math.floor(parseFloat(s.substring(0,s.length-2)))-.1;s=`${e}px`}z(e,HTMLIFrameElement)&&"display"===i&&"inline"===s&&(s="block"),"d"===i&&t.getAttribute("d")&&(s=`path(${t.getAttribute("d")})`),n.setProperty(i,s,r.getPropertyPriority(i))}))}(e,t),function(e,t){W(e,t,":before"),W(e,t,":after")}(e,t),function(e,t){z(e,HTMLTextAreaElement)&&(t.innerHTML=e.value),z(e,HTMLInputElement)&&t.setAttribute("value",e.value)}(e,t),function(e,t){if(z(e,HTMLSelectElement)){const n=t,r=Array.from(n.children).find((t=>e.value===t.getAttribute("value")));r&&r.setAttribute("selected","")}}(e,t)),t}async function ie(e,t,n){return n||!t.filter||t.filter(e)?Promise.resolve(e).then((e=>te(e,t))).then((n=>async function(e,t,n){var r,i;let s=[];return s=ne(e)&&e.assignedNodes?F(e.assignedNodes()):z(e,HTMLIFrameElement)&&(null===(r=e.contentDocument)||void 0===r?void 0:r.body)?F(e.contentDocument.body.childNodes):F((null!==(i=e.shadowRoot)&&void 0!==i?i:e).childNodes),0===s.length||z(e,HTMLVideoElement)||await s.reduce(((e,r)=>e.then((()=>ie(r,n))).then((e=>{e&&t.appendChild(e)}))),Promise.resolve()),t}(e,n,t))).then((t=>re(e,t))).then((e=>async function(e,t){const n=e.querySelectorAll?e.querySelectorAll("use"):[];if(0===n.length)return e;const r={};for(let i=0;i<n.length;i++){const s=n[i].getAttribute("xlink:href");if(s){const n=e.querySelector(s),i=document.querySelector(s);n||!i||r[s]||(r[s]=await ie(i,t,!0))}}const i=Object.values(r);if(i.length){const t="http://www.w3.org/1999/xhtml",n=document.createElementNS(t,"svg");n.setAttribute("xmlns",t),n.style.position="absolute",n.style.width="0",n.style.height="0",n.style.overflow="hidden",n.style.display="none";const r=document.createElementNS(t,"defs");n.appendChild(r);for(let e=0;e<i.length;e++)r.appendChild(i[e]);e.appendChild(n)}return e}(e,t))):null}const se=/url\((['"]?)([^'"]+?)\1\)/g,oe=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,ae=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;async function ce(e,t,n,r,i){try{const s=n?function(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i))return e;const n=document.implementation.createHTMLDocument(),r=n.createElement("base"),i=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(i),t&&(r.href=t),i.href=e,i.href}(t,n):t,o=K(t);let a;if(i){a=J(await i(s),o)}else a=await ee(s,o,r);return e.replace(function(e){const t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}(t),`$1${a}$3`)}catch(e){}return e}function ue(e){return-1!==e.search(se)}async function le(e,t,n){if(!ue(e))return e;const r=function(e,{preferredFontFormat:t}){return t?e.replace(ae,(e=>{for(;;){const[n,,r]=oe.exec(e)||[];if(!r)return"";if(r===t)return`src: ${n};`}})):e}(e,n),i=function(e){const t=[];return e.replace(se,((e,n,r)=>(t.push(r),e))),t.filter((e=>!Y(e)))}(r);return i.reduce(((e,r)=>e.then((e=>ce(e,r,t,n)))),Promise.resolve(r))}async function he(e,t,n){var r;const i=null===(r=t.style)||void 0===r?void 0:r.getPropertyValue(e);if(i){const r=await le(i,null,n);return t.style.setProperty(e,r,t.style.getPropertyPriority(e)),!0}return!1}async function de(e,t){z(e,Element)&&(await async function(e,t){await he("background",e,t)||await he("background-image",e,t),await he("mask",e,t)||await he("mask-image",e,t)}(e,t),await async function(e,t){const n=z(e,HTMLImageElement);if((!n||Y(e.src))&&(!z(e,SVGImageElement)||Y(e.href.baseVal)))return;const r=n?e.src:e.href.baseVal,i=await ee(r,K(r),t);await new Promise(((t,r)=>{e.onload=t,e.onerror=r;const s=e;s.decode&&(s.decode=t),"lazy"===s.loading&&(s.loading="eager"),n?(e.srcset="",e.src=i):e.href.baseVal=i}))}(e,t),await async function(e,t){const n=F(e.childNodes).map((e=>de(e,t)));await Promise.all(n).then((()=>e))}(e,t))}const fe={};async function pe(e){let t=fe[e];if(null!=t)return t;const n=await fetch(e);return t={url:e,cssText:await n.text()},fe[e]=t,t}async function me(e,t){let n=e.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,i=(n.match(/url\([^)]+\)/g)||[]).map((async i=>{let s=i.replace(r,"$1");return s.startsWith("https://")||(s=new URL(s,e.url).href),X(s,t.fetchRequestInit,(({result:e})=>(n=n.replace(i,`url(${e})`),[i,e])))}));return Promise.all(i).then((()=>n))}function ge(e){if(null==e)return[];const t=[];let n=e.replace(/(\/\*[\s\S]*?\*\/)/gi,"");const r=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const e=r.exec(n);if(null===e)break;t.push(e[0])}n=n.replace(r,"");const i=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,s=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let e=i.exec(n);if(null===e){if(e=s.exec(n),null===e)break;i.lastIndex=s.lastIndex}else s.lastIndex=i.lastIndex;t.push(e[0])}return t}async function ye(e,t){if(null==e.ownerDocument)throw new Error("Provided element is not within a Document");const n=F(e.ownerDocument.styleSheets),r=await async function(e,t){const n=[],r=[];return e.forEach((n=>{if("cssRules"in n)try{F(n.cssRules||[]).forEach(((e,i)=>{if(e.type===CSSRule.IMPORT_RULE){let s=i+1;const o=pe(e.href).then((e=>me(e,t))).then((e=>ge(e).forEach((e=>{try{n.insertRule(e,e.startsWith("@import")?s+=1:n.cssRules.length)}catch(t){console.error("Error inserting rule from remote css",{rule:e,error:t})}})))).catch((e=>{console.error("Error loading remote css",e.toString())}));r.push(o)}}))}catch(i){const s=e.find((e=>null==e.href))||document.styleSheets[0];null!=n.href&&r.push(pe(n.href).then((e=>me(e,t))).then((e=>ge(e).forEach((e=>{s.insertRule(e,n.cssRules.length)})))).catch((e=>{console.error("Error loading remote stylesheet",e)}))),console.error("Error inlining remote css file",i)}})),Promise.all(r).then((()=>(e.forEach((e=>{if("cssRules"in e)try{F(e.cssRules||[]).forEach((e=>{n.push(e)}))}catch(t){console.error(`Error while reading CSS rules from ${e.href}`,t)}})),n)))}(n,t);return function(e){return e.filter((e=>e.type===CSSRule.FONT_FACE_RULE)).filter((e=>ue(e.style.getPropertyValue("src"))))}(r)}async function ve(e,t){const n=null!=t.fontEmbedCSS?t.fontEmbedCSS:t.skipFonts?null:await async function(e,t){const n=await ye(e,t);return(await Promise.all(n.map((e=>{const n=e.parentStyleSheet?e.parentStyleSheet.href:null;return le(e.cssText,n,t)})))).join("\n")}(e,t);if(n){const t=document.createElement("style"),r=document.createTextNode(n);t.appendChild(r),e.firstChild?e.insertBefore(t,e.firstChild):e.appendChild(t)}}async function _e(e,t={}){const{width:n,height:r}=q(e,t),i=await ie(e,t,!0);await ve(i,t),await de(i,t),function(e,t){const{style:n}=e;t.backgroundColor&&(n.backgroundColor=t.backgroundColor),t.width&&(n.width=`${t.width}px`),t.height&&(n.height=`${t.height}px`);const r=t.style;null!=r&&Object.keys(r).forEach((e=>{n[e]=r[e]}))}(i,t);return await B(i,n,r)}async function we(e,t={}){const{width:n,height:r}=q(e,t),i=await _e(e,t),s=await U(i),o=document.createElement("canvas"),a=o.getContext("2d"),c=t.pixelRatio||function(){let e,t;try{t=M}catch(e){}const n=t&&t.env?t.env.devicePixelRatio:null;return n&&(e=parseInt(n,10),Number.isNaN(e)&&(e=1)),e||window.devicePixelRatio||1}(),u=t.canvasWidth||n,l=t.canvasHeight||r;return o.width=u*c,o.height=l*c,t.skipAutoScale||function(e){(e.width>V||e.height>V)&&(e.width>V&&e.height>V?e.width>e.height?(e.height*=V/e.width,e.width=V):(e.width*=V/e.height,e.height=V):e.width>V?(e.height*=V/e.width,e.width=V):(e.width*=V/e.height,e.height=V))}(o),o.style.width=`${u}`,o.style.height=`${l}`,t.backgroundColor&&(a.fillStyle=t.backgroundColor,a.fillRect(0,0,o.width,o.height)),a.drawImage(s,0,0,o.width,o.height),o}function be(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Ie(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var n=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),n}var Ee,Te={exports:{}},Se={exports:{}},ke={};var Ce,xe,Ae,Ne,De,Re,Oe,Pe,Me,Le,Fe,je,qe,Ve,Ue={};function Be(){return xe||(xe=1,"production"===M.env.NODE_ENV?Se.exports=function(){if(Ee)return ke;Ee=1;var e="function"==typeof Symbol&&Symbol.for,t=e?Symbol.for("react.element"):60103,n=e?Symbol.for("react.portal"):60106,r=e?Symbol.for("react.fragment"):60107,i=e?Symbol.for("react.strict_mode"):60108,s=e?Symbol.for("react.profiler"):60114,o=e?Symbol.for("react.provider"):60109,a=e?Symbol.for("react.context"):60110,c=e?Symbol.for("react.async_mode"):60111,u=e?Symbol.for("react.concurrent_mode"):60111,l=e?Symbol.for("react.forward_ref"):60112,h=e?Symbol.for("react.suspense"):60113,d=e?Symbol.for("react.suspense_list"):60120,f=e?Symbol.for("react.memo"):60115,p=e?Symbol.for("react.lazy"):60116,m=e?Symbol.for("react.block"):60121,g=e?Symbol.for("react.fundamental"):60117,y=e?Symbol.for("react.responder"):60118,v=e?Symbol.for("react.scope"):60119;function _(e){if("object"==typeof e&&null!==e){var d=e.$$typeof;switch(d){case t:switch(e=e.type){case c:case u:case r:case s:case i:case h:return e;default:switch(e=e&&e.$$typeof){case a:case l:case p:case f:case o:return e;default:return d}}case n:return d}}}function w(e){return _(e)===u}return ke.AsyncMode=c,ke.ConcurrentMode=u,ke.ContextConsumer=a,ke.ContextProvider=o,ke.Element=t,ke.ForwardRef=l,ke.Fragment=r,ke.Lazy=p,ke.Memo=f,ke.Portal=n,ke.Profiler=s,ke.StrictMode=i,ke.Suspense=h,ke.isAsyncMode=function(e){return w(e)||_(e)===c},ke.isConcurrentMode=w,ke.isContextConsumer=function(e){return _(e)===a},ke.isContextProvider=function(e){return _(e)===o},ke.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===t},ke.isForwardRef=function(e){return _(e)===l},ke.isFragment=function(e){return _(e)===r},ke.isLazy=function(e){return _(e)===p},ke.isMemo=function(e){return _(e)===f},ke.isPortal=function(e){return _(e)===n},ke.isProfiler=function(e){return _(e)===s},ke.isStrictMode=function(e){return _(e)===i},ke.isSuspense=function(e){return _(e)===h},ke.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===r||e===u||e===s||e===i||e===h||e===d||"object"==typeof e&&null!==e&&(e.$$typeof===p||e.$$typeof===f||e.$$typeof===o||e.$$typeof===a||e.$$typeof===l||e.$$typeof===g||e.$$typeof===y||e.$$typeof===v||e.$$typeof===m)},ke.typeOf=_,ke}():Se.exports=(Ce||(Ce=1,"production"!==M.env.NODE_ENV&&function(){var e="function"==typeof Symbol&&Symbol.for,t=e?Symbol.for("react.element"):60103,n=e?Symbol.for("react.portal"):60106,r=e?Symbol.for("react.fragment"):60107,i=e?Symbol.for("react.strict_mode"):60108,s=e?Symbol.for("react.profiler"):60114,o=e?Symbol.for("react.provider"):60109,a=e?Symbol.for("react.context"):60110,c=e?Symbol.for("react.async_mode"):60111,u=e?Symbol.for("react.concurrent_mode"):60111,l=e?Symbol.for("react.forward_ref"):60112,h=e?Symbol.for("react.suspense"):60113,d=e?Symbol.for("react.suspense_list"):60120,f=e?Symbol.for("react.memo"):60115,p=e?Symbol.for("react.lazy"):60116,m=e?Symbol.for("react.block"):60121,g=e?Symbol.for("react.fundamental"):60117,y=e?Symbol.for("react.responder"):60118,v=e?Symbol.for("react.scope"):60119;function _(e){if("object"==typeof e&&null!==e){var d=e.$$typeof;switch(d){case t:var m=e.type;switch(m){case c:case u:case r:case s:case i:case h:return m;default:var g=m&&m.$$typeof;switch(g){case a:case l:case p:case f:case o:return g;default:return d}}case n:return d}}}var w=c,b=u,I=a,E=o,T=t,S=l,k=r,C=p,x=f,A=n,N=s,D=i,R=h,O=!1;function P(e){return _(e)===u}Ue.AsyncMode=w,Ue.ConcurrentMode=b,Ue.ContextConsumer=I,Ue.ContextProvider=E,Ue.Element=T,Ue.ForwardRef=S,Ue.Fragment=k,Ue.Lazy=C,Ue.Memo=x,Ue.Portal=A,Ue.Profiler=N,Ue.StrictMode=D,Ue.Suspense=R,Ue.isAsyncMode=function(e){return O||(O=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.")),P(e)||_(e)===c},Ue.isConcurrentMode=P,Ue.isContextConsumer=function(e){return _(e)===a},Ue.isContextProvider=function(e){return _(e)===o},Ue.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===t},Ue.isForwardRef=function(e){return _(e)===l},Ue.isFragment=function(e){return _(e)===r},Ue.isLazy=function(e){return _(e)===p},Ue.isMemo=function(e){return _(e)===f},Ue.isPortal=function(e){return _(e)===n},Ue.isProfiler=function(e){return _(e)===s},Ue.isStrictMode=function(e){return _(e)===i},Ue.isSuspense=function(e){return _(e)===h},Ue.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===r||e===u||e===s||e===i||e===h||e===d||"object"==typeof e&&null!==e&&(e.$$typeof===p||e.$$typeof===f||e.$$typeof===o||e.$$typeof===a||e.$$typeof===l||e.$$typeof===g||e.$$typeof===y||e.$$typeof===v||e.$$typeof===m)},Ue.typeOf=_}()),Ue)),Se.exports}
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/function ze(){if(Ne)return Ae;Ne=1;var e=Object.getOwnPropertySymbols,t=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable;return Ae=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach((function(e){r[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(r,i){for(var s,o,a=function(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(r),c=1;c<arguments.length;c++){for(var u in s=Object(arguments[c]))t.call(s,u)&&(a[u]=s[u]);if(e){o=e(s);for(var l=0;l<o.length;l++)n.call(s,o[l])&&(a[o[l]]=s[o[l]])}}return a},Ae}function $e(){if(Re)return De;Re=1;return De="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"}function We(){return Pe?Oe:(Pe=1,Oe=Function.call.bind(Object.prototype.hasOwnProperty))}if("production"!==M.env.NODE_ENV){var Qe=Be();Te.exports=function(){if(je)return Fe;je=1;var e=Be(),t=ze(),n=$e(),r=We(),i=function(){if(Le)return Me;Le=1;var e=function(){};if("production"!==M.env.NODE_ENV){var t=$e(),n={},r=We();e=function(e){var t="Warning: "+e;"undefined"!=typeof console&&console.error(t);try{throw new Error(t)}catch(e){}}}function i(i,s,o,a,c){if("production"!==M.env.NODE_ENV)for(var u in i)if(r(i,u)){var l;try{if("function"!=typeof i[u]){var h=Error((a||"React class")+": "+o+" type `"+u+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof i[u]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw h.name="Invariant Violation",h}l=i[u](s,u,a,o,null,t)}catch(e){l=e}if(!l||l instanceof Error||e((a||"React class")+": type specification of "+o+" `"+u+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+typeof l+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."),l instanceof Error&&!(l.message in n)){n[l.message]=!0;var d=c?c():"";e("Failed "+o+" type: "+l.message+(null!=d?d:""))}}}return i.resetWarningCache=function(){"production"!==M.env.NODE_ENV&&(n={})},Me=i}(),s=function(){};function o(){return null}return"production"!==M.env.NODE_ENV&&(s=function(e){var t="Warning: "+e;"undefined"!=typeof console&&console.error(t);try{throw new Error(t)}catch(e){}}),Fe=function(a,c){var u="function"==typeof Symbol&&Symbol.iterator,l="@@iterator",h="<<anonymous>>",d={array:g("array"),bigint:g("bigint"),bool:g("boolean"),func:g("function"),number:g("number"),object:g("object"),string:g("string"),symbol:g("symbol"),any:m(o),arrayOf:function(e){return m((function(t,r,i,s,o){if("function"!=typeof e)return new p("Property `"+o+"` of component `"+i+"` has invalid PropType notation inside arrayOf.");var a=t[r];if(!Array.isArray(a))return new p("Invalid "+s+" `"+o+"` of type `"+_(a)+"` supplied to `"+i+"`, expected an array.");for(var c=0;c<a.length;c++){var u=e(a,c,i,s,o+"["+c+"]",n);if(u instanceof Error)return u}return null}))},element:m((function(e,t,n,r,i){var s=e[t];return a(s)?null:new p("Invalid "+r+" `"+i+"` of type `"+_(s)+"` supplied to `"+n+"`, expected a single ReactElement.")})),elementType:m((function(t,n,r,i,s){var o=t[n];return e.isValidElementType(o)?null:new p("Invalid "+i+" `"+s+"` of type `"+_(o)+"` supplied to `"+r+"`, expected a single ReactElement type.")})),instanceOf:function(e){return m((function(t,n,r,i,s){if(!(t[n]instanceof e)){var o=e.name||h;return new p("Invalid "+i+" `"+s+"` of type `"+((a=t[n]).constructor&&a.constructor.name?a.constructor.name:h)+"` supplied to `"+r+"`, expected instance of `"+o+"`.")}var a;return null}))},node:m((function(e,t,n,r,i){return v(e[t])?null:new p("Invalid "+r+" `"+i+"` supplied to `"+n+"`, expected a ReactNode.")})),objectOf:function(e){return m((function(t,i,s,o,a){if("function"!=typeof e)return new p("Property `"+a+"` of component `"+s+"` has invalid PropType notation inside objectOf.");var c=t[i],u=_(c);if("object"!==u)return new p("Invalid "+o+" `"+a+"` of type `"+u+"` supplied to `"+s+"`, expected an object.");for(var l in c)if(r(c,l)){var h=e(c,l,s,o,a+"."+l,n);if(h instanceof Error)return h}return null}))},oneOf:function(e){return Array.isArray(e)?m((function(t,n,r,i,s){for(var o=t[n],a=0;a<e.length;a++)if(f(o,e[a]))return null;var c=JSON.stringify(e,(function(e,t){return"symbol"===w(t)?String(t):t}));return new p("Invalid "+i+" `"+s+"` of value `"+String(o)+"` supplied to `"+r+"`, expected one of "+c+".")})):("production"!==M.env.NODE_ENV&&s(arguments.length>1?"Invalid arguments supplied to oneOf, expected an array, got "+arguments.length+" arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).":"Invalid argument supplied to oneOf, expected an array."),o)},oneOfType:function(e){if(!Array.isArray(e))return"production"!==M.env.NODE_ENV&&s("Invalid argument supplied to oneOfType, expected an instance of array."),o;for(var t=0;t<e.length;t++){var i=e[t];if("function"!=typeof i)return s("Invalid argument supplied to oneOfType. Expected an array of check functions, but received "+b(i)+" at index "+t+"."),o}return m((function(t,i,s,o,a){for(var c=[],u=0;u<e.length;u++){var l=(0,e[u])(t,i,s,o,a,n);if(null==l)return null;l.data&&r(l.data,"expectedType")&&c.push(l.data.expectedType)}return new p("Invalid "+o+" `"+a+"` supplied to `"+s+"`"+(c.length>0?", expected one of type ["+c.join(", ")+"]":"")+".")}))},shape:function(e){return m((function(t,r,i,s,o){var a=t[r],c=_(a);if("object"!==c)return new p("Invalid "+s+" `"+o+"` of type `"+c+"` supplied to `"+i+"`, expected `object`.");for(var u in e){var l=e[u];if("function"!=typeof l)return y(i,s,o,u,w(l));var h=l(a,u,i,s,o+"."+u,n);if(h)return h}return null}))},exact:function(e){return m((function(i,s,o,a,c){var u=i[s],l=_(u);if("object"!==l)return new p("Invalid "+a+" `"+c+"` of type `"+l+"` supplied to `"+o+"`, expected `object`.");var h=t({},i[s],e);for(var d in h){var f=e[d];if(r(e,d)&&"function"!=typeof f)return y(o,a,c,d,w(f));if(!f)return new p("Invalid "+a+" `"+c+"` key `"+d+"` supplied to `"+o+"`.\nBad object: "+JSON.stringify(i[s],null,"  ")+"\nValid keys: "+JSON.stringify(Object.keys(e),null,"  "));var m=f(u,d,o,a,c+"."+d,n);if(m)return m}return null}))}};function f(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}function p(e,t){this.message=e,this.data=t&&"object"==typeof t?t:{},this.stack=""}function m(e){if("production"!==M.env.NODE_ENV)var t={},r=0;function i(i,o,a,u,l,d,f){if(u=u||h,d=d||a,f!==n){if(c){var m=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");throw m.name="Invariant Violation",m}if("production"!==M.env.NODE_ENV&&"undefined"!=typeof console){var g=u+":"+a;!t[g]&&r<3&&(s("You are manually calling a React.PropTypes validation function for the `"+d+"` prop on `"+u+"`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."),t[g]=!0,r++)}}return null==o[a]?i?null===o[a]?new p("The "+l+" `"+d+"` is marked as required in `"+u+"`, but its value is `null`."):new p("The "+l+" `"+d+"` is marked as required in `"+u+"`, but its value is `undefined`."):null:e(o,a,u,l,d)}var o=i.bind(null,!1);return o.isRequired=i.bind(null,!0),o}function g(e){return m((function(t,n,r,i,s,o){var a=t[n];return _(a)!==e?new p("Invalid "+i+" `"+s+"` of type `"+w(a)+"` supplied to `"+r+"`, expected `"+e+"`.",{expectedType:e}):null}))}function y(e,t,n,r,i){return new p((e||"React class")+": "+t+" type `"+n+"."+r+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+i+"`.")}function v(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(v);if(null===e||a(e))return!0;var t=function(e){var t=e&&(u&&e[u]||e[l]);if("function"==typeof t)return t}(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!v(n.value))return!1}else for(;!(n=r.next()).done;){var i=n.value;if(i&&!v(i[1]))return!1}return!0;default:return!1}}function _(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":function(e,t){return"symbol"===e||!!t&&("Symbol"===t["@@toStringTag"]||"function"==typeof Symbol&&t instanceof Symbol)}(t,e)?"symbol":t}function w(e){if(null==e)return""+e;var t=_(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function b(e){var t=w(e);switch(t){case"array":case"object":return"an "+t;case"boolean":case"date":case"regexp":return"a "+t;default:return t}}return p.prototype=Error.prototype,d.checkPropTypes=i,d.resetWarningCache=i.resetWarningCache,d.PropTypes=d,d},Fe}()(Qe.isElement,!0)}else Te.exports=function(){if(Ve)return qe;Ve=1;var e=$e();function t(){}function n(){}return n.resetWarningCache=t,qe=function(){function r(t,n,r,i,s,o){if(o!==e){var a=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw a.name="Invariant Violation",a}}function i(){return r}r.isRequired=r;var s={array:r,bigint:r,bool:r,func:r,number:r,object:r,string:r,symbol:r,any:r,arrayOf:i,element:r,elementType:r,instanceOf:i,node:r,objectOf:i,oneOf:i,oneOfType:i,shape:i,exact:i,checkPropTypes:n,resetWarningCache:t};return s.PropTypes=s,s}}()();var He=be(Te.exports),Ge={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},Ke=Object.defineProperty,Ye=Object.defineProperties,Je=Object.getOwnPropertyDescriptors,Xe=Object.getOwnPropertySymbols,Ze=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable,tt=(e,t,n)=>t in e?Ke(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,nt=(e,t)=>{for(var n in t||(t={}))Ze.call(t,n)&&tt(e,n,t[n]);if(Xe)for(var n of Xe(t))et.call(t,n)&&tt(e,n,t[n]);return e},rt=(e,t,r)=>{const i=n.forwardRef(((t,i)=>{var s=t,{color:o="currentColor",size:a=24,stroke:c=2,children:u}=s,l=((e,t)=>{var n={};for(var r in e)Ze.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&Xe)for(var r of Xe(e))t.indexOf(r)<0&&et.call(e,r)&&(n[r]=e[r]);return n})(s,["color","size","stroke","children"]);return n.createElement("svg",nt(((e,t)=>Ye(e,Je(t)))(nt({ref:i},Ge),{width:a,height:a,stroke:o,strokeWidth:c,className:`tabler-icon tabler-icon-${e}`}),l),[...r.map((([e,t])=>n.createElement(e,t))),...u||[]])}));return i.propTypes={color:He.string,size:He.oneOfType([He.string,He.number]),stroke:He.oneOfType([He.string,He.number])},i.displayName=`${t}`,i},it=rt("camera-plus","IconCameraPlus",[["path",{d:"M12 20h-7a2 2 0 0 1 -2 -2v-9a2 2 0 0 1 2 -2h1a2 2 0 0 0 2 -2a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1a2 2 0 0 0 2 2h1a2 2 0 0 1 2 2v3.5",key:"svg-0"}],["path",{d:"M16 19h6",key:"svg-1"}],["path",{d:"M19 16v6",key:"svg-2"}],["path",{d:"M9 13a3 3 0 1 0 6 0a3 3 0 0 0 -6 0",key:"svg-3"}]]),st=rt("message-report","IconMessageReport",[["path",{d:"M4 21v-13a3 3 0 0 1 3 -3h10a3 3 0 0 1 3 3v6a3 3 0 0 1 -3 3h-9l-4 4",key:"svg-0"}],["path",{d:"M12 8l0 3",key:"svg-1"}],["path",{d:"M12 14l0 .01",key:"svg-2"}]]),ot=rt("message","IconMessage",[["path",{d:"M8 9h8",key:"svg-0"}],["path",{d:"M8 13h6",key:"svg-1"}],["path",{d:"M18 4a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-5l-5 3v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12z",key:"svg-2"}]]),at=rt("photo-down","IconPhotoDown",[["path",{d:"M15 8h.01",key:"svg-0"}],["path",{d:"M12.5 21h-6.5a3 3 0 0 1 -3 -3v-12a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v6.5",key:"svg-1"}],["path",{d:"M3 16l5 -5c.928 -.893 2.072 -.893 3 0l4 4",key:"svg-2"}],["path",{d:"M14 14l1 -1c.653 -.629 1.413 -.815 2.13 -.559",key:"svg-3"}],["path",{d:"M19 16v6",key:"svg-4"}],["path",{d:"M22 19l-3 3l-3 -3",key:"svg-5"}]]),ct=rt("photo-plus","IconPhotoPlus",[["path",{d:"M15 8h.01",key:"svg-0"}],["path",{d:"M12.5 21h-6.5a3 3 0 0 1 -3 -3v-12a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v6.5",key:"svg-1"}],["path",{d:"M3 16l5 -5c.928 -.893 2.072 -.893 3 0l4 4",key:"svg-2"}],["path",{d:"M14 14l1 -1c.67 -.644 1.45 -.824 2.182 -.54",key:"svg-3"}],["path",{d:"M16 19h6",key:"svg-4"}],["path",{d:"M19 16v6",key:"svg-5"}]]),ut=rt("zoom-reset","IconZoomReset",[["path",{d:"M21 21l-6 -6",key:"svg-0"}],["path",{d:"M3.268 12.043a7.017 7.017 0 0 0 6.634 4.957a7.012 7.012 0 0 0 7.043 -6.131a7 7 0 0 0 -5.314 -7.672a7.021 7.021 0 0 0 -8.241 4.403",key:"svg-1"}],["path",{d:"M3 4v4h4",key:"svg-2"}]]),lt=function(e,t){return lt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},lt(e,t)};function ht(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}lt(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var dt=function(){return dt=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},dt.apply(this,arguments)};function ft(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}function pt(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}function mt(e,t){var n,r,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function gt(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return o}function yt(e,t,n){if(n||2===arguments.length)for(var r,i=0,s=t.length;i<s;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var vt="Invariant Violation",_t=Object.setPrototypeOf,wt=void 0===_t?function(e,t){return e.__proto__=t,e}:_t,bt=function(e){function t(n){void 0===n&&(n=vt);var r=e.call(this,"number"==typeof n?vt+": "+n+" (see https://github.com/apollographql/invariant-packages)":n)||this;return r.framesToPop=1,r.name=vt,wt(r,t.prototype),r}return ht(t,e),t}(Error);function It(e,t){if(!e)throw new bt(t)}var Et=["debug","log","warn","error","silent"],Tt=Et.indexOf("log");function St(e){return function(){if(Et.indexOf(e)>=Tt)return(console[e]||console.log).apply(console,arguments)}}function kt(e){try{return e()}catch(e){}}!function(e){e.debug=St("debug"),e.log=St("log"),e.warn=St("warn"),e.error=St("error")}(It||(It={}));var Ct=kt((function(){return globalThis}))||kt((function(){return window}))||kt((function(){return self}))||kt((function(){return h}))||kt((function(){return kt.constructor("return this")()})),xt="__",At=[xt,xt].join("DEV");var Nt=function(){try{return Boolean(__DEV__)}catch(e){return Object.defineProperty(Ct,At,{value:"production"!==kt((function(){return M.env.NODE_ENV})),enumerable:!1,configurable:!0,writable:!0}),Ct[At]}}();function Dt(e){try{return e()}catch(e){}}var Rt=Dt((function(){return globalThis}))||Dt((function(){return window}))||Dt((function(){return self}))||Dt((function(){return h}))||Dt((function(){return Dt.constructor("return this")()})),Ot=!1;function Pt(){Ot&&(delete Rt.process,Ot=!1)}function Mt(e,t){var n=e.directives;return!n||!n.length||function(e){var t=[];e&&e.length&&e.forEach((function(e){if(function(e){var t=e.name.value;return"skip"===t||"include"===t}(e)){var n=e.arguments,r=e.name.value;__DEV__?It(n&&1===n.length,"Incorrect number of arguments for the @".concat(r," directive.")):It(n&&1===n.length,41);var i=n[0];__DEV__?It(i.name&&"if"===i.name.value,"Invalid argument for the @".concat(r," directive.")):It(i.name&&"if"===i.name.value,42);var s=i.value;__DEV__?It(s&&("Variable"===s.kind||"BooleanValue"===s.kind),"Argument for the @".concat(r," directive must be a variable or a boolean value.")):It(s&&("Variable"===s.kind||"BooleanValue"===s.kind),43),t.push({directive:e,ifArgument:i})}}));return t}(n).every((function(e){var n=e.directive,r=e.ifArgument,i=!1;return"Variable"===r.value.kind?(i=t&&t[r.value.name.value],__DEV__?It(void 0!==i,"Invalid variable referenced in @".concat(n.name.value," directive.")):It(void 0!==i,40)):i=r.value.value,"skip"===n.name.value?!i:i}))}function Lt(e,t,n){var i=new Set(e),s=i.size;return r.visit(t,{Directive:function(e){if(i.delete(e.name.value)&&(!n||!i.size))return r.BREAK}}),n?!i.size:i.size<s}function Ft(e){return e&&Lt(["client","export"],e,!0)}function jt(e,t){var n=t,r=[];return e.definitions.forEach((function(e){if("OperationDefinition"===e.kind)throw __DEV__?new bt("Found a ".concat(e.operation," operation").concat(e.name?" named '".concat(e.name.value,"'"):"",". ")+"No operations are allowed when using a fragment as a query. Only fragments are allowed."):new bt(44);"FragmentDefinition"===e.kind&&r.push(e)})),void 0===n&&(__DEV__?It(1===r.length,"Found ".concat(r.length," fragments. `fragmentName` must be provided when there is not exactly 1 fragment.")):It(1===r.length,45),n=r[0].name.value),dt(dt({},e),{definitions:yt([{kind:"OperationDefinition",operation:"query",selectionSet:{kind:"SelectionSet",selections:[{kind:"FragmentSpread",name:{kind:"Name",value:n}}]}}],e.definitions,!0)})}function qt(e){void 0===e&&(e=[]);var t={};return e.forEach((function(e){t[e.name.value]=e})),t}function Vt(e,t){switch(e.kind){case"InlineFragment":return e;case"FragmentSpread":var n=e.name.value;if("function"==typeof t)return t(n);var r=t&&t[n];return __DEV__?It(r,"No fragment named ".concat(n)):It(r,46),r||null;default:return null}}function Ut(e){return null!==e&&"object"==typeof e}function Bt(e){return{__ref:String(e)}}function zt(e){return Boolean(e&&"object"==typeof e&&"string"==typeof e.__ref)}function $t(e,t,n,r){if(function(e){return"IntValue"===e.kind}(n)||function(e){return"FloatValue"===e.kind}(n))e[t.value]=Number(n.value);else if(function(e){return"BooleanValue"===e.kind}(n)||function(e){return"StringValue"===e.kind}(n))e[t.value]=n.value;else if(function(e){return"ObjectValue"===e.kind}(n)){var i={};n.fields.map((function(e){return $t(i,e.name,e.value,r)})),e[t.value]=i}else if(function(e){return"Variable"===e.kind}(n)){var s=(r||{})[n.name.value];e[t.value]=s}else if(function(e){return"ListValue"===e.kind}(n))e[t.value]=n.values.map((function(e){var n={};return $t(n,t,e,r),n[t.value]}));else if(function(e){return"EnumValue"===e.kind}(n))e[t.value]=n.value;else{if(!function(e){return"NullValue"===e.kind}(n))throw __DEV__?new bt('The inline argument "'.concat(t.value,'" of kind "').concat(n.kind,'"')+"is not supported. Use variables instead of inline arguments to overcome this limitation."):new bt(55);e[t.value]=null}}!Rt||Dt((function(){return M.env.NODE_ENV}))||Dt((function(){return M}))||(Object.defineProperty(Rt,"process",{value:{env:{NODE_ENV:"production"}},configurable:!0,enumerable:!1,writable:!0}),Ot=!0),r.Source,Pt(),__DEV__?It("boolean"==typeof Nt,Nt):It("boolean"==typeof Nt,39);var Wt=["connection","include","skip","client","rest","export"],Qt=Object.assign((function(e,t,n){if(t&&n&&n.connection&&n.connection.key){if(n.connection.filter&&n.connection.filter.length>0){var r=n.connection.filter?n.connection.filter:[];r.sort();var i={};return r.forEach((function(e){i[e]=t[e]})),"".concat(n.connection.key,"(").concat(Ht(i),")")}return n.connection.key}var s=e;if(t){var o=Ht(t);s+="(".concat(o,")")}return n&&Object.keys(n).forEach((function(e){-1===Wt.indexOf(e)&&(n[e]&&Object.keys(n[e]).length?s+="@".concat(e,"(").concat(Ht(n[e]),")"):s+="@".concat(e))})),s}),{setStringify:function(e){var t=Ht;return Ht=e,t}}),Ht=function(e){return JSON.stringify(e,Gt)};function Gt(e,t){return Ut(t)&&!Array.isArray(t)&&(t=Object.keys(t).sort().reduce((function(e,n){return e[n]=t[n],e}),{})),t}function Kt(e,t){if(e.arguments&&e.arguments.length){var n={};return e.arguments.forEach((function(e){var r=e.name,i=e.value;return $t(n,r,i,t)})),n}return null}function Yt(e){return e.alias?e.alias.value:e.name.value}function Jt(e,t,n){for(var r,i=0,s=t.selections;i<s.length;i++){if(Xt(c=s[i])){if("__typename"===c.name.value)return e[Yt(c)]}else r?r.push(c):r=[c]}if("string"==typeof e.__typename)return e.__typename;if(r)for(var o=0,a=r;o<a.length;o++){var c,u=Jt(e,Vt(c=a[o],n).selectionSet,n);if("string"==typeof u)return u}}function Xt(e){return"Field"===e.kind}function Zt(e){__DEV__?It(e&&"Document"===e.kind,'Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a "gql" tag? http://docs.apollostack.com/apollo-client/core.html#gql'):It(e&&"Document"===e.kind,47);var t=e.definitions.filter((function(e){return"FragmentDefinition"!==e.kind})).map((function(e){if("OperationDefinition"!==e.kind)throw __DEV__?new bt('Schema type definitions not allowed in queries. Found: "'.concat(e.kind,'"')):new bt(48);return e}));return __DEV__?It(t.length<=1,"Ambiguous GraphQL document: contains ".concat(t.length," operations")):It(t.length<=1,49),e}function en(e){return Zt(e),e.definitions.filter((function(e){return"OperationDefinition"===e.kind}))[0]}function tn(e){return e.definitions.filter((function(e){return"OperationDefinition"===e.kind&&!!e.name})).map((function(e){return e.name.value}))[0]||null}function nn(e){return e.definitions.filter((function(e){return"FragmentDefinition"===e.kind}))}function rn(e){var t=en(e);return __DEV__?It(t&&"query"===t.operation,"Must contain a query definition."):It(t&&"query"===t.operation,50),t}function sn(e){var t;Zt(e);for(var n=0,r=e.definitions;n<r.length;n++){var i=r[n];if("OperationDefinition"===i.kind){var s=i.operation;if("query"===s||"mutation"===s||"subscription"===s)return i}"FragmentDefinition"!==i.kind||t||(t=i)}if(t)return t;throw __DEV__?new bt("Expected a parsed GraphQL query with a query, mutation, subscription, or a fragment."):new bt(54)}function on(e){var t=Object.create(null),n=e&&e.variableDefinitions;return n&&n.length&&n.forEach((function(e){e.defaultValue&&$t(t,e.variable.name,e.defaultValue)})),t}var an=Array.isArray;function cn(e){return Array.isArray(e)&&e.length>0}var un={kind:r.Kind.FIELD,name:{kind:r.Kind.NAME,value:"__typename"}};function ln(e,t){return!e||e.selectionSet.selections.every((function(e){return e.kind===r.Kind.FRAGMENT_SPREAD&&ln(t[e.name.value],t)}))}function hn(e){return ln(en(e)||function(e){__DEV__?It("Document"===e.kind,'Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a "gql" tag? http://docs.apollostack.com/apollo-client/core.html#gql'):It("Document"===e.kind,51),__DEV__?It(e.definitions.length<=1,"Fragment must have exactly one definition."):It(e.definitions.length<=1,52);var t=e.definitions[0];return __DEV__?It("FragmentDefinition"===t.kind,"Must be a fragment definition."):It("FragmentDefinition"===t.kind,53),t}(e),qt(nn(e)))?null:e}function dn(e){var t=new Map;return function(n){void 0===n&&(n=e);var r=t.get(n);return r||t.set(n,r={variables:new Set,fragmentSpreads:new Set}),r}}function fn(e,t){for(var n=dn(""),i=dn(""),s=function(e){for(var t=0,s=void 0;t<e.length&&(s=e[t]);++t)if(!an(s)){if(s.kind===r.Kind.OPERATION_DEFINITION)return n(s.name&&s.name.value);if(s.kind===r.Kind.FRAGMENT_DEFINITION)return i(s.name.value)}return __DEV__&&It.error("Could not find operation or fragment"),null},o=0,a=t.definitions.length-1;a>=0;--a)t.definitions[a].kind===r.Kind.OPERATION_DEFINITION&&++o;var c=function(e){var t=new Set,n=[];return e.forEach((function(e){e.name?t.add(e.name):e.test&&n.push(e.test)})),function(e){return t.has(e.name.value)||n.some((function(t){return t(e)}))}}(e),u=e.some((function(e){return e.remove})),l=function(e){return u&&e&&e.some(c)},h=new Map,d=!1,f={enter:function(e){if(l(e.directives))return d=!0,null}},p=r.visit(t,{Field:f,InlineFragment:f,VariableDefinition:{enter:function(){return!1}},Variable:{enter:function(e,t,n,r,i){var o=s(i);o&&o.variables.add(e.name.value)}},FragmentSpread:{enter:function(e,t,n,r,i){if(l(e.directives))return d=!0,null;var o=s(i);o&&o.fragmentSpreads.add(e.name.value)}},FragmentDefinition:{enter:function(e,t,n,r){h.set(JSON.stringify(r),e)},leave:function(e,t,n,s){return e===h.get(JSON.stringify(s))?e:o>0&&e.selectionSet.selections.every((function(e){return e.kind===r.Kind.FIELD&&"__typename"===e.name.value}))?(i(e.name.value).removed=!0,d=!0,null):void 0}},Directive:{leave:function(e){if(c(e))return d=!0,null}}});if(!d)return t;var m=function(e){return e.transitiveVars||(e.transitiveVars=new Set(e.variables),e.removed||e.fragmentSpreads.forEach((function(t){m(i(t)).transitiveVars.forEach((function(t){e.transitiveVars.add(t)}))}))),e},g=new Set;p.definitions.forEach((function(e){e.kind===r.Kind.OPERATION_DEFINITION?m(n(e.name&&e.name.value)).fragmentSpreads.forEach((function(e){g.add(e)})):e.kind!==r.Kind.FRAGMENT_DEFINITION||0!==o||i(e.name.value).removed||g.add(e.name.value)})),g.forEach((function(e){m(i(e)).fragmentSpreads.forEach((function(e){g.add(e)}))}));var y={enter:function(e){if(t=e.name.value,!g.has(t)||i(t).removed)return null;var t}};return hn(r.visit(p,{FragmentSpread:y,FragmentDefinition:y,OperationDefinition:{leave:function(e){if(e.variableDefinitions){var t=m(n(e.name&&e.name.value)).transitiveVars;if(t.size<e.variableDefinitions.length)return dt(dt({},e),{variableDefinitions:e.variableDefinitions.filter((function(e){return t.has(e.variable.name.value)}))})}}}}))}var pn=Object.assign((function(e){return r.visit(e,{SelectionSet:{enter:function(e,t,n){if(!n||n.kind!==r.Kind.OPERATION_DEFINITION){var i=e.selections;if(i)if(!i.some((function(e){return Xt(e)&&("__typename"===e.name.value||0===e.name.value.lastIndexOf("__",0))}))){var s=n;if(!(Xt(s)&&s.directives&&s.directives.some((function(e){return"export"===e.name.value}))))return dt(dt({},e),{selections:yt(yt([],i,!0),[un],!1)})}}}}})}),{added:function(e){return e===un}}),mn={test:function(e){var t="connection"===e.name.value;return t&&(e.arguments&&e.arguments.some((function(e){return"key"===e.name.value}))||__DEV__&&It.warn("Removing an @connection directive even though it does not have a key. You may want to use the key parameter to specify a store key.")),t}};function gn(e){return"query"===sn(e).operation?e:r.visit(e,{OperationDefinition:{enter:function(e){return dt(dt({},e),{operation:"query"})}}})}var yn=Object.prototype.hasOwnProperty;function vn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return _n(e)}function _n(e){var t=e[0]||{},n=e.length;if(n>1)for(var r=new bn,i=1;i<n;++i)t=r.merge(t,e[i]);return t}var wn=function(e,t,n){return this.merge(e[n],t[n])},bn=function(){function e(e){void 0===e&&(e=wn),this.reconciler=e,this.isObject=Ut,this.pastCopies=new Set}return e.prototype.merge=function(e,t){for(var n=this,r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];return Ut(t)&&Ut(e)?(Object.keys(t).forEach((function(i){if(yn.call(e,i)){var s=e[i];if(t[i]!==s){var o=n.reconciler.apply(n,yt([e,t,i],r,!1));o!==s&&((e=n.shallowCopyForMerge(e))[i]=o)}}else(e=n.shallowCopyForMerge(e))[i]=t[i]})),e):t},e.prototype.shallowCopyForMerge=function(e){return Ut(e)&&(this.pastCopies.has(e)||(e=Array.isArray(e)?e.slice(0):dt({__proto__:Object.getPrototypeOf(e)},e),this.pastCopies.add(e))),e},e}();function In(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return En(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return En(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function En(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function Tn(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function Sn(e,t,n){return t&&Tn(e.prototype,t),n&&Tn(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}var kn=function(){return"function"==typeof Symbol},Cn=function(e){return kn()&&Boolean(Symbol[e])},xn=function(e){return Cn(e)?Symbol[e]:"@@"+e};kn()&&!Cn("observable")&&(Symbol.observable=Symbol("observable"));var An=xn("iterator"),Nn=xn("observable"),Dn=xn("species");function Rn(e,t){var n=e[t];if(null!=n){if("function"!=typeof n)throw new TypeError(n+" is not a function");return n}}function On(e){var t=e.constructor;return void 0!==t&&null===(t=t[Dn])&&(t=void 0),void 0!==t?t:zn}function Pn(e){return e instanceof zn}function Mn(e){Mn.log?Mn.log(e):setTimeout((function(){throw e}))}function Ln(e){Promise.resolve().then((function(){try{e()}catch(e){Mn(e)}}))}function Fn(e){var t=e._cleanup;if(void 0!==t&&(e._cleanup=void 0,t))try{if("function"==typeof t)t();else{var n=Rn(t,"unsubscribe");n&&n.call(t)}}catch(e){Mn(e)}}function jn(e){e._observer=void 0,e._queue=void 0,e._state="closed"}function qn(e,t,n){e._state="running";var r=e._observer;try{var i=Rn(r,t);switch(t){case"next":i&&i.call(r,n);break;case"error":if(jn(e),!i)throw n;i.call(r,n);break;case"complete":jn(e),i&&i.call(r)}}catch(e){Mn(e)}"closed"===e._state?Fn(e):"running"===e._state&&(e._state="ready")}function Vn(e,t,n){if("closed"!==e._state){if("buffering"!==e._state)return"ready"!==e._state?(e._state="buffering",e._queue=[{type:t,value:n}],void Ln((function(){return function(e){var t=e._queue;if(t){e._queue=void 0,e._state="ready";for(var n=0;n<t.length&&(qn(e,t[n].type,t[n].value),"closed"!==e._state);++n);}}(e)}))):void qn(e,t,n);e._queue.push({type:t,value:n})}}var Un=function(){function e(e,t){this._cleanup=void 0,this._observer=e,this._queue=void 0,this._state="initializing";var n=new Bn(this);try{this._cleanup=t.call(void 0,n)}catch(e){n.error(e)}"initializing"===this._state&&(this._state="ready")}return e.prototype.unsubscribe=function(){"closed"!==this._state&&(jn(this),Fn(this))},Sn(e,[{key:"closed",get:function(){return"closed"===this._state}}]),e}(),Bn=function(){function e(e){this._subscription=e}var t=e.prototype;return t.next=function(e){Vn(this._subscription,"next",e)},t.error=function(e){Vn(this._subscription,"error",e)},t.complete=function(){Vn(this._subscription,"complete")},Sn(e,[{key:"closed",get:function(){return"closed"===this._subscription._state}}]),e}(),zn=function(){function e(t){if(!(this instanceof e))throw new TypeError("Observable cannot be called as a function");if("function"!=typeof t)throw new TypeError("Observable initializer must be a function");this._subscriber=t}var t=e.prototype;return t.subscribe=function(e){return"object"==typeof e&&null!==e||(e={next:e,error:arguments[1],complete:arguments[2]}),new Un(e,this._subscriber)},t.forEach=function(e){var t=this;return new Promise((function(n,r){if("function"==typeof e)var i=t.subscribe({next:function(t){try{e(t,s)}catch(e){r(e),i.unsubscribe()}},error:r,complete:n});else r(new TypeError(e+" is not a function"));function s(){i.unsubscribe(),n()}}))},t.map=function(e){var t=this;if("function"!=typeof e)throw new TypeError(e+" is not a function");return new(On(this))((function(n){return t.subscribe({next:function(t){try{t=e(t)}catch(e){return n.error(e)}n.next(t)},error:function(e){n.error(e)},complete:function(){n.complete()}})}))},t.filter=function(e){var t=this;if("function"!=typeof e)throw new TypeError(e+" is not a function");return new(On(this))((function(n){return t.subscribe({next:function(t){try{if(!e(t))return}catch(e){return n.error(e)}n.next(t)},error:function(e){n.error(e)},complete:function(){n.complete()}})}))},t.reduce=function(e){var t=this;if("function"!=typeof e)throw new TypeError(e+" is not a function");var n=On(this),r=arguments.length>1,i=!1,s=arguments[1];return new n((function(n){return t.subscribe({next:function(t){var o=!i;if(i=!0,!o||r)try{s=e(s,t)}catch(e){return n.error(e)}else s=t},error:function(e){n.error(e)},complete:function(){if(!i&&!r)return n.error(new TypeError("Cannot reduce an empty sequence"));n.next(s),n.complete()}})}))},t.concat=function(){for(var e=this,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];var i=On(this);return new i((function(t){var r,s=0;return function e(o){r=o.subscribe({next:function(e){t.next(e)},error:function(e){t.error(e)},complete:function(){s===n.length?(r=void 0,t.complete()):e(i.from(n[s++]))}})}(e),function(){r&&(r.unsubscribe(),r=void 0)}}))},t.flatMap=function(e){var t=this;if("function"!=typeof e)throw new TypeError(e+" is not a function");var n=On(this);return new n((function(r){var i=[],s=t.subscribe({next:function(t){if(e)try{t=e(t)}catch(e){return r.error(e)}var s=n.from(t).subscribe({next:function(e){r.next(e)},error:function(e){r.error(e)},complete:function(){var e=i.indexOf(s);e>=0&&i.splice(e,1),o()}});i.push(s)},error:function(e){r.error(e)},complete:function(){o()}});function o(){s.closed&&0===i.length&&r.complete()}return function(){i.forEach((function(e){return e.unsubscribe()})),s.unsubscribe()}}))},t[Nn]=function(){return this},e.from=function(t){var n="function"==typeof this?this:e;if(null==t)throw new TypeError(t+" is not an object");var r=Rn(t,Nn);if(r){var i=r.call(t);if(Object(i)!==i)throw new TypeError(i+" is not an object");return Pn(i)&&i.constructor===n?i:new n((function(e){return i.subscribe(e)}))}if(Cn("iterator")&&(r=Rn(t,An)))return new n((function(e){Ln((function(){if(!e.closed){for(var n,i=In(r.call(t));!(n=i()).done;){var s=n.value;if(e.next(s),e.closed)return}e.complete()}}))}));if(Array.isArray(t))return new n((function(e){Ln((function(){if(!e.closed){for(var n=0;n<t.length;++n)if(e.next(t[n]),e.closed)return;e.complete()}}))}));throw new TypeError(t+" is not observable")},e.of=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return new("function"==typeof this?this:e)((function(e){Ln((function(){if(!e.closed){for(var t=0;t<n.length;++t)if(e.next(n[t]),e.closed)return;e.complete()}}))}))},Sn(e,null,[{key:Dn,get:function(){return this}}]),e}();kn()&&Object.defineProperty(zn,Symbol("extensions"),{value:{symbol:Nn,hostReportError:Mn},configurable:!0}),function(e){var t,n=e.Symbol;if("function"==typeof n)if(n.observable)t=n.observable;else{t="function"==typeof n.for?n.for("https://github.com/benlesh/symbol-observable"):n("https://github.com/benlesh/symbol-observable");try{n.observable=t}catch(e){}}else t="@@observable"}("undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==h?h:"undefined"!=typeof module?module:Function("return this")());var $n=zn.prototype,Wn="@@observable";$n[Wn]||($n[Wn]=function(){return this});var Qn=Object.prototype.toString;function Hn(e){return Gn(e)}function Gn(e,t){switch(Qn.call(e)){case"[object Array]":if((t=t||new Map).has(e))return t.get(e);var n=e.slice(0);return t.set(e,n),n.forEach((function(e,r){n[r]=Gn(e,t)})),n;case"[object Object]":if((t=t||new Map).has(e))return t.get(e);var r=Object.create(Object.getPrototypeOf(e));return t.set(e,r),Object.keys(e).forEach((function(n){r[n]=Gn(e[n],t)})),r;default:return e}}function Kn(e){var t=new Set([e]);return t.forEach((function(e){Ut(e)&&function(e){if(__DEV__&&!Object.isFrozen(e))try{Object.freeze(e)}catch(e){if(e instanceof TypeError)return null;throw e}return e}(e)===e&&Object.getOwnPropertyNames(e).forEach((function(n){Ut(e[n])&&t.add(e[n])}))})),e}function Yn(e){return __DEV__&&Kn(e),e}function Jn(e,t,n){var r=[];e.forEach((function(e){return e[t]&&r.push(e)})),r.forEach((function(e){return e[t](n)}))}function Xn(e,t,n){return new zn((function(r){var i=r.next,s=r.error,o=r.complete,a=0,c=!1,u={then:function(e){return new Promise((function(t){return t(e())}))}};function l(e,t){return e?function(t){++a;var n=function(){return e(t)};u=u.then(n,n).then((function(e){--a,i&&i.call(r,e),c&&h.complete()}),(function(e){throw--a,e})).catch((function(e){s&&s.call(r,e)}))}:function(e){return t&&t.call(r,e)}}var h={next:l(t,i),error:l(n,s),complete:function(){c=!0,a||o&&o.call(r)}},d=e.subscribe(h);return function(){return d.unsubscribe()}}))}var Zn="function"==typeof WeakMap&&"ReactNative"!==kt((function(){return navigator.product})),er="function"==typeof WeakSet,tr="function"==typeof Symbol&&"function"==typeof Symbol.for,nr=tr&&Symbol.asyncIterator;function rr(e){function t(t){Object.defineProperty(e,t,{value:zn})}return tr&&Symbol.species&&t(Symbol.species),t("@@species"),e}function ir(e){return e&&"function"==typeof e.then}kt((function(){return window.document.createElement})),kt((function(){return navigator.userAgent.indexOf("jsdom")>=0}));var sr=function(e){function t(t){var n=e.call(this,(function(e){return n.addObserver(e),function(){return n.removeObserver(e)}}))||this;return n.observers=new Set,n.promise=new Promise((function(e,t){n.resolve=e,n.reject=t})),n.handlers={next:function(e){null!==n.sub&&(n.latest=["next",e],n.notify("next",e),Jn(n.observers,"next",e))},error:function(e){var t=n.sub;null!==t&&(t&&setTimeout((function(){return t.unsubscribe()})),n.sub=null,n.latest=["error",e],n.reject(e),n.notify("error",e),Jn(n.observers,"error",e))},complete:function(){var e=n,t=e.sub,r=e.sources;if(null!==t){var i=(void 0===r?[]:r).shift();i?ir(i)?i.then((function(e){return n.sub=e.subscribe(n.handlers)})):n.sub=i.subscribe(n.handlers):(t&&setTimeout((function(){return t.unsubscribe()})),n.sub=null,n.latest&&"next"===n.latest[0]?n.resolve(n.latest[1]):n.resolve(),n.notify("complete"),Jn(n.observers,"complete"))}}},n.nextResultListeners=new Set,n.cancel=function(e){n.reject(e),n.sources=[],n.handlers.complete()},n.promise.catch((function(e){})),"function"==typeof t&&(t=[new zn(t)]),ir(t)?t.then((function(e){return n.start(e)}),n.handlers.error):n.start(t),n}return ht(t,e),t.prototype.start=function(e){void 0===this.sub&&(this.sources=Array.from(e),this.handlers.complete())},t.prototype.deliverLastMessage=function(e){if(this.latest){var t=this.latest[0],n=e[t];n&&n.call(e,this.latest[1]),null===this.sub&&"next"===t&&e.complete&&e.complete()}},t.prototype.addObserver=function(e){this.observers.has(e)||(this.deliverLastMessage(e),this.observers.add(e))},t.prototype.removeObserver=function(e){this.observers.delete(e)&&this.observers.size<1&&this.handlers.complete()},t.prototype.notify=function(e,t){var n=this.nextResultListeners;n.size&&(this.nextResultListeners=new Set,n.forEach((function(n){return n(e,t)})))},t.prototype.beforeNext=function(e){var t=!1;this.nextResultListeners.add((function(n,r){t||(t=!0,e(n,r))}))},t}(zn);function or(e){return"incremental"in e}function ar(e){return Ut(e)&&"payload"in e}function cr(e,t){var n=e,r=new bn;return or(t)&&cn(t.incremental)&&t.incremental.forEach((function(e){for(var t=e.data,i=e.path,s=i.length-1;s>=0;--s){var o=i[s],a=!isNaN(+o)?[]:{};a[o]=t,t=a}n=r.merge(n,t)})),n}function ur(e){return cn(lr(e))}function lr(e){var t=cn(e.errors)?e.errors.slice(0):[];return or(e)&&cn(e.incremental)&&e.incremental.forEach((function(e){e.errors&&t.push.apply(t,e.errors)})),t}function hr(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=Object.create(null);return e.forEach((function(e){e&&Object.keys(e).forEach((function(t){var r=e[t];void 0!==r&&(n[t]=r)}))})),n}rr(sr);var dr=new Map;function fr(e){var t=dr.get(e)||1;return dr.set(e,t+1),"".concat(e,":").concat(t,":").concat(Math.random().toString(36).slice(2))}function pr(e,t){return hr(e,t,t.variables&&{variables:dt(dt({},e&&e.variables),t.variables)})}function mr(e){return new zn((function(t){t.error(e)}))}var gr=function(e,t,n){var r=new Error(n);throw r.name="ServerError",r.response=e,r.statusCode=e.status,r.result=t,r};function yr(e,t){return t?t(e):zn.of()}function vr(e){return"function"==typeof e?new br(e):e}function _r(e){return e.request.length<=1}var wr=function(e){function t(t,n){var r=e.call(this,t)||this;return r.link=n,r}return ht(t,e),t}(Error),br=function(){function e(e){e&&(this.request=e)}return e.empty=function(){return new e((function(){return zn.of()}))},e.from=function(t){return 0===t.length?e.empty():t.map(vr).reduce((function(e,t){return e.concat(t)}))},e.split=function(t,n,r){var i=vr(n),s=vr(r||new e(yr));return _r(i)&&_r(s)?new e((function(e){return t(e)?i.request(e)||zn.of():s.request(e)||zn.of()})):new e((function(e,n){return t(e)?i.request(e,n)||zn.of():s.request(e,n)||zn.of()}))},e.execute=function(e,t){return e.request(function(e,t){var n=dt({},e);return Object.defineProperty(t,"setContext",{enumerable:!1,value:function(e){n=dt(dt({},n),"function"==typeof e?e(n):e)}}),Object.defineProperty(t,"getContext",{enumerable:!1,value:function(){return dt({},n)}}),t}(t.context,function(e){var t={variables:e.variables||{},extensions:e.extensions||{},operationName:e.operationName,query:e.query};return t.operationName||(t.operationName="string"!=typeof t.query?tn(t.query)||void 0:""),t}(function(e){for(var t=["query","operationName","variables","extensions","context"],n=0,r=Object.keys(e);n<r.length;n++){var i=r[n];if(t.indexOf(i)<0)throw __DEV__?new bt("illegal argument: ".concat(i)):new bt(27)}return e}(t))))||zn.of()},e.concat=function(t,n){var r=vr(t);if(_r(r))return __DEV__&&It.warn(new wr("You are calling concat on a terminating link, which will have no effect",r)),r;var i=vr(n);return _r(i)?new e((function(e){return r.request(e,(function(e){return i.request(e)||zn.of()}))||zn.of()})):new e((function(e,t){return r.request(e,(function(e){return i.request(e,t)||zn.of()}))||zn.of()}))},e.prototype.split=function(t,n,r){return this.concat(e.split(t,n,r||new e(yr)))},e.prototype.concat=function(t){return e.concat(this,t)},e.prototype.request=function(e,t){throw __DEV__?new bt("request is not implemented"):new bt(22)},e.prototype.onError=function(e,t){if(t&&t.error)return t.error(e),!1;throw e},e.prototype.setOnError=function(e){return this.onError=e,this},e}(),Ir=br.split,Er=br.execute;function Tr(e){var t=null,n=null,r=!1,i=[],s=[];function o(e){if(!n){if(s.length){var t=s.shift();if(Array.isArray(t)&&t[0])return t[0]({value:e,done:!1})}i.push(e)}}function a(e){n=e,s.slice().forEach((function(t){t[1](e)})),!t||t()}function c(){r=!0,s.slice().forEach((function(e){e[0]({value:void 0,done:!0})})),!t||t()}t=function(){t=null,e.removeListener("data",o),e.removeListener("error",a),e.removeListener("end",c),e.removeListener("finish",c),e.removeListener("close",c)},e.on("data",o),e.on("error",a),e.on("end",c),e.on("finish",c),e.on("close",c);var u={next:function(){return new Promise((function(e,t){return n?t(n):i.length?e({value:i.shift(),done:!1}):r?e({value:void 0,done:!0}):void s.push([e,t])}))}};return nr&&(u[Symbol.asyncIterator]=function(){return this}),u}function Sr(e){var t={next:function(){return e.read()}};return nr&&(t[Symbol.asyncIterator]=function(){return this}),t}function kr(e){var t,n,r,i=e;if(e.body&&(i=e.body),function(e){return!(!nr||!e[Symbol.asyncIterator])}(i))return function(e){var t,n=e[Symbol.asyncIterator]();return(t={next:function(){return n.next()}})[Symbol.asyncIterator]=function(){return this},t}(i);if(function(e){return!!e.getReader}(i))return Sr(i.getReader());if(function(e){return!!e.stream}(i))return Sr(i.stream().getReader());if(function(e){return!!e.arrayBuffer}(i))return t=i.arrayBuffer(),n=!1,r={next:function(){return n?Promise.resolve({value:void 0,done:!0}):(n=!0,new Promise((function(e,n){t.then((function(t){e({value:t,done:!1})})).catch(n)})))}},nr&&(r[Symbol.asyncIterator]=function(){return this}),r;if(function(e){return!!e.pipe}(i))return Tr(i);throw new Error("Unknown body type for responseIterator. Please pass a streamable response.")}var Cr=Symbol();var xr=function(e){function t(n){var r,i,s=n.graphQLErrors,o=n.protocolErrors,a=n.clientErrors,c=n.networkError,u=n.errorMessage,l=n.extraInfo,h=e.call(this,u)||this;return h.name="ApolloError",h.graphQLErrors=s||[],h.protocolErrors=o||[],h.clientErrors=a||[],h.networkError=c||null,h.message=u||(i=yt(yt(yt([],(r=h).graphQLErrors,!0),r.clientErrors,!0),r.protocolErrors,!0),r.networkError&&i.push(r.networkError),i.map((function(e){return Ut(e)&&e.message||"Error message not found."})).join("\n")),h.extraInfo=l,h.__proto__=t.prototype,h}return ht(t,e),t}(Error),Ar=Object.prototype.hasOwnProperty;function Nr(e){var t={};return e.split("\n").forEach((function(e){var n=e.indexOf(":");if(n>-1){var r=e.slice(0,n).trim().toLowerCase(),i=e.slice(n+1).trim();t[r]=i}})),t}function Dr(e,t){if(e.status>=300){gr(e,function(){try{return JSON.parse(t)}catch(e){return t}}(),"Response not successful: Received status code ".concat(e.status))}try{return JSON.parse(t)}catch(r){var n=r;throw n.name="ServerParseError",n.response=e,n.statusCode=e.status,n.bodyText=t,n}}function Rr(e,t){var n,r;"AbortError"!==e.name&&(e.result&&e.result.errors&&e.result.data&&(null===(n=t.next)||void 0===n||n.call(t,e.result)),null===(r=t.error)||void 0===r||r.call(t,e))}function Or(e,t,n){var r;(r=t,function(e){return e.text().then((function(t){return Dr(e,t)})).then((function(t){return e.status>=300&&gr(e,t,"Response not successful: Received status code ".concat(e.status)),Array.isArray(t)||Ar.call(t,"data")||Ar.call(t,"errors")||gr(e,t,"Server response was missing for query '".concat(Array.isArray(r)?r.map((function(e){return e.operationName})):r.operationName,"'.")),t}))})(e).then((function(e){var t,r;null===(t=n.next)||void 0===t||t.call(n,e),null===(r=n.complete)||void 0===r||r.call(n)})).catch((function(e){return Rr(e,n)}))}var Pr=function(e,t){var n;try{n=JSON.stringify(e)}catch(e){var r=__DEV__?new bt("Network request failed. ".concat(t," is not serializable: ").concat(e.message)):new bt(24);throw r.parseError=e,r}return n},Mr={http:{includeQuery:!0,includeExtensions:!1,preserveHeaderCase:!1},headers:{accept:"*/*","content-type":"application/json"},options:{method:"POST"}},Lr=function(e,t){return t(e)};function Fr(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];var s={},o={};n.forEach((function(e){s=dt(dt(dt({},s),e.options),{headers:dt(dt({},s.headers),e.headers)}),e.credentials&&(s.credentials=e.credentials),o=dt(dt({},o),e.http)})),s.headers&&(s.headers=function(e,t){if(!t){var n=Object.create(null);return Object.keys(Object(e)).forEach((function(t){n[t.toLowerCase()]=e[t]})),n}var r=Object.create(null);Object.keys(Object(e)).forEach((function(t){r[t.toLowerCase()]={originalName:t,value:e[t]}}));var i=Object.create(null);return Object.keys(r).forEach((function(e){i[r[e].originalName]=r[e].value})),i}(s.headers,o.preserveHeaderCase));var a=e.operationName,c=e.extensions,u=e.variables,l=e.query,h={operationName:a,variables:u};return o.includeExtensions&&(h.extensions=c),o.includeQuery&&(h.query=t(l,r.print)),{options:s,body:h}}var jr=kt((function(){return fetch})),qr=function(e){void 0===e&&(e={});var t=e.uri,n=void 0===t?"/graphql":t,i=e.fetch,s=e.print,o=void 0===s?Lr:s,a=e.includeExtensions,c=e.preserveHeaderCase,u=e.useGETForQueries,l=e.includeUnusedVariables,h=void 0!==l&&l,d=ft(e,["uri","fetch","print","includeExtensions","preserveHeaderCase","useGETForQueries","includeUnusedVariables"]);__DEV__&&function(e){if(!e&&"undefined"==typeof fetch)throw __DEV__?new bt("\n\"fetch\" has not been found globally and no fetcher has been configured. To fix this, install a fetch package (like https://www.npmjs.com/package/cross-fetch), instantiate the fetcher, and pass it into your HttpLink constructor. For example:\n\nimport fetch from 'cross-fetch';\nimport { ApolloClient, HttpLink } from '@apollo/client';\nconst client = new ApolloClient({\n  link: new HttpLink({ uri: '/graphql', fetch })\n});\n    "):new bt(23)}(i||jr);var f={http:{includeExtensions:a,preserveHeaderCase:c},options:d.fetchOptions,credentials:d.credentials,headers:d.headers};return new br((function(e){var t=function(e,t){var n=e.getContext().uri;return n||("function"==typeof t?t(e):t||"/graphql")}(e,n),s=e.getContext(),a={};if(s.clientAwareness){var c=s.clientAwareness,l=c.name,d=c.version;l&&(a["apollographql-client-name"]=l),d&&(a["apollographql-client-version"]=d)}var p,m=dt(dt({},a),s.headers),g={http:s.http,options:s.fetchOptions,credentials:s.credentials,headers:m},y=Fr(e,o,Mr,f,g),v=y.options,_=y.body;if(_.variables&&!h){var w=new Set(Object.keys(_.variables));r.visit(e.query,{Variable:function(e,t,n){n&&"VariableDefinition"!==n.kind&&w.delete(e.name.value)}}),w.size&&(_.variables=dt({},_.variables),w.forEach((function(e){delete _.variables[e]})))}if(!v.signal){var b=function(){if("undefined"==typeof AbortController)return{controller:!1,signal:!1};var e=new AbortController;return{controller:e,signal:e.signal}}(),I=b.controller,E=b.signal;(p=I)&&(v.signal=E)}var T,S="OperationDefinition"===(T=sn(e.query)).kind&&"subscription"===T.operation,k=Lt(["defer"],e.query);if(u&&!e.query.definitions.some((function(e){return"OperationDefinition"===e.kind&&"mutation"===e.operation}))&&(v.method="GET"),k||S){v.headers=v.headers||{};var C="multipart/mixed;";S&&k&&__DEV__&&It.warn("Multipart-subscriptions do not support @defer"),S?C+="boundary=graphql;subscriptionSpec=1.0,application/json":k&&(C+="deferSpec=20220824,application/json"),v.headers.accept=C}if("GET"===v.method){var x=function(e,t){var n=[],r=function(e,t){n.push("".concat(e,"=").concat(encodeURIComponent(t)))};if("query"in t&&r("query",t.query),t.operationName&&r("operationName",t.operationName),t.variables){var i=void 0;try{i=Pr(t.variables,"Variables map")}catch(e){return{parseError:e}}r("variables",i)}if(t.extensions){var s=void 0;try{s=Pr(t.extensions,"Extensions map")}catch(e){return{parseError:e}}r("extensions",s)}var o="",a=e,c=e.indexOf("#");-1!==c&&(o=e.substr(c),a=e.substr(0,c));var u=-1===a.indexOf("?")?"?":"&";return{newURI:a+u+n.join("&")+o}}(t,_),A=x.newURI,N=x.parseError;if(N)return mr(N);t=A}else try{v.body=Pr(_,"Payload")}catch(N){return mr(N)}return new zn((function(n){return(i||kt((function(){return fetch}))||jr)(t,v).then((function(t){var r;e.setContext({response:t});var i=null===(r=t.headers)||void 0===r?void 0:r.get("content-type");return null!==i&&/^multipart\/mixed/i.test(i)?function(e,t){var n,r,i,s,o;return pt(this,void 0,void 0,(function(){var a,c,u,l,h,d,f,p,m,g,y,v,_,w,b,I,E,T,S,k,C,x,A;return mt(this,(function(N){switch(N.label){case 0:if(void 0===TextDecoder)throw new Error("TextDecoder must be defined in the environment: please import a polyfill.");a=new TextDecoder("utf-8"),c=null===(n=e.headers)||void 0===n?void 0:n.get("content-type"),u="boundary=",l=(null==c?void 0:c.includes(u))?null==c?void 0:c.substring((null==c?void 0:c.indexOf(u))+9).replace(/['"]/g,"").replace(/\;(.*)/gm,"").trim():"-",h="\r\n--".concat(l),d="",f=kr(e),p=!0,N.label=1;case 1:return p?[4,f.next()]:[3,3];case 2:for(m=N.sent(),g=m.value,y=m.done,v="string"==typeof g?g:a.decode(g),_=d.length-h.length+1,p=!y,w=(d+=v).indexOf(h,_);w>-1;){if(b=void 0,x=[d.slice(0,w),d.slice(w+h.length)],d=x[1],I=(b=x[0]).indexOf("\r\n\r\n"),E=Nr(b.slice(0,I)),(T=E["content-type"])&&-1===T.toLowerCase().indexOf("application/json"))throw new Error("Unsupported patch content type: application/json is required.");if(S=b.slice(I))try{k=Dr(e,S),Object.keys(k).length>1||"data"in k||"incremental"in k||"errors"in k||"payload"in k?ar(k)?(C={},"payload"in k&&(C=dt({},k.payload)),"errors"in k&&(C=dt(dt({},C),{extensions:dt(dt({},"extensions"in C?C.extensions:null),(A={},A[Cr]=k.errors,A))})),null===(r=t.next)||void 0===r||r.call(t,C)):null===(i=t.next)||void 0===i||i.call(t,k):1===Object.keys(k).length&&"hasNext"in k&&!k.hasNext&&(null===(s=t.complete)||void 0===s||s.call(t))}catch(e){Rr(e,t)}w=d.indexOf(h)}return[3,1];case 3:return null===(o=t.complete)||void 0===o||o.call(t),[2]}}))}))}(t,n):Or(t,e,n)})).catch((function(e){return Rr(e,n)})),function(){p&&p.abort()}}))}))},Vr=function(e){function t(t){void 0===t&&(t={});var n=e.call(this,qr(t).request)||this;return n.options=t,n}return ht(t,e),t}(br);const{toString:Ur,hasOwnProperty:Br}=Object.prototype,zr=Function.prototype.toString,$r=new Map;function Wr(e,t){try{return Qr(e,t)}finally{$r.clear()}}function Qr(e,t){if(e===t)return!0;const n=Ur.call(e);if(n!==Ur.call(t))return!1;switch(n){case"[object Array]":if(e.length!==t.length)return!1;case"[object Object]":{if(Yr(e,t))return!0;const n=Hr(e),r=Hr(t),i=n.length;if(i!==r.length)return!1;for(let e=0;e<i;++e)if(!Br.call(t,n[e]))return!1;for(let r=0;r<i;++r){const i=n[r];if(!Qr(e[i],t[i]))return!1}return!0}case"[object Error]":return e.name===t.name&&e.message===t.message;case"[object Number]":if(e!=e)return t!=t;case"[object Boolean]":case"[object Date]":return+e==+t;case"[object RegExp]":case"[object String]":return e==`${t}`;case"[object Map]":case"[object Set]":{if(e.size!==t.size)return!1;if(Yr(e,t))return!0;const r=e.entries(),i="[object Map]"===n;for(;;){const e=r.next();if(e.done)break;const[n,s]=e.value;if(!t.has(n))return!1;if(i&&!Qr(s,t.get(n)))return!1}return!0}case"[object Uint16Array]":case"[object Uint8Array]":case"[object Uint32Array]":case"[object Int32Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object ArrayBuffer]":e=new Uint8Array(e),t=new Uint8Array(t);case"[object DataView]":{let n=e.byteLength;if(n===t.byteLength)for(;n--&&e[n]===t[n];);return-1===n}case"[object AsyncFunction]":case"[object GeneratorFunction]":case"[object AsyncGeneratorFunction]":case"[object Function]":{const n=zr.call(e);return n===zr.call(t)&&!function(e,t){const n=e.length-t.length;return n>=0&&e.indexOf(t,n)===n}(n,Kr)}}return!1}function Hr(e){return Object.keys(e).filter(Gr,e)}function Gr(e){return void 0!==this[e]}const Kr="{ [native code] }";function Yr(e,t){let n=$r.get(e);if(n){if(n.has(t))return!0}else $r.set(e,n=new Set);return n.add(t),!1}var Jr=function(){return Object.create(null)},Xr=Array.prototype,Zr=Xr.forEach,ei=Xr.slice,ti=function(){function e(e,t){void 0===e&&(e=!0),void 0===t&&(t=Jr),this.weakness=e,this.makeData=t}return e.prototype.lookup=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.lookupArray(e)},e.prototype.lookupArray=function(e){var t=this;return Zr.call(e,(function(e){return t=t.getChildTrie(e)})),t.data||(t.data=this.makeData(ei.call(e)))},e.prototype.getChildTrie=function(t){var n=this.weakness&&function(e){switch(typeof e){case"object":if(null===e)break;case"function":return!0}return!1}(t)?this.weak||(this.weak=new WeakMap):this.strong||(this.strong=new Map),r=n.get(t);return r||n.set(t,r=new e(this.weakness,this.makeData)),r},e}();let ni=null;const ri={};let ii=1;function si(e){try{return e()}catch(e){}}const oi="@wry/context:Slot",ai=si((()=>globalThis))||si((()=>h))||Object.create(null),ci=ai[oi]||Array[oi]||function(e){try{Object.defineProperty(ai,oi,{value:e,enumerable:!1,writable:!1,configurable:!0})}finally{return e}}(class{constructor(){this.id=["slot",ii++,Date.now(),Math.random().toString(36).slice(2)].join(":")}hasValue(){for(let e=ni;e;e=e.parent)if(this.id in e.slots){const t=e.slots[this.id];if(t===ri)break;return e!==ni&&(ni.slots[this.id]=t),!0}return ni&&(ni.slots[this.id]=ri),!1}getValue(){if(this.hasValue())return ni.slots[this.id]}withValue(e,t,n,r){const i={__proto__:null,[this.id]:e},s=ni;ni={parent:s,slots:i};try{return t.apply(r,n)}finally{ni=s}}static bind(e){const t=ni;return function(){const n=ni;try{return ni=t,e.apply(this,arguments)}finally{ni=n}}}static noContext(e,t,n){if(!ni)return e.apply(n,t);{const r=ni;try{return ni=null,e.apply(n,t)}finally{ni=r}}}});function ui(){}var li,hi=function(){function e(e,t){void 0===e&&(e=1/0),void 0===t&&(t=ui),this.max=e,this.dispose=t,this.map=new Map,this.newest=null,this.oldest=null}return e.prototype.has=function(e){return this.map.has(e)},e.prototype.get=function(e){var t=this.getNode(e);return t&&t.value},e.prototype.getNode=function(e){var t=this.map.get(e);if(t&&t!==this.newest){var n=t.older,r=t.newer;r&&(r.older=n),n&&(n.newer=r),t.older=this.newest,t.older.newer=t,t.newer=null,this.newest=t,t===this.oldest&&(this.oldest=r)}return t},e.prototype.set=function(e,t){var n=this.getNode(e);return n?n.value=t:(n={key:e,value:t,newer:null,older:this.newest},this.newest&&(this.newest.newer=n),this.newest=n,this.oldest=this.oldest||n,this.map.set(e,n),n.value)},e.prototype.clean=function(){for(;this.oldest&&this.map.size>this.max;)this.delete(this.oldest.key)},e.prototype.delete=function(e){var t=this.map.get(e);return!!t&&(t===this.newest&&(this.newest=t.older),t===this.oldest&&(this.oldest=t.newer),t.newer&&(t.newer.older=t.older),t.older&&(t.older.newer=t.newer),this.map.delete(e),this.dispose(t.value,e),!0)},e}(),di=new ci,fi=Object.prototype.hasOwnProperty,pi=void 0===(li=Array.from)?function(e){var t=[];return e.forEach((function(e){return t.push(e)})),t}:li;function mi(e){var t=e.unsubscribe;"function"==typeof t&&(e.unsubscribe=void 0,t())}var gi=[],yi=100;function vi(e,t){if(!e)throw new Error(t||"assertion failure")}function _i(e){switch(e.length){case 0:throw new Error("unknown value");case 1:return e[0];case 2:throw e[1]}}var wi=function(){function e(t){this.fn=t,this.parents=new Set,this.childValues=new Map,this.dirtyChildren=null,this.dirty=!0,this.recomputing=!1,this.value=[],this.deps=null,++e.count}return e.prototype.peek=function(){if(1===this.value.length&&!Ei(this))return bi(this),this.value[0]},e.prototype.recompute=function(e){return vi(!this.recomputing,"already recomputing"),bi(this),Ei(this)?function(e,t){Ni(e),di.withValue(e,Ii,[e,t]),function(e,t){if("function"==typeof e.subscribe)try{mi(e),e.unsubscribe=e.subscribe.apply(null,t)}catch(t){return e.setDirty(),!1}return!0}(e,t)&&function(e){if(e.dirty=!1,Ei(e))return;Si(e)}(e);return _i(e.value)}(this,e):_i(this.value)},e.prototype.setDirty=function(){this.dirty||(this.dirty=!0,this.value.length=0,Ti(this),mi(this))},e.prototype.dispose=function(){var e=this;this.setDirty(),Ni(this),ki(this,(function(t,n){t.setDirty(),Di(t,e)}))},e.prototype.forget=function(){this.dispose()},e.prototype.dependOn=function(e){e.add(this),this.deps||(this.deps=gi.pop()||new Set),this.deps.add(e)},e.prototype.forgetDeps=function(){var e=this;this.deps&&(pi(this.deps).forEach((function(t){return t.delete(e)})),this.deps.clear(),gi.push(this.deps),this.deps=null)},e.count=0,e}();function bi(e){var t=di.getValue();if(t)return e.parents.add(t),t.childValues.has(e)||t.childValues.set(e,[]),Ei(e)?Ci(t,e):xi(t,e),t}function Ii(e,t){e.recomputing=!0,e.value.length=0;try{e.value[0]=e.fn.apply(null,t)}catch(t){e.value[1]=t}e.recomputing=!1}function Ei(e){return e.dirty||!(!e.dirtyChildren||!e.dirtyChildren.size)}function Ti(e){ki(e,Ci)}function Si(e){ki(e,xi)}function ki(e,t){var n=e.parents.size;if(n)for(var r=pi(e.parents),i=0;i<n;++i)t(r[i],e)}function Ci(e,t){vi(e.childValues.has(t)),vi(Ei(t));var n=!Ei(e);if(e.dirtyChildren){if(e.dirtyChildren.has(t))return}else e.dirtyChildren=gi.pop()||new Set;e.dirtyChildren.add(t),n&&Ti(e)}function xi(e,t){vi(e.childValues.has(t)),vi(!Ei(t));var n=e.childValues.get(t);0===n.length?e.childValues.set(t,t.value.slice(0)):function(e,t){var n=e.length;return n>0&&n===t.length&&e[n-1]===t[n-1]}(n,t.value)||e.setDirty(),Ai(e,t),Ei(e)||Si(e)}function Ai(e,t){var n=e.dirtyChildren;n&&(n.delete(t),0===n.size&&(gi.length<yi&&gi.push(n),e.dirtyChildren=null))}function Ni(e){e.childValues.size>0&&e.childValues.forEach((function(t,n){Di(e,n)})),e.forgetDeps(),vi(null===e.dirtyChildren)}function Di(e,t){t.parents.delete(e),e.childValues.delete(t),Ai(e,t)}var Ri={setDirty:!0,dispose:!0,forget:!0};function Oi(e){var t=new Map,n=e&&e.subscribe;function r(e){var r=di.getValue();if(r){var i=t.get(e);i||t.set(e,i=new Set),r.dependOn(i),"function"==typeof n&&(mi(i),i.unsubscribe=n(e))}}return r.dirty=function(e,n){var r=t.get(e);if(r){var i=n&&fi.call(Ri,n)?n:"setDirty";pi(r).forEach((function(e){return e[i]()})),t.delete(e),mi(r)}},r}function Pi(){var e=new ti("function"==typeof WeakMap);return function(){return e.lookupArray(arguments)}}Pi();var Mi=new Set;function Li(e,t){void 0===t&&(t=Object.create(null));var n=new hi(t.max||Math.pow(2,16),(function(e){return e.dispose()})),r=t.keyArgs,i=t.makeCacheKey||Pi(),s=function(){var s=i.apply(null,r?r.apply(null,arguments):arguments);if(void 0===s)return e.apply(null,arguments);var o=n.get(s);o||(n.set(s,o=new wi(e)),o.subscribe=t.subscribe,o.forget=function(){return n.delete(s)});var a=o.recompute(Array.prototype.slice.call(arguments));return n.set(s,o),Mi.add(n),di.hasValue()||(Mi.forEach((function(e){return e.clean()})),Mi.clear()),a};function o(e){var t=n.get(e);t&&t.setDirty()}function a(e){var t=n.get(e);if(t)return t.peek()}function c(e){return n.delete(e)}return Object.defineProperty(s,"size",{get:function(){return n.map.size},configurable:!1,enumerable:!1}),s.dirtyKey=o,s.dirty=function(){o(i.apply(null,arguments))},s.peekKey=a,s.peek=function(){return a(i.apply(null,arguments))},s.forgetKey=c,s.forget=function(){return c(i.apply(null,arguments))},s.makeCacheKey=i,s.getKey=r?function(){return i.apply(null,r.apply(null,arguments))}:i,Object.freeze(s)}var Fi=function(){function e(){this.getFragmentDoc=Li(jt)}return e.prototype.batch=function(e){var t,n=this,r="string"==typeof e.optimistic?e.optimistic:!1===e.optimistic?null:void 0;return this.performTransaction((function(){return t=e.update(n)}),r),t},e.prototype.recordOptimisticTransaction=function(e,t){this.performTransaction(e,t)},e.prototype.transformDocument=function(e){return e},e.prototype.transformForLink=function(e){return e},e.prototype.identify=function(e){},e.prototype.gc=function(){return[]},e.prototype.modify=function(e){return!1},e.prototype.readQuery=function(e,t){return void 0===t&&(t=!!e.optimistic),this.read(dt(dt({},e),{rootId:e.id||"ROOT_QUERY",optimistic:t}))},e.prototype.readFragment=function(e,t){return void 0===t&&(t=!!e.optimistic),this.read(dt(dt({},e),{query:this.getFragmentDoc(e.fragment,e.fragmentName),rootId:e.id,optimistic:t}))},e.prototype.writeQuery=function(e){var t=e.id,n=e.data,r=ft(e,["id","data"]);return this.write(Object.assign(r,{dataId:t||"ROOT_QUERY",result:n}))},e.prototype.writeFragment=function(e){var t=e.id,n=e.data,r=e.fragment,i=e.fragmentName,s=ft(e,["id","data","fragment","fragmentName"]);return this.write(Object.assign(s,{query:this.getFragmentDoc(r,i),dataId:t,result:n}))},e.prototype.updateQuery=function(e,t){return this.batch({update:function(n){var r=n.readQuery(e),i=t(r);return null==i?r:(n.writeQuery(dt(dt({},e),{data:i})),i)}})},e.prototype.updateFragment=function(e,t){return this.batch({update:function(n){var r=n.readFragment(e),i=t(r);return null==i?r:(n.writeFragment(dt(dt({},e),{data:i})),i)}})},e}(),ji=function(e){function t(n,r,i,s){var o,a=e.call(this,n)||this;if(a.message=n,a.path=r,a.query=i,a.variables=s,Array.isArray(a.path)){a.missing=a.message;for(var c=a.path.length-1;c>=0;--c)a.missing=((o={})[a.path[c]]=a.missing,o)}else a.missing=a.path;return a.__proto__=t.prototype,a}return ht(t,e),t}(Error);const qi=()=>Object.create(null),{forEach:Vi,slice:Ui}=Array.prototype,{hasOwnProperty:Bi}=Object.prototype;class zi{constructor(e=!0,t=qi){this.weakness=e,this.makeData=t}lookup(...e){return this.lookupArray(e)}lookupArray(e){let t=this;return Vi.call(e,(e=>t=t.getChildTrie(e))),Bi.call(t,"data")?t.data:t.data=this.makeData(Ui.call(e))}peek(...e){return this.peekArray(e)}peekArray(e){let t=this;for(let n=0,r=e.length;t&&n<r;++n){const r=this.weakness&&$i(e[n])?t.weak:t.strong;t=r&&r.get(e[n])}return t&&t.data}getChildTrie(e){const t=this.weakness&&$i(e)?this.weak||(this.weak=new WeakMap):this.strong||(this.strong=new Map);let n=t.get(e);return n||t.set(e,n=new zi(this.weakness,this.makeData)),n}}function $i(e){switch(typeof e){case"object":if(null===e)break;case"function":return!0}return!1}var Wi=Object.prototype.hasOwnProperty;function Qi(e){return null==e}function Hi(e,t){var n=e.__typename,r=e.id,i=e._id;if("string"==typeof n&&(t&&(t.keyObject=Qi(r)?Qi(i)?void 0:{_id:i}:{id:r}),Qi(r)&&!Qi(i)&&(r=i),!Qi(r)))return"".concat(n,":").concat("number"==typeof r||"string"==typeof r?r:JSON.stringify(r))}var Gi={dataIdFromObject:Hi,addTypename:!0,resultCaching:!0,canonizeResults:!1};function Ki(e){var t=e.canonizeResults;return void 0===t?Gi.canonizeResults:t}var Yi=/^[_a-z][_0-9a-z]*/i;function Ji(e){var t=e.match(Yi);return t?t[0]:e}function Xi(e,t,n){return!!Ut(t)&&(an(t)?t.every((function(t){return Xi(e,t,n)})):e.selections.every((function(e){if(Xt(e)&&Mt(e,n)){var r=Yt(e);return Wi.call(t,r)&&(!e.selectionSet||Xi(e.selectionSet,t[r],n))}return!0})))}function Zi(e){return Ut(e)&&!zt(e)&&!an(e)}function es(e,t){var n=qt(nn(e));return{fragmentMap:n,lookupFragment:function(e){var r=n[e];return!r&&t&&(r=t.lookup(e)),r||null}}}var ts=Object.create(null),ns=function(){return ts},rs=Object.create(null),is=function(){function e(e,t){var n=this;this.policies=e,this.group=t,this.data=Object.create(null),this.rootIds=Object.create(null),this.refs=Object.create(null),this.getFieldValue=function(e,t){return Yn(zt(e)?n.get(e.__ref,t):e&&e[t])},this.canRead=function(e){return zt(e)?n.has(e.__ref):"object"==typeof e},this.toReference=function(e,t){if("string"==typeof e)return Bt(e);if(zt(e))return e;var r=n.policies.identify(e)[0];if(r){var i=Bt(r);return t&&n.merge(r,e),i}}}return e.prototype.toObject=function(){return dt({},this.data)},e.prototype.has=function(e){return void 0!==this.lookup(e,!0)},e.prototype.get=function(e,t){if(this.group.depend(e,t),Wi.call(this.data,e)){var n=this.data[e];if(n&&Wi.call(n,t))return n[t]}return"__typename"===t&&Wi.call(this.policies.rootTypenamesById,e)?this.policies.rootTypenamesById[e]:this instanceof cs?this.parent.get(e,t):void 0},e.prototype.lookup=function(e,t){return t&&this.group.depend(e,"__exists"),Wi.call(this.data,e)?this.data[e]:this instanceof cs?this.parent.lookup(e,t):this.policies.rootTypenamesById[e]?Object.create(null):void 0},e.prototype.merge=function(e,t){var n,r=this;zt(e)&&(e=e.__ref),zt(t)&&(t=t.__ref);var i="string"==typeof e?this.lookup(n=e):e,s="string"==typeof t?this.lookup(n=t):t;if(s){__DEV__?It("string"==typeof n,"store.merge expects a string ID"):It("string"==typeof n,1);var o=new bn(ls).merge(i,s);if(this.data[n]=o,o!==i&&(delete this.refs[n],this.group.caching)){var a=Object.create(null);i||(a.__exists=1),Object.keys(s).forEach((function(e){if(!i||i[e]!==o[e]){a[e]=1;var t=Ji(e);t===e||r.policies.hasKeyArgs(o.__typename,t)||(a[t]=1),void 0!==o[e]||r instanceof cs||delete o[e]}})),!a.__typename||i&&i.__typename||this.policies.rootTypenamesById[n]!==o.__typename||delete a.__typename,Object.keys(a).forEach((function(e){return r.group.dirty(n,e)}))}}},e.prototype.modify=function(e,t){var n=this,r=this.lookup(e);if(r){var i=Object.create(null),s=!1,o=!0,a={DELETE:ts,INVALIDATE:rs,isReference:zt,toReference:this.toReference,canRead:this.canRead,readField:function(t,r){return n.policies.readField("string"==typeof t?{fieldName:t,from:r||Bt(e)}:t,{store:n})}};if(Object.keys(r).forEach((function(c){var u=Ji(c),l=r[c];if(void 0!==l){var h="function"==typeof t?t:t[c]||t[u];if(h){var d=h===ns?ts:h(Yn(l),dt(dt({},a),{fieldName:u,storeFieldName:c,storage:n.getStorage(e,c)}));d===rs?n.group.dirty(e,c):(d===ts&&(d=void 0),d!==l&&(i[c]=d,s=!0,l=d))}void 0!==l&&(o=!1)}})),s)return this.merge(e,i),o&&(this instanceof cs?this.data[e]=void 0:delete this.data[e],this.group.dirty(e,"__exists")),!0}return!1},e.prototype.delete=function(e,t,n){var r,i=this.lookup(e);if(i){var s=this.getFieldValue(i,"__typename"),o=t&&n?this.policies.getStoreFieldName({typename:s,fieldName:t,args:n}):t;return this.modify(e,o?((r={})[o]=ns,r):ns)}return!1},e.prototype.evict=function(e,t){var n=!1;return e.id&&(Wi.call(this.data,e.id)&&(n=this.delete(e.id,e.fieldName,e.args)),this instanceof cs&&this!==t&&(n=this.parent.evict(e,t)||n),(e.fieldName||n)&&this.group.dirty(e.id,e.fieldName||"__exists")),n},e.prototype.clear=function(){this.replace(null)},e.prototype.extract=function(){var e=this,t=this.toObject(),n=[];return this.getRootIdSet().forEach((function(t){Wi.call(e.policies.rootTypenamesById,t)||n.push(t)})),n.length&&(t.__META={extraRootIds:n.sort()}),t},e.prototype.replace=function(e){var t=this;if(Object.keys(this.data).forEach((function(n){e&&Wi.call(e,n)||t.delete(n)})),e){var n=e.__META,r=ft(e,["__META"]);Object.keys(r).forEach((function(e){t.merge(e,r[e])})),n&&n.extraRootIds.forEach(this.retain,this)}},e.prototype.retain=function(e){return this.rootIds[e]=(this.rootIds[e]||0)+1},e.prototype.release=function(e){if(this.rootIds[e]>0){var t=--this.rootIds[e];return t||delete this.rootIds[e],t}return 0},e.prototype.getRootIdSet=function(e){return void 0===e&&(e=new Set),Object.keys(this.rootIds).forEach(e.add,e),this instanceof cs?this.parent.getRootIdSet(e):Object.keys(this.policies.rootTypenamesById).forEach(e.add,e),e},e.prototype.gc=function(){var e=this,t=this.getRootIdSet(),n=this.toObject();t.forEach((function(r){Wi.call(n,r)&&(Object.keys(e.findChildRefIds(r)).forEach(t.add,t),delete n[r])}));var r=Object.keys(n);if(r.length){for(var i=this;i instanceof cs;)i=i.parent;r.forEach((function(e){return i.delete(e)}))}return r},e.prototype.findChildRefIds=function(e){if(!Wi.call(this.refs,e)){var t=this.refs[e]=Object.create(null),n=this.data[e];if(!n)return t;var r=new Set([n]);r.forEach((function(e){zt(e)&&(t[e.__ref]=!0),Ut(e)&&Object.keys(e).forEach((function(t){var n=e[t];Ut(n)&&r.add(n)}))}))}return this.refs[e]},e.prototype.makeCacheKey=function(){return this.group.keyMaker.lookupArray(arguments)},e}(),ss=function(){function e(e,t){void 0===t&&(t=null),this.caching=e,this.parent=t,this.d=null,this.resetCaching()}return e.prototype.resetCaching=function(){this.d=this.caching?Oi():null,this.keyMaker=new zi(Zn)},e.prototype.depend=function(e,t){if(this.d){this.d(os(e,t));var n=Ji(t);n!==t&&this.d(os(e,n)),this.parent&&this.parent.depend(e,t)}},e.prototype.dirty=function(e,t){this.d&&this.d.dirty(os(e,t),"__exists"===t?"forget":"setDirty")},e}();function os(e,t){return t+"#"+e}function as(e,t){hs(e)&&e.group.depend(t,"__exists")}!function(e){var t=function(e){function t(t){var n=t.policies,r=t.resultCaching,i=void 0===r||r,s=t.seed,o=e.call(this,n,new ss(i))||this;return o.stump=new us(o),o.storageTrie=new zi(Zn),s&&o.replace(s),o}return ht(t,e),t.prototype.addLayer=function(e,t){return this.stump.addLayer(e,t)},t.prototype.removeLayer=function(){return this},t.prototype.getStorage=function(){return this.storageTrie.lookupArray(arguments)},t}(e);e.Root=t}(is||(is={}));var cs=function(e){function t(t,n,r,i){var s=e.call(this,n.policies,i)||this;return s.id=t,s.parent=n,s.replay=r,s.group=i,r(s),s}return ht(t,e),t.prototype.addLayer=function(e,n){return new t(e,this,n,this.group)},t.prototype.removeLayer=function(e){var t=this,n=this.parent.removeLayer(e);return e===this.id?(this.group.caching&&Object.keys(this.data).forEach((function(e){var r=t.data[e],i=n.lookup(e);i?r?r!==i&&Object.keys(r).forEach((function(n){Wr(r[n],i[n])||t.group.dirty(e,n)})):(t.group.dirty(e,"__exists"),Object.keys(i).forEach((function(n){t.group.dirty(e,n)}))):t.delete(e)})),n):n===this.parent?this:n.addLayer(this.id,this.replay)},t.prototype.toObject=function(){return dt(dt({},this.parent.toObject()),this.data)},t.prototype.findChildRefIds=function(t){var n=this.parent.findChildRefIds(t);return Wi.call(this.data,t)?dt(dt({},n),e.prototype.findChildRefIds.call(this,t)):n},t.prototype.getStorage=function(){for(var e=this.parent;e.parent;)e=e.parent;return e.getStorage.apply(e,arguments)},t}(is),us=function(e){function t(t){return e.call(this,"EntityStore.Stump",t,(function(){}),new ss(t.group.caching,t.group))||this}return ht(t,e),t.prototype.removeLayer=function(){return this},t.prototype.merge=function(){return this.parent.merge.apply(this.parent,arguments)},t}(cs);function ls(e,t,n){var r=e[n],i=t[n];return Wr(r,i)?r:i}function hs(e){return!!(e instanceof is&&e.group.caching)}var ds,fs,ps=function(){function e(){this.known=new(er?WeakSet:Set),this.pool=new zi(Zn),this.passes=new WeakMap,this.keysByJSON=new Map,this.empty=this.admit({})}return e.prototype.isKnown=function(e){return Ut(e)&&this.known.has(e)},e.prototype.pass=function(e){if(Ut(e)){var t=function(e){return Ut(e)?an(e)?e.slice(0):dt({__proto__:Object.getPrototypeOf(e)},e):e}(e);return this.passes.set(t,e),t}return e},e.prototype.admit=function(e){var t=this;if(Ut(e)){var n=this.passes.get(e);if(n)return n;switch(Object.getPrototypeOf(e)){case Array.prototype:if(this.known.has(e))return e;var r=e.map(this.admit,this);return(a=this.pool.lookupArray(r)).array||(this.known.add(a.array=r),__DEV__&&Object.freeze(r)),a.array;case null:case Object.prototype:if(this.known.has(e))return e;var i=Object.getPrototypeOf(e),s=[i],o=this.sortedKeys(e);s.push(o.json);var a,c=s.length;if(o.sorted.forEach((function(n){s.push(t.admit(e[n]))})),!(a=this.pool.lookupArray(s)).object){var u=a.object=Object.create(i);this.known.add(u),o.sorted.forEach((function(e,t){u[e]=s[c+t]})),__DEV__&&Object.freeze(u)}return a.object}}return e},e.prototype.sortedKeys=function(e){var t=Object.keys(e),n=this.pool.lookupArray(t);if(!n.keys){t.sort();var r=JSON.stringify(t);(n.keys=this.keysByJSON.get(r))||this.keysByJSON.set(r,n.keys={sorted:t,json:r})}return n.keys},e}(),ms=Object.assign((function(e){if(Ut(e)){void 0===ds&&gs();var t=ds.admit(e),n=fs.get(t);return void 0===n&&fs.set(t,n=JSON.stringify(t)),n}return JSON.stringify(e)}),{reset:gs});function gs(){ds=new ps,fs=new(Zn?WeakMap:Map)}function ys(e){return[e.selectionSet,e.objectOrReference,e.context,e.context.canonizeResults]}var vs=function(){function e(e){var t=this;this.knownResults=new(Zn?WeakMap:Map),this.config=hr(e,{addTypename:!1!==e.addTypename,canonizeResults:Ki(e)}),this.canon=e.canon||new ps,this.executeSelectionSet=Li((function(e){var n,r=e.context.canonizeResults,i=ys(e);i[3]=!r;var s=(n=t.executeSelectionSet).peek.apply(n,i);return s?r?dt(dt({},s),{result:t.canon.admit(s.result)}):s:(as(e.context.store,e.enclosingRef.__ref),t.execSelectionSetImpl(e))}),{max:this.config.resultCacheMaxSize,keyArgs:ys,makeCacheKey:function(e,t,n,r){if(hs(n.store))return n.store.makeCacheKey(e,zt(t)?t.__ref:t,n.varString,r)}}),this.executeSubSelectedArray=Li((function(e){return as(e.context.store,e.enclosingRef.__ref),t.execSubSelectedArrayImpl(e)}),{max:this.config.resultCacheMaxSize,makeCacheKey:function(e){var t=e.field,n=e.array,r=e.context;if(hs(r.store))return r.store.makeCacheKey(t,n,r.varString)}})}return e.prototype.resetCanon=function(){this.canon=new ps},e.prototype.diffQueryAgainstStore=function(e){var t=e.store,n=e.query,r=e.rootId,i=void 0===r?"ROOT_QUERY":r,s=e.variables,o=e.returnPartialData,a=void 0===o||o,c=e.canonizeResults,u=void 0===c?this.config.canonizeResults:c,l=this.config.cache.policies;s=dt(dt({},on(rn(n))),s);var h,d=Bt(i),f=this.executeSelectionSet({selectionSet:sn(n).selectionSet,objectOrReference:d,enclosingRef:d,context:dt({store:t,query:n,policies:l,variables:s,varString:ms(s),canonizeResults:u},es(n,this.config.fragments))});if(f.missing&&(h=[new ji(_s(f.missing),f.missing,n,s)],!a))throw h[0];return{result:f.result,complete:!h,missing:h}},e.prototype.isFresh=function(e,t,n,r){if(hs(r.store)&&this.knownResults.get(e)===n){var i=this.executeSelectionSet.peek(n,t,r,this.canon.isKnown(e));if(i&&e===i.result)return!0}return!1},e.prototype.execSelectionSetImpl=function(e){var t=this,n=e.selectionSet,i=e.objectOrReference,s=e.enclosingRef,o=e.context;if(zt(i)&&!o.policies.rootTypenamesById[i.__ref]&&!o.store.has(i.__ref))return{result:this.canon.empty,missing:"Dangling reference to missing ".concat(i.__ref," object")};var a,c=o.variables,u=o.policies,l=o.store.getFieldValue(i,"__typename"),h=[],d=new bn;function f(e,t){var n;return e.missing&&(a=d.merge(a,((n={})[t]=e.missing,n))),e.result}this.config.addTypename&&"string"==typeof l&&!u.rootIdsByTypename[l]&&h.push({__typename:l});var p=new Set(n.selections);p.forEach((function(e){var n,m;if(Mt(e,c))if(Xt(e)){var g=u.readField({fieldName:e.name.value,field:e,variables:o.variables,from:i},o),y=Yt(e);void 0===g?pn.added(e)||(a=d.merge(a,((n={})[y]="Can't find field '".concat(e.name.value,"' on ").concat(zt(i)?i.__ref+" object":"object "+JSON.stringify(i,null,2)),n))):an(g)?g=f(t.executeSubSelectedArray({field:e,array:g,enclosingRef:s,context:o}),y):e.selectionSet?null!=g&&(g=f(t.executeSelectionSet({selectionSet:e.selectionSet,objectOrReference:g,enclosingRef:zt(g)?g:s,context:o}),y)):o.canonizeResults&&(g=t.canon.pass(g)),void 0!==g&&h.push(((m={})[y]=g,m))}else{var v=Vt(e,o.lookupFragment);if(!v&&e.kind===r.Kind.FRAGMENT_SPREAD)throw __DEV__?new bt("No fragment named ".concat(e.name.value)):new bt(5);v&&u.fragmentMatches(v,l)&&v.selectionSet.selections.forEach(p.add,p)}}));var m={result:_n(h),missing:a},g=o.canonizeResults?this.canon.admit(m):Yn(m);return g.result&&this.knownResults.set(g.result,n),g},e.prototype.execSubSelectedArrayImpl=function(e){var t,n=this,r=e.field,i=e.array,s=e.enclosingRef,o=e.context,a=new bn;function c(e,n){var r;return e.missing&&(t=a.merge(t,((r={})[n]=e.missing,r))),e.result}return r.selectionSet&&(i=i.filter(o.store.canRead)),i=i.map((function(e,t){return null===e?null:an(e)?c(n.executeSubSelectedArray({field:r,array:e,enclosingRef:s,context:o}),t):r.selectionSet?c(n.executeSelectionSet({selectionSet:r.selectionSet,objectOrReference:e,enclosingRef:zt(e)?e:s,context:o}),t):(__DEV__&&function(e,t,n){if(!t.selectionSet){var r=new Set([n]);r.forEach((function(n){Ut(n)&&(__DEV__?It(!zt(n),"Missing selection set for object of type ".concat(function(e,t){return zt(t)?e.get(t.__ref,"__typename"):t&&t.__typename}(e,n)," returned for query field ").concat(t.name.value)):It(!zt(n),6),Object.values(n).forEach(r.add,r))}))}}(o.store,r,e),e)})),{result:o.canonizeResults?this.canon.admit(i):i,missing:t}},e}();function _s(e){try{JSON.stringify(e,(function(e,t){if("string"==typeof t)throw t;return t}))}catch(e){return e}}var ws=new ci,bs=new WeakMap;function Is(e){var t=bs.get(e);return t||bs.set(e,t={vars:new Set,dep:Oi()}),t}function Es(e){Is(e).vars.forEach((function(t){return t.forgetCache(e)}))}function Ts(e){var t=new Set,n=new Set,r=function(s){if(arguments.length>0){if(e!==s){e=s,t.forEach((function(e){Is(e).dep.dirty(r),function(e){e.broadcastWatches&&e.broadcastWatches()}(e)}));var o=Array.from(n);n.clear(),o.forEach((function(t){return t(e)}))}}else{var a=ws.getValue();a&&(i(a),Is(a).dep(r))}return e};r.onNextChange=function(e){return n.add(e),function(){n.delete(e)}};var i=r.attachCache=function(e){return t.add(e),Is(e).vars.add(r),r};return r.forgetCache=function(e){return t.delete(e)},r}var Ss=Object.create(null);function ks(e){var t=JSON.stringify(e);return Ss[t]||(Ss[t]=Object.create(null))}function Cs(e){var t=ks(e);return t.keyFieldsFn||(t.keyFieldsFn=function(t,n){var r=function(e,t){return n.readField(t,e)},i=n.keyObject=As(e,(function(e){var i=Rs(n.storeObject,e,r);return void 0===i&&t!==n.storeObject&&Wi.call(t,e[0])&&(i=Rs(t,e,Ds)),__DEV__?It(void 0!==i,"Missing field '".concat(e.join("."),"' while extracting keyFields from ").concat(JSON.stringify(t))):It(void 0!==i,2),i}));return"".concat(n.typename,":").concat(JSON.stringify(i))})}function xs(e){var t=ks(e);return t.keyArgsFn||(t.keyArgsFn=function(t,n){var r=n.field,i=n.variables,s=n.fieldName,o=As(e,(function(e){var n=e[0],s=n.charAt(0);if("@"!==s)if("$"!==s){if(t)return Rs(t,e)}else{var o=n.slice(1);if(i&&Wi.call(i,o)){var a=e.slice(0);return a[0]=o,Rs(i,a)}}else if(r&&cn(r.directives)){var c=n.slice(1),u=r.directives.find((function(e){return e.name.value===c})),l=u&&Kt(u,i);return l&&Rs(l,e.slice(1))}})),a=JSON.stringify(o);return(t||"{}"!==a)&&(s+=":"+a),s})}function As(e,t){var n=new bn;return Ns(e).reduce((function(e,r){var i,s=t(r);if(void 0!==s){for(var o=r.length-1;o>=0;--o)(i={})[r[o]]=s,s=i;e=n.merge(e,s)}return e}),Object.create(null))}function Ns(e){var t=ks(e);if(!t.paths){var n=t.paths=[],r=[];e.forEach((function(t,i){an(t)?(Ns(t).forEach((function(e){return n.push(r.concat(e))})),r.length=0):(r.push(t),an(e[i+1])||(n.push(r.slice(0)),r.length=0))}))}return t.paths}function Ds(e,t){return e[t]}function Rs(e,t,n){return n=n||Ds,Os(t.reduce((function e(t,r){return an(t)?t.map((function(t){return e(t,r)})):t&&n(t,r)}),e))}function Os(e){return Ut(e)?an(e)?e.map(Os):As(Object.keys(e).sort(),(function(t){return Rs(e,t)})):e}function Ps(e){return void 0!==e.args?e.args:e.field?Kt(e.field,e.variables):null}Qt.setStringify(ms);var Ms=function(){},Ls=function(e,t){return t.fieldName},Fs=function(e,t,n){return(0,n.mergeObjects)(e,t)},js=function(e,t){return t},qs=function(){function e(e){this.config=e,this.typePolicies=Object.create(null),this.toBeAdded=Object.create(null),this.supertypeMap=new Map,this.fuzzySubtypes=new Map,this.rootIdsByTypename=Object.create(null),this.rootTypenamesById=Object.create(null),this.usingPossibleTypes=!1,this.config=dt({dataIdFromObject:Hi},e),this.cache=this.config.cache,this.setRootTypename("Query"),this.setRootTypename("Mutation"),this.setRootTypename("Subscription"),e.possibleTypes&&this.addPossibleTypes(e.possibleTypes),e.typePolicies&&this.addTypePolicies(e.typePolicies)}return e.prototype.identify=function(e,t){var n,r=this,i=t&&(t.typename||(null===(n=t.storeObject)||void 0===n?void 0:n.__typename))||e.__typename;if(i===this.rootTypenamesById.ROOT_QUERY)return["ROOT_QUERY"];for(var s,o=t&&t.storeObject||e,a=dt(dt({},t),{typename:i,storeObject:o,readField:t&&t.readField||function(){var e=Us(arguments,o);return r.readField(e,{store:r.cache.data,variables:e.variables})}}),c=i&&this.getTypePolicy(i),u=c&&c.keyFn||this.config.dataIdFromObject;u;){var l=u(dt(dt({},e),o),a);if(!an(l)){s=l;break}u=Cs(l)}return s=s?String(s):void 0,a.keyObject?[s,a.keyObject]:[s]},e.prototype.addTypePolicies=function(e){var t=this;Object.keys(e).forEach((function(n){var r=e[n],i=r.queryType,s=r.mutationType,o=r.subscriptionType,a=ft(r,["queryType","mutationType","subscriptionType"]);i&&t.setRootTypename("Query",n),s&&t.setRootTypename("Mutation",n),o&&t.setRootTypename("Subscription",n),Wi.call(t.toBeAdded,n)?t.toBeAdded[n].push(a):t.toBeAdded[n]=[a]}))},e.prototype.updateTypePolicy=function(e,t){var n=this,r=this.getTypePolicy(e),i=t.keyFields,s=t.fields;function o(e,t){e.merge="function"==typeof t?t:!0===t?Fs:!1===t?js:e.merge}o(r,t.merge),r.keyFn=!1===i?Ms:an(i)?Cs(i):"function"==typeof i?i:r.keyFn,s&&Object.keys(s).forEach((function(t){var r=n.getFieldPolicy(e,t,!0),i=s[t];if("function"==typeof i)r.read=i;else{var a=i.keyArgs,c=i.read,u=i.merge;r.keyFn=!1===a?Ls:an(a)?xs(a):"function"==typeof a?a:r.keyFn,"function"==typeof c&&(r.read=c),o(r,u)}r.read&&r.merge&&(r.keyFn=r.keyFn||Ls)}))},e.prototype.setRootTypename=function(e,t){void 0===t&&(t=e);var n="ROOT_"+e.toUpperCase(),r=this.rootTypenamesById[n];t!==r&&(__DEV__?It(!r||r===e,"Cannot change root ".concat(e," __typename more than once")):It(!r||r===e,3),r&&delete this.rootIdsByTypename[r],this.rootIdsByTypename[t]=n,this.rootTypenamesById[n]=t)},e.prototype.addPossibleTypes=function(e){var t=this;this.usingPossibleTypes=!0,Object.keys(e).forEach((function(n){t.getSupertypeSet(n,!0),e[n].forEach((function(e){t.getSupertypeSet(e,!0).add(n);var r=e.match(Yi);r&&r[0]===e||t.fuzzySubtypes.set(e,new RegExp(e))}))}))},e.prototype.getTypePolicy=function(e){var t=this;if(!Wi.call(this.typePolicies,e)){var n=this.typePolicies[e]=Object.create(null);n.fields=Object.create(null);var r=this.supertypeMap.get(e);r&&r.size&&r.forEach((function(e){var r=t.getTypePolicy(e),i=r.fields,s=ft(r,["fields"]);Object.assign(n,s),Object.assign(n.fields,i)}))}var i=this.toBeAdded[e];return i&&i.length&&i.splice(0).forEach((function(n){t.updateTypePolicy(e,n)})),this.typePolicies[e]},e.prototype.getFieldPolicy=function(e,t,n){if(e){var r=this.getTypePolicy(e).fields;return r[t]||n&&(r[t]=Object.create(null))}},e.prototype.getSupertypeSet=function(e,t){var n=this.supertypeMap.get(e);return!n&&t&&this.supertypeMap.set(e,n=new Set),n},e.prototype.fragmentMatches=function(e,t,n,r){var i=this;if(!e.typeCondition)return!0;if(!t)return!1;var s=e.typeCondition.name.value;if(t===s)return!0;if(this.usingPossibleTypes&&this.supertypeMap.has(s))for(var o=this.getSupertypeSet(t,!0),a=[o],c=function(e){var t=i.getSupertypeSet(e,!1);t&&t.size&&a.indexOf(t)<0&&a.push(t)},u=!(!n||!this.fuzzySubtypes.size),l=!1,h=0;h<a.length;++h){var d=a[h];if(d.has(s))return o.has(s)||(l&&__DEV__&&It.warn("Inferring subtype ".concat(t," of supertype ").concat(s)),o.add(s)),!0;d.forEach(c),u&&h===a.length-1&&Xi(e.selectionSet,n,r)&&(u=!1,l=!0,this.fuzzySubtypes.forEach((function(e,n){var r=t.match(e);r&&r[0]===t&&c(n)})))}return!1},e.prototype.hasKeyArgs=function(e,t){var n=this.getFieldPolicy(e,t,!1);return!(!n||!n.keyFn)},e.prototype.getStoreFieldName=function(e){var t,n=e.typename,r=e.fieldName,i=this.getFieldPolicy(n,r,!1),s=i&&i.keyFn;if(s&&n)for(var o={typename:n,fieldName:r,field:e.field||null,variables:e.variables},a=Ps(e);s;){var c=s(a,o);if(!an(c)){t=c||r;break}s=xs(c)}return void 0===t&&(t=e.field?function(e,t){var n=null;e.directives&&(n={},e.directives.forEach((function(e){n[e.name.value]={},e.arguments&&e.arguments.forEach((function(r){var i=r.name,s=r.value;return $t(n[e.name.value],i,s,t)}))})));var r=null;return e.arguments&&e.arguments.length&&(r={},e.arguments.forEach((function(e){var n=e.name,i=e.value;return $t(r,n,i,t)}))),Qt(e.name.value,r,n)}(e.field,e.variables):Qt(r,Ps(e))),!1===t?r:r===Ji(t)?t:r+":"+t},e.prototype.readField=function(e,t){var n=e.from;if(n&&(e.field||e.fieldName)){if(void 0===e.typename){var r=t.store.getFieldValue(n,"__typename");r&&(e.typename=r)}var i=this.getStoreFieldName(e),s=Ji(i),o=t.store.getFieldValue(n,i),a=this.getFieldPolicy(e.typename,s,!1),c=a&&a.read;if(c){var u=Vs(this,n,e,t,t.store.getStorage(zt(n)?n.__ref:n,i));return ws.withValue(this.cache,c,[o,u])}return o}},e.prototype.getReadFunction=function(e,t){var n=this.getFieldPolicy(e,t,!1);return n&&n.read},e.prototype.getMergeFunction=function(e,t,n){var r=this.getFieldPolicy(e,t,!1),i=r&&r.merge;return!i&&n&&(i=(r=this.getTypePolicy(n))&&r.merge),i},e.prototype.runMergeFunction=function(e,t,n,r,i){var s=n.field,o=n.typename,a=n.merge;return a===Fs?Bs(r.store)(e,t):a===js?t:(r.overwrite&&(e=void 0),a(e,t,Vs(this,void 0,{typename:o,fieldName:s.name.value,field:s,variables:r.variables},r,i||Object.create(null))))},e}();function Vs(e,t,n,r,i){var s=e.getStoreFieldName(n),o=Ji(s),a=n.variables||r.variables,c=r.store,u=c.toReference,l=c.canRead;return{args:Ps(n),field:n.field||null,fieldName:o,storeFieldName:s,variables:a,isReference:zt,toReference:u,storage:i,cache:e.cache,canRead:l,readField:function(){return e.readField(Us(arguments,t,a),r)},mergeObjects:Bs(r.store)}}function Us(e,t,n){var r,i,s,o=e[0],a=e[1],c=e.length;return"string"==typeof o?r={fieldName:o,from:c>1?a:t}:(r=dt({},o),Wi.call(r,"from")||(r.from=t)),__DEV__&&void 0===r.from&&__DEV__&&It.warn("Undefined 'from' passed to readField with arguments ".concat((i=Array.from(e),s=fr("stringifyForDisplay"),JSON.stringify(i,(function(e,t){return void 0===t?s:t})).split(JSON.stringify(s)).join("<undefined>")))),void 0===r.variables&&(r.variables=n),r}function Bs(e){return function(t,n){if(an(t)||an(n))throw __DEV__?new bt("Cannot automatically merge arrays"):new bt(4);if(Ut(t)&&Ut(n)){var r=e.getFieldValue(t,"__typename"),i=e.getFieldValue(n,"__typename");if(r&&i&&r!==i)return n;if(zt(t)&&Zi(n))return e.merge(t.__ref,n),t;if(Zi(t)&&zt(n))return e.merge(t,n.__ref),n;if(Zi(t)&&Zi(n))return dt(dt({},t),n)}return n}}function zs(e,t,n){var r="".concat(t).concat(n),i=e.flavors.get(r);return i||e.flavors.set(r,i=e.clientOnly===t&&e.deferred===n?e:dt(dt({},e),{clientOnly:t,deferred:n})),i}var $s=function(){function e(e,t,n){this.cache=e,this.reader=t,this.fragments=n}return e.prototype.writeToStore=function(e,t){var n=this,r=t.query,i=t.result,s=t.dataId,o=t.variables,a=t.overwrite,c=en(r),u=new bn;o=dt(dt({},on(c)),o);var l=dt(dt({store:e,written:Object.create(null),merge:function(e,t){return u.merge(e,t)},variables:o,varString:ms(o)},es(r,this.fragments)),{overwrite:!!a,incomingById:new Map,clientOnly:!1,deferred:!1,flavors:new Map}),h=this.processSelectionSet({result:i||Object.create(null),dataId:s,selectionSet:c.selectionSet,mergeTree:{map:new Map},context:l});if(!zt(h))throw __DEV__?new bt("Could not identify object ".concat(JSON.stringify(i))):new bt(7);return l.incomingById.forEach((function(t,r){var i=t.storeObject,s=t.mergeTree,o=t.fieldNodeSet,a=Bt(r);if(s&&s.map.size){var c=n.applyMerges(s,a,i,l);if(zt(c))return;i=c}if(__DEV__&&!l.overwrite){var u=Object.create(null);o.forEach((function(e){e.selectionSet&&(u[e.name.value]=!0)}));Object.keys(i).forEach((function(e){(function(e){return!0===u[Ji(e)]})(e)&&!function(e){var t=s&&s.map.get(e);return Boolean(t&&t.info&&t.info.merge)}(e)&&function(e,t,n,r){var i=function(e){var t=r.getFieldValue(e,n);return"object"==typeof t&&t},s=i(e);if(!s)return;var o=i(t);if(!o)return;if(zt(s))return;if(Wr(s,o))return;if(Object.keys(s).every((function(e){return void 0!==r.getFieldValue(o,e)})))return;var a=r.getFieldValue(e,"__typename")||r.getFieldValue(t,"__typename"),c=Ji(n),u="".concat(a,".").concat(c);if(Ys.has(u))return;Ys.add(u);var l=[];an(s)||an(o)||[s,o].forEach((function(e){var t=r.getFieldValue(e,"__typename");"string"!=typeof t||l.includes(t)||l.push(t)}));__DEV__&&It.warn("Cache data may be lost when replacing the ".concat(c," field of a ").concat(a," object.\n\nThis could cause additional (usually avoidable) network requests to fetch data that were otherwise cached.\n\nTo address this problem (which is not a bug in Apollo Client), ").concat(l.length?"either ensure all objects of type "+l.join(" and ")+" have an ID or a custom merge function, or ":"","define a custom merge function for the ").concat(u," field, so InMemoryCache can safely merge these objects:\n\n  existing: ").concat(JSON.stringify(s).slice(0,1e3),"\n  incoming: ").concat(JSON.stringify(o).slice(0,1e3),"\n\nFor more information about these options, please refer to the documentation:\n\n  * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers\n  * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects\n"))}(a,i,e,l.store)}))}e.merge(r,i)})),e.retain(h.__ref),h},e.prototype.processSelectionSet=function(e){var t=this,n=e.dataId,r=e.result,i=e.selectionSet,s=e.context,o=e.mergeTree,a=this.cache.policies,c=Object.create(null),u=n&&a.rootTypenamesById[n]||Jt(r,i,s.fragmentMap)||n&&s.store.get(n,"__typename");"string"==typeof u&&(c.__typename=u);var l=function(){var e=Us(arguments,c,s.variables);if(zt(e.from)){var t=s.incomingById.get(e.from.__ref);if(t){var n=a.readField(dt(dt({},e),{from:t.storeObject}),s);if(void 0!==n)return n}}return a.readField(e,s)},h=new Set;this.flattenFields(i,r,s,u).forEach((function(e,n){var i,s=Yt(n),d=r[s];if(h.add(n),void 0!==d){var f=a.getStoreFieldName({typename:u,fieldName:n.name.value,field:n,variables:e.variables}),p=Qs(o,f),m=t.processFieldValue(d,n,n.selectionSet?zs(e,!1,!1):e,p),g=void 0;n.selectionSet&&(zt(m)||Zi(m))&&(g=l("__typename",m));var y=a.getMergeFunction(u,n.name.value,g);y?p.info={field:n,typename:u,merge:y}:Ks(o,f),c=e.merge(c,((i={})[f]=m,i))}else!__DEV__||e.clientOnly||e.deferred||pn.added(n)||a.getReadFunction(u,n.name.value)||__DEV__&&It.error("Missing field '".concat(Yt(n),"' while writing result ").concat(JSON.stringify(r,null,2)).substring(0,1e3))}));try{var d=a.identify(r,{typename:u,selectionSet:i,fragmentMap:s.fragmentMap,storeObject:c,readField:l}),f=d[0],p=d[1];n=n||f,p&&(c=s.merge(c,p))}catch(e){if(!n)throw e}if("string"==typeof n){var m=Bt(n),g=s.written[n]||(s.written[n]=[]);if(g.indexOf(i)>=0)return m;if(g.push(i),this.reader&&this.reader.isFresh(r,m,i,s))return m;var y=s.incomingById.get(n);return y?(y.storeObject=s.merge(y.storeObject,c),y.mergeTree=Hs(y.mergeTree,o),h.forEach((function(e){return y.fieldNodeSet.add(e)}))):s.incomingById.set(n,{storeObject:c,mergeTree:Gs(o)?void 0:o,fieldNodeSet:h}),m}return c},e.prototype.processFieldValue=function(e,t,n,r){var i=this;return t.selectionSet&&null!==e?an(e)?e.map((function(e,s){var o=i.processFieldValue(e,t,n,Qs(r,s));return Ks(r,s),o})):this.processSelectionSet({result:e,selectionSet:t.selectionSet,context:n,mergeTree:r}):__DEV__?Hn(e):e},e.prototype.flattenFields=function(e,t,n,i){void 0===i&&(i=Jt(t,e,n.fragmentMap));var s=new Map,o=this.cache.policies,a=new zi(!1);return function e(c,u){var l=a.lookup(c,u.clientOnly,u.deferred);l.visited||(l.visited=!0,c.selections.forEach((function(a){if(Mt(a,n.variables)){var c=u.clientOnly,l=u.deferred;if(c&&l||!cn(a.directives)||a.directives.forEach((function(e){var t=e.name.value;if("client"===t&&(c=!0),"defer"===t){var r=Kt(e,n.variables);r&&!1===r.if||(l=!0)}})),Xt(a)){var h=s.get(a);h&&(c=c&&h.clientOnly,l=l&&h.deferred),s.set(a,zs(n,c,l))}else{var d=Vt(a,n.lookupFragment);if(!d&&a.kind===r.Kind.FRAGMENT_SPREAD)throw __DEV__?new bt("No fragment named ".concat(a.name.value)):new bt(8);d&&o.fragmentMatches(d,i,t,n.variables)&&e(d.selectionSet,zs(n,c,l))}}})))}(e,n),s},e.prototype.applyMerges=function(e,t,n,r,i){var s,o=this;if(e.map.size&&!zt(n)){var a,c=an(n)||!zt(t)&&!Zi(t)?void 0:t,u=n;c&&!i&&(i=[zt(c)?c.__ref:c]);var l=function(e,t){return an(e)?"number"==typeof t?e[t]:void 0:r.store.getFieldValue(e,String(t))};e.map.forEach((function(e,t){var n=l(c,t),s=l(u,t);if(void 0!==s){i&&i.push(t);var h=o.applyMerges(e,n,s,r,i);h!==s&&(a=a||new Map).set(t,h),i&&It(i.pop()===t)}})),a&&(n=an(u)?u.slice(0):dt({},u),a.forEach((function(e,t){n[t]=e})))}return e.info?this.cache.policies.runMergeFunction(t,n,e.info,r,i&&(s=r.store).getStorage.apply(s,i)):n},e}(),Ws=[];function Qs(e,t){var n=e.map;return n.has(t)||n.set(t,Ws.pop()||{map:new Map}),n.get(t)}function Hs(e,t){if(e===t||!t||Gs(t))return e;if(!e||Gs(e))return t;var n=e.info&&t.info?dt(dt({},e.info),t.info):e.info||t.info,r=e.map.size&&t.map.size,i={info:n,map:r?new Map:e.map.size?e.map:t.map};if(r){var s=new Set(t.map.keys());e.map.forEach((function(e,n){i.map.set(n,Hs(e,t.map.get(n))),s.delete(n)})),s.forEach((function(n){i.map.set(n,Hs(t.map.get(n),e.map.get(n)))}))}return i}function Gs(e){return!e||!(e.info||e.map.size)}function Ks(e,t){var n=e.map,r=n.get(t);r&&Gs(r)&&(Ws.push(r),n.delete(t))}var Ys=new Set;var Js,Xs=function(e){function t(t){void 0===t&&(t={});var n=e.call(this)||this;return n.watches=new Set,n.typenameDocumentCache=new Map,n.makeVar=Ts,n.txCount=0,n.config=function(e){return hr(Gi,e)}(t),n.addTypename=!!n.config.addTypename,n.policies=new qs({cache:n,dataIdFromObject:n.config.dataIdFromObject,possibleTypes:n.config.possibleTypes,typePolicies:n.config.typePolicies}),n.init(),n}return ht(t,e),t.prototype.init=function(){var e=this.data=new is.Root({policies:this.policies,resultCaching:this.config.resultCaching});this.optimisticData=e.stump,this.resetResultCache()},t.prototype.resetResultCache=function(e){var t=this,n=this.storeReader,r=this.config.fragments;this.storeWriter=new $s(this,this.storeReader=new vs({cache:this,addTypename:this.addTypename,resultCacheMaxSize:this.config.resultCacheMaxSize,canonizeResults:Ki(this.config),canon:e?void 0:n&&n.canon,fragments:r}),r),this.maybeBroadcastWatch=Li((function(e,n){return t.broadcastWatch(e,n)}),{max:this.config.resultCacheMaxSize,makeCacheKey:function(e){var n=e.optimistic?t.optimisticData:t.data;if(hs(n)){var r=e.optimistic,i=e.id,s=e.variables;return n.makeCacheKey(e.query,e.callback,ms({optimistic:r,id:i,variables:s}))}}}),new Set([this.data.group,this.optimisticData.group]).forEach((function(e){return e.resetCaching()}))},t.prototype.restore=function(e){return this.init(),e&&this.data.replace(e),this},t.prototype.extract=function(e){return void 0===e&&(e=!1),(e?this.optimisticData:this.data).extract()},t.prototype.read=function(e){var t=e.returnPartialData,n=void 0!==t&&t;try{return this.storeReader.diffQueryAgainstStore(dt(dt({},e),{store:e.optimistic?this.optimisticData:this.data,config:this.config,returnPartialData:n})).result||null}catch(e){if(e instanceof ji)return null;throw e}},t.prototype.write=function(e){try{return++this.txCount,this.storeWriter.writeToStore(this.data,e)}finally{--this.txCount||!1===e.broadcast||this.broadcastWatches()}},t.prototype.modify=function(e){if(Wi.call(e,"id")&&!e.id)return!1;var t=e.optimistic?this.optimisticData:this.data;try{return++this.txCount,t.modify(e.id||"ROOT_QUERY",e.fields)}finally{--this.txCount||!1===e.broadcast||this.broadcastWatches()}},t.prototype.diff=function(e){return this.storeReader.diffQueryAgainstStore(dt(dt({},e),{store:e.optimistic?this.optimisticData:this.data,rootId:e.id||"ROOT_QUERY",config:this.config}))},t.prototype.watch=function(e){var t=this;return this.watches.size||function(e){Is(e).vars.forEach((function(t){return t.attachCache(e)}))}(this),this.watches.add(e),e.immediate&&this.maybeBroadcastWatch(e),function(){t.watches.delete(e)&&!t.watches.size&&Es(t),t.maybeBroadcastWatch.forget(e)}},t.prototype.gc=function(e){ms.reset();var t=this.optimisticData.gc();return e&&!this.txCount&&(e.resetResultCache?this.resetResultCache(e.resetResultIdentities):e.resetResultIdentities&&this.storeReader.resetCanon()),t},t.prototype.retain=function(e,t){return(t?this.optimisticData:this.data).retain(e)},t.prototype.release=function(e,t){return(t?this.optimisticData:this.data).release(e)},t.prototype.identify=function(e){if(zt(e))return e.__ref;try{return this.policies.identify(e)[0]}catch(e){__DEV__&&It.warn(e)}},t.prototype.evict=function(e){if(!e.id){if(Wi.call(e,"id"))return!1;e=dt(dt({},e),{id:"ROOT_QUERY"})}try{return++this.txCount,this.optimisticData.evict(e,this.data)}finally{--this.txCount||!1===e.broadcast||this.broadcastWatches()}},t.prototype.reset=function(e){var t=this;return this.init(),ms.reset(),e&&e.discardWatches?(this.watches.forEach((function(e){return t.maybeBroadcastWatch.forget(e)})),this.watches.clear(),Es(this)):this.broadcastWatches(),Promise.resolve()},t.prototype.removeOptimistic=function(e){var t=this.optimisticData.removeLayer(e);t!==this.optimisticData&&(this.optimisticData=t,this.broadcastWatches())},t.prototype.batch=function(e){var t,n=this,r=e.update,i=e.optimistic,s=void 0===i||i,o=e.removeOptimistic,a=e.onWatchUpdated,c=function(e){var i=n,s=i.data,o=i.optimisticData;++n.txCount,e&&(n.data=n.optimisticData=e);try{return t=r(n)}finally{--n.txCount,n.data=s,n.optimisticData=o}},u=new Set;return a&&!this.txCount&&this.broadcastWatches(dt(dt({},e),{onWatchUpdated:function(e){return u.add(e),!1}})),"string"==typeof s?this.optimisticData=this.optimisticData.addLayer(s,c):!1===s?c(this.data):c(),"string"==typeof o&&(this.optimisticData=this.optimisticData.removeLayer(o)),a&&u.size?(this.broadcastWatches(dt(dt({},e),{onWatchUpdated:function(e,t){var n=a.call(this,e,t);return!1!==n&&u.delete(e),n}})),u.size&&u.forEach((function(e){return n.maybeBroadcastWatch.dirty(e)}))):this.broadcastWatches(e),t},t.prototype.performTransaction=function(e,t){return this.batch({update:e,optimistic:t||null!==t})},t.prototype.transformDocument=function(e){if(this.addTypename){var t=this.typenameDocumentCache.get(e);return t||(t=pn(e),this.typenameDocumentCache.set(e,t),this.typenameDocumentCache.set(t,t)),t}return e},t.prototype.transformForLink=function(e){var t=this.config.fragments;return t?t.transform(e):e},t.prototype.broadcastWatches=function(e){var t=this;this.txCount||this.watches.forEach((function(n){return t.maybeBroadcastWatch(n,e)}))},t.prototype.broadcastWatch=function(e,t){var n=e.lastDiff,r=this.diff(e);t&&(e.optimistic&&"string"==typeof t.optimistic&&(r.fromOptimisticTransaction=!0),t.onWatchUpdated&&!1===t.onWatchUpdated.call(this,e,r,n))||n&&Wr(n.result,r.result)||e.callback(e.lastDiff=r,n)},t}(Fi);function Zs(e){return!!e&&e<7}!function(e){e[e.loading=1]="loading",e[e.setVariables=2]="setVariables",e[e.fetchMore=3]="fetchMore",e[e.refetch=4]="refetch",e[e.poll=6]="poll",e[e.ready=7]="ready",e[e.error=8]="error"}(Js||(Js={}));var eo=Object.assign,to=Object.hasOwnProperty,no=function(e){function t(t){var n=t.queryManager,r=t.queryInfo,i=t.options,s=e.call(this,(function(e){try{var t=e._subscription._observer;t&&!t.error&&(t.error=io)}catch(e){}var n=!s.observers.size;s.observers.add(e);var r=s.last;return r&&r.error?e.error&&e.error(r.error):r&&r.result&&e.next&&e.next(r.result),n&&s.reobserve().catch((function(){})),function(){s.observers.delete(e)&&!s.observers.size&&s.tearDownQuery()}}))||this;s.observers=new Set,s.subscriptions=new Set,s.queryInfo=r,s.queryManager=n,s.waitForOwnResult=oo(i.fetchPolicy),s.isTornDown=!1;var o=n.defaultOptions.watchQuery,a=(void 0===o?{}:o).fetchPolicy,c=void 0===a?"cache-first":a,u=i.fetchPolicy,l=void 0===u?c:u,h=i.initialFetchPolicy,d=void 0===h?"standby"===l?c:l:h;s.options=dt(dt({},i),{initialFetchPolicy:d,fetchPolicy:l}),s.queryId=r.queryId||n.generateQueryId();var f=en(s.query);return s.queryName=f&&f.name&&f.name.value,s}return ht(t,e),Object.defineProperty(t.prototype,"query",{get:function(){return this.queryManager.transform(this.options.query).document},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"variables",{get:function(){return this.options.variables},enumerable:!1,configurable:!0}),t.prototype.result=function(){var e=this;return new Promise((function(t,n){var r={next:function(n){t(n),e.observers.delete(r),e.observers.size||e.queryManager.removeQuery(e.queryId),setTimeout((function(){i.unsubscribe()}),0)},error:n},i=e.subscribe(r)}))},t.prototype.getCurrentResult=function(e){void 0===e&&(e=!0);var t=this.getLastResult(!0),n=this.queryInfo.networkStatus||t&&t.networkStatus||Js.ready,r=dt(dt({},t),{loading:Zs(n),networkStatus:n}),i=this.options.fetchPolicy,s=void 0===i?"cache-first":i;if(oo(s)||this.queryManager.transform(this.options.query).hasForcedResolvers);else if(this.waitForOwnResult)this.queryInfo.updateWatch();else{var o=this.queryInfo.getDiff();(o.complete||this.options.returnPartialData)&&(r.data=o.result),Wr(r.data,{})&&(r.data=void 0),o.complete?(delete r.partial,!o.complete||r.networkStatus!==Js.loading||"cache-first"!==s&&"cache-only"!==s||(r.networkStatus=Js.ready,r.loading=!1)):r.partial=!0,!__DEV__||o.complete||this.options.partialRefetch||r.loading||r.data||r.error||so(o.missing)}return e&&this.updateLastResult(r),r},t.prototype.isDifferentFromLastResult=function(e,t){return!this.last||!Wr(this.last.result,e)||t&&!Wr(this.last.variables,t)},t.prototype.getLast=function(e,t){var n=this.last;if(n&&n[e]&&(!t||Wr(n.variables,this.variables)))return n[e]},t.prototype.getLastResult=function(e){return this.getLast("result",e)},t.prototype.getLastError=function(e){return this.getLast("error",e)},t.prototype.resetLastResults=function(){delete this.last,this.isTornDown=!1},t.prototype.resetQueryStoreErrors=function(){this.queryManager.resetErrors(this.queryId)},t.prototype.refetch=function(e){var t,n={pollInterval:0},r=this.options.fetchPolicy;if(n.fetchPolicy="cache-and-network"===r?r:"no-cache"===r?"no-cache":"network-only",__DEV__&&e&&to.call(e,"variables")){var i=rn(this.query),s=i.variableDefinitions;s&&s.some((function(e){return"variables"===e.variable.name.value}))||__DEV__&&It.warn("Called refetch(".concat(JSON.stringify(e),") for query ").concat((null===(t=i.name)||void 0===t?void 0:t.value)||JSON.stringify(i),", which does not declare a $variables variable.\nDid you mean to call refetch(variables) instead of refetch({ variables })?"))}return e&&!Wr(this.options.variables,e)&&(n.variables=this.options.variables=dt(dt({},this.options.variables),e)),this.queryInfo.resetLastWrite(),this.reobserve(n,Js.refetch)},t.prototype.fetchMore=function(e){var t=this,n=dt(dt({},e.query?e:dt(dt(dt(dt({},this.options),{query:this.query}),e),{variables:dt(dt({},this.options.variables),e.variables)})),{fetchPolicy:"no-cache"}),r=this.queryManager.generateQueryId(),i=this.queryInfo,s=i.networkStatus;i.networkStatus=Js.fetchMore,n.notifyOnNetworkStatusChange&&this.observe();var o=new Set;return this.queryManager.fetchQuery(r,n,Js.fetchMore).then((function(a){return t.queryManager.removeQuery(r),i.networkStatus===Js.fetchMore&&(i.networkStatus=s),t.queryManager.cache.batch({update:function(r){var i=e.updateQuery;i?r.updateQuery({query:t.query,variables:t.variables,returnPartialData:!0,optimistic:!1},(function(e){return i(e,{fetchMoreResult:a.data,variables:n.variables})})):r.writeQuery({query:n.query,variables:n.variables,data:a.data})},onWatchUpdated:function(e){o.add(e.query)}}),a})).finally((function(){o.has(t.query)||ro(t)}))},t.prototype.subscribeToMore=function(e){var t=this,n=this.queryManager.startGraphQLSubscription({query:e.document,variables:e.variables,context:e.context}).subscribe({next:function(n){var r=e.updateQuery;r&&t.updateQuery((function(e,t){var i=t.variables;return r(e,{subscriptionData:n,variables:i})}))},error:function(t){e.onError?e.onError(t):__DEV__&&It.error("Unhandled GraphQL subscription error",t)}});return this.subscriptions.add(n),function(){t.subscriptions.delete(n)&&n.unsubscribe()}},t.prototype.setOptions=function(e){return this.reobserve(e)},t.prototype.setVariables=function(e){return Wr(this.variables,e)?this.observers.size?this.result():Promise.resolve():(this.options.variables=e,this.observers.size?this.reobserve({fetchPolicy:this.options.initialFetchPolicy,variables:e},Js.setVariables):Promise.resolve())},t.prototype.updateQuery=function(e){var t=this.queryManager,n=e(t.cache.diff({query:this.options.query,variables:this.variables,returnPartialData:!0,optimistic:!1}).result,{variables:this.variables});n&&(t.cache.writeQuery({query:this.options.query,data:n,variables:this.variables}),t.broadcastQueries())},t.prototype.startPolling=function(e){this.options.pollInterval=e,this.updatePolling()},t.prototype.stopPolling=function(){this.options.pollInterval=0,this.updatePolling()},t.prototype.applyNextFetchPolicy=function(e,t){if(t.nextFetchPolicy){var n=t.fetchPolicy,r=void 0===n?"cache-first":n,i=t.initialFetchPolicy,s=void 0===i?r:i;"standby"===r||("function"==typeof t.nextFetchPolicy?t.fetchPolicy=t.nextFetchPolicy(r,{reason:e,options:t,observable:this,initialFetchPolicy:s}):t.fetchPolicy="variables-changed"===e?s:t.nextFetchPolicy)}return t.fetchPolicy},t.prototype.fetch=function(e,t){return this.queryManager.setObservableQuery(this),this.queryManager.fetchConcastWithInfo(this.queryId,e,t)},t.prototype.updatePolling=function(){var e=this;if(!this.queryManager.ssrMode){var t=this.pollingInfo,n=this.options.pollInterval;if(n){if(!t||t.interval!==n){__DEV__?It(n,"Attempted to start a polling query without a polling interval."):It(n,13),(t||(this.pollingInfo={})).interval=n;var r=function(){e.pollingInfo&&(Zs(e.queryInfo.networkStatus)?i():e.reobserve({fetchPolicy:"no-cache"===e.options.initialFetchPolicy?"no-cache":"network-only"},Js.poll).then(i,i))},i=function(){var t=e.pollingInfo;t&&(clearTimeout(t.timeout),t.timeout=setTimeout(r,t.interval))};i()}}else t&&(clearTimeout(t.timeout),delete this.pollingInfo)}},t.prototype.updateLastResult=function(e,t){return void 0===t&&(t=this.variables),this.last=dt(dt({},this.last),{result:this.queryManager.assumeImmutableResults?e:Hn(e),variables:t}),cn(e.errors)||delete this.last.error,this.last},t.prototype.reobserveAsConcast=function(e,t){var n=this;this.isTornDown=!1;var r=t===Js.refetch||t===Js.fetchMore||t===Js.poll,i=this.options.variables,s=this.options.fetchPolicy,o=hr(this.options,e||{}),a=r?o:eo(this.options,o);r||(this.updatePolling(),e&&e.variables&&!Wr(e.variables,i)&&"standby"!==a.fetchPolicy&&a.fetchPolicy===s&&(this.applyNextFetchPolicy("variables-changed",a),void 0===t&&(t=Js.setVariables))),this.waitForOwnResult&&(this.waitForOwnResult=oo(a.fetchPolicy));var c=function(){n.concast===h&&(n.waitForOwnResult=!1)},u=a.variables&&dt({},a.variables),l=this.fetch(a,t),h=l.concast,d=l.fromLink,f={next:function(e){c(),n.reportResult(e,u)},error:function(e){c(),n.reportError(e,u)}};return!r&&d&&(this.concast&&this.observer&&this.concast.removeObserver(this.observer),this.concast=h,this.observer=f),h.addObserver(f),h},t.prototype.reobserve=function(e,t){return this.reobserveAsConcast(e,t).promise},t.prototype.observe=function(){this.reportResult(this.getCurrentResult(!1),this.variables)},t.prototype.reportResult=function(e,t){var n=this.getLastError();(n||this.isDifferentFromLastResult(e,t))&&((n||!e.partial||this.options.returnPartialData)&&this.updateLastResult(e,t),Jn(this.observers,"next",e))},t.prototype.reportError=function(e,t){var n=dt(dt({},this.getLastResult()),{error:e,errors:e.graphQLErrors,networkStatus:Js.error,loading:!1});this.updateLastResult(n,t),Jn(this.observers,"error",this.last.error=e)},t.prototype.hasObservers=function(){return this.observers.size>0},t.prototype.tearDownQuery=function(){this.isTornDown||(this.concast&&this.observer&&(this.concast.removeObserver(this.observer),delete this.concast,delete this.observer),this.stopPolling(),this.subscriptions.forEach((function(e){return e.unsubscribe()})),this.subscriptions.clear(),this.queryManager.stopQuery(this.queryId),this.observers.clear(),this.isTornDown=!0)},t}(zn);function ro(e){var t=e.options,n=t.fetchPolicy,r=t.nextFetchPolicy;return"cache-and-network"===n||"network-only"===n?e.reobserve({fetchPolicy:"cache-first",nextFetchPolicy:function(){return this.nextFetchPolicy=r,"function"==typeof r?r.apply(this,arguments):n}}):e.reobserve()}function io(e){__DEV__&&It.error("Unhandled error",e.message,e.stack)}function so(e){__DEV__&&e&&__DEV__&&It.debug("Missing cache result fields: ".concat(JSON.stringify(e)),e)}function oo(e){return"network-only"===e||"no-cache"===e||"standby"===e}rr(no);var ao=function(){function e(e){var t=e.cache,n=e.client,r=e.resolvers,i=e.fragmentMatcher;this.selectionsToResolveCache=new WeakMap,this.cache=t,n&&(this.client=n),r&&this.addResolvers(r),i&&this.setFragmentMatcher(i)}return e.prototype.addResolvers=function(e){var t=this;this.resolvers=this.resolvers||{},Array.isArray(e)?e.forEach((function(e){t.resolvers=vn(t.resolvers,e)})):this.resolvers=vn(this.resolvers,e)},e.prototype.setResolvers=function(e){this.resolvers={},this.addResolvers(e)},e.prototype.getResolvers=function(){return this.resolvers||{}},e.prototype.runResolvers=function(e){var t=e.document,n=e.remoteResult,r=e.context,i=e.variables,s=e.onlyRunForcedResolvers,o=void 0!==s&&s;return pt(this,void 0,void 0,(function(){return mt(this,(function(e){return t?[2,this.resolveDocument(t,n.data,r,i,this.fragmentMatcher,o).then((function(e){return dt(dt({},n),{data:e.result})}))]:[2,n]}))}))},e.prototype.setFragmentMatcher=function(e){this.fragmentMatcher=e},e.prototype.getFragmentMatcher=function(){return this.fragmentMatcher},e.prototype.clientQuery=function(e){return Lt(["client"],e)&&this.resolvers?e:null},e.prototype.serverQuery=function(e){return function(e){return Zt(e),fn([{test:function(e){return"client"===e.name.value},remove:!0}],e)}(e)},e.prototype.prepareContext=function(e){var t=this.cache;return dt(dt({},e),{cache:t,getCacheKey:function(e){return t.identify(e)}})},e.prototype.addExportedVariables=function(e,t,n){return void 0===t&&(t={}),void 0===n&&(n={}),pt(this,void 0,void 0,(function(){return mt(this,(function(r){return e?[2,this.resolveDocument(e,this.buildRootValueFromCache(e,t)||{},this.prepareContext(n),t).then((function(e){return dt(dt({},t),e.exportedVariables)}))]:[2,dt({},t)]}))}))},e.prototype.shouldForceResolvers=function(e){var t=!1;return r.visit(e,{Directive:{enter:function(e){if("client"===e.name.value&&e.arguments&&(t=e.arguments.some((function(e){return"always"===e.name.value&&"BooleanValue"===e.value.kind&&!0===e.value.value}))))return r.BREAK}}}),t},e.prototype.buildRootValueFromCache=function(e,t){return this.cache.diff({query:gn(e),variables:t,returnPartialData:!0,optimistic:!1}).result},e.prototype.resolveDocument=function(e,t,n,r,i,s){return void 0===n&&(n={}),void 0===r&&(r={}),void 0===i&&(i=function(){return!0}),void 0===s&&(s=!1),pt(this,void 0,void 0,(function(){var o,a,c,u,l,h,d,f,p,m;return mt(this,(function(g){return o=sn(e),a=nn(e),c=qt(a),u=this.collectSelectionsToResolve(o,c),l=o.operation,h=l?l.charAt(0).toUpperCase()+l.slice(1):"Query",f=(d=this).cache,p=d.client,m={fragmentMap:c,context:dt(dt({},n),{cache:f,client:p}),variables:r,fragmentMatcher:i,defaultOperationType:h,exportedVariables:{},selectionsToResolve:u,onlyRunForcedResolvers:s},!1,[2,this.resolveSelectionSet(o.selectionSet,false,t,m).then((function(e){return{result:e,exportedVariables:m.exportedVariables}}))]}))}))},e.prototype.resolveSelectionSet=function(e,t,n,r){return pt(this,void 0,void 0,(function(){var i,s,o,a,c,u=this;return mt(this,(function(l){return i=r.fragmentMap,s=r.context,o=r.variables,a=[n],c=function(e){return pt(u,void 0,void 0,(function(){var c,u;return mt(this,(function(l){return(t||r.selectionsToResolve.has(e))&&Mt(e,o)?Xt(e)?[2,this.resolveField(e,t,n,r).then((function(t){var n;void 0!==t&&a.push(((n={})[Yt(e)]=t,n))}))]:(!function(e){return"InlineFragment"===e.kind}(e)?(c=i[e.name.value],__DEV__?It(c,"No fragment named ".concat(e.name.value)):It(c,11)):c=e,c&&c.typeCondition&&(u=c.typeCondition.name.value,r.fragmentMatcher(n,u,s))?[2,this.resolveSelectionSet(c.selectionSet,t,n,r).then((function(e){a.push(e)}))]:[2]):[2]}))}))},[2,Promise.all(e.selections.map(c)).then((function(){return _n(a)}))]}))}))},e.prototype.resolveField=function(e,t,n,r){return pt(this,void 0,void 0,(function(){var i,s,o,a,c,u,l,h,d,f=this;return mt(this,(function(p){return n?(i=r.variables,s=e.name.value,o=Yt(e),a=s!==o,c=n[o]||n[s],u=Promise.resolve(c),r.onlyRunForcedResolvers&&!this.shouldForceResolvers(e)||(l=n.__typename||r.defaultOperationType,(h=this.resolvers&&this.resolvers[l])&&(d=h[a?s:o])&&(u=Promise.resolve(ws.withValue(this.cache,d,[n,Kt(e,i),r.context,{field:e,fragmentMap:r.fragmentMap}])))),[2,u.then((function(n){var i,s;if(void 0===n&&(n=c),e.directives&&e.directives.forEach((function(e){"export"===e.name.value&&e.arguments&&e.arguments.forEach((function(e){"as"===e.name.value&&"StringValue"===e.value.kind&&(r.exportedVariables[e.value.value]=n)}))})),!e.selectionSet)return n;if(null==n)return n;var o=null!==(s=null===(i=e.directives)||void 0===i?void 0:i.some((function(e){return"client"===e.name.value})))&&void 0!==s&&s;return Array.isArray(n)?f.resolveSubSelectedArray(e,t||o,n,r):e.selectionSet?f.resolveSelectionSet(e.selectionSet,t||o,n,r):void 0}))]):[2,null]}))}))},e.prototype.resolveSubSelectedArray=function(e,t,n,r){var i=this;return Promise.all(n.map((function(n){return null===n?null:Array.isArray(n)?i.resolveSubSelectedArray(e,t,n,r):e.selectionSet?i.resolveSelectionSet(e.selectionSet,t,n,r):void 0})))},e.prototype.collectSelectionsToResolve=function(e,t){var n=function(e){return!Array.isArray(e)},i=this.selectionsToResolveCache;return function e(s){if(!i.has(s)){var o=new Set;i.set(s,o),r.visit(s,{Directive:function(e,t,i,s,a){"client"===e.name.value&&a.forEach((function(e){n(e)&&r.isSelectionNode(e)&&o.add(e)}))},FragmentSpread:function(i,s,a,c,u){var l=t[i.name.value];__DEV__?It(l,"No fragment named ".concat(i.name.value)):It(l,12);var h=e(l);h.size>0&&(u.forEach((function(e){n(e)&&r.isSelectionNode(e)&&o.add(e)})),o.add(i),h.forEach((function(e){o.add(e)})))}})}return i.get(s)}(e)},e}(),co=new(Zn?WeakMap:Map);function uo(e,t){var n=e[t];"function"==typeof n&&(e[t]=function(){return co.set(e,(co.get(e)+1)%1e15),n.apply(this,arguments)})}function lo(e){e.notifyTimeout&&(clearTimeout(e.notifyTimeout),e.notifyTimeout=void 0)}var ho=function(){function e(e,t){void 0===t&&(t=e.generateQueryId()),this.queryId=t,this.listeners=new Set,this.document=null,this.lastRequestId=1,this.subscriptions=new Set,this.stopped=!1,this.dirty=!1,this.observableQuery=null;var n=this.cache=e.cache;co.has(n)||(co.set(n,0),uo(n,"evict"),uo(n,"modify"),uo(n,"reset"))}return e.prototype.init=function(e){var t=e.networkStatus||Js.loading;return this.variables&&this.networkStatus!==Js.loading&&!Wr(this.variables,e.variables)&&(t=Js.setVariables),Wr(e.variables,this.variables)||(this.lastDiff=void 0),Object.assign(this,{document:e.document,variables:e.variables,networkError:null,graphQLErrors:this.graphQLErrors||[],networkStatus:t}),e.observableQuery&&this.setObservableQuery(e.observableQuery),e.lastRequestId&&(this.lastRequestId=e.lastRequestId),this},e.prototype.reset=function(){lo(this),this.dirty=!1},e.prototype.getDiff=function(e){void 0===e&&(e=this.variables);var t=this.getDiffOptions(e);if(this.lastDiff&&Wr(t,this.lastDiff.options))return this.lastDiff.diff;this.updateWatch(this.variables=e);var n=this.observableQuery;if(n&&"no-cache"===n.options.fetchPolicy)return{complete:!1};var r=this.cache.diff(t);return this.updateLastDiff(r,t),r},e.prototype.updateLastDiff=function(e,t){this.lastDiff=e?{diff:e,options:t||this.getDiffOptions()}:void 0},e.prototype.getDiffOptions=function(e){var t;return void 0===e&&(e=this.variables),{query:this.document,variables:e,returnPartialData:!0,optimistic:!0,canonizeResults:null===(t=this.observableQuery)||void 0===t?void 0:t.options.canonizeResults}},e.prototype.setDiff=function(e){var t=this,n=this.lastDiff&&this.lastDiff.diff;this.updateLastDiff(e),this.dirty||Wr(n&&n.result,e&&e.result)||(this.dirty=!0,this.notifyTimeout||(this.notifyTimeout=setTimeout((function(){return t.notify()}),0)))},e.prototype.setObservableQuery=function(e){var t=this;e!==this.observableQuery&&(this.oqListener&&this.listeners.delete(this.oqListener),this.observableQuery=e,e?(e.queryInfo=this,this.listeners.add(this.oqListener=function(){t.getDiff().fromOptimisticTransaction?e.observe():ro(e)})):delete this.oqListener)},e.prototype.notify=function(){var e=this;lo(this),this.shouldNotify()&&this.listeners.forEach((function(t){return t(e)})),this.dirty=!1},e.prototype.shouldNotify=function(){if(!this.dirty||!this.listeners.size)return!1;if(Zs(this.networkStatus)&&this.observableQuery){var e=this.observableQuery.options.fetchPolicy;if("cache-only"!==e&&"cache-and-network"!==e)return!1}return!0},e.prototype.stop=function(){if(!this.stopped){this.stopped=!0,this.reset(),this.cancel(),this.cancel=e.prototype.cancel,this.subscriptions.forEach((function(e){return e.unsubscribe()}));var t=this.observableQuery;t&&t.stopPolling()}},e.prototype.cancel=function(){},e.prototype.updateWatch=function(e){var t=this;void 0===e&&(e=this.variables);var n=this.observableQuery;if(!n||"no-cache"!==n.options.fetchPolicy){var r=dt(dt({},this.getDiffOptions(e)),{watcher:this,callback:function(e){return t.setDiff(e)}});this.lastWatch&&Wr(r,this.lastWatch)||(this.cancel(),this.cancel=this.cache.watch(this.lastWatch=r))}},e.prototype.resetLastWrite=function(){this.lastWrite=void 0},e.prototype.shouldWrite=function(e,t){var n=this.lastWrite;return!(n&&n.dmCount===co.get(this.cache)&&Wr(t,n.variables)&&Wr(e.data,n.result.data))},e.prototype.markResult=function(e,t,n,r){var i=this,s=new bn,o=cn(e.errors)?e.errors.slice(0):[];if(this.reset(),"incremental"in e&&cn(e.incremental)){var a=cr(this.getDiff().result,e);e.data=a}else if("hasNext"in e&&e.hasNext){var c=this.getDiff();e.data=s.merge(c.result,e.data)}this.graphQLErrors=o,"no-cache"===n.fetchPolicy?this.updateLastDiff({result:e.data,complete:!0},this.getDiffOptions(n.variables)):0!==r&&(fo(e,n.errorPolicy)?this.cache.performTransaction((function(s){if(i.shouldWrite(e,n.variables))s.writeQuery({query:t,data:e.data,variables:n.variables,overwrite:1===r}),i.lastWrite={result:e,variables:n.variables,dmCount:co.get(i.cache)};else if(i.lastDiff&&i.lastDiff.diff.complete)return void(e.data=i.lastDiff.diff.result);var o=i.getDiffOptions(n.variables),a=s.diff(o);i.stopped||i.updateWatch(n.variables),i.updateLastDiff(a,o),a.complete&&(e.data=a.result)})):this.lastWrite=void 0)},e.prototype.markReady=function(){return this.networkError=null,this.networkStatus=Js.ready},e.prototype.markError=function(e){return this.networkStatus=Js.error,this.lastWrite=void 0,this.reset(),e.graphQLErrors&&(this.graphQLErrors=e.graphQLErrors),e.networkError&&(this.networkError=e.networkError),e},e}();function fo(e,t){void 0===t&&(t="none");var n="ignore"===t||"all"===t,r=!ur(e);return!r&&n&&e.data&&(r=!0),r}var po=Object.prototype.hasOwnProperty,mo=function(){function e(e){var t=e.cache,n=e.link,r=e.defaultOptions,i=e.queryDeduplication,s=void 0!==i&&i,o=e.onBroadcast,a=e.ssrMode,c=void 0!==a&&a,u=e.clientAwareness,l=void 0===u?{}:u,h=e.localState,d=e.assumeImmutableResults;this.clientAwareness={},this.queries=new Map,this.fetchCancelFns=new Map,this.transformCache=new(Zn?WeakMap:Map),this.queryIdCounter=1,this.requestIdCounter=1,this.mutationIdCounter=1,this.inFlightLinkObservables=new Map,this.cache=t,this.link=n,this.defaultOptions=r||Object.create(null),this.queryDeduplication=s,this.clientAwareness=l,this.localState=h||new ao({cache:t}),this.ssrMode=c,this.assumeImmutableResults=!!d,(this.onBroadcast=o)&&(this.mutationStore=Object.create(null))}return e.prototype.stop=function(){var e=this;this.queries.forEach((function(t,n){e.stopQueryNoBroadcast(n)})),this.cancelPendingFetches(__DEV__?new bt("QueryManager stopped while query was in flight"):new bt(14))},e.prototype.cancelPendingFetches=function(e){this.fetchCancelFns.forEach((function(t){return t(e)})),this.fetchCancelFns.clear()},e.prototype.mutate=function(e){var t,n,r=e.mutation,i=e.variables,s=e.optimisticResponse,o=e.updateQueries,a=e.refetchQueries,c=void 0===a?[]:a,u=e.awaitRefetchQueries,l=void 0!==u&&u,h=e.update,d=e.onQueryUpdated,f=e.fetchPolicy,p=void 0===f?(null===(t=this.defaultOptions.mutate)||void 0===t?void 0:t.fetchPolicy)||"network-only":f,m=e.errorPolicy,g=void 0===m?(null===(n=this.defaultOptions.mutate)||void 0===n?void 0:n.errorPolicy)||"none":m,y=e.keepRootFields,v=e.context;return pt(this,void 0,void 0,(function(){var e,t,n,a,u,f;return mt(this,(function(m){switch(m.label){case 0:return __DEV__?It(r,"mutation option is required. You must specify your GraphQL document in the mutation option."):It(r,15),__DEV__?It("network-only"===p||"no-cache"===p,"Mutations support only 'network-only' or 'no-cache' fetchPolicy strings. The default `network-only` behavior automatically writes mutation results to the cache. Passing `no-cache` skips the cache write."):It("network-only"===p||"no-cache"===p,16),e=this.generateMutationId(),t=this.transform(r),n=t.document,a=t.hasClientExports,r=this.cache.transformForLink(n),i=this.getVariables(r,i),a?[4,this.localState.addExportedVariables(r,i,v)]:[3,2];case 1:i=m.sent(),m.label=2;case 2:return u=this.mutationStore&&(this.mutationStore[e]={mutation:r,variables:i,loading:!0,error:null}),s&&this.markMutationOptimistic(s,{mutationId:e,document:r,variables:i,fetchPolicy:p,errorPolicy:g,context:v,updateQueries:o,update:h,keepRootFields:y}),this.broadcastQueries(),f=this,[2,new Promise((function(t,n){return Xn(f.getObservableFromLink(r,dt(dt({},v),{optimisticResponse:s}),i,!1),(function(t){if(ur(t)&&"none"===g)throw new xr({graphQLErrors:lr(t)});u&&(u.loading=!1,u.error=null);var n=dt({},t);return"function"==typeof c&&(c=c(n)),"ignore"===g&&ur(n)&&delete n.errors,f.markMutationResult({mutationId:e,result:n,document:r,variables:i,fetchPolicy:p,errorPolicy:g,context:v,update:h,updateQueries:o,awaitRefetchQueries:l,refetchQueries:c,removeOptimistic:s?e:void 0,onQueryUpdated:d,keepRootFields:y})})).subscribe({next:function(e){f.broadcastQueries(),"hasNext"in e&&!1!==e.hasNext||t(e)},error:function(t){u&&(u.loading=!1,u.error=t),s&&f.cache.removeOptimistic(e),f.broadcastQueries(),n(t instanceof xr?t:new xr({networkError:t}))}})}))]}}))}))},e.prototype.markMutationResult=function(e,t){var n=this;void 0===t&&(t=this.cache);var r=e.result,i=[],s="no-cache"===e.fetchPolicy;if(!s&&fo(r,e.errorPolicy)){if(or(r)||i.push({result:r.data,dataId:"ROOT_MUTATION",query:e.document,variables:e.variables}),or(r)&&cn(r.incremental)){var o=t.diff({id:"ROOT_MUTATION",query:this.transform(e.document).asQuery,variables:e.variables,optimistic:!1,returnPartialData:!0}),a=void 0;o.result&&(a=cr(o.result,r)),void 0!==a&&(r.data=a,i.push({result:a,dataId:"ROOT_MUTATION",query:e.document,variables:e.variables}))}var c=e.updateQueries;c&&this.queries.forEach((function(e,s){var o=e.observableQuery,a=o&&o.queryName;if(a&&po.call(c,a)){var u=c[a],l=n.queries.get(s),h=l.document,d=l.variables,f=t.diff({query:h,variables:d,returnPartialData:!0,optimistic:!1}),p=f.result;if(f.complete&&p){var m=u(p,{mutationResult:r,queryName:h&&tn(h)||void 0,queryVariables:d});m&&i.push({result:m,dataId:"ROOT_QUERY",query:h,variables:d})}}}))}if(i.length>0||e.refetchQueries||e.update||e.onQueryUpdated||e.removeOptimistic){var u=[];if(this.refetchQueries({updateCache:function(t){s||i.forEach((function(e){return t.write(e)}));var o,a=e.update,c=!(or(o=r)||function(e){return"hasNext"in e&&"data"in e}(o))||or(r)&&!r.hasNext;if(a){if(!s){var u=t.diff({id:"ROOT_MUTATION",query:n.transform(e.document).asQuery,variables:e.variables,optimistic:!1,returnPartialData:!0});u.complete&&("incremental"in(r=dt(dt({},r),{data:u.result}))&&delete r.incremental,"hasNext"in r&&delete r.hasNext)}c&&a(t,r,{context:e.context,variables:e.variables})}s||e.keepRootFields||!c||t.modify({id:"ROOT_MUTATION",fields:function(e,t){var n=t.fieldName,r=t.DELETE;return"__typename"===n?e:r}})},include:e.refetchQueries,optimistic:!1,removeOptimistic:e.removeOptimistic,onQueryUpdated:e.onQueryUpdated||null}).forEach((function(e){return u.push(e)})),e.awaitRefetchQueries||e.onQueryUpdated)return Promise.all(u).then((function(){return r}))}return Promise.resolve(r)},e.prototype.markMutationOptimistic=function(e,t){var n=this,r="function"==typeof e?e(t.variables):e;return this.cache.recordOptimisticTransaction((function(e){try{n.markMutationResult(dt(dt({},t),{result:{data:r}}),e)}catch(e){__DEV__&&It.error(e)}}),t.mutationId)},e.prototype.fetchQuery=function(e,t,n){return this.fetchQueryObservable(e,t,n).promise},e.prototype.getQueryStore=function(){var e=Object.create(null);return this.queries.forEach((function(t,n){e[n]={variables:t.variables,networkStatus:t.networkStatus,networkError:t.networkError,graphQLErrors:t.graphQLErrors}})),e},e.prototype.resetErrors=function(e){var t=this.queries.get(e);t&&(t.networkError=void 0,t.graphQLErrors=[])},e.prototype.transform=function(e){var t=this.transformCache;if(!t.has(e)){var n=this.cache.transformDocument(e),r=fn([mn],Zt(n)),i=this.localState.clientQuery(n),s=r&&this.localState.serverQuery(r),o={document:n,hasClientExports:Ft(n),hasForcedResolvers:this.localState.shouldForceResolvers(n),clientQuery:i,serverQuery:s,defaultVars:on(en(n)),asQuery:dt(dt({},n),{definitions:n.definitions.map((function(e){return"OperationDefinition"===e.kind&&"query"!==e.operation?dt(dt({},e),{operation:"query"}):e}))})},a=function(e){e&&!t.has(e)&&t.set(e,o)};a(e),a(n),a(i),a(s)}return t.get(e)},e.prototype.getVariables=function(e,t){return dt(dt({},this.transform(e).defaultVars),t)},e.prototype.watchQuery=function(e){void 0===(e=dt(dt({},e),{variables:this.getVariables(e.query,e.variables)})).notifyOnNetworkStatusChange&&(e.notifyOnNetworkStatusChange=!1);var t=new ho(this),n=new no({queryManager:this,queryInfo:t,options:e});return this.queries.set(n.queryId,t),t.init({document:n.query,observableQuery:n,variables:n.variables}),n},e.prototype.query=function(e,t){var n=this;return void 0===t&&(t=this.generateQueryId()),__DEV__?It(e.query,"query option is required. You must specify your GraphQL document in the query option."):It(e.query,17),__DEV__?It("Document"===e.query.kind,'You must wrap the query string in a "gql" tag.'):It("Document"===e.query.kind,18),__DEV__?It(!e.returnPartialData,"returnPartialData option only supported on watchQuery."):It(!e.returnPartialData,19),__DEV__?It(!e.pollInterval,"pollInterval option only supported on watchQuery."):It(!e.pollInterval,20),this.fetchQuery(t,e).finally((function(){return n.stopQuery(t)}))},e.prototype.generateQueryId=function(){return String(this.queryIdCounter++)},e.prototype.generateRequestId=function(){return this.requestIdCounter++},e.prototype.generateMutationId=function(){return String(this.mutationIdCounter++)},e.prototype.stopQueryInStore=function(e){this.stopQueryInStoreNoBroadcast(e),this.broadcastQueries()},e.prototype.stopQueryInStoreNoBroadcast=function(e){var t=this.queries.get(e);t&&t.stop()},e.prototype.clearStore=function(e){return void 0===e&&(e={discardWatches:!0}),this.cancelPendingFetches(__DEV__?new bt("Store reset while query was in flight (not completed in link chain)"):new bt(21)),this.queries.forEach((function(e){e.observableQuery?e.networkStatus=Js.loading:e.stop()})),this.mutationStore&&(this.mutationStore=Object.create(null)),this.cache.reset(e)},e.prototype.getObservableQueries=function(e){var t=this;void 0===e&&(e="active");var n=new Map,r=new Map,i=new Set;return Array.isArray(e)&&e.forEach((function(e){var n;"string"==typeof e?r.set(e,!1):Ut(n=e)&&"Document"===n.kind&&Array.isArray(n.definitions)?r.set(t.transform(e).document,!1):Ut(e)&&e.query&&i.add(e)})),this.queries.forEach((function(t,i){var s=t.observableQuery,o=t.document;if(s){if("all"===e)return void n.set(i,s);var a=s.queryName;if("standby"===s.options.fetchPolicy||"active"===e&&!s.hasObservers())return;("active"===e||a&&r.has(a)||o&&r.has(o))&&(n.set(i,s),a&&r.set(a,!0),o&&r.set(o,!0))}})),i.size&&i.forEach((function(e){var r=fr("legacyOneTimeQuery"),i=t.getQuery(r).init({document:e.query,variables:e.variables}),s=new no({queryManager:t,queryInfo:i,options:dt(dt({},e),{fetchPolicy:"network-only"})});It(s.queryId===r),i.setObservableQuery(s),n.set(r,s)})),__DEV__&&r.size&&r.forEach((function(e,t){e||__DEV__&&It.warn("Unknown query ".concat("string"==typeof t?"named ":"").concat(JSON.stringify(t,null,2)," requested in refetchQueries options.include array"))})),n},e.prototype.reFetchObservableQueries=function(e){var t=this;void 0===e&&(e=!1);var n=[];return this.getObservableQueries(e?"all":"active").forEach((function(r,i){var s=r.options.fetchPolicy;r.resetLastResults(),(e||"standby"!==s&&"cache-only"!==s)&&n.push(r.refetch()),t.getQuery(i).setDiff(null)})),this.broadcastQueries(),Promise.all(n)},e.prototype.setObservableQuery=function(e){this.getQuery(e.queryId).setObservableQuery(e)},e.prototype.startGraphQLSubscription=function(e){var t=this,n=e.query,r=e.fetchPolicy,i=e.errorPolicy,s=e.variables,o=e.context,a=void 0===o?{}:o;n=this.transform(n).document,s=this.getVariables(n,s);var c=function(e){return t.getObservableFromLink(n,a,e).map((function(s){"no-cache"!==r&&(fo(s,i)&&t.cache.write({query:n,result:s.data,dataId:"ROOT_SUBSCRIPTION",variables:e}),t.broadcastQueries());var o=ur(s),a=function(e){return!!e.extensions&&Array.isArray(e.extensions[Cr])}(s);if(o||a){var c={};throw o&&(c.graphQLErrors=s.errors),a&&(c.protocolErrors=s.extensions[Cr]),new xr(c)}return s}))};if(this.transform(n).hasClientExports){var u=this.localState.addExportedVariables(n,s,a).then(c);return new zn((function(e){var t=null;return u.then((function(n){return t=n.subscribe(e)}),e.error),function(){return t&&t.unsubscribe()}}))}return c(s)},e.prototype.stopQuery=function(e){this.stopQueryNoBroadcast(e),this.broadcastQueries()},e.prototype.stopQueryNoBroadcast=function(e){this.stopQueryInStoreNoBroadcast(e),this.removeQuery(e)},e.prototype.removeQuery=function(e){this.fetchCancelFns.delete(e),this.queries.has(e)&&(this.getQuery(e).stop(),this.queries.delete(e))},e.prototype.broadcastQueries=function(){this.onBroadcast&&this.onBroadcast(),this.queries.forEach((function(e){return e.notify()}))},e.prototype.getLocalState=function(){return this.localState},e.prototype.getObservableFromLink=function(e,t,n,r){var i,s,o=this;void 0===r&&(r=null!==(i=null==t?void 0:t.queryDeduplication)&&void 0!==i?i:this.queryDeduplication);var a=this.transform(e).serverQuery;if(a){var c=this.inFlightLinkObservables,u=this.link,l={query:a,variables:n,operationName:tn(a)||void 0,context:this.prepareContext(dt(dt({},t),{forceFetch:!r}))};if(t=l.context,r){var h=c.get(a)||new Map;c.set(a,h);var d=ms(n);if(!(s=h.get(d))){var f=new sr([Er(u,l)]);h.set(d,s=f),f.beforeNext((function(){h.delete(d)&&h.size<1&&c.delete(a)}))}}else s=new sr([Er(u,l)])}else s=new sr([zn.of({data:{}})]),t=this.prepareContext(t);var p=this.transform(e).clientQuery;return p&&(s=Xn(s,(function(e){return o.localState.runResolvers({document:p,remoteResult:e,context:t,variables:n})}))),s},e.prototype.getResultsFromLink=function(e,t,n){var r=e.lastRequestId=this.generateRequestId(),i=this.cache.transformForLink(this.transform(e.document).document);return Xn(this.getObservableFromLink(i,n.context,n.variables),(function(s){var o=lr(s),a=o.length>0;if(r>=e.lastRequestId){if(a&&"none"===n.errorPolicy)throw e.markError(new xr({graphQLErrors:o}));e.markResult(s,i,n,t),e.markReady()}var c={data:s.data,loading:!1,networkStatus:Js.ready};return a&&"ignore"!==n.errorPolicy&&(c.errors=o,c.networkStatus=Js.error),c}),(function(t){var n=t.hasOwnProperty("graphQLErrors")?t:new xr({networkError:t});throw r>=e.lastRequestId&&e.markError(n),n}))},e.prototype.fetchQueryObservable=function(e,t,n){return this.fetchConcastWithInfo(e,t,n).concast},e.prototype.fetchConcastWithInfo=function(e,t,n){var r=this;void 0===n&&(n=Js.loading);var i,s,o=this.transform(t.query).document,a=this.getVariables(o,t.variables),c=this.getQuery(e),u=this.defaultOptions.watchQuery,l=t.fetchPolicy,h=void 0===l?u&&u.fetchPolicy||"cache-first":l,d=t.errorPolicy,f=void 0===d?u&&u.errorPolicy||"none":d,p=t.returnPartialData,m=void 0!==p&&p,g=t.notifyOnNetworkStatusChange,y=void 0!==g&&g,v=t.context,_=void 0===v?{}:v,w=Object.assign({},t,{query:o,variables:a,fetchPolicy:h,errorPolicy:f,returnPartialData:m,notifyOnNetworkStatusChange:y,context:_}),b=function(e){w.variables=e;var i=r.fetchQueryByPolicy(c,w,n);return"standby"!==w.fetchPolicy&&i.sources.length>0&&c.observableQuery&&c.observableQuery.applyNextFetchPolicy("after-fetch",t),i},I=function(){return r.fetchCancelFns.delete(e)};if(this.fetchCancelFns.set(e,(function(e){I(),setTimeout((function(){return i.cancel(e)}))})),this.transform(w.query).hasClientExports)i=new sr(this.localState.addExportedVariables(w.query,w.variables,w.context).then(b).then((function(e){return e.sources}))),s=!0;else{var E=b(w.variables);s=E.fromLink,i=new sr(E.sources)}return i.promise.then(I,I),{concast:i,fromLink:s}},e.prototype.refetchQueries=function(e){var t=this,n=e.updateCache,r=e.include,i=e.optimistic,s=void 0!==i&&i,o=e.removeOptimistic,a=void 0===o?s?fr("refetchQueries"):void 0:o,c=e.onQueryUpdated,u=new Map;r&&this.getObservableQueries(r).forEach((function(e,n){u.set(n,{oq:e,lastDiff:t.getQuery(n).getDiff()})}));var l=new Map;return n&&this.cache.batch({update:n,optimistic:s&&a||!1,removeOptimistic:a,onWatchUpdated:function(e,t,n){var r=e.watcher instanceof ho&&e.watcher.observableQuery;if(r){if(c){u.delete(r.queryId);var i=c(r,t,n);return!0===i&&(i=r.refetch()),!1!==i&&l.set(r,i),i}null!==c&&u.set(r.queryId,{oq:r,lastDiff:n,diff:t})}}}),u.size&&u.forEach((function(e,n){var r,i=e.oq,s=e.lastDiff,o=e.diff;if(c){if(!o){var a=i.queryInfo;a.reset(),o=a.getDiff()}r=c(i,o,s)}c&&!0!==r||(r=i.refetch()),!1!==r&&l.set(i,r),n.indexOf("legacyOneTimeQuery")>=0&&t.stopQueryNoBroadcast(n)})),a&&this.cache.removeOptimistic(a),l},e.prototype.fetchQueryByPolicy=function(e,t,n){var r=this,i=t.query,s=t.variables,o=t.fetchPolicy,a=t.refetchWritePolicy,c=t.errorPolicy,u=t.returnPartialData,l=t.context,h=t.notifyOnNetworkStatusChange,d=e.networkStatus;e.init({document:this.transform(i).document,variables:s,networkStatus:n});var f=function(){return e.getDiff(s)},p=function(t,n){void 0===n&&(n=e.networkStatus||Js.loading);var o=t.result;!__DEV__||u||Wr(o,{})||so(t.missing);var a=function(e){return zn.of(dt({data:e,loading:Zs(n),networkStatus:n},t.complete?null:{partial:!0}))};return o&&r.transform(i).hasForcedResolvers?r.localState.runResolvers({document:i,remoteResult:{data:o},context:l,variables:s,onlyRunForcedResolvers:!0}).then((function(e){return a(e.data||void 0)})):"none"===c&&n===Js.refetch&&Array.isArray(t.missing)?a(void 0):a(o)},m="no-cache"===o?0:n===Js.refetch&&"merge"!==a?1:2,g=function(){return r.getResultsFromLink(e,m,{variables:s,context:l,fetchPolicy:o,errorPolicy:c})},y=h&&"number"==typeof d&&d!==n&&Zs(n);switch(o){default:case"cache-first":return(v=f()).complete?{fromLink:!1,sources:[p(v,e.markReady())]}:u||y?{fromLink:!0,sources:[p(v),g()]}:{fromLink:!0,sources:[g()]};case"cache-and-network":var v;return(v=f()).complete||u||y?{fromLink:!0,sources:[p(v),g()]}:{fromLink:!0,sources:[g()]};case"cache-only":return{fromLink:!1,sources:[p(f(),e.markReady())]};case"network-only":return y?{fromLink:!0,sources:[p(f()),g()]}:{fromLink:!0,sources:[g()]};case"no-cache":return y?{fromLink:!0,sources:[p(e.getDiff()),g()]}:{fromLink:!0,sources:[g()]};case"standby":return{fromLink:!1,sources:[]}}},e.prototype.getQuery=function(e){return e&&!this.queries.has(e)&&this.queries.set(e,new ho(this,e)),this.queries.get(e)},e.prototype.prepareContext=function(e){void 0===e&&(e={});var t=this.localState.prepareContext(e);return dt(dt({},t),{clientAwareness:this.clientAwareness})},e}(),go=!1,yo=function(){function e(e){var t=this;this.resetStoreCallbacks=[],this.clearStoreCallbacks=[];var n=e.uri,r=e.credentials,i=e.headers,s=e.cache,o=e.ssrMode,a=void 0!==o&&o,c=e.ssrForceFetchDelay,u=void 0===c?0:c,l=e.connectToDevTools,h=void 0===l?"object"==typeof window&&!window.__APOLLO_CLIENT__&&__DEV__:l,d=e.queryDeduplication,f=void 0===d||d,p=e.defaultOptions,m=e.assumeImmutableResults,g=void 0!==m&&m,y=e.resolvers,v=e.typeDefs,_=e.fragmentMatcher,w=e.name,b=e.version,I=e.link;if(I||(I=n?new Vr({uri:n,credentials:r,headers:i}):br.empty()),!s)throw __DEV__?new bt("To initialize Apollo Client, you must specify a 'cache' property in the options object. \nFor more information, please visit: https://go.apollo.dev/c/docs"):new bt(9);if(this.link=I,this.cache=s,this.disableNetworkFetches=a||u>0,this.queryDeduplication=f,this.defaultOptions=p||Object.create(null),this.typeDefs=v,u&&setTimeout((function(){return t.disableNetworkFetches=!1}),u),this.watchQuery=this.watchQuery.bind(this),this.query=this.query.bind(this),this.mutate=this.mutate.bind(this),this.resetStore=this.resetStore.bind(this),this.reFetchObservableQueries=this.reFetchObservableQueries.bind(this),h&&"object"==typeof window&&(window.__APOLLO_CLIENT__=this),!go&&h&&__DEV__&&(go=!0,"undefined"!=typeof window&&window.document&&window.top===window.self&&!window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__)){var E=window.navigator,T=E&&E.userAgent,S=void 0;"string"==typeof T&&(T.indexOf("Chrome/")>-1?S="https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm":T.indexOf("Firefox/")>-1&&(S="https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/")),S&&__DEV__&&It.log("Download the Apollo DevTools for a better development experience: "+S)}this.version="3.7.17",this.localState=new ao({cache:s,client:this,resolvers:y,fragmentMatcher:_}),this.queryManager=new mo({cache:this.cache,link:this.link,defaultOptions:this.defaultOptions,queryDeduplication:f,ssrMode:a,clientAwareness:{name:w,version:b},localState:this.localState,assumeImmutableResults:g,onBroadcast:h?function(){t.devToolsHookCb&&t.devToolsHookCb({action:{},state:{queries:t.queryManager.getQueryStore(),mutations:t.queryManager.mutationStore||{}},dataWithOptimisticResults:t.cache.extract(!0)})}:void 0})}return e.prototype.stop=function(){this.queryManager.stop()},e.prototype.watchQuery=function(e){return this.defaultOptions.watchQuery&&(e=pr(this.defaultOptions.watchQuery,e)),!this.disableNetworkFetches||"network-only"!==e.fetchPolicy&&"cache-and-network"!==e.fetchPolicy||(e=dt(dt({},e),{fetchPolicy:"cache-first"})),this.queryManager.watchQuery(e)},e.prototype.query=function(e){return this.defaultOptions.query&&(e=pr(this.defaultOptions.query,e)),__DEV__?It("cache-and-network"!==e.fetchPolicy,"The cache-and-network fetchPolicy does not work with client.query, because client.query can only return a single result. Please use client.watchQuery to receive multiple results from the cache and the network, or consider using a different fetchPolicy, such as cache-first or network-only."):It("cache-and-network"!==e.fetchPolicy,10),this.disableNetworkFetches&&"network-only"===e.fetchPolicy&&(e=dt(dt({},e),{fetchPolicy:"cache-first"})),this.queryManager.query(e)},e.prototype.mutate=function(e){return this.defaultOptions.mutate&&(e=pr(this.defaultOptions.mutate,e)),this.queryManager.mutate(e)},e.prototype.subscribe=function(e){return this.queryManager.startGraphQLSubscription(e)},e.prototype.readQuery=function(e,t){return void 0===t&&(t=!1),this.cache.readQuery(e,t)},e.prototype.readFragment=function(e,t){return void 0===t&&(t=!1),this.cache.readFragment(e,t)},e.prototype.writeQuery=function(e){var t=this.cache.writeQuery(e);return!1!==e.broadcast&&this.queryManager.broadcastQueries(),t},e.prototype.writeFragment=function(e){var t=this.cache.writeFragment(e);return!1!==e.broadcast&&this.queryManager.broadcastQueries(),t},e.prototype.__actionHookForDevTools=function(e){this.devToolsHookCb=e},e.prototype.__requestRaw=function(e){return Er(this.link,e)},e.prototype.resetStore=function(){var e=this;return Promise.resolve().then((function(){return e.queryManager.clearStore({discardWatches:!1})})).then((function(){return Promise.all(e.resetStoreCallbacks.map((function(e){return e()})))})).then((function(){return e.reFetchObservableQueries()}))},e.prototype.clearStore=function(){var e=this;return Promise.resolve().then((function(){return e.queryManager.clearStore({discardWatches:!0})})).then((function(){return Promise.all(e.clearStoreCallbacks.map((function(e){return e()})))}))},e.prototype.onResetStore=function(e){var t=this;return this.resetStoreCallbacks.push(e),function(){t.resetStoreCallbacks=t.resetStoreCallbacks.filter((function(t){return t!==e}))}},e.prototype.onClearStore=function(e){var t=this;return this.clearStoreCallbacks.push(e),function(){t.clearStoreCallbacks=t.clearStoreCallbacks.filter((function(t){return t!==e}))}},e.prototype.reFetchObservableQueries=function(e){return this.queryManager.reFetchObservableQueries(e)},e.prototype.refetchQueries=function(e){var t=this.queryManager.refetchQueries(e),n=[],r=[];t.forEach((function(e,t){n.push(t),r.push(e)}));var i=Promise.all(r);return i.queries=n,i.results=r,i.catch((function(e){__DEV__&&It.debug("In client.refetchQueries, Promise.all promise rejected with error ".concat(e))})),i},e.prototype.getObservableQueries=function(e){return void 0===e&&(e="active"),this.queryManager.getObservableQueries(e)},e.prototype.extract=function(e){return this.cache.extract(e)},e.prototype.restore=function(e){return this.cache.restore(e)},e.prototype.addResolvers=function(e){this.localState.addResolvers(e)},e.prototype.setResolvers=function(e){this.localState.setResolvers(e)},e.prototype.getResolvers=function(){return this.localState.getResolvers()},e.prototype.setLocalStateFragmentMatcher=function(e){this.localState.setFragmentMatcher(e)},e.prototype.setLink=function(e){this.link=this.queryManager.link=e},e}(),vo=new Map,_o=new Map,wo=!0,bo=!1;function Io(e){return e.replace(/[\s,]+/g," ").trim()}function Eo(e){var t=new Set,n=[];return e.definitions.forEach((function(e){if("FragmentDefinition"===e.kind){var r=e.name.value,i=Io((o=e.loc).source.body.substring(o.start,o.end)),s=_o.get(r);s&&!s.has(i)?wo&&console.warn("Warning: fragment with name "+r+" already exists.\ngraphql-tag enforces all fragment names across your application to be unique; read more about\nthis in the docs: http://dev.apollodata.com/core/fragments.html#unique-names"):s||_o.set(r,s=new Set),s.add(i),t.has(i)||(t.add(i),n.push(e))}else n.push(e);var o})),dt(dt({},e),{definitions:n})}function To(e){var t=Io(e);if(!vo.has(t)){var n=r.parse(e,{experimentalFragmentVariables:bo,allowLegacyFragmentVariables:bo});if(!n||"Document"!==n.kind)throw new Error("Not a valid GraphQL document.");vo.set(t,function(e){var t=new Set(e.definitions);t.forEach((function(e){e.loc&&delete e.loc,Object.keys(e).forEach((function(n){var r=e[n];r&&"object"==typeof r&&t.add(r)}))}));var n=e.loc;return n&&(delete n.startToken,delete n.endToken),e}(Eo(n)))}return vo.get(t)}function So(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];"string"==typeof e&&(e=[e]);var r=e[0];return t.forEach((function(t,n){t&&"Document"===t.kind?r+=t.loc.source.body:r+=t,r+=e[n+1]})),To(r)}var ko,Co=So,xo=function(){vo.clear(),_o.clear()},Ao=function(){wo=!1},No=function(){bo=!0},Do=function(){bo=!1};(ko=So||(So={})).gql=Co,ko.resetCaches=xo,ko.disableFragmentWarnings=Ao,ko.enableExperimentalFragmentVariables=No,ko.disableExperimentalFragmentVariables=Do,So.default=So;var Ro=tr?Symbol.for("__APOLLO_CONTEXT__"):"__APOLLO_CONTEXT__";function Oo(){var e=l.createContext[Ro];return e||(Object.defineProperty(l.createContext,Ro,{value:e=l.createContext({}),enumerable:!1,writable:!1,configurable:!0}),e.displayName="ApolloContext"),e}var Po,Mo=function(e){var t=e.client,n=e.children,r=Oo();return l.createElement(r.Consumer,null,(function(e){return void 0===e&&(e={}),t&&e.client!==t&&(e=Object.assign({},e,{client:t})),__DEV__?It(e.client,'ApolloProvider was not passed a client instance. Make sure you pass in your client via the "client" prop.'):It(e.client,29),l.createElement(r.Provider,{value:e},n)}))};!function(e){e[e.Query=0]="Query",e[e.Mutation=1]="Mutation",e[e.Subscription=2]="Subscription"}(Po||(Po={}));var Lo=new Map;function Fo(e){var t;switch(e){case Po.Query:t="Query";break;case Po.Mutation:t="Mutation";break;case Po.Subscription:t="Subscription"}return t}function jo(e,t){var n=function(e){var t,n,r=Lo.get(e);if(r)return r;__DEV__?It(!!e&&!!e.kind,"Argument of ".concat(e," passed to parser was not a valid GraphQL ")+"DocumentNode. You may need to use 'graphql-tag' or another method to convert your operation into a document"):It(!!e&&!!e.kind,33);for(var i=[],s=[],o=[],a=[],c=0,u=e.definitions;c<u.length;c++){var l=u[c];if("FragmentDefinition"!==l.kind){if("OperationDefinition"===l.kind)switch(l.operation){case"query":s.push(l);break;case"mutation":o.push(l);break;case"subscription":a.push(l)}}else i.push(l)}__DEV__?It(!i.length||s.length||o.length||a.length,"Passing only a fragment to 'graphql' is not yet supported. You must include a query, subscription or mutation as well"):It(!i.length||s.length||o.length||a.length,34),__DEV__?It(s.length+o.length+a.length<=1,"react-apollo only supports a query, subscription, or a mutation per HOC. "+"".concat(e," had ").concat(s.length," queries, ").concat(a.length," ")+"subscriptions and ".concat(o.length," mutations. ")+"You can use 'compose' to join multiple operation types to a component"):It(s.length+o.length+a.length<=1,35),n=s.length?Po.Query:Po.Mutation,s.length||o.length||(n=Po.Subscription);var h=s.length?s:o.length?o:a;__DEV__?It(1===h.length,"react-apollo only supports one definition per HOC. ".concat(e," had ")+"".concat(h.length," definitions. ")+"You can use 'compose' to join multiple operation types to a component"):It(1===h.length,36);var d=h[0];t=d.variableDefinitions||[];var f={name:d.name&&"Name"===d.name.kind?d.name.value:"data",type:n,variables:t};return Lo.set(e,f),f}(e),r=Fo(t),i=Fo(n.type);__DEV__?It(n.type===t,"Running a ".concat(r," requires a graphql ")+"".concat(r,", but a ").concat(i," was used instead.")):It(n.type===t,37)}function qo(e,t){var r=function(e){var t=n.useContext(Oo()),r=e||t.client;return __DEV__?It(!!r,'Could not find "client" in the context or passed in as an option. Wrap the root component in an <ApolloProvider>, or pass an ApolloClient instance in via options.'):It(!!r,32),r}(null==t?void 0:t.client);jo(e,Po.Mutation);var i=n.useState({called:!1,loading:!1,client:r}),s=i[0],o=i[1],a=n.useRef({result:s,mutationId:0,isMounted:!0,client:r,mutation:e,options:t});Object.assign(a.current,{client:r,options:t,mutation:e});var c=n.useCallback((function(e){void 0===e&&(e={});var t=a.current,n=t.options,r=t.mutation,i=dt(dt({},n),{mutation:r}),s=e.client||a.current.client;a.current.result.loading||i.ignoreResults||!a.current.isMounted||o(a.current.result={loading:!0,error:void 0,data:void 0,called:!0,client:s});var c=++a.current.mutationId,u=pr(i,e);return s.mutate(u).then((function(t){var n,r=t.data,i=t.errors,l=i&&i.length>0?new xr({graphQLErrors:i}):void 0;if(c===a.current.mutationId&&!u.ignoreResults){var h={called:!0,loading:!1,data:r,error:l,client:s};a.current.isMounted&&!Wr(a.current.result,h)&&o(a.current.result=h)}var d=e.onCompleted||(null===(n=a.current.options)||void 0===n?void 0:n.onCompleted);return null==d||d(t.data,u),t})).catch((function(t){var n;if(c===a.current.mutationId&&a.current.isMounted){var r={loading:!1,error:t,data:void 0,called:!0,client:s};Wr(a.current.result,r)||o(a.current.result=r)}var i=e.onError||(null===(n=a.current.options)||void 0===n?void 0:n.onError);if(i)return i(t,u),{data:void 0,errors:t};throw t}))}),[]),u=n.useCallback((function(){a.current.isMounted&&o({called:!1,loading:!1,client:r})}),[]);return n.useEffect((function(){return a.current.isMounted=!0,function(){a.current.isMounted=!1}}),[]),[c,dt({reset:u},s)]}const Vo=So`
  mutation updateFeedbackItem(
    $id: Int!
    $title: String!
    $type: String!
    $status: String!
    $comments: jsonb!
    $screenshot_images: jsonb!
  ) {
    update_aime_feedback_tools_by_pk(
      pk_columns: { id: $id }
      _set: {
        type: $type
        status: $status
        comments: $comments
        title: $title
        screenshot_images: $screenshot_images
      }
    ) {
      id
    }
  }
`,Uo=So`
  mutation InsertAimeFeedbackTools(
    $type: String
    $title: String
    $project: String
    $project_id: Int
    $created_by: String
    $org_id: String
    $org_name: String
    $creator_id: String
    $creator_name: String
    $screenshot_images: jsonb
    $comments: jsonb
  ) {
    insert_aime_feedback_tools(
      objects: {
        type: $type
        title: $title
        project: $project
        project_id: $project_id
        created_by: $created_by
        org_id: $org_id
        org_name: $org_name
        creator_id: $creator_id
        creator_name: $creator_name
        screenshot_images: $screenshot_images
        comments: $comments
      }
    ) {
      affected_rows
      returning {
        id
        type
        title
        project
        project_id
        status
        comments
        screenshot_images
        created_at
        updated_at
        created_by
        org_id
        org_name
        creator_id
        creator_name
        client_accepted
        client_accept_date
        brief_content
      }
    }
  }
`;So`
	query fetchTeamMembers($org_id: String!) {
		users(where: { org_id: { _eq: $org_id }, deleted_at: { _is_null: true } }) {
			last_seen
			org_id
			user_id
			username
		}
	}
`,So`
	query GetAimeProjects {
		aime_projects {
			id
			project_name
		}
	}
`;const Bo=So`
	query FetchFeedbackTools($id: Int!) {
		aime_feedback_tools_by_pk(id: $id) {
			id
			type
			title
			project
			project_id
			status
			comments
			screenshot_images
			created_at
			updated_at
			created_by
			org_id
			org_name
			creator_id
			creator_name
			client_accepted
			client_accept_date
			brief_content
		}
	}
`;So`
	query GetFeedbackAssignments {
		feedback_assignments {
			created_at
			updated_at
			feedback_tool_id
			id
			no_of_revisions
			priority
			assignee_id
			assignee_org
			assigner_id
			due_date
			org_id
			aime_feedback_tool {
				brief_content
				client_accept_date
				client_accepted
				comments
				created_at
				created_by
				creator_id
				creator_name
				id
				org_id
				org_name
				project
				project_id
				screenshot_images
				status
				title
				type
				updated_at
			}
		}
	}
`;const zo=So`
  query FetchFeedbackTools($project_id: Int!) {
    aime_feedback_tools(where: { project_id: { _eq: $project_id } }) {
      id
      project_id
      type
      status
      comments
      title
      screenshot_images
      org_id
      client_accepted
      client_accept_date
    }
  }
`,$o=n.createContext(void 0),Wo={comments:[],screenshot_images:[]};function Qo({children:t}){const[r,i]=n.useState(Wo),[s,o]=n.useState({id:null,type:"",index:0}),[a,c]=n.useState(),[u,l]=n.useState({type:"Bug",priority:"low",title:"",description:""});return n.useEffect((()=>{console.log("STATE",r.screenshot_images),console.log("Selected Item",s)}),[s]),e.jsx($o.Provider,{value:{state:r,resetState:()=>{i(Wo)},updateComments:e=>{i((t=>({...t,comments:e})))},updateScreenshots:e=>{i((t=>({...t,screenshot_images:e})))},updateScreenshotsObject:e=>{i((t=>({...t,screenshot_images:[...t.screenshot_images,...e]})))},selectedItem:s,setSelectedItem:o,toggleState:a,setToggleState:c,feedbackItem:u,setFeedbackItem:l},children:t})}const Ho=t=>{const{isSelected:r,onSelect:s,onChange:o,comment:a,onDoubleClick:c,isReadOnly:u,stage:l}=t,h=n.useRef(),d=n.useRef(),f=n.useRef();n.useEffect((()=>{r&&(d.current.nodes([h.current]),d.current.getLayer().batchDraw())}),[r]);const p={id:a.id,x:a.x,y:a.y,width:a.width,height:a.height};return e.jsxs(n.Fragment,{children:[e.jsxs(i.Label,{...p,draggable:!u,onClick:s,onTap:s,ref:h,onDragEnd:e=>{o({...p,x:e.target.x(),y:e.target.y()})},onDblClick:e=>{c({...p,x:e.target.x(),y:e.target.y()})},onTransformEnd:e=>{const t=h.current,n=t.scaleX(),r=t.scaleY();t.scaleX(1),t.scaleY(1),o({...p,x:t.x(),y:t.y(),width:Math.max(5,t.width()*n),height:Math.max(t.height()*r)})},children:[e.jsx(i.Tag,{id:a.id,width:a.width,height:a.height,fill:a.fill,pointerDirection:"down",pointerWidth:10,pointerHeight:10,lineJoin:"round",shadowColor:"black",shadowBlur:10,shadowOffsetX:10,shadowOffsetY:10,shadowOpacity:.5}),e.jsx(i.Text,{padding:18,ref:f,width:a.width,height:a.height,text:a.text,wrap:"word",fontSize:20,align:"center",listening:!1})]}),r&&e.jsx(i.Transformer,{ref:d,boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t})]})},Go=n=>e.jsx(t.Icon,{width:"1rem",height:"1rem",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n,children:e.jsx("path",{d:"M3.33325 8H12.6666",stroke:"white",strokeLinecap:"round",strokeLinejoin:"round"})}),Ko=n=>e.jsx(t.Icon,{width:"1rem",height:"1rem",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n,children:e.jsx("path",{d:"M7.99992 3.33398V12.6673M3.33325 8.00065H12.6666",stroke:"white",strokeLinecap:"round",strokeLinejoin:"round"})}),Yo="#1E2841",Jo="#242e46",Xo="#3066F0",Zo="#ffffff",ea=999999,ta="#48ffd3";function na(n){const{zoom:r,handleZoomIn:i,handleZoomOut:s,resetZoomAndPosition:o}=n,a=n=>{const{icon:r,first:i,last:s,onClick:o,active:a}=n;return e.jsx(t.Button,{variant:"unstyled",_hover:{bg:a?"":Yo},display:"grid",placeItems:"center",cursor:"pointer",borderRadius:i?".25rem 0 0 .25rem":s?"0 .25rem .25rem 0":".25rem",bg:a?Xo:Jo,w:"3rem",h:"3rem",...n,onClick:o,children:r})};return e.jsx(t.HStack,{spacing:".5rem",position:"fixed",left:"50%",transform:"translate(-50% , 2rem)",zIndex:ea,bottom:"4rem",children:e.jsx(t.HStack,{spacing:".5rem",children:e.jsxs(t.HStack,{spacing:"0",children:[e.jsx(a,{icon:e.jsx(Go,{}),first:!0,onClick:s}),e.jsx(t.Box,{display:"grid",placeItems:"center",bg:Yo,w:"5.3rem",h:"3rem",children:e.jsxs(t.Text,{color:Zo,fontSize:".75rem",fontWeight:"700",children:[Math.round(100*r),"% "]})}),e.jsx(a,{icon:e.jsx(Ko,{}),last:!0,onClick:i}),e.jsx(t.Spacer,{}),e.jsx(a,{icon:e.jsx(ut,{}),last:!0,onClick:o})]})})})}const ra=n=>{const{currentFill:r="#FFFF00",onColorPicked:i}=n;return e.jsx(t.Flex,{gap:2,children:["#FFFF00","#3CC960","#d99634","#2979ff","#bdbdbd","#ce4848"].map(((n,s)=>e.jsx(t.Circle,{bg:n,size:"18px",border:r===n?"2px solid #000a":"none",onClick:()=>i(n)},s)))})};function ia(t){const{onSelect:r,onChange:s,onDragEnd:a,imageObj:c,isSelected:u,isReadOnly:l,onDoubleClick:h}=t,[d]=o(c?.url,"anonymous","origin"),f=n.useRef(),p=n.useRef(null),m=n.useMemo((()=>({width:c?.width??window.innerWidth/1.5,height:c?.height??window.innerHeight/1.5})),[c]);return console.log("dimens",m),n.useEffect((()=>{u&&(f.current.nodes([p.current]),f.current.getLayer().batchDraw())}),[u]),e.jsxs(n.Fragment,{children:[e.jsx(i.Image,{ref:p,image:d,x:window.innerWidth/2-m.width/2,y:window.innerHeight/2-m.height/2,onDragEnd:a,width:m.width,height:m.height,onClick:r,onTap:r,onDblClick:h,onTransformEnd:e=>{const t=p.current,n=t.scaleX(),r=t.scaleY();t.scaleX(1),t.scaleY(1),s({x:t.x(),y:t.y(),width:Math.max(5,t.width()*n),height:Math.max(t.height()*r)})}}),u&&e.jsx(i.Transformer,{ref:f,boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t})]})}const sa=100,oa=100,aa=e=>e?.map(((e,t)=>({id:e.id??t.toString(),text:e.text,width:e.width??200,height:e.height??100,fill:e.fill??"yellow",x:e.x??300*Math.random()+140,y:e.y??150*Math.random()+100}))),ca={id:null,type:"",index:0},ua=r=>{const o=n.useContext($o),a=o?.updateComments??(e=>{}),c=o?.updateScreenshots??(e=>{}),u=o?.selectedItem,l=o?.setSelectedItem??(e=>{});o?.toggleState,o?.setToggleState;const{screenshotImages:h,comments:d,isReadOnly:f=!1}=r,[p,m]=n.useState(null),{isOpen:g,onOpen:y,onClose:v}=t.useDisclosure(),_=n.useRef(null),w=n.useRef(null),b=n.useRef(null),I=n.useRef(null);n.useEffect((()=>{if(!u)return;const e=b.current;if(!e)return;const t=e=>{if(!g)switch(e.keyCode){case 8:case 46:!f&&u?.id&&("comment"===u?.type?(()=>{if(window.confirm("Delete Comment?")){const e=d.slice();e.splice(u?.index,1),a(e)}})():"image"===u?.type&&(()=>{if(window.confirm("Delete Image?")){const e=h.slice();e.splice(u?.index,1),c(e)}})())}};return e.addEventListener("keydown",t),()=>{e.removeEventListener("keydown",t)}}),[]),n.useEffect((()=>{_.current.getContainer().style.backgroundColor="#ffffff",_.current.getContainer().style.overflow="hidden";let e=document.querySelector("#stage-parent");_.current.width(e?.offsetWidth||window.innerWidth),_.current.height(e?.offsetHeight||window.innerHeight)}));const[E,T]=n.useState({x:0,y:0});Math.floor((-E.x-window.innerWidth)/sa),Math.floor((-E.x+2*window.innerWidth)/sa),Math.floor((-E.y-window.innerHeight)/oa),Math.floor((-E.y+2*window.innerHeight)/oa);const S=e=>{e.target===e.target.getStage()&&l(ca)},[k,C]=n.useState(1);return n.useEffect((()=>{const e=e=>{if(e.ctrlKey||e.metaKey){const t=.9,n=_?.current?.getStage(),r=n.scaleX();let i=e.deltaY>0?r*t:r/t;i=Math.min(i,5),i=Math.max(i,.2);const s=n.getPointerPosition(),o={x:s.x/r-n.x()/r,y:s.y/r-n.y()/r};n.scale({x:i,y:i});const a={x:-(o.x-s.x/i)*i,y:-(o.y-s.y/i)*i};n.position(a),C(i)}};return window.addEventListener("wheel",e),()=>{window.removeEventListener("wheel",e)}}),[_,C]),e.jsxs(t.Box,{ref:b,w:"100%",height:"100%",id:"stage-parent",bg:"red.200",children:[e.jsxs(i.Stage,{x:E.x,y:E.y,width:window.innerWidth,height:window.innerHeight,draggable:!0,onDragEnd:e=>{T(e.currentTarget.position())},onMouseDown:e=>S(e),onTouchStart:e=>S(e),ref:_,scaleX:k,scaleY:k,style:{backgroundColor:"#FF0000"},children:[e.jsx(i.Layer,{children:e.jsx(i.Rect,{x:-2e5,y:-2e5,width:4e5,height:4e5,fill:"#29334b",listening:!1,draggable:!1})}),e.jsx(i.Layer,{ref:w,children:e.jsxs(i.Group,{draggable:!0,children:[h&&h?.map(((t,n)=>e.jsx(ia,{isReadOnly:f,isSelected:t?.id===u?.id,onSelect:()=>{f||(console.log("image",t),l({id:t?.id,type:"image",index:n,x:t?.x,y:t?.y}))},onChange:e=>{const r=s.cloneDeep(h);r[n]={...r[n],...e,url:t?.url},c(r)},onDoubleClick:()=>{},onDragEnd:e=>{const r=s.cloneDeep(h);r[n]={url:t?.url,width:e.target.width(),height:e.target.height(),x:e.target.x(),y:e.target.y(),id:t?.id},c(r)},imageObj:t},n))),d?.map(((t,n)=>e.jsx(Ho,{comment:t,stage:_.current,isReadOnly:f,isSelected:t.id===u?.id,onSelect:()=>{f||l({id:t?.id,type:"comment",index:n,x:t?.x,y:t?.y})},onChange:e=>{const t=d.slice();t[n]=Object.assign(t[n],e),a(t)},onDoubleClick:()=>{f||(m({...t,id:n}),y())}},t.id)))]})})]}),e.jsx(na,{zoom:k,handleZoomIn:()=>{C(Math.min(1.2*k,5))},handleZoomOut:()=>{C(Math.max(k/1.2,.2))},resetZoomAndPosition:()=>{C(1),T({x:0,y:0})}}),e.jsxs(t.Modal,{isCentered:!0,isOpen:g,onClose:v,scrollBehavior:"inside",size:"xs",children:[e.jsx(t.ModalOverlay,{}),e.jsxs(t.ModalContent,{color:"white",bg:"#353535",children:[e.jsx(t.ModalHeader,{children:"Edit Comment"}),e.jsx(t.ModalCloseButton,{}),e.jsx(t.ModalBody,{children:e.jsxs(t.Stack,{spacing:2,children:[e.jsx(t.Text,{children:"Comment"}),e.jsx(t.Textarea,{ref:I,name:"comment",placeholder:"Enter Comment",color:"white",value:p?.text,onChange:e=>{const t=s.cloneDeep(p);t.text=e.target.value,m(t)},borderColor:"gray",_placeholder:{color:"gray"},required:!0}),e.jsx(ra,{currentFill:p?.fill,onColorPicked:e=>{m({...p,fill:e})}})]})}),e.jsx(t.ModalFooter,{children:e.jsxs(t.ButtonGroup,{size:"sm",children:[e.jsx(t.Button,{variant:"ghost",colorScheme:"orange",onClick:v,children:"Cancel"}),e.jsx(t.Button,{colorScheme:"green",onClick:e=>{const t=d.slice();t[p?.id]=Object.assign(t[p?.id],p),a(t),v()},children:"Update"})]})})]})]})]})},la=!1,ha="${JSCORE_VERSION}",da=function(e,t){if(!e)throw fa(t)},fa=function(e){return new Error("Firebase Database ("+ha+") INTERNAL ASSERT FAILED: "+e)},pa=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++r)),t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t},ma={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(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let t=0;t<e.length;t+=3){const i=e[t],s=t+1<e.length,o=s?e[t+1]:0,a=t+2<e.length,c=a?e[t+2]:0,u=i>>2,l=(3&i)<<4|o>>4;let h=(15&o)<<2|c>>6,d=63&c;a||(d=64,s||(h=64)),r.push(n[u],n[l],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(pa(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;){const i=e[n++];if(i<128)t[r++]=String.fromCharCode(i);else if(i>191&&i<224){const s=e[n++];t[r++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],o=e[n++];t[r++]=String.fromCharCode((15&i)<<12|(63&s)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let t=0;t<e.length;){const i=n[e.charAt(t++)],s=t<e.length?n[e.charAt(t)]:0;++t;const o=t<e.length?n[e.charAt(t)]:64;++t;const a=t<e.length?n[e.charAt(t)]:64;if(++t,null==i||null==s||null==o||null==a)throw new ga;const c=i<<2|s>>4;if(r.push(c),64!==o){const e=s<<4&240|o>>2;if(r.push(e),64!==a){const e=o<<6&192|a;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class ga extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const ya=function(e){const t=pa(e);return ma.encodeByteArray(t,!0)},va=function(e){return ya(e).replace(/\./g,"")},_a=function(e){try{return ma.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function wa(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const n in t)t.hasOwnProperty(n)&&"__proto__"!==n&&(e[n]=wa(e[n],t[n]));return e}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const ba=()=>
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==h)return h;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,Ia=()=>{try{return ba()||(()=>{if(void 0===M||void 0===M.env)return;const e=M.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&_a(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},Ea=()=>{var e;return null===(e=Ia())||void 0===e?void 0:e.config};
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class Ta{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,n))}}}
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Sa(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.');const n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[va(JSON.stringify({alg:"none",type:"JWT"})),va(JSON.stringify(s)),""].join(".")}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function ka(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function Ca(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(ka())}function xa(){var e;const t=null===(e=Ia())||void 0===e?void 0:e.forceEnvironment;if("node"===t)return!0;if("browser"===t)return!1;try{return"[object process]"===Object.prototype.toString.call(h.process)}catch(e){return!1}}function Aa(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function Na(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function Da(){const e=ka();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}function Ra(){return!0===la}function Oa(){try{return"object"==typeof indexedDB}catch(e){return!1}}class Pa extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,Pa.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Ma.prototype.create)}}class Ma{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,i=this.errors[e],s=i?function(e,t){return e.replace(La,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(i,n):"Error",o=`${this.serviceName}: ${s} (${r}).`;return new Pa(r,o,n)}}const La=/\{\$([^}]+)}/g;
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Fa(e){return JSON.parse(e)}function ja(e){return JSON.stringify(e)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const qa=function(e){let t={},n={},r={},i="";try{const s=e.split(".");t=Fa(_a(s[0])||""),n=Fa(_a(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}};
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function Va(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ua(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ba(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function za(e,t,n){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}function $a(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const i of n){if(!r.includes(i))return!1;const n=e[i],s=t[i];if(Wa(n)&&Wa(s)){if(!$a(n,s))return!1}else if(n!==s)return!1}for(const e of r)if(!n.includes(e))return!1;return!0}function Wa(e){return null!==e&&"object"==typeof e}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Qa(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function Ha(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[n,r]=e.split("=");t[decodeURIComponent(n)]=decodeURIComponent(r)}})),t}function Ga(e){const t=e.indexOf("?");if(!t)return"";const n=e.indexOf("#",t);return e.substring(t,n>0?n:void 0)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Ka{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(e,t){t||(t=0);const n=this.W_;if("string"==typeof e)for(let r=0;r<16;r++)n[r]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(let r=0;r<16;r++)n[r]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(let e=16;e<80;e++){const t=n[e-3]^n[e-8]^n[e-14]^n[e-16];n[e]=4294967295&(t<<1|t>>>31)}let r,i,s=this.chain_[0],o=this.chain_[1],a=this.chain_[2],c=this.chain_[3],u=this.chain_[4];for(let e=0;e<80;e++){e<40?e<20?(r=c^o&(a^c),i=1518500249):(r=o^a^c,i=1859775393):e<60?(r=o&a|c&(o|a),i=2400959708):(r=o^a^c,i=3395469782);const t=(s<<5|s>>>27)+r+u+i+n[e]&4294967295;u=c,c=a,a=4294967295&(o<<30|o>>>2),o=s,s=t}this.chain_[0]=this.chain_[0]+s&4294967295,this.chain_[1]=this.chain_[1]+o&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+c&4294967295,this.chain_[4]=this.chain_[4]+u&4294967295}update(e,t){if(null==e)return;void 0===t&&(t=e.length);const n=t-this.blockSize;let r=0;const i=this.buf_;let s=this.inbuf_;for(;r<t;){if(0===s)for(;r<=n;)this.compress_(e,r),r+=this.blockSize;if("string"==typeof e){for(;r<t;)if(i[s]=e.charCodeAt(r),++s,++r,s===this.blockSize){this.compress_(i),s=0;break}}else for(;r<t;)if(i[s]=e[r],++s,++r,s===this.blockSize){this.compress_(i),s=0;break}}this.inbuf_=s,this.total_+=t}digest(){const e=[];let t=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let e=this.blockSize-1;e>=56;e--)this.buf_[e]=255&t,t/=256;this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++)for(let r=24;r>=0;r-=8)e[n]=this.chain_[t]>>r&255,++n;return e}}function Ya(e,t){const n=new Ja(e,t);return n.subscribe.bind(n)}class Ja{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,n){let r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e,t){if("object"!=typeof e||null===e)return!1;for(const n of t)if(n in e&&"function"==typeof e[n])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=Xa),void 0===r.error&&(r.error=Xa),void 0===r.complete&&(r.complete=Xa);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}})),this.observers.push(r),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then((()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}}))}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function Xa(){}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Za=function(e,t,n,r){let i;if(r<t?i="at least "+t:r>n&&(i=0===n?"none":"no more than "+n),i){throw new Error(e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".")}};function ec(e,t){return`${e} failed: ${t} argument `}function tc(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(ec(e,t)+"must be a valid function.")}function nc(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(ec(e,t)+"must be a valid context object.")}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const rc=function(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);r<128?t++:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t};
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function ic(e){return e&&e._delegate?e._delegate:e}class sc{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}}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const oc="[DEFAULT]";
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ac{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new Ta;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),r=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(r)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if(function(e){return"EAGER"===e.instantiationMode}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e))try{this.getOrInitializeService({instanceIdentifier:oc})}catch(e){}for(const[e,t]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}}clearInstance(e=oc){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter((e=>"INTERNAL"in e)).map((e=>e.INTERNAL.delete())),...e.filter((e=>"_delete"in e)).map((e=>e._delete()))])}isComponentSet(){return null!=this.component}isInitialized(e=oc){return this.instances.has(e)}getOptions(e=oc){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const r=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries()){n===this.normalizeInstanceIdentifier(e)&&t.resolve(r)}return r}onInit(e,t){var n;const r=this.normalizeInstanceIdentifier(t),i=null!==(n=this.onInitCallbacks.get(r))&&void 0!==n?n:new Set;i.add(e),this.onInitCallbacks.set(r,i);const s=this.instances.get(r);return s&&e(s,r),()=>{i.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e,r===oc?void 0:r),options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e=oc){return this.component?this.component.multipleInstances?e:oc:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class cc{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new ac(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const uc=[];var lc;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(lc||(lc={}));const hc={debug:lc.DEBUG,verbose:lc.VERBOSE,info:lc.INFO,warn:lc.WARN,error:lc.ERROR,silent:lc.SILENT},dc=lc.INFO,fc={[lc.DEBUG]:"log",[lc.VERBOSE]:"log",[lc.INFO]:"info",[lc.WARN]:"warn",[lc.ERROR]:"error"},pc=(e,t,...n)=>{if(t<e.logLevel)return;const r=(new Date).toISOString(),i=fc[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}]  ${e.name}:`,...n)};class mc{constructor(e){this.name=e,this._logLevel=dc,this._logHandler=pc,this._userLogHandler=null,uc.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in lc))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?hc[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,lc.DEBUG,...e),this._logHandler(this,lc.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,lc.VERBOSE,...e),this._logHandler(this,lc.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,lc.INFO,...e),this._logHandler(this,lc.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,lc.WARN,...e),this._logHandler(this,lc.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,lc.ERROR,...e),this._logHandler(this,lc.ERROR,...e)}}const gc=(e,t)=>t.some((t=>e instanceof t));let yc,vc;const _c=new WeakMap,wc=new WeakMap,bc=new WeakMap,Ic=new WeakMap,Ec=new WeakMap;let Tc={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return wc.get(e);if("objectStoreNames"===t)return e.objectStoreNames||bc.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Cc(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Sc(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(vc||(vc=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(xc(this),t),Cc(_c.get(this))}:function(...t){return Cc(e.apply(xc(this),t))}:function(t,...n){const r=e.call(xc(this),t,...n);return bc.set(r,t.sort?t.sort():[t]),Cc(r)}}function kc(e){return"function"==typeof e?Sc(e):(e instanceof IDBTransaction&&function(e){if(wc.has(e))return;const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{t(),r()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)}));wc.set(e,t)}(e),gc(e,yc||(yc=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,Tc):e)}function Cc(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{t(Cc(e.result)),r()},s=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",s)}));return t.then((t=>{t instanceof IDBCursor&&_c.set(t,e)})).catch((()=>{})),Ec.set(t,e),t}(e);if(Ic.has(e))return Ic.get(e);const t=kc(e);return t!==e&&(Ic.set(e,t),Ec.set(t,e)),t}const xc=e=>Ec.get(e);const Ac=["get","getKey","getAll","getAllKeys","count"],Nc=["put","add","delete","clear"],Dc=new Map;function Rc(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Dc.get(t))return Dc.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=Nc.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!Ac.includes(n))return;const s=async function(e,...t){const s=this.transaction(e,i?"readwrite":"readonly");let o=s.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),i&&s.done]))[0]};return Dc.set(t,s),s}Tc=(e=>({...e,get:(t,n,r)=>Rc(t,n)||e.get(t,n,r),has:(t,n)=>!!Rc(t,n)||e.has(t,n)}))(Tc);
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class Oc{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map((e=>{if(function(e){const t=e.getComponent();return"VERSION"===(null==t?void 0:t.type)}(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}return null})).filter((e=>e)).join(" ")}}const Pc="@firebase/app",Mc="0.9.13",Lc=new mc("@firebase/app"),Fc="[DEFAULT]",jc={[Pc]:"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","fire-js":"fire-js",firebase:"fire-js-all"},qc=new Map,Vc=new Map;function Uc(e,t){try{e.container.addComponent(t)}catch(n){Lc.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function Bc(e,t){e.container.addOrOverwriteComponent(t)}function zc(e){const t=e.name;if(Vc.has(t))return Lc.debug(`There were multiple attempts to register component ${t}.`),!1;Vc.set(t,e);for(const t of qc.values())Uc(t,e);return!0}function $c(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const Wc=new Ma("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}."});
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
let Qc=class{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new sc("app",(()=>this),"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw Wc.create("app-deleted",{appName:this._name})}};
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Hc="9.23.0";function Gc(e,t={}){let n=e;if("object"!=typeof t){t={name:t}}const r=Object.assign({name:Fc,automaticDataCollectionEnabled:!1},t),i=r.name;if("string"!=typeof i||!i)throw Wc.create("bad-app-name",{appName:String(i)});if(n||(n=Ea()),!n)throw Wc.create("no-options");const s=qc.get(i);if(s){if($a(n,s.options)&&$a(r,s.config))return s;throw Wc.create("duplicate-app",{appName:i})}const o=new cc(i);for(const e of Vc.values())o.addComponent(e);const a=new Qc(n,r,o);return qc.set(i,a),a}async function Kc(e){const t=e.name;qc.has(t)&&(qc.delete(t),await Promise.all(e.container.getProviders().map((e=>e.delete()))),e.isDeleted=!0)}function Yc(e,t,n){var r;let i=null!==(r=jc[e])&&void 0!==r?r:e;n&&(i+=`-${n}`);const s=i.match(/\s|\//),o=t.match(/\s|\//);if(s||o){const e=[`Unable to register library "${i}" with version "${t}":`];return s&&e.push(`library name "${i}" contains illegal characters (whitespace or "/")`),s&&o&&e.push("and"),o&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void Lc.warn(e.join(" "))}zc(new sc(`${i}-version`,(()=>({library:i,version:t})),"VERSION"))}function Jc(e,t){if(null!==e&&"function"!=typeof e)throw Wc.create("invalid-log-argument");!function(e,t){for(const n of uc){let r=null;t&&t.level&&(r=hc[t.level]),n.userLogHandler=null===e?null:(t,n,...i)=>{const s=i.map((e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}})).filter((e=>e)).join(" ");n>=(null!=r?r:t.logLevel)&&e({level:lc[n].toLowerCase(),message:s,args:i,type:t.name})}}}(e,t)}function Xc(e){var t;t=e,uc.forEach((e=>{e.setLogLevel(t)}))}
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Zc="firebase-heartbeat-database",eu=1,tu="firebase-heartbeat-store";let nu=null;function ru(){return nu||(nu=function(e,t,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const o=indexedDB.open(e,t),a=Cc(o);return r&&o.addEventListener("upgradeneeded",(e=>{r(Cc(o.result),e.oldVersion,e.newVersion,Cc(o.transaction),e)})),n&&o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),a.then((e=>{s&&e.addEventListener("close",(()=>s())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}(Zc,eu,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(tu)}}).catch((e=>{throw Wc.create("idb-open",{originalErrorMessage:e.message})}))),nu}async function iu(e,t){try{const n=(await ru()).transaction(tu,"readwrite"),r=n.objectStore(tu);await r.put(t,su(e)),await n.done}catch(e){if(e instanceof Pa)Lc.warn(e.message);else{const t=Wc.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});Lc.warn(t.message)}}}function su(e){return`${e.name}!${e.options.appId}`}
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ou{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new cu(t),this._heartbeatsCachePromise=this._storage.read().then((e=>(this._heartbeatsCache=e,e)))}async triggerHeartbeat(){const e=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),t=au();if(null===this._heartbeatsCache&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==t&&!this._heartbeatsCache.heartbeats.some((e=>e.date===t)))return this._heartbeatsCache.heartbeats.push({date:t,agent:e}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter((e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=2592e6})),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null===this._heartbeatsCache||0===this._heartbeatsCache.heartbeats.length)return"";const e=au(),{heartbeatsToSend:t,unsentEntries:n}=function(e,t=1024){const n=[];let r=e.slice();for(const i of e){const e=n.find((e=>e.agent===i.agent));if(e){if(e.dates.push(i.date),uu(n)>t){e.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),uu(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),r=va(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,n.length>0?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),r}}function au(){return(new Date).toISOString().substring(0,10)}class cu{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!Oa()&&new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var e;t((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}})).then((()=>!0)).catch((()=>!1))}async read(){if(await this._canUseIndexedDBPromise){const e=await async function(e){try{const t=await ru();return await t.transaction(tu).objectStore(tu).get(su(e))}catch(e){if(e instanceof Pa)Lc.warn(e.message);else{const t=Wc.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});Lc.warn(t.message)}}}(this.app);return e||{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return iu(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return iu(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function uu(e){return va(JSON.stringify({version:2,heartbeats:e})).length}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var lu;lu="",zc(new sc("platform-logger",(e=>new Oc(e)),"PRIVATE")),zc(new sc("heartbeat",(e=>new ou(e)),"PRIVATE")),Yc(Pc,Mc,lu),Yc(Pc,Mc,"esm2017"),Yc("fire-js","");var hu=Object.freeze({__proto__:null,FirebaseError:Pa,SDK_VERSION:Hc,_DEFAULT_ENTRY_NAME:Fc,_addComponent:Uc,_addOrOverwriteComponent:Bc,_apps:qc,_clearComponents:function(){Vc.clear()},_components:Vc,_getProvider:$c,_registerComponent:zc,_removeServiceInstance:function(e,t,n=Fc){$c(e,t).clearInstance(n)},deleteApp:Kc,getApp:function(e=Fc){const t=qc.get(e);if(!t&&e===Fc&&Ea())return Gc();if(!t)throw Wc.create("no-app",{appName:e});return t},getApps:function(){return Array.from(qc.values())},initializeApp:Gc,onLog:Jc,registerVersion:Yc,setLogLevel:Xc});
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const du="firebasestorage.googleapis.com",fu="storageBucket";
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class pu extends Pa{constructor(e,t,n=0){super(yu(e),`Firebase Storage: ${t} (${yu(e)})`),this.status_=n,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,pu.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return yu(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}var mu,gu;function yu(e){return"storage/"+e}function vu(){return new pu(mu.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function _u(){return new pu(mu.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function wu(){return new pu(mu.CANCELED,"User canceled the upload/download.")}function bu(){return new pu(mu.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function Iu(e){return new pu(mu.INVALID_ARGUMENT,e)}function Eu(){return new pu(mu.APP_DELETED,"The Firebase app was deleted.")}function Tu(e){return new pu(mu.INVALID_ROOT_OPERATION,"The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function Su(e,t){return new pu(mu.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function ku(e){throw new pu(mu.INTERNAL_ERROR,"Internal error: "+e)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */!function(e){e.UNKNOWN="unknown",e.OBJECT_NOT_FOUND="object-not-found",e.BUCKET_NOT_FOUND="bucket-not-found",e.PROJECT_NOT_FOUND="project-not-found",e.QUOTA_EXCEEDED="quota-exceeded",e.UNAUTHENTICATED="unauthenticated",e.UNAUTHORIZED="unauthorized",e.UNAUTHORIZED_APP="unauthorized-app",e.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",e.INVALID_CHECKSUM="invalid-checksum",e.CANCELED="canceled",e.INVALID_EVENT_NAME="invalid-event-name",e.INVALID_URL="invalid-url",e.INVALID_DEFAULT_BUCKET="invalid-default-bucket",e.NO_DEFAULT_BUCKET="no-default-bucket",e.CANNOT_SLICE_BLOB="cannot-slice-blob",e.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",e.NO_DOWNLOAD_URL="no-download-url",e.INVALID_ARGUMENT="invalid-argument",e.INVALID_ARGUMENT_COUNT="invalid-argument-count",e.APP_DELETED="app-deleted",e.INVALID_ROOT_OPERATION="invalid-root-operation",e.INVALID_FORMAT="invalid-format",e.INTERNAL_ERROR="internal-error",e.UNSUPPORTED_ENVIRONMENT="unsupported-environment"}(mu||(mu={}));class Cu{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(e,t){let n;try{n=Cu.makeFromUrl(e,t)}catch(t){return new Cu(e,"")}if(""===n.path)return n;throw r=e,new pu(mu.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+r+"'.");var r}static makeFromUrl(e,t){let n=null;const r="([A-Za-z0-9.\\-_]+)";const i=new RegExp("^gs://"+r+"(/(.*))?$","i");function s(e){e.path_=decodeURIComponent(e.path)}const o=t.replace(/[.]/g,"\\."),a=[{regex:i,indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:new RegExp(`^https?://${o}/v[A-Za-z0-9_]+/b/${r}/o(/([^?#]*).*)?$`,"i"),indices:{bucket:1,path:3},postModify:s},{regex:new RegExp(`^https?://${t===du?"(?:storage.googleapis.com|storage.cloud.google.com)":t}/${r}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:s}];for(let t=0;t<a.length;t++){const r=a[t],i=r.regex.exec(e);if(i){const e=i[r.indices.bucket];let t=i[r.indices.path];t||(t=""),n=new Cu(e,t),r.postModify(n);break}}if(null==n)throw function(e){return new pu(mu.INVALID_URL,"Invalid URL '"+e+"'.")}(e);return n}}class xu{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Au(e){return"string"==typeof e||e instanceof String}function Nu(e){return Du()&&e instanceof Blob}function Du(){return"undefined"!=typeof Blob&&!xa()}function Ru(e,t,n,r){if(r<t)throw Iu(`Invalid value for '${e}'. Expected ${t} or greater.`);if(r>n)throw Iu(`Invalid value for '${e}'. Expected ${n} or less.`)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Ou(e,t,n){let r=t;return null==n&&(r=`https://${t}`),`${n}://${r}/v0${e}`}function Pu(e){const t=encodeURIComponent;let n="?";for(const r in e)if(e.hasOwnProperty(r)){n=n+(t(r)+"="+t(e[r]))+"&"}return n=n.slice(0,-1),n}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function Mu(e,t){const n=e>=500&&e<600,r=-1!==[408,429].indexOf(e),i=-1!==t.indexOf(e);return n||r||i}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */!function(e){e[e.NO_ERROR=0]="NO_ERROR",e[e.NETWORK_ERROR=1]="NETWORK_ERROR",e[e.ABORT=2]="ABORT"}(gu||(gu={}));class Lu{constructor(e,t,n,r,i,s,o,a,c,u,l,h=!0){this.url_=e,this.method_=t,this.headers_=n,this.body_=r,this.successCodes_=i,this.additionalRetryCodes_=s,this.callback_=o,this.errorCallback_=a,this.timeout_=c,this.progressCallback_=u,this.connectionFactory_=l,this.retry=h,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise(((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()}))}start_(){const e=(e,t)=>{if(t)return void e(!1,new Fu(!1,null,!0));const n=this.connectionFactory_();this.pendingConnection_=n;const r=e=>{const t=e.loaded,n=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,n)};null!==this.progressCallback_&&n.addUploadProgressListener(r),n.send(this.url_,this.method_,this.body_,this.headers_).then((()=>{null!==this.progressCallback_&&n.removeUploadProgressListener(r),this.pendingConnection_=null;const t=n.getErrorCode()===gu.NO_ERROR,i=n.getStatus();if(!t||Mu(i,this.additionalRetryCodes_)&&this.retry){const t=n.getErrorCode()===gu.ABORT;return void e(!1,new Fu(!1,null,t))}const s=-1!==this.successCodes_.indexOf(i);e(!0,new Fu(s,n))}))},t=(e,t)=>{const n=this.resolve_,r=this.reject_,i=t.connection;if(t.wasSuccessCode)try{const e=this.callback_(i,i.getResponse());!
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function(e){return void 0!==e}(e)?n():n(e)}catch(e){r(e)}else if(null!==i){const e=vu();e.serverResponse=i.getErrorText(),this.errorCallback_?r(this.errorCallback_(i,e)):r(e)}else if(t.canceled){r(this.appDelete_?Eu():wu())}else{r(_u())}};this.canceled_?t(0,new Fu(!1,null,!0)):this.backoffId_=function(e,t,n){let r=1,i=null,s=null,o=!1,a=0;function c(){return 2===a}let u=!1;function l(...e){u||(u=!0,t.apply(null,e))}function h(t){i=setTimeout((()=>{i=null,e(f,c())}),t)}function d(){s&&clearTimeout(s)}function f(e,...t){if(u)return void d();if(e)return d(),void l.call(null,e,...t);if(c()||o)return d(),void l.call(null,e,...t);let n;r<64&&(r*=2),1===a?(a=2,n=0):n=1e3*(r+Math.random()),h(n)}let p=!1;function m(e){p||(p=!0,d(),u||(null!==i?(e||(a=2),clearTimeout(i),h(0)):e||(a=1)))}return h(0),s=setTimeout((()=>{o=!0,m(!0)}),n),m}(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&function(e){e(!1)}(this.backoffId_),null!==this.pendingConnection_&&this.pendingConnection_.abort()}}class Fu{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function ju(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function qu(...e){const t=ju();if(void 0!==t){const n=new t;for(let t=0;t<e.length;t++)n.append(e[t]);return n.getBlob()}if(Du())return new Blob(e);throw new pu(mu.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function Vu(e){if("undefined"==typeof atob)throw t="base-64",new pu(mu.UNSUPPORTED_ENVIRONMENT,`${t} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`);var t;return atob(e)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Uu={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class Bu{constructor(e,t){this.data=e,this.contentType=t||null}}function zu(e,t){switch(e){case Uu.RAW:return new Bu($u(t));case Uu.BASE64:case Uu.BASE64URL:return new Bu(Wu(e,t));case Uu.DATA_URL:return new Bu(function(e){const t=new Qu(e);return t.base64?Wu(Uu.BASE64,t.rest):function(e){let t;try{t=decodeURIComponent(e)}catch(e){throw Su(Uu.DATA_URL,"Malformed data URL.")}return $u(t)}(t.rest)}(t),new Qu(t).contentType)}throw vu()}function $u(e){const t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<=127)t.push(r);else if(r<=2047)t.push(192|r>>6,128|63&r);else if(55296==(64512&r)){if(n<e.length-1&&56320==(64512&e.charCodeAt(n+1))){r=65536|(1023&r)<<10|1023&e.charCodeAt(++n),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}else t.push(239,191,189)}else 56320==(64512&r)?t.push(239,191,189):t.push(224|r>>12,128|r>>6&63,128|63&r)}return new Uint8Array(t)}function Wu(e,t){switch(e){case Uu.BASE64:{const n=-1!==t.indexOf("-"),r=-1!==t.indexOf("_");if(n||r){throw Su(e,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?")}break}case Uu.BASE64URL:{const n=-1!==t.indexOf("+"),r=-1!==t.indexOf("/");if(n||r){throw Su(e,"Invalid character '"+(n?"+":"/")+"' found: is it base64 encoded?")}t=t.replace(/-/g,"+").replace(/_/g,"/");break}}let n;try{n=Vu(t)}catch(t){if(t.message.includes("polyfill"))throw t;throw Su(e,"Invalid character found")}const r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}class Qu{constructor(e){this.base64=!1,this.contentType=null;const t=e.match(/^data:([^,]+)?,/);if(null===t)throw Su(Uu.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const n=t[1]||null;null!=n&&(this.base64=function(e,t){if(!(e.length>=t.length))return!1;return e.substring(e.length-t.length)===t}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(n,";base64"),this.contentType=this.base64?n.substring(0,n.length-7):n),this.rest=e.substring(e.indexOf(",")+1)}}class Hu{constructor(e,t){let n=0,r="";Nu(e)?(this.data_=e,n=e.size,r=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),n=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),n=e.length),this.size_=n,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,t){if(Nu(this.data_)){const n=function(e,t,n){return e.webkitSlice?e.webkitSlice(t,n):e.mozSlice?e.mozSlice(t,n):e.slice?e.slice(t,n):null}(this.data_,e,t);return null===n?null:new Hu(n)}{const n=new Uint8Array(this.data_.buffer,e,t-e);return new Hu(n,!0)}}static getBlob(...e){if(Du()){const t=e.map((e=>e instanceof Hu?e.data_:e));return new Hu(qu.apply(null,t))}{const t=e.map((e=>Au(e)?zu(Uu.RAW,e).data:e.data_));let n=0;t.forEach((e=>{n+=e.byteLength}));const r=new Uint8Array(n);let i=0;return t.forEach((e=>{for(let t=0;t<e.length;t++)r[i++]=e[t]})),new Hu(r,!0)}}uploadData(){return this.data_}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Gu(e){let t;try{t=JSON.parse(e)}catch(e){return null}return function(e){return"object"==typeof e&&!Array.isArray(e)}(t)?t:null}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Ku(e){const t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Yu(e,t){return t}class Ju{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||Yu}}let Xu=null;function Zu(){if(Xu)return Xu;const e=[];e.push(new Ju("bucket")),e.push(new Ju("generation")),e.push(new Ju("metageneration")),e.push(new Ju("name","fullPath",!0));const t=new Ju("name");t.xform=function(e,t){return function(e){return!Au(e)||e.length<2?e:Ku(e)}(t)},e.push(t);const n=new Ju("size");return n.xform=function(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new Ju("timeCreated")),e.push(new Ju("updated")),e.push(new Ju("md5Hash",null,!0)),e.push(new Ju("cacheControl",null,!0)),e.push(new Ju("contentDisposition",null,!0)),e.push(new Ju("contentEncoding",null,!0)),e.push(new Ju("contentLanguage",null,!0)),e.push(new Ju("contentType",null,!0)),e.push(new Ju("metadata","customMetadata",!0)),Xu=e,Xu}function el(e,t,n){const r={type:"file"},i=n.length;for(let e=0;e<i;e++){const i=n[e];r[i.local]=i.xform(r,t[i.server])}return function(e,t){Object.defineProperty(e,"ref",{get:function(){const n=e.bucket,r=e.fullPath,i=new Cu(n,r);return t._makeStorageReference(i)}})}(r,e),r}function tl(e,t,n){const r=Gu(t);if(null===r)return null;return el(e,r,n)}function nl(e,t){const n={},r=t.length;for(let i=0;i<r;i++){const r=t[i];r.writable&&(n[r.server]=e[r.local])}return JSON.stringify(n)}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const rl="prefixes",il="items";function sl(e,t,n){const r=Gu(n);if(null===r)return null;return function(e,t,n){const r={prefixes:[],items:[],nextPageToken:n.nextPageToken};if(n[rl])for(const i of n[rl]){const n=i.replace(/\/$/,""),s=e._makeStorageReference(new Cu(t,n));r.prefixes.push(s)}if(n[il])for(const i of n[il]){const n=e._makeStorageReference(new Cu(t,i.name));r.items.push(n)}return r}(e,t,r)}class ol{constructor(e,t,n,r){this.url=e,this.method=t,this.handler=n,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function al(e){if(!e)throw vu()}function cl(e,t){return function(n,r){const i=tl(e,r,t);return al(null!==i),i}}function ul(e,t){return function(n,r){const i=tl(e,r,t);return al(null!==i),function(e,t,n,r){const i=Gu(t);if(null===i)return null;if(!Au(i.downloadTokens))return null;const s=i.downloadTokens;if(0===s.length)return null;const o=encodeURIComponent;return s.split(",").map((t=>{const i=e.bucket,s=e.fullPath;return Ou("/b/"+o(i)+"/o/"+o(s),n,r)+Pu({alt:"media",token:t})}))[0]}(i,r,e.host,e._protocol)}}function ll(e){return function(t,n){let r;var i,s;return 401===t.getStatus()?r=t.getErrorText().includes("Firebase App Check token is invalid")?new pu(mu.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project."):new pu(mu.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===t.getStatus()?(s=e.bucket,r=new pu(mu.QUOTA_EXCEEDED,"Quota for bucket '"+s+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===t.getStatus()?(i=e.path,r=new pu(mu.UNAUTHORIZED,"User does not have permission to access '"+i+"'.")):r=n,r.status=t.getStatus(),r.serverResponse=n.serverResponse,r}}function hl(e){const t=ll(e);return function(n,r){let i=t(n,r);var s;return 404===n.getStatus()&&(s=e.path,i=new pu(mu.OBJECT_NOT_FOUND,"Object '"+s+"' does not exist.")),i.serverResponse=r.serverResponse,i}}function dl(e,t,n){const r=Ou(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime,s=new ol(r,"GET",cl(e,n),i);return s.errorHandler=hl(t),s}function fl(e,t,n,r,i){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",n&&n.length>0&&(s.delimiter=n),r&&(s.pageToken=r),i&&(s.maxResults=i);const o=Ou(t.bucketOnlyServerUrl(),e.host,e._protocol),a=e.maxOperationRetryTime,c=new ol(o,"GET",function(e,t){return function(n,r){const i=sl(e,t,r);return al(null!==i),i}}(e,t.bucket),a);return c.urlParams=s,c.errorHandler=ll(t),c}function pl(e,t,n){const r=Object.assign({},n);return r.fullPath=e.path,r.size=t.size(),r.contentType||(r.contentType=function(e,t){return e&&e.contentType||t&&t.type()||"application/octet-stream"}(null,t)),r}function ml(e,t,n,r,i){const s=t.bucketOnlyServerUrl(),o={"X-Goog-Upload-Protocol":"multipart"};const a=function(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();o["Content-Type"]="multipart/related; boundary="+a;const c=pl(t,r,i),u="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+nl(c,n)+"\r\n--"+a+"\r\nContent-Type: "+c.contentType+"\r\n\r\n",l="\r\n--"+a+"--",h=Hu.getBlob(u,r,l);if(null===h)throw bu();const d={name:c.fullPath},f=Ou(s,e.host,e._protocol),p=e.maxUploadRetryTime,m=new ol(f,"POST",cl(e,n),p);return m.urlParams=d,m.headers=o,m.body=h.uploadData(),m.errorHandler=ll(t),m}class gl{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function yl(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){al(!1)}return al(!!n&&-1!==(t||["active"]).indexOf(n)),n}const vl=262144;function _l(e,t,n,r,i,s,o,a){const c=new gl(0,0);if(o?(c.current=o.current,c.total=o.total):(c.current=0,c.total=r.size()),r.size()!==c.total)throw new pu(mu.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.");const u=c.total-c.current;let l=u;i>0&&(l=Math.min(l,i));const h=c.current,d=h+l;let f="";f=0===l?"finalize":u===l?"upload, finalize":"upload";const p={"X-Goog-Upload-Command":f,"X-Goog-Upload-Offset":`${c.current}`},m=r.slice(h,d);if(null===m)throw bu();const g=t.maxUploadRetryTime,y=new ol(n,"POST",(function(e,n){const i=yl(e,["active","final"]),o=c.current+l,a=r.size();let u;return u="final"===i?cl(t,s)(e,n):null,new gl(o,a,"final"===i,u)}),g);return y.headers=p,y.body=m.uploadData(),y.progressCallback=a||null,y.errorHandler=ll(e),y}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const wl={STATE_CHANGED:"state_changed"},bl={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function Il(e){switch(e){case"running":case"pausing":case"canceling":return bl.RUNNING;case"paused":return bl.PAUSED;case"success":return bl.SUCCESS;case"canceled":return bl.CANCELED;default:return bl.ERROR}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class El{constructor(e,t,n){const r=function(e){return"function"==typeof e}(e)||null!=t||null!=n;if(r)this.next=e,this.error=null!=t?t:void 0,this.complete=null!=n?n:void 0;else{const t=e;this.next=t.next,this.error=t.error,this.complete=t.complete}}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Tl(e){return(...t)=>{Promise.resolve().then((()=>e(...t)))}}class Sl{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=gu.NO_ERROR,this.sendPromise_=new Promise((e=>{this.xhr_.addEventListener("abort",(()=>{this.errorCode_=gu.ABORT,e()})),this.xhr_.addEventListener("error",(()=>{this.errorCode_=gu.NETWORK_ERROR,e()})),this.xhr_.addEventListener("load",(()=>{e()}))}))}send(e,t,n,r){if(this.sent_)throw ku("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==r)for(const e in r)r.hasOwnProperty(e)&&this.xhr_.setRequestHeader(e,r[e].toString());return void 0!==n?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw ku("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw ku("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw ku("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw ku("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}class kl extends Sl{initXhr(){this.xhr_.responseType="text"}}function Cl(){return new kl}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class xl{constructor(e,t,n=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=n,this._mappings=Zu(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(mu.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{const t=this.isExponentialBackoffExpired();if(Mu(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=_u()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(mu.CANCELED)?this.completeTransitions_():(this._error=e,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t,this._start()})),this._promise.then(null,(()=>{}))}isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}_makeProgressCallback(){const e=this._transferred;return t=>this._updateProgress(e+t)}_shouldDoResumable(e){return e.size()>262144}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout((()=>{this.pendingTimeout=void 0,this._continueUpload()}),this.sleepTime):this._oneShotUpload())}_resolveToken(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then((([t,n])=>{switch(this._state){case"running":e(t,n);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}}))}_createResumable(){this._resolveToken(((e,t)=>{const n=function(e,t,n,r,i){const s=t.bucketOnlyServerUrl(),o=pl(t,r,i),a={name:o.fullPath},c=Ou(s,e.host,e._protocol),u={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${r.size()}`,"X-Goog-Upload-Header-Content-Type":o.contentType,"Content-Type":"application/json; charset=utf-8"},l=nl(o,n),h=e.maxUploadRetryTime,d=new ol(c,"POST",(function(e){let t;yl(e);try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){al(!1)}return al(Au(t)),t}),h);return d.urlParams=a,d.headers=u,d.body=l,d.errorHandler=ll(t),d}(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(n,Cl,e,t);this._request=r,r.getPromise().then((e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()}),this._errorHandler)}))}_fetchStatus(){const e=this._uploadUrl;this._resolveToken(((t,n)=>{const r=function(e,t,n,r){const i=e.maxUploadRetryTime,s=new ol(n,"POST",(function(e){const t=yl(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){al(!1)}n||al(!1);const i=Number(n);return al(!isNaN(i)),new gl(i,r.size(),"final"===t)}),i);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=ll(t),s}(this._ref.storage,this._ref._location,e,this._blob),i=this._ref.storage._makeRequest(r,Cl,t,n);this._request=i,i.getPromise().then((e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()}),this._errorHandler)}))}_continueUpload(){const e=vl*this._chunkMultiplier,t=new gl(this._transferred,this._blob.size()),n=this._uploadUrl;this._resolveToken(((r,i)=>{let s;try{s=_l(this._ref._location,this._ref.storage,n,this._blob,e,this._mappings,t,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}const o=this._ref.storage._makeRequest(s,Cl,r,i,!1);this._request=o,o.getPromise().then((e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()}),this._errorHandler)}))}_increaseMultiplier(){2*(vl*this._chunkMultiplier)<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken(((e,t)=>{const n=dl(this._ref.storage,this._ref._location,this._mappings),r=this._ref.storage._makeRequest(n,Cl,e,t);this._request=r,r.getPromise().then((e=>{this._request=void 0,this._metadata=e,this._transition("success")}),this._metadataErrorHandler)}))}_oneShotUpload(){this._resolveToken(((e,t)=>{const n=ml(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(n,Cl,e,t);this._request=r,r.getPromise().then((e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")}),this._errorHandler)}))}_updateProgress(e){const t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":const t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":case"error":case"success":this._state=e,this._notifyObservers();break;case"canceled":this._error=wu(),this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){const e=Il(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,n,r){const i=new El(t||void 0,n||void 0,r||void 0);return this._addObserver(i),()=>{this._removeObserver(i)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){const t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise();this._observers.slice().forEach((e=>{this._notifyObserver(e)}))}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(Il(this._state)){case bl.SUCCESS:Tl(this._resolve.bind(null,this.snapshot))();break;case bl.CANCELED:case bl.ERROR:Tl(this._reject.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(Il(this._state)){case bl.RUNNING:case bl.PAUSED:e.next&&Tl(e.next.bind(e,this.snapshot))();break;case bl.SUCCESS:e.complete&&Tl(e.complete.bind(e))();break;default:e.error&&Tl(e.error.bind(e,this._error))()}}resume(){const e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){const e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){const e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Al=class e{constructor(e,t){this._service=e,this._location=t instanceof Cu?t:Cu.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(t,n){return new e(t,n)}get root(){const e=new Cu(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return Ku(this._location.path)}get storage(){return this._service}get parent(){const t=function(e){if(0===e.length)return null;const t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===t)return null;const n=new Cu(this._location.bucket,t);return new e(this._service,n)}_throwIfRoot(e){if(""===this._location.path)throw Tu(e)}};function Nl(e,t,n){e._throwIfRoot("uploadBytes");const r=ml(e.storage,e._location,Zu(),new Hu(t,!0),n);return e.storage.makeRequestWithTokens(r,Cl).then((t=>({metadata:t,ref:e})))}function Dl(e){const t={prefixes:[],items:[]};return Rl(e,t).then((()=>t))}async function Rl(e,t,n){const r={pageToken:n},i=await Ol(e,r);t.prefixes.push(...i.prefixes),t.items.push(...i.items),null!=i.nextPageToken&&await Rl(e,t,i.nextPageToken)}function Ol(e,t){null!=t&&"number"==typeof t.maxResults&&Ru("options.maxResults",1,1e3,t.maxResults);const n=t||{},r=fl(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(r,Cl)}function Pl(e,t){e._throwIfRoot("updateMetadata");const n=function(e,t,n,r){const i=Ou(t.fullServerUrl(),e.host,e._protocol),s=nl(n,r),o=e.maxOperationRetryTime,a=new ol(i,"PATCH",cl(e,r),o);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=s,a.errorHandler=hl(t),a}(e.storage,e._location,t,Zu());return e.storage.makeRequestWithTokens(n,Cl)}function Ml(e){e._throwIfRoot("getDownloadURL");const t=function(e,t,n){const r=Ou(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime,s=new ol(r,"GET",ul(e,n),i);return s.errorHandler=hl(t),s}(e.storage,e._location,Zu());return e.storage.makeRequestWithTokens(t,Cl).then((e=>{if(null===e)throw new pu(mu.NO_DOWNLOAD_URL,"The given file does not have any download URLs.");return e}))}function Ll(e){e._throwIfRoot("deleteObject");const t=function(e,t){const n=Ou(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime,i=new ol(n,"DELETE",(function(e,t){}),r);return i.successCodes=[200,204],i.errorHandler=hl(t),i}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,Cl)}function Fl(e,t){const n=function(e,t){const n=t.split("/").filter((e=>e.length>0)).join("/");return 0===e.length?n:e+"/"+n}(e._location.path,t),r=new Cu(e._location.bucket,n);return new Al(e.storage,r)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function jl(e,t){if(e instanceof Ul){const n=e;if(null==n._bucket)throw new pu(mu.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+fu+"' property when initializing the app?");const r=new Al(n,n._bucket);return null!=t?jl(r,t):r}return void 0!==t?Fl(e,t):e}function ql(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof Ul)return new Al(e,t);throw Iu("To use ref(service, url), the first argument must be a Storage instance.")}return jl(e,t)}function Vl(e,t){const n=null==t?void 0:t[fu];return null==n?null:Cu.makeFromBucketSpec(n,e)}class Ul{constructor(e,t,n,r,i){this.app=e,this._authProvider=t,this._appCheckProvider=n,this._url=r,this._firebaseVersion=i,this._bucket=null,this._host=du,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?Cu.makeFromBucketSpec(r,this._host):Vl(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=Cu.makeFromBucketSpec(this._url,e):this._bucket=Vl(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){Ru("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){Ru("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){const t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){const e=this._appCheckProvider.getImmediate({optional:!0});if(e){return(await e.getToken()).token}return null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach((e=>e.cancel())),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new Al(this,e)}_makeRequest(e,t,n,r,i=!0){if(this._deleted)return new xu(Eu());{const s=function(e,t,n,r,i,s,o=!0){const a=Pu(e.urlParams),c=e.url+a,u=Object.assign({},e.headers);return function(e,t){t&&(e["X-Firebase-GMPID"]=t)}(u,t),function(e,t){null!==t&&t.length>0&&(e.Authorization="Firebase "+t)}(u,n),function(e,t){e["X-Firebase-Storage-Version"]="webjs/"+(null!=t?t:"AppManager")}(u,s),function(e,t){null!==t&&(e["X-Firebase-AppCheck"]=t)}(u,r),new Lu(c,e.method,u,e.body,e.successCodes,e.additionalRetryCodes,e.handler,e.errorHandler,e.timeout,e.progressCallback,i,o)}(e,this._appId,n,r,t,this._firebaseVersion,i);return this._requests.add(s),s.getPromise().then((()=>this._requests.delete(s)),(()=>this._requests.delete(s))),s}}async makeRequestWithTokens(e,t){const[n,r]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,n,r).getPromise()}}const Bl="@firebase/storage",zl="0.11.2";function $l(e,t,n){return Nl(e=ic(e),t,n)}function Wl(e,t,n,r){return function(e,t,n=Uu.RAW,r){e._throwIfRoot("uploadString");const i=zu(n,t),s=Object.assign({},r);return null==s.contentType&&null!=i.contentType&&(s.contentType=i.contentType),Nl(e,i.data,s)}(e=ic(e),t,n,r)}function Ql(e,t,n){return function(e,t,n){return e._throwIfRoot("uploadBytesResumable"),new xl(e,new Hu(t),n)}(e=ic(e),t,n)}function Hl(e){return function(e){e._throwIfRoot("getMetadata");const t=dl(e.storage,e._location,Zu());return e.storage.makeRequestWithTokens(t,Cl)}(e=ic(e))}function Gl(e){return Ml(e=ic(e))}function Kl(e,t){return ql(e=ic(e),t)}function Yl(e,t,n,r={}){!function(e,t,n,r={}){e.host=`${t}:${n}`,e._protocol="http";const{mockUserToken:i}=r;i&&(e._overrideAuthToken="string"==typeof i?i:Sa(i,e.app.options.projectId))}(e,t,n,r)}function Jl(e,{instanceIdentifier:t}){const n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new Ul(n,r,i,t,Hc)}zc(new sc("storage",Jl,"PUBLIC").setMultipleInstances(!0)),Yc(Bl,zl,""),Yc(Bl,zl,"esm2017");const Xl={feedbackItems:[],setFeedbackItems:()=>{},user:null,setUser:()=>{},stats:null,feedbackAssignments:[],setFeedbackAssignments:()=>{},activeProjectID:void 0,setActiveProjectID:()=>{},fetchFeedbackLoading:!1},Zl=n.createContext(Xl),eh=n=>e.jsxs(t.Icon,{width:"3rem",height:".875rem",viewBox:"0 0 48 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n,children:[e.jsxs("g",{clipPath:"url(#clip0_208_4665)",children:[e.jsx("path",{d:"M8.80613 0H4.37212L0 13.8906H4.10061C4.86124 13.8906 5.52804 13.3284 5.72768 12.5169L6.97942 7.42875L8.56856 13.8906H13.9588L9.58673 0H8.80613Z",fill:"white"}),e.jsx("path",{d:"M14.8691 14H18.3209C19.2512 14 20.0059 13.1666 20.0059 12.1384V0.109375H14.8691V14Z",fill:"white"}),e.jsx("path",{d:"M43.0463 10.1084V8.89437H46.552V5.17562H43.0463V4.00094H46.9193L47.8956 0.109375H38.3867V14H46.8834L47.9136 10.1084H43.0463Z",fill:"white"}),e.jsx("path",{d:"M30.7757 0.109375L29.1606 5.47531L27.5455 0.109375H22.8041L20.9175 14H25.5431L26.2958 8.78062L27.1363 12.2019L27.5795 14H30.7418L31.185 12.2019L32.0694 8.60563L32.848 14H37.4716L35.585 0.109375H30.7757Z",fill:"white"})]}),e.jsx("defs",{children:e.jsx("clipPath",{id:"clip0_208_4665",children:e.jsx("rect",{width:"47.9137",height:"14",fill:"white"})})})]}),th=n=>e.jsxs(t.Icon,{width:"1.25rem",height:"1.25rem",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n,children:[e.jsx("path",{d:"M8.33317 12.4993L5.77046 15.0941C5.41299 15.456 5.23426 15.637 5.08063 15.6498C4.94735 15.6608 4.81685 15.6073 4.7298 15.5057C4.62947 15.3887 4.62947 15.1343 4.62947 14.6256V13.3257C4.62947 12.8693 4.25573 12.5391 3.80417 12.473V12.473C2.71129 12.3129 1.85298 11.4546 1.6929 10.3617C1.6665 10.1815 1.6665 9.96645 1.6665 9.53638V5.66602C1.6665 4.26588 1.6665 3.56582 1.93899 3.03104C2.17867 2.56063 2.56112 2.17818 3.03153 1.9385C3.56631 1.66602 4.26637 1.66602 5.6665 1.66602H11.8332C13.2333 1.66602 13.9334 1.66602 14.4681 1.9385C14.9386 2.17818 15.321 2.56063 15.5607 3.03104C15.8332 3.56582 15.8332 4.26588 15.8332 5.66602V9.16602",stroke:"white",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M18.3335 11.8327C18.3335 10.8993 18.3335 10.4326 18.1518 10.076C17.9921 9.76243 17.7371 9.50746 17.4235 9.34767C17.067 9.16602 16.6003 9.16602 15.6668 9.16602H11.0002C10.0667 9.16602 9.60003 9.16602 9.24351 9.34767C8.92991 9.50746 8.67494 9.76243 8.51515 10.076C8.3335 10.4326 8.3335 10.8993 8.3335 11.8327V13.9279C8.3335 14.8613 8.3335 15.3281 8.51515 15.6846C8.67494 15.9982 8.92991 16.2531 9.24351 16.4129C9.60003 16.5946 10.0667 16.5946 11.0002 16.5946H12.4976C12.8081 16.5946 12.9634 16.5946 13.1131 16.6222C13.2461 16.6467 13.3755 16.6873 13.4987 16.743C13.6374 16.8059 13.7649 16.8945 14.0198 17.0717L15.8335 18.3327V16.5946C16.6101 16.5946 16.9984 16.5946 17.3046 16.4677C17.713 16.2986 18.0375 15.9741 18.2066 15.5657C18.3335 15.2594 18.3335 14.8712 18.3335 14.0946V11.8327Z",stroke:"white",strokeLinecap:"round",strokeLinejoin:"round"})]}),nh=n=>e.jsxs(t.Icon,{width:"1.25rem",height:"1.25rem",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n,children:[e.jsx("path",{d:"M9.99988 12.5C11.3806 12.5 12.4999 11.3807 12.4999 10C12.4999 8.61929 11.3806 7.5 9.99988 7.5C8.61917 7.5 7.49988 8.61929 7.49988 10C7.49988 11.3807 8.61917 12.5 9.99988 12.5Z",stroke:"white",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M15.606 12.2721C15.5051 12.5006 15.475 12.754 15.5196 12.9998C15.5642 13.2455 15.6813 13.4723 15.856 13.6509L15.9014 13.6963C16.0423 13.837 16.154 14.0041 16.2303 14.1881C16.3065 14.372 16.3458 14.5692 16.3458 14.7683C16.3458 14.9674 16.3065 15.1646 16.2303 15.3485C16.154 15.5324 16.0423 15.6995 15.9014 15.8403C15.7607 15.9811 15.5936 16.0929 15.4097 16.1691C15.2257 16.2454 15.0286 16.2846 14.8294 16.2846C14.6303 16.2846 14.4332 16.2454 14.2492 16.1691C14.0653 16.0929 13.8982 15.9811 13.7575 15.8403L13.712 15.7948C13.5335 15.6202 13.3067 15.503 13.061 15.4584C12.8152 15.4139 12.5617 15.444 12.3332 15.5448C12.1092 15.6408 11.9181 15.8003 11.7835 16.0035C11.6489 16.2068 11.5766 16.445 11.5757 16.6887V16.8175C11.5757 17.2194 11.416 17.6048 11.1319 17.8889C10.8477 18.1731 10.4623 18.3327 10.0605 18.3327C9.65866 18.3327 9.27328 18.1731 8.98913 17.8889C8.70498 17.6048 8.54535 17.2194 8.54535 16.8175V16.7493C8.53949 16.4986 8.45832 16.2554 8.31241 16.0514C8.16649 15.8474 7.96258 15.692 7.72717 15.6054C7.49867 15.5046 7.24521 15.4745 6.99945 15.519C6.7537 15.5636 6.52693 15.6808 6.34838 15.8554L6.30293 15.9009C6.16221 16.0417 5.99511 16.1535 5.81117 16.2297C5.62724 16.306 5.43007 16.3452 5.23096 16.3452C5.03184 16.3452 4.83468 16.306 4.65075 16.2297C4.46681 16.1535 4.29971 16.0417 4.15899 15.9009C4.01812 15.7601 3.90636 15.593 3.83011 15.4091C3.75386 15.2252 3.71462 15.028 3.71462 14.8289C3.71462 14.6298 3.75386 14.4326 3.83011 14.2487C3.90636 14.0647 4.01812 13.8976 4.15899 13.7569L4.20444 13.7115C4.37909 13.5329 4.49625 13.3062 4.54081 13.0604C4.58537 12.8146 4.55529 12.5612 4.45444 12.3327C4.35841 12.1086 4.19896 11.9175 3.99571 11.7829C3.79246 11.6483 3.55428 11.5761 3.3105 11.5751H3.18172C2.77987 11.5751 2.39449 11.4155 2.11034 11.1313C1.8262 10.8472 1.66656 10.4618 1.66656 10.06C1.66656 9.65811 1.8262 9.27273 2.11034 8.98858C2.39449 8.70444 2.77987 8.5448 3.18172 8.5448H3.2499C3.50065 8.53894 3.74384 8.45777 3.94785 8.31186C4.15186 8.16594 4.30726 7.96203 4.39384 7.72662C4.49468 7.49813 4.52476 7.24466 4.4802 6.9989C4.43565 6.75315 4.31849 6.52638 4.14384 6.34783L4.09838 6.30238C3.95751 6.16166 3.84575 5.99456 3.7695 5.81062C3.69326 5.62669 3.65401 5.42952 3.65401 5.23041C3.65401 5.0313 3.69326 4.83413 3.7695 4.6502C3.84575 4.46626 3.95751 4.29916 4.09838 4.15844C4.2391 4.01757 4.4062 3.90581 4.59014 3.82956C4.77408 3.75331 4.97124 3.71407 5.17035 3.71407C5.36947 3.71407 5.56663 3.75331 5.75057 3.82956C5.9345 3.90581 6.10161 4.01757 6.24232 4.15844L6.28778 4.20389C6.46632 4.37854 6.69309 4.4957 6.93885 4.54026C7.1846 4.58482 7.43807 4.55474 7.66657 4.45389H7.72717C7.95124 4.35786 8.14234 4.19841 8.27694 3.99516C8.41154 3.79191 8.48377 3.55373 8.48475 3.30996V3.18117C8.48475 2.77932 8.64438 2.39394 8.92852 2.10979C9.21267 1.82565 9.59806 1.66602 9.9999 1.66602C10.4017 1.66602 10.7871 1.82565 11.0713 2.10979C11.3554 2.39394 11.5151 2.77932 11.5151 3.18117V3.24935C11.516 3.49313 11.5883 3.7313 11.7229 3.93455C11.8575 4.1378 12.0486 4.29726 12.2726 4.39329C12.5011 4.49413 12.7546 4.52422 13.0003 4.47966C13.2461 4.4351 13.4729 4.31794 13.6514 4.14329L13.6969 4.09783C13.8376 3.95696 14.0047 3.8452 14.1886 3.76896C14.3726 3.69271 14.5697 3.65346 14.7688 3.65346C14.968 3.65346 15.1651 3.69271 15.3491 3.76896C15.533 3.8452 15.7001 3.95696 15.8408 4.09783C15.9817 4.23855 16.0934 4.40565 16.1697 4.58959C16.2459 4.77353 16.2852 4.97069 16.2852 5.1698C16.2852 5.36892 16.2459 5.56608 16.1697 5.75002C16.0934 5.93395 15.9817 6.10106 15.8408 6.24177L15.7954 6.28723C15.6207 6.46577 15.5035 6.69254 15.459 6.9383C15.4144 7.18405 15.4445 7.43752 15.5454 7.66602V7.72662C15.6414 7.95069 15.8008 8.14179 16.0041 8.27639C16.2073 8.41099 16.4455 8.48323 16.6893 8.4842H16.8181C17.2199 8.4842 17.6053 8.64383 17.8895 8.92798C18.1736 9.21212 18.3332 9.59751 18.3332 9.99935C18.3332 10.4012 18.1736 10.7866 17.8895 11.0707C17.6053 11.3549 17.2199 11.5145 16.8181 11.5145H16.7499C16.5061 11.5155 16.2679 11.5877 16.0647 11.7223C15.8614 11.8569 15.702 12.048 15.606 12.2721Z",stroke:"white",strokeLinecap:"round",strokeLinejoin:"round"})]}),rh=n=>e.jsx(t.Icon,{width:"0.875rem",height:"0.875rem",viewBox:"0 0 14 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n,children:e.jsx("path",{d:"M9.91666 4.08398L4.08333 9.91732M4.08333 4.08398L9.91666 9.91732",stroke:"white","stroke-linecap":"round","stroke-linejoin":"round"})});function ih(r){const{appName:i,onClose:s}=r,o=n.useContext($o),a=o?.toggleState,c=o?.setToggleState??(()=>{}),u=()=>{c("chat"===a?void 0:"chat")},l=()=>{c("settings"===a?void 0:"settings")},h=()=>{c("image"===a?void 0:"image")},d=[{id:3,icon:e.jsx(Ko,{}),onClick:h,active:"image"===a},{id:1,icon:e.jsx(th,{}),onClick:u,active:"chat"===a},{id:2,icon:e.jsx(nh,{}),onClick:l,active:"settings"===a},{id:3,icon:e.jsx(rh,{}),onClick:s,active:!1}],f=({children:n,active:r,onClick:i})=>e.jsx(t.Box,{cursor:"pointer",_hover:{bg:r?Xo:Yo},_active:{bg:Xo},bg:r?Xo:"",p:".94rem 1rem",onClick:i,children:n});return n.useEffect((()=>{const e=e=>{if(!(e.target instanceof HTMLElement)||"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName)switch(e.key){case"c":u();break;case"i":h();break;case"s":l()}};return window.addEventListener("keydown",e),()=>{window.removeEventListener("keydown",e)}}),[a]),e.jsxs(t.Flex,{align:"center",w:"100%",bg:Jo,borderBottom:".0625rem solid",borderColor:Yo,position:"absolute",left:"0",justify:"space-between",top:"0",zIndex:ea,children:[e.jsx(e.Fragment,{children:e.jsxs(t.HStack,{spacing:".75rem",position:"absolute",left:"50%",transform:"translate(-50% , 0%)",children:[e.jsx(eh,{boxSize:8}),e.jsxs(t.Text,{color:Zo,fontSize:"0.9rem",children:["Feedback - ",i]})]})}),e.jsx(t.Box,{ml:"auto",px:"50px",children:e.jsx(t.HStack,{children:d.map((({id:t,icon:r,onClick:i,active:s})=>e.jsx(n.Fragment,{children:e.jsx(f,{onClick:i,active:s,children:r})},t)))})})]})}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class sh{constructor(e,t){this._delegate=e,this.firebase=t,Uc(e,new sc("app-compat",(()=>this),"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise((e=>{this._delegate.checkDestroyed(),e()})).then((()=>(this.firebase.INTERNAL.removeApp(this.name),Kc(this._delegate))))}_getService(e,t=Fc){var n;this._delegate.checkDestroyed();const r=this._delegate.container.getProvider(e);return r.isInitialized()||"EXPLICIT"!==(null===(n=r.getComponent())||void 0===n?void 0:n.instantiationMode)||r.initialize(),r.getImmediate({identifier:t})}_removeServiceInstance(e,t=Fc){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){Uc(this._delegate,e)}_addOrOverwriteComponent(e){Bc(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const oh=new Ma("app-compat","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."});const ah=
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function e(){const t=
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function(e){const t={},n={__esModule:!0,initializeApp:function(r,i={}){const s=Gc(r,i);if(Va(t,s.name))return t[s.name];const o=new e(s,n);return t[s.name]=o,o},app:r,registerVersion:Yc,setLogLevel:Xc,onLog:Jc,apps:null,SDK_VERSION:Hc,INTERNAL:{registerComponent:function(t){const i=t.name,s=i.replace("-compat","");if(zc(t)&&"PUBLIC"===t.type){const o=(e=r())=>{if("function"!=typeof e[s])throw oh.create("invalid-app-argument",{appName:i});return e[s]()};void 0!==t.serviceProps&&wa(o,t.serviceProps),n[s]=o,e.prototype[s]=function(...e){return this._getService.bind(this,i).apply(this,t.multipleInstances?e:[])}}return"PUBLIC"===t.type?n[s]:null},removeApp:function(e){delete t[e]},useAsService:function(e,t){if("serverAuth"===t)return null;return t},modularAPIs:hu}};function r(e){if(!Va(t,e=e||Fc))throw oh.create("no-app",{appName:e});return t[e]}return n.default=n,Object.defineProperty(n,"apps",{get:function(){return Object.keys(t).map((e=>t[e]))}}),r.App=e,n}(sh);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){wa(t,e)},createSubscribe:Ya,ErrorFactory:Ma,deepExtend:wa}),t}(),ch=new mc("@firebase/app-compat");
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
if("object"==typeof self&&self.self===self&&void 0!==self.firebase){ch.warn("\n    Warning: Firebase is already defined in the global scope. Please make sure\n    Firebase library is only loaded once.\n  ");const e=self.firebase.SDK_VERSION;e&&e.indexOf("LITE")>=0&&ch.warn("\n    Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n    You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n    ")}const uh=ah;!
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function(e){Yc("@firebase/app-compat","0.2.13",e)}();
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
uh.registerVersion("firebase","9.23.0","app-compat");var lh,hh="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==h?h:"undefined"!=typeof self?self:{},dh=dh||{},fh=hh||self;function ph(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 mh(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var gh="closure_uid_"+(1e9*Math.random()>>>0),yh=0;function vh(e,t,n){return e.call.apply(e.bind,arguments)}function _h(e,t,n){if(!e)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var n=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(n,r),e.apply(t,n)}}return function(){return e.apply(t,arguments)}}function wh(e,t,n){return(wh=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?vh:_h).apply(null,arguments)}function bh(e,t){var n=Array.prototype.slice.call(arguments,1);return function(){var t=n.slice();return t.push.apply(t,arguments),e.apply(this,t)}}function Ih(e,t){function n(){}n.prototype=t.prototype,e.$=t.prototype,e.prototype=new n,e.prototype.constructor=e,e.ac=function(e,n,r){for(var i=Array(arguments.length-2),s=2;s<arguments.length;s++)i[s-2]=arguments[s];return t.prototype[n].apply(e,i)}}function Eh(){this.s=this.s,this.o=this.o}Eh.prototype.s=!1,Eh.prototype.sa=function(){var e;!this.s&&(this.s=!0,this.N(),0)&&(e=this,Object.prototype.hasOwnProperty.call(e,gh)&&e[gh]||(e[gh]=++yh))},Eh.prototype.N=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const Th=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if("string"==typeof e)return"string"!=typeof t||1!=t.length?-1:e.indexOf(t,0);for(let n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1};function Sh(e){const t=e.length;if(0<t){const n=Array(t);for(let r=0;r<t;r++)n[r]=e[r];return n}return[]}function kh(e,t){for(let t=1;t<arguments.length;t++){const n=arguments[t];if(ph(n)){const t=e.length||0,r=n.length||0;e.length=t+r;for(let i=0;i<r;i++)e[t+i]=n[i]}else e.push(n)}}function Ch(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}Ch.prototype.h=function(){this.defaultPrevented=!0};var xh=function(){if(!fh.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{fh.addEventListener("test",(()=>{}),t),fh.removeEventListener("test",(()=>{}),t)}catch(e){}return e}();function Ah(e){return/^[\s\xa0]*$/.test(e)}function Nh(){var e=fh.navigator;return e&&(e=e.userAgent)?e:""}function Dh(e){return-1!=Nh().indexOf(e)}function Rh(e){return Rh[" "](e),e}Rh[" "]=function(){};var Oh,Ph,Mh,Lh=Dh("Opera"),Fh=Dh("Trident")||Dh("MSIE"),jh=Dh("Edge"),qh=jh||Fh,Vh=Dh("Gecko")&&!(-1!=Nh().toLowerCase().indexOf("webkit")&&!Dh("Edge"))&&!(Dh("Trident")||Dh("MSIE"))&&!Dh("Edge"),Uh=-1!=Nh().toLowerCase().indexOf("webkit")&&!Dh("Edge");function Bh(){var e=fh.document;return e?e.documentMode:void 0}e:{var zh="",$h=(Ph=Nh(),Vh?/rv:([^\);]+)(\)|;)/.exec(Ph):jh?/Edge\/([\d\.]+)/.exec(Ph):Fh?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(Ph):Uh?/WebKit\/(\S+)/.exec(Ph):Lh?/(?:Version)[ \/]?(\S+)/.exec(Ph):void 0);if($h&&(zh=$h?$h[1]:""),Fh){var Wh=Bh();if(null!=Wh&&Wh>parseFloat(zh)){Oh=String(Wh);break e}}Oh=zh}if(fh.document&&Fh){var Qh=Bh();Mh=Qh||(parseInt(Oh,10)||void 0)}else Mh=void 0;var Hh=Mh;function Gh(e,t){if(Ch.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(Vh){e:{try{Rh(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:Kh[e.pointerType]||"",this.state=e.state,this.i=e,e.defaultPrevented&&Gh.$.h.call(this)}}Ih(Gh,Ch);var Kh={2:"touch",3:"pen",4:"mouse"};Gh.prototype.h=function(){Gh.$.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var Yh="closure_listenable_"+(1e6*Math.random()|0),Jh=0;function Xh(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.la=i,this.key=++Jh,this.fa=this.ia=!1}function Zh(e){e.fa=!0,e.listener=null,e.proxy=null,e.src=null,e.la=null}function ed(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function td(e){const t={};for(const n in e)t[n]=e[n];return t}const nd="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function rd(e,t){let n,r;for(let t=1;t<arguments.length;t++){for(n in r=arguments[t],r)e[n]=r[n];for(let t=0;t<nd.length;t++)n=nd[t],Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}}function id(e){this.src=e,this.g={},this.h=0}function sd(e,t){var n=t.type;if(n in e.g){var r,i=e.g[n],s=Th(i,t);(r=0<=s)&&Array.prototype.splice.call(i,s,1),r&&(Zh(t),0==e.g[n].length&&(delete e.g[n],e.h--))}}function od(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.fa&&s.listener==t&&s.capture==!!n&&s.la==r)return i}return-1}id.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var o=od(e,t,r,i);return-1<o?(t=e[o],n||(t.ia=!1)):((t=new Xh(t,this.src,s,!!r,i)).ia=n,e.push(t)),t};var ad="closure_lm_"+(1e6*Math.random()|0),cd={};function ud(e,t,n,r,i){if(r&&r.once)return hd(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)ud(e,t[s],n,r,i);return null}return n=vd(n),e&&e[Yh]?e.O(t,n,mh(r)?!!r.capture:!!r,i):ld(e,t,n,!1,r,i)}function ld(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var o=mh(i)?!!i.capture:!!i,a=gd(e);if(a||(e[ad]=a=new id(e)),(n=a.add(t,n,r,o,s)).proxy)return n;if(r=function(){function e(n){return t.call(e.src,e.listener,n)}const t=md;return e}(),n.proxy=r,r.src=e,r.listener=n,e.addEventListener)xh||(i=o),void 0===i&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(pd(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function hd(e,t,n,r,i){if(Array.isArray(t)){for(var s=0;s<t.length;s++)hd(e,t[s],n,r,i);return null}return n=vd(n),e&&e[Yh]?e.P(t,n,mh(r)?!!r.capture:!!r,i):ld(e,t,n,!0,r,i)}function dd(e,t,n,r,i){if(Array.isArray(t))for(var s=0;s<t.length;s++)dd(e,t[s],n,r,i);else r=mh(r)?!!r.capture:!!r,n=vd(n),e&&e[Yh]?(e=e.i,(t=String(t).toString())in e.g&&(-1<(n=od(s=e.g[t],n,r,i))&&(Zh(s[n]),Array.prototype.splice.call(s,n,1),0==s.length&&(delete e.g[t],e.h--)))):e&&(e=gd(e))&&(t=e.g[t.toString()],e=-1,t&&(e=od(t,n,r,i)),(n=-1<e?t[e]:null)&&fd(n))}function fd(e){if("number"!=typeof e&&e&&!e.fa){var t=e.src;if(t&&t[Yh])sd(t.i,e);else{var n=e.type,r=e.proxy;t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(pd(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=gd(t))?(sd(n,e),0==n.h&&(n.src=null,t[ad]=null)):Zh(e)}}}function pd(e){return e in cd?cd[e]:cd[e]="on"+e}function md(e,t){if(e.fa)e=!0;else{t=new Gh(t,this);var n=e.listener,r=e.la||e.src;e.ia&&fd(e),e=n.call(r,t)}return e}function gd(e){return(e=e[ad])instanceof id?e:null}var yd="__closure_events_fn_"+(1e9*Math.random()>>>0);function vd(e){return"function"==typeof e?e:(e[yd]||(e[yd]=function(t){return e.handleEvent(t)}),e[yd])}function _d(){Eh.call(this),this.i=new id(this),this.S=this,this.J=null}function wd(e,t){var n,r=e.J;if(r)for(n=[];r;r=r.J)n.push(r);if(e=e.S,r=t.type||t,"string"==typeof t)t=new Ch(t,e);else if(t instanceof Ch)t.target=t.target||e;else{var i=t;rd(t=new Ch(r,e),i)}if(i=!0,n)for(var s=n.length-1;0<=s;s--){var o=t.g=n[s];i=bd(o,r,!0,t)&&i}if(i=bd(o=t.g=e,r,!0,t)&&i,i=bd(o,r,!1,t)&&i,n)for(s=0;s<n.length;s++)i=bd(o=t.g=n[s],r,!1,t)&&i}function bd(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var o=t[s];if(o&&!o.fa&&o.capture==n){var a=o.listener,c=o.la||o.src;o.ia&&sd(e.i,o),i=!1!==a.call(c,r)&&i}}return i&&!r.defaultPrevented}Ih(_d,Eh),_d.prototype[Yh]=!0,_d.prototype.removeEventListener=function(e,t,n,r){dd(this,e,t,n,r)},_d.prototype.N=function(){if(_d.$.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)Zh(n[r]);delete t.g[e],t.h--}}this.J=null},_d.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},_d.prototype.P=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var Id=fh.JSON.stringify;function Ed(){var e=Nd;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}var Td=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 Sd),(e=>e.reset()));class Sd{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 kd(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}function Cd(e){fh.setTimeout((()=>{throw e}),0)}let xd,Ad=!1,Nd=new class{constructor(){this.h=this.g=null}add(e,t){const n=Td.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},Dd=()=>{const e=fh.Promise.resolve(void 0);xd=()=>{e.then(Rd)}};var Rd=()=>{for(var e;e=Ed();){try{e.h.call(e.g)}catch(e){Cd(e)}var t=Td;t.j(e),100>t.h&&(t.h++,e.next=t.g,t.g=e)}Ad=!1};function Od(e,t){_d.call(this),this.h=e||1,this.g=t||fh,this.j=wh(this.qb,this),this.l=Date.now()}function Pd(e){e.ga=!1,e.T&&(e.g.clearTimeout(e.T),e.T=null)}function Md(e,t,n){if("function"==typeof e)n&&(e=wh(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=wh(e.handleEvent,e)}return 2147483647<Number(t)?-1:fh.setTimeout(e,t||0)}function Ld(e){e.g=Md((()=>{e.g=null,e.i&&(e.i=!1,Ld(e))}),e.j);const t=e.h;e.h=null,e.m.apply(null,t)}Ih(Od,_d),(lh=Od.prototype).ga=!1,lh.T=null,lh.qb=function(){if(this.ga){var e=Date.now()-this.l;0<e&&e<.8*this.h?this.T=this.g.setTimeout(this.j,this.h-e):(this.T&&(this.g.clearTimeout(this.T),this.T=null),wd(this,"tick"),this.ga&&(Pd(this),this.start()))}},lh.start=function(){this.ga=!0,this.T||(this.T=this.g.setTimeout(this.j,this.h),this.l=Date.now())},lh.N=function(){Od.$.N.call(this),Pd(this),delete this.g};class Fd extends Eh{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:Ld(this)}N(){super.N(),this.g&&(fh.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function jd(e){Eh.call(this),this.h=e,this.g={}}Ih(jd,Eh);var qd=[];function Vd(e,t,n,r){Array.isArray(n)||(n&&(qd[0]=n.toString()),n=qd);for(var i=0;i<n.length;i++){var s=ud(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function Ud(e){ed(e.g,(function(e,t){this.g.hasOwnProperty(t)&&fd(e)}),e),e.g={}}function Bd(){this.g=!0}function zd(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(!(2>r.length)){var i=r[1];if(Array.isArray(i)&&!(1>i.length)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var o=1;o<i.length;o++)i[o]=""}}}return Id(n)}catch(e){return t}}(e,n)+(r?" "+r:"")}))}jd.prototype.N=function(){jd.$.N.call(this),Ud(this)},jd.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},Bd.prototype.Ea=function(){this.g=!1},Bd.prototype.info=function(){};var $d={},Wd=null;function Qd(){return Wd=Wd||new _d}function Hd(e){Ch.call(this,$d.Ta,e)}function Gd(e){const t=Qd();wd(t,new Hd(t))}function Kd(e,t){Ch.call(this,$d.STAT_EVENT,e),this.stat=t}function Yd(e){const t=Qd();wd(t,new Kd(t,e))}function Jd(e,t){Ch.call(this,$d.Ua,e),this.size=t}function Xd(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return fh.setTimeout((function(){e()}),t)}$d.Ta="serverreachability",Ih(Hd,Ch),$d.STAT_EVENT="statevent",Ih(Kd,Ch),$d.Ua="timingevent",Ih(Jd,Ch);var Zd={NO_ERROR:0,rb:1,Eb:2,Db:3,yb:4,Cb:5,Fb:6,Qa:7,TIMEOUT:8,Ib:9},ef={wb:"complete",Sb:"success",Ra:"error",Qa:"abort",Kb:"ready",Lb:"readystatechange",TIMEOUT:"timeout",Gb:"incrementaldata",Jb:"progress",zb:"downloadprogress",$b:"uploadprogress"};function tf(){}function nf(e){return e.h||(e.h=e.i())}function rf(){}tf.prototype.h=null;var sf,of={OPEN:"a",vb:"b",Ra:"c",Hb:"d"};function af(){Ch.call(this,"d")}function cf(){Ch.call(this,"c")}function uf(){}function lf(e,t,n,r){this.l=e,this.j=t,this.m=n,this.W=r||1,this.U=new jd(this),this.P=df,e=qh?125:void 0,this.V=new Od(e),this.I=null,this.i=!1,this.s=this.A=this.v=this.L=this.G=this.Y=this.B=null,this.F=[],this.g=null,this.C=0,this.o=this.u=null,this.ca=-1,this.J=!1,this.O=0,this.M=null,this.ba=this.K=this.aa=this.S=!1,this.h=new hf}function hf(){this.i=null,this.g="",this.h=!1}Ih(af,Ch),Ih(cf,Ch),Ih(uf,tf),uf.prototype.g=function(){return new XMLHttpRequest},uf.prototype.i=function(){return{}},sf=new uf;var df=45e3,ff={},pf={};function mf(e,t,n){e.L=1,e.v=Pf(Af(t)),e.s=n,e.S=!0,gf(e,null)}function gf(e,t){e.G=Date.now(),wf(e),e.A=Af(e.v);var n=e.A,r=e.W;Array.isArray(r)||(r=[String(r)]),Hf(n.i,"t",r),e.C=0,n=e.l.J,e.h=new hf,e.g=Qp(e.l,n?t:null,!e.s),0<e.O&&(e.M=new Fd(wh(e.Pa,e,e.g),e.O)),Vd(e.U,e.g,"readystatechange",e.nb),t=e.I?td(e.I):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ha(e.A,e.u,e.s,t)):(e.u="GET",e.g.ha(e.A,e.u,null,t)),Gd(),function(e,t,n,r,i,s){e.info((function(){if(e.g)if(s)for(var o="",a=s.split("&"),c=0;c<a.length;c++){var u=a[c].split("=");if(1<u.length){var l=u[0];u=u[1];var h=l.split("_");o=2<=h.length&&"type"==h[1]?o+(l+"=")+u+"&":o+(l+"=redacted&")}}else o=null;else o=s;return"XMLHTTP REQ ("+r+") [attempt "+i+"]: "+t+"\n"+n+"\n"+o}))}(e.j,e.u,e.A,e.m,e.W,e.s)}function yf(e){return!!e.g&&("GET"==e.u&&2!=e.L&&e.l.Ha)}function vf(e,t,n){let r,i=!0;for(;!e.J&&e.C<n.length;){if(r=_f(e,n),r==pf){4==t&&(e.o=4,Yd(14),i=!1),zd(e.j,e.m,null,"[Incomplete Response]");break}if(r==ff){e.o=4,Yd(15),zd(e.j,e.m,n,"[Invalid Chunk]"),i=!1;break}zd(e.j,e.m,r,null),Sf(e,r)}yf(e)&&r!=pf&&r!=ff&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,Yd(16),i=!1),e.i=e.i&&i,i?0<n.length&&!e.ba&&(e.ba=!0,(t=e.l).g==e&&t.ca&&!t.M&&(t.l.info("Great, no buffering proxy detected. Bytes received: "+n.length),jp(t),t.M=!0,Yd(11))):(zd(e.j,e.m,n,"[Invalid Chunked Response]"),Tf(e),Ef(e))}function _f(e,t){var n=e.C,r=t.indexOf("\n",n);return-1==r?pf:(n=Number(t.substring(n,r)),isNaN(n)?ff:(r+=1)+n>t.length?pf:(t=t.slice(r,r+n),e.C=r+n,t))}function wf(e){e.Y=Date.now()+e.P,bf(e,e.P)}function bf(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=Xd(wh(e.lb,e),t)}function If(e){e.B&&(fh.clearTimeout(e.B),e.B=null)}function Ef(e){0==e.l.H||e.J||Up(e.l,e)}function Tf(e){If(e);var t=e.M;t&&"function"==typeof t.sa&&t.sa(),e.M=null,Pd(e.V),Ud(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.sa())}function Sf(e,t){try{var n=e.l;if(0!=n.H&&(n.g==e||Zf(n.i,e)))if(!e.K&&Zf(n.i,e)&&3==n.H){try{var r=n.Ja.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.G+3e3<e.G))break e;Vp(n),Np(n)}Fp(n),Yd(18)}}else n.Fa=i[1],0<n.Fa-n.V&&37500>i[2]&&n.G&&0==n.A&&!n.v&&(n.v=Xd(wh(n.ib,n),6e3));if(1>=Xf(n.i)&&n.oa){try{n.oa()}catch(e){}n.oa=void 0}}else zp(n,11)}else if((e.K||n.g==e)&&Vp(n),!Ah(t))for(i=n.Ja.g.parse(t),t=0;t<i.length;t++){let u=i[t];if(n.V=u[0],u=u[1],2==n.H)if("c"==u[0]){n.K=u[1],n.pa=u[2];const t=u[3];null!=t&&(n.ra=t,n.l.info("VER="+n.ra));const i=u[4];null!=i&&(n.Ga=i,n.l.info("SVER="+n.Ga));const l=u[5];null!=l&&"number"==typeof l&&0<l&&(r=1.5*l,n.L=r,n.l.info("backChannelRequestTimeoutMs_="+r)),r=n;const h=e.g;if(h){const e=h.g?h.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(e){var s=r.i;s.g||-1==e.indexOf("spdy")&&-1==e.indexOf("quic")&&-1==e.indexOf("h2")||(s.j=s.l,s.g=new Set,s.h&&(ep(s,s.h),s.h=null))}if(r.F){const e=h.g?h.g.getResponseHeader("X-HTTP-Session-Id"):null;e&&(r.Da=e,Of(r.I,r.F,e))}}n.H=3,n.h&&n.h.Ba(),n.ca&&(n.S=Date.now()-e.G,n.l.info("Handshake RTT: "+n.S+"ms"));var o=e;if((r=n).wa=Wp(r,r.J?r.pa:null,r.Y),o.K){tp(r.i,o);var a=o,c=r.L;c&&a.setTimeout(c),a.B&&(If(a),wf(a)),r.g=o}else Lp(r);0<n.j.length&&Rp(n)}else"stop"!=u[0]&&"close"!=u[0]||zp(n,7);else 3==n.H&&("stop"==u[0]||"close"==u[0]?"stop"==u[0]?zp(n,7):Ap(n):"noop"!=u[0]&&n.h&&n.h.Aa(u),n.A=0)}Gd()}catch(e){}}function kf(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(ph(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.ta&&"function"==typeof e.ta)return e.ta();if(!e.Z||"function"!=typeof e.Z){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(ph(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.Z&&"function"==typeof e.Z)return e.Z();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(ph(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}(lh=lf.prototype).setTimeout=function(e){this.P=e},lh.nb=function(e){e=e.target;const t=this.M;t&&3==Ep(e)?t.l():this.Pa(e)},lh.Pa=function(e){try{if(e==this.g)e:{const l=Ep(this.g);var t=this.g.Ia();this.g.da();if(!(3>l)&&(3!=l||qh||this.g&&(this.h.h||this.g.ja()||Tp(this.g)))){this.J||4!=l||7==t||Gd(),If(this);var n=this.g.da();this.ca=n;t:if(yf(this)){var r=Tp(this.g);e="";var i=r.length,s=4==Ep(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){Tf(this),Ef(this);var o="";break t}this.h.i=new fh.TextDecoder}for(t=0;t<i;t++)this.h.h=!0,e+=this.h.i.decode(r[t],{stream:s&&t==i-1});r.splice(0,i),this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.ja();if(this.i=200==n,function(e,t,n,r,i,s,o){e.info((function(){return"XMLHTTP RESP ("+r+") [ attempt "+i+"]: "+t+"\n"+n+"\n"+s+" "+o}))}(this.j,this.u,this.A,this.m,this.W,l,n),this.i){if(this.aa&&!this.K){t:{if(this.g){var a,c=this.g;if((a=c.g?c.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!Ah(a)){var u=a;break t}}u=null}if(!(n=u)){this.i=!1,this.o=3,Yd(12),Tf(this),Ef(this);break e}zd(this.j,this.m,n,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Sf(this,n)}this.S?(vf(this,l,o),qh&&this.i&&3==l&&(Vd(this.U,this.V,"tick",this.mb),this.V.start())):(zd(this.j,this.m,o,null),Sf(this,o)),4==l&&Tf(this),this.i&&!this.J&&(4==l?Up(this.l,this):(this.i=!1,wf(this)))}else(function(e){const t={};e=(e.g&&2<=Ep(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let r=0;r<e.length;r++){if(Ah(e[r]))continue;var n=kd(e[r]);const i=n[0];if("string"!=typeof(n=n[1]))continue;n=n.trim();const s=t[i]||[];t[i]=s,s.push(n)}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,(function(e){return e.join(", ")}))})(this.g),400==n&&0<o.indexOf("Unknown SID")?(this.o=3,Yd(12)):(this.o=0,Yd(13)),Tf(this),Ef(this)}}}catch(e){}},lh.mb=function(){if(this.g){var e=Ep(this.g),t=this.g.ja();this.C<t.length&&(If(this),vf(this,e,t),this.i&&4!=e&&wf(this))}},lh.cancel=function(){this.J=!0,Tf(this)},lh.lb=function(){this.B=null;const e=Date.now();0<=e-this.Y?(function(e,t){e.info((function(){return"TIMEOUT: "+t}))}(this.j,this.A),2!=this.L&&(Gd(),Yd(17)),Tf(this),this.o=2,Ef(this)):bf(this,this.Y-e)};var Cf=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function xf(e){if(this.g=this.s=this.j="",this.m=null,this.o=this.l="",this.h=!1,e instanceof xf){this.h=e.h,Nf(this,e.j),this.s=e.s,this.g=e.g,Df(this,e.m),this.l=e.l;var t=e.i,n=new zf;n.i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),Rf(this,n),this.o=e.o}else e&&(t=String(e).match(Cf))?(this.h=!1,Nf(this,t[1]||"",!0),this.s=Mf(t[2]||""),this.g=Mf(t[3]||"",!0),Df(this,t[4]),this.l=Mf(t[5]||"",!0),Rf(this,t[6]||"",!0),this.o=Mf(t[7]||"")):(this.h=!1,this.i=new zf(null,this.h))}function Af(e){return new xf(e)}function Nf(e,t,n){e.j=n?Mf(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Df(e,t){if(t){if(t=Number(t),isNaN(t)||0>t)throw Error("Bad port number "+t);e.m=t}else e.m=null}function Rf(e,t,n){t instanceof zf?(e.i=t,function(e,t){t&&!e.j&&($f(e),e.i=null,e.g.forEach((function(e,t){var n=t.toLowerCase();t!=n&&(Wf(this,t),Hf(this,n,e))}),e)),e.j=t}(e.i,e.h)):(n||(t=Lf(t,Uf)),e.i=new zf(t,e.h))}function Of(e,t,n){e.i.set(t,n)}function Pf(e){return Of(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Mf(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Lf(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,Ff),n&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function Ff(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}xf.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Lf(t,jf,!0),":");var n=this.g;return(n||"file"==t)&&(e.push("//"),(t=this.s)&&e.push(Lf(t,jf,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(Lf(n,"/"==n.charAt(0)?Vf:qf,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Lf(n,Bf)),e.join("")};var jf=/[#\/\?@]/g,qf=/[#\?:]/g,Vf=/[#\?]/g,Uf=/[#\?@]/g,Bf=/#/g;function zf(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function $f(e){e.g||(e.g=new Map,e.h=0,e.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r=e[n].indexOf("="),i=null;if(0<=r){var s=e[n].substring(0,r);i=e[n].substring(r+1)}else s=e[n];t(s,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(e.i,(function(t,n){e.add(decodeURIComponent(t.replace(/\+/g," ")),n)})))}function Wf(e,t){$f(e),t=Gf(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function Qf(e,t){return $f(e),t=Gf(e,t),e.g.has(t)}function Hf(e,t,n){Wf(e,t),0<n.length&&(e.i=null,e.g.set(Gf(e,t),Sh(n)),e.h+=n.length)}function Gf(e,t){return t=String(t),e.j&&(t=t.toLowerCase()),t}(lh=zf.prototype).add=function(e,t){$f(this),this.i=null,e=Gf(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},lh.forEach=function(e,t){$f(this),this.g.forEach((function(n,r){n.forEach((function(n){e.call(t,n,r,this)}),this)}),this)},lh.ta=function(){$f(this);const e=Array.from(this.g.values()),t=Array.from(this.g.keys()),n=[];for(let r=0;r<t.length;r++){const i=e[r];for(let e=0;e<i.length;e++)n.push(t[r])}return n},lh.Z=function(e){$f(this);let t=[];if("string"==typeof e)Qf(this,e)&&(t=t.concat(this.g.get(Gf(this,e))));else{e=Array.from(this.g.values());for(let n=0;n<e.length;n++)t=t.concat(e[n])}return t},lh.set=function(e,t){return $f(this),this.i=null,Qf(this,e=Gf(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},lh.get=function(e,t){return e&&0<(e=this.Z(e)).length?String(e[0]):t},lh.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++){var r=t[n];const s=encodeURIComponent(String(r)),o=this.Z(r);for(r=0;r<o.length;r++){var i=s;""!==o[r]&&(i+="="+encodeURIComponent(String(o[r]))),e.push(i)}}return this.i=e.join("&")};function Kf(e){this.l=e||Yf,fh.PerformanceNavigationTiming?e=0<(e=fh.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):e=!!(fh.g&&fh.g.Ka&&fh.g.Ka()&&fh.g.Ka().ec),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}var Yf=10;function Jf(e){return!!e.h||!!e.g&&e.g.size>=e.j}function Xf(e){return e.h?1:e.g?e.g.size:0}function Zf(e,t){return e.h?e.h==t:!!e.g&&e.g.has(t)}function ep(e,t){e.g?e.g.add(t):e.h=t}function tp(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function np(e){if(null!=e.h)return e.i.concat(e.h.F);if(null!=e.g&&0!==e.g.size){let t=e.i;for(const n of e.g.values())t=t.concat(n.F);return t}return Sh(e.i)}Kf.prototype.cancel=function(){if(this.i=np(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}};var rp=class{stringify(e){return fh.JSON.stringify(e,void 0)}parse(e){return fh.JSON.parse(e,void 0)}};function ip(){this.g=new rp}function sp(e,t,n){const r=n||"";try{kf(e,(function(e,n){let i=e;mh(e)&&(i=Id(e)),t.push(r+n+"="+encodeURIComponent(i))}))}catch(e){throw t.push(r+"type="+encodeURIComponent("_badmap")),e}}function op(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function ap(e){this.l=e.fc||null,this.j=e.ob||!1}function cp(e,t){_d.call(this),this.F=e,this.u=t,this.m=void 0,this.readyState=up,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}Ih(ap,tf),ap.prototype.g=function(){return new cp(this.l,this.j)},ap.prototype.i=function(e){return function(){return e}}({}),Ih(cp,_d);var up=0;function lp(e){e.j.read().then(e.Xa.bind(e)).catch(e.ka.bind(e))}function hp(e){e.readyState=4,e.l=null,e.j=null,e.A=null,dp(e)}function dp(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(lh=cp.prototype).open=function(e,t){if(this.readyState!=up)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,dp(this)},lh.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.F||fh).fetch(new Request(this.B,t)).then(this.$a.bind(this),this.ka.bind(this))},lh.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch((()=>{})),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,hp(this)),this.readyState=up},lh.$a=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,dp(this)),this.g&&(this.readyState=3,dp(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ya.bind(this),this.ka.bind(this));else if(void 0!==fh.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;lp(this)}else e.text().then(this.Za.bind(this),this.ka.bind(this))},lh.Xa=function(e){if(this.g){if(this.u&&e.value)this.response.push(e.value);else if(!this.u){var t=e.value?e.value:new Uint8Array(0);(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)}e.done?hp(this):dp(this),3==this.readyState&&lp(this)}},lh.Za=function(e){this.g&&(this.response=this.responseText=e,hp(this))},lh.Ya=function(e){this.g&&(this.response=e,hp(this))},lh.ka=function(){this.g&&hp(this)},lh.setRequestHeader=function(e,t){this.v.append(e,t)},lh.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},lh.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(cp.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var fp=fh.JSON.parse;function pp(e){_d.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.I="",this.m=0,this.j="",this.l=this.G=this.v=this.F=!1,this.B=0,this.A=null,this.K=mp,this.L=this.M=!1}Ih(pp,_d);var mp="",gp=/^https?$/i,yp=["POST","PUT"];function vp(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,_p(e),bp(e)}function _p(e){e.F||(e.F=!0,wd(e,"complete"),wd(e,"error"))}function wp(e){if(e.h&&void 0!==dh&&(!e.C[1]||4!=Ep(e)||2!=e.da()))if(e.v&&4==Ep(e))Md(e.La,0,e);else if(wd(e,"readystatechange"),4==Ep(e)){e.h=!1;try{const o=e.da();e:switch(o){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var t=!0;break e;default:t=!1}var n;if(!(n=t)){var r;if(r=0===o){var i=String(e.I).match(Cf)[1]||null;!i&&fh.self&&fh.self.location&&(i=fh.self.location.protocol.slice(0,-1)),r=!gp.test(i?i.toLowerCase():"")}n=r}if(n)wd(e,"complete"),wd(e,"success");else{e.m=6;try{var s=2<Ep(e)?e.g.statusText:""}catch(e){s=""}e.j=s+" ["+e.da()+"]",_p(e)}}finally{bp(e)}}}function bp(e,t){if(e.g){Ip(e);const n=e.g,r=e.C[0]?()=>{}:null;e.g=null,e.C=null,t||wd(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Ip(e){e.g&&e.L&&(e.g.ontimeout=null),e.A&&(fh.clearTimeout(e.A),e.A=null)}function Ep(e){return e.g?e.g.readyState:0}function Tp(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.K){case mp:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Sp(e){let t="";return ed(e,(function(e,n){t+=n,t+=":",t+=e,t+="\r\n"})),t}function kp(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=Sp(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):Of(e,t,n))}function Cp(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function xp(e){this.Ga=0,this.j=[],this.l=new Bd,this.pa=this.wa=this.I=this.Y=this.g=this.Da=this.F=this.na=this.o=this.U=this.s=null,this.fb=this.W=0,this.cb=Cp("failFast",!1,e),this.G=this.v=this.u=this.m=this.h=null,this.aa=!0,this.Fa=this.V=-1,this.ba=this.A=this.C=0,this.ab=Cp("baseRetryDelayMs",5e3,e),this.hb=Cp("retryDelaySeedMs",1e4,e),this.eb=Cp("forwardChannelMaxRetries",2,e),this.xa=Cp("forwardChannelRequestTimeoutMs",2e4,e),this.va=e&&e.xmlHttpFactory||void 0,this.Ha=e&&e.dc||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.i=new Kf(e&&e.concurrentRequestLimit),this.Ja=new ip,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.bb=e&&e.bc||!1,e&&e.Ea&&this.l.Ea(),e&&e.forceLongPolling&&(this.aa=!1),this.ca=!this.P&&this.aa&&e&&e.detectBufferingProxy||!1,this.qa=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.qa=e.longPollingTimeout),this.oa=void 0,this.S=0,this.M=!1,this.ma=this.B=null}function Ap(e){if(Dp(e),3==e.H){var t=e.W++,n=Af(e.I);if(Of(n,"SID",e.K),Of(n,"RID",t),Of(n,"TYPE","terminate"),Pp(e,n),(t=new lf(e,e.l,t)).L=2,t.v=Pf(Af(n)),n=!1,fh.navigator&&fh.navigator.sendBeacon)try{n=fh.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&fh.Image&&((new Image).src=t.v,n=!0),n||(t.g=Qp(t.l,null),t.g.ha(t.v)),t.G=Date.now(),wf(t)}$p(e)}function Np(e){e.g&&(jp(e),e.g.cancel(),e.g=null)}function Dp(e){Np(e),e.u&&(fh.clearTimeout(e.u),e.u=null),Vp(e),e.i.cancel(),e.m&&("number"==typeof e.m&&fh.clearTimeout(e.m),e.m=null)}function Rp(e){if(!Jf(e.i)&&!e.m){e.m=!0;var t=e.Na;xd||Dd(),Ad||(xd(),Ad=!0),Nd.add(t,e),e.C=0}}function Op(e,t){var n;n=t?t.m:e.W++;const r=Af(e.I);Of(r,"SID",e.K),Of(r,"RID",n),Of(r,"AID",e.V),Pp(e,r),e.o&&e.s&&kp(r,e.o,e.s),n=new lf(e,e.l,n,e.C+1),null===e.o&&(n.I=e.s),t&&(e.j=t.F.concat(e.j)),t=Mp(e,n,1e3),n.setTimeout(Math.round(.5*e.xa)+Math.round(.5*e.xa*Math.random())),ep(e.i,n),mf(n,r,t)}function Pp(e,t){e.na&&ed(e.na,(function(e,n){Of(t,n,e)})),e.h&&kf({},(function(e,n){Of(t,n,e)}))}function Mp(e,t,n){n=Math.min(e.j.length,n);var r=e.h?wh(e.h.Va,e.h,e):null;e:{var i=e.j;let t=-1;for(;;){const e=["count="+n];-1==t?0<n?(t=i[0].g,e.push("ofs="+t)):t=0:e.push("ofs="+t);let s=!0;for(let o=0;o<n;o++){let n=i[o].g;const a=i[o].map;if(n-=t,0>n)t=Math.max(0,i[o].g-100),s=!1;else try{sp(a,e,"req"+n+"_")}catch(e){r&&r(a)}}if(s){r=e.join("&");break e}}}return e=e.j.splice(0,n),t.F=e,r}function Lp(e){if(!e.g&&!e.u){e.ba=1;var t=e.Ma;xd||Dd(),Ad||(xd(),Ad=!0),Nd.add(t,e),e.A=0}}function Fp(e){return!(e.g||e.u||3<=e.A)&&(e.ba++,e.u=Xd(wh(e.Ma,e),Bp(e,e.A)),e.A++,!0)}function jp(e){null!=e.B&&(fh.clearTimeout(e.B),e.B=null)}function qp(e){e.g=new lf(e,e.l,"rpc",e.ba),null===e.o&&(e.g.I=e.s),e.g.O=0;var t=Af(e.wa);Of(t,"RID","rpc"),Of(t,"SID",e.K),Of(t,"AID",e.V),Of(t,"CI",e.G?"0":"1"),!e.G&&e.qa&&Of(t,"TO",e.qa),Of(t,"TYPE","xmlhttp"),Pp(e,t),e.o&&e.s&&kp(t,e.o,e.s),e.L&&e.g.setTimeout(e.L);var n=e.g;e=e.pa,n.L=1,n.v=Pf(Af(t)),n.s=null,n.S=!0,gf(n,e)}function Vp(e){null!=e.v&&(fh.clearTimeout(e.v),e.v=null)}function Up(e,t){var n=null;if(e.g==t){Vp(e),jp(e),e.g=null;var r=2}else{if(!Zf(e.i,t))return;n=t.F,tp(e.i,t),r=1}if(0!=e.H)if(t.i)if(1==r){n=t.s?t.s.length:0,t=Date.now()-t.G;var i=e.C;wd(r=Qd(),new Jd(r,n)),Rp(e)}else Lp(e);else if(3==(i=t.o)||0==i&&0<t.ca||!(1==r&&function(e,t){return!(Xf(e.i)>=e.i.j-(e.m?1:0)||(e.m?(e.j=t.F.concat(e.j),0):1==e.H||2==e.H||e.C>=(e.cb?0:e.eb)||(e.m=Xd(wh(e.Na,e,t),Bp(e,e.C)),e.C++,0)))}(e,t)||2==r&&Fp(e)))switch(n&&0<n.length&&(t=e.i,t.i=t.i.concat(n)),i){case 1:zp(e,5);break;case 4:zp(e,10);break;case 3:zp(e,6);break;default:zp(e,2)}}function Bp(e,t){let n=e.ab+Math.floor(Math.random()*e.hb);return e.isActive()||(n*=2),n*t}function zp(e,t){if(e.l.info("Error code "+t),2==t){var n=null;e.h&&(n=null);var r=wh(e.pb,e);n||(n=new xf("//www.google.com/images/cleardot.gif"),fh.location&&"http"==fh.location.protocol||Nf(n,"https"),Pf(n)),function(e,t){const n=new Bd;if(fh.Image){const r=new Image;r.onload=bh(op,n,r,"TestLoadImage: loaded",!0,t),r.onerror=bh(op,n,r,"TestLoadImage: error",!1,t),r.onabort=bh(op,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=bh(op,n,r,"TestLoadImage: timeout",!1,t),fh.setTimeout((function(){r.ontimeout&&r.ontimeout()}),1e4),r.src=e}else t(!1)}(n.toString(),r)}else Yd(2);e.H=0,e.h&&e.h.za(t),$p(e),Dp(e)}function $p(e){if(e.H=0,e.ma=[],e.h){const t=np(e.i);0==t.length&&0==e.j.length||(kh(e.ma,t),kh(e.ma,e.j),e.i.i.length=0,Sh(e.j),e.j.length=0),e.h.ya()}}function Wp(e,t,n){var r=n instanceof xf?Af(n):new xf(n);if(""!=r.g)t&&(r.g=t+"."+r.g),Df(r,r.m);else{var i=fh.location;r=i.protocol,t=t?t+"."+i.hostname:i.hostname,i=+i.port;var s=new xf(null);r&&Nf(s,r),t&&(s.g=t),i&&Df(s,i),n&&(s.l=n),r=s}return n=e.F,t=e.Da,n&&t&&Of(r,n,t),Of(r,"VER",e.ra),Pp(e,r),r}function Qp(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ha&&!e.va?new pp(new ap({ob:!0})):new pp(e.va)).Oa(e.J),t}function Hp(){}function Gp(){if(Fh&&!(10<=Number(Hh)))throw Error("Environmental error: no available transport.")}function Kp(e,t){_d.call(this),this.g=new xp(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.s=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.Ca&&(e?e["X-WebChannel-Client-Profile"]=t.Ca:e={"X-WebChannel-Client-Profile":t.Ca}),this.g.U=e,(e=t&&t.cc)&&!Ah(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!Ah(t)&&(this.g.F=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new Xp(this)}function Yp(e){af.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function Jp(){cf.call(this),this.status=1}function Xp(e){this.g=e}function Zp(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.m=Array(this.blockSize),this.i=this.h=0,this.reset()}function em(e,t,n){n||(n=0);var r=Array(16);if("string"==typeof t)for(var i=0;16>i;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;16>i;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1],i=e.g[2];var s=e.g[3],o=t+(s^n&(i^s))+r[0]+3614090360&4294967295;o=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+(o<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|o>>>10))+((o=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|o>>>12))+((o=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|o>>>9))+((o=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|o>>>11))+((o=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|o>>>11))+((o=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|o>>>11))+((s=(t=n+((o=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|o>>>22))^((i=s+((o=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|o>>>17))|~t))+r[9]+3951481745&4294967295,e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(o<<21&4294967295|o>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function tm(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}(lh=pp.prototype).Oa=function(e){this.M=e},lh.ha=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.I+"; newUri="+e);t=t?t.toUpperCase():"GET",this.I=e,this.j="",this.m=0,this.F=!1,this.h=!0,this.g=this.u?this.u.g():sf.g(),this.C=this.u?nf(this.u):nf(sf),this.g.onreadystatechange=wh(this.La,this);try{this.G=!0,this.g.open(t,String(e),!0),this.G=!1}catch(e){return void vp(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!=typeof r.keys||"function"!=typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const e of r.keys())n.set(e,r.get(e))}r=Array.from(n.keys()).find((e=>"content-type"==e.toLowerCase())),i=fh.FormData&&e instanceof fh.FormData,!(0<=Th(yp,t))||r||i||n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(const[e,t]of n)this.g.setRequestHeader(e,t);this.K&&(this.g.responseType=this.K),"withCredentials"in this.g&&this.g.withCredentials!==this.M&&(this.g.withCredentials=this.M);try{Ip(this),0<this.B&&((this.L=function(e){return Fh&&"number"==typeof e.timeout&&void 0!==e.ontimeout}(this.g))?(this.g.timeout=this.B,this.g.ontimeout=wh(this.ua,this)):this.A=Md(this.ua,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){vp(this,e)}},lh.ua=function(){void 0!==dh&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,wd(this,"timeout"),this.abort(8))},lh.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,wd(this,"complete"),wd(this,"abort"),bp(this))},lh.N=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),bp(this,!0)),pp.$.N.call(this)},lh.La=function(){this.s||(this.G||this.v||this.l?wp(this):this.kb())},lh.kb=function(){wp(this)},lh.isActive=function(){return!!this.g},lh.da=function(){try{return 2<Ep(this)?this.g.status:-1}catch(e){return-1}},lh.ja=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},lh.Wa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),fp(t)}},lh.Ia=function(){return this.m},lh.Sa=function(){return"string"==typeof this.j?this.j:String(this.j)},(lh=xp.prototype).ra=8,lh.H=1,lh.Na=function(e){if(this.m)if(this.m=null,1==this.H){if(!e){this.W=Math.floor(1e5*Math.random()),e=this.W++;const i=new lf(this,this.l,e);let s=this.s;if(this.U&&(s?(s=td(s),rd(s,this.U)):s=this.U),null!==this.o||this.O||(i.I=s,s=null),this.P)e:{for(var t=0,n=0;n<this.j.length;n++){var r=this.j[n];if(void 0===(r="__data__"in r.map&&"string"==typeof(r=r.map.__data__)?r.length:void 0))break;if(4096<(t+=r)){t=n;break e}if(4096===t||n===this.j.length-1){t=n+1;break e}}t=1e3}else t=1e3;t=Mp(this,i,t),Of(n=Af(this.I),"RID",e),Of(n,"CVER",22),this.F&&Of(n,"X-HTTP-Session-Id",this.F),Pp(this,n),s&&(this.O?t="headers="+encodeURIComponent(String(Sp(s)))+"&"+t:this.o&&kp(n,this.o,s)),ep(this.i,i),this.bb&&Of(n,"TYPE","init"),this.P?(Of(n,"$req",t),Of(n,"SID","null"),i.aa=!0,mf(i,n,null)):mf(i,n,t),this.H=2}}else 3==this.H&&(e?Op(this,e):0==this.j.length||Jf(this.i)||Op(this))},lh.Ma=function(){if(this.u=null,qp(this),this.ca&&!(this.M||null==this.g||0>=this.S)){var e=2*this.S;this.l.info("BP detection timer enabled: "+e),this.B=Xd(wh(this.jb,this),e)}},lh.jb=function(){this.B&&(this.B=null,this.l.info("BP detection timeout reached."),this.l.info("Buffering proxy detected and switch to long-polling!"),this.G=!1,this.M=!0,Yd(10),Np(this),qp(this))},lh.ib=function(){null!=this.v&&(this.v=null,Np(this),Fp(this),Yd(19))},lh.pb=function(e){e?(this.l.info("Successfully pinged google.com"),Yd(2)):(this.l.info("Failed to ping google.com"),Yd(1))},lh.isActive=function(){return!!this.h&&this.h.isActive(this)},(lh=Hp.prototype).Ba=function(){},lh.Aa=function(){},lh.za=function(){},lh.ya=function(){},lh.isActive=function(){return!0},lh.Va=function(){},Gp.prototype.g=function(e,t){return new Kp(e,t)},Ih(Kp,_d),Kp.prototype.m=function(){this.g.h=this.j,this.A&&(this.g.J=!0);var e=this.g,t=this.l,n=this.h||void 0;Yd(0),e.Y=t,e.na=n||{},e.G=e.aa,e.I=Wp(e,null,e.Y),Rp(e)},Kp.prototype.close=function(){Ap(this.g)},Kp.prototype.u=function(e){var t=this.g;if("string"==typeof e){var n={};n.__data__=e,e=n}else this.v&&((n={}).__data__=Id(e),e=n);t.j.push(new class{constructor(e,t){this.g=e,this.map=t}}(t.fb++,e)),3==t.H&&Rp(t)},Kp.prototype.N=function(){this.g.h=null,delete this.j,Ap(this.g),delete this.g,Kp.$.N.call(this)},Ih(Yp,af),Ih(Jp,cf),Ih(Xp,Hp),Xp.prototype.Ba=function(){wd(this.g,"a")},Xp.prototype.Aa=function(e){wd(this.g,new Yp(e))},Xp.prototype.za=function(e){wd(this.g,new Jp)},Xp.prototype.ya=function(){wd(this.g,"b")},Ih(Zp,(function(){this.blockSize=-1})),Zp.prototype.reset=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.i=this.h=0},Zp.prototype.j=function(e,t){void 0===t&&(t=e.length);for(var n=t-this.blockSize,r=this.m,i=this.h,s=0;s<t;){if(0==i)for(;s<=n;)em(this,e,s),s+=this.blockSize;if("string"==typeof e){for(;s<t;)if(r[i++]=e.charCodeAt(s++),i==this.blockSize){em(this,r),i=0;break}}else for(;s<t;)if(r[i++]=e[s++],i==this.blockSize){em(this,r),i=0;break}}this.h=i,this.i+=t},Zp.prototype.l=function(){var e=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;var n=8*this.i;for(t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.j(e),e=Array(16),t=n=0;4>t;++t)for(var r=0;32>r;r+=8)e[n++]=this.g[t]>>>r&255;return e};var nm={};function rm(e){return-128<=e&&128>e?function(e,t){var n=nm;return Object.prototype.hasOwnProperty.call(n,e)?n[e]:n[e]=t(e)}(e,(function(e){return new tm([0|e],0>e?-1:0)})):new tm([0|e],0>e?-1:0)}function im(e){if(isNaN(e)||!isFinite(e))return om;if(0>e)return hm(im(-e));for(var t=[],n=1,r=0;e>=n;r++)t[r]=e/n|0,n*=sm;return new tm(t,0)}var sm=4294967296,om=rm(0),am=rm(1),cm=rm(16777216);function um(e){if(0!=e.h)return!1;for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return!1;return!0}function lm(e){return-1==e.h}function hm(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new tm(n,~e.h).add(am)}function dm(e,t){return e.add(hm(t))}function fm(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function pm(e,t){this.g=e,this.h=t}function mm(e,t){if(um(t))throw Error("division by zero");if(um(e))return new pm(om,om);if(lm(e))return t=mm(hm(e),t),new pm(hm(t.g),hm(t.h));if(lm(t))return t=mm(e,hm(t)),new pm(hm(t.g),t.h);if(30<e.g.length){if(lm(e)||lm(t))throw Error("slowDivide_ only works with positive integers.");for(var n=am,r=t;0>=r.X(e);)n=gm(n),r=gm(r);var i=ym(n,1),s=ym(r,1);for(r=ym(r,2),n=ym(n,2);!um(r);){var o=s.add(r);0>=o.X(e)&&(i=i.add(n),s=o),r=ym(r,1),n=ym(n,1)}return t=dm(e,i.R(t)),new pm(i,t)}for(i=om;0<=e.X(t);){for(n=Math.max(1,Math.floor(e.ea()/t.ea())),r=48>=(r=Math.ceil(Math.log(n)/Math.LN2))?1:Math.pow(2,r-48),o=(s=im(n)).R(t);lm(o)||0<o.X(e);)o=(s=im(n-=r)).R(t);um(s)&&(s=am),i=i.add(s),e=dm(e,o)}return new pm(i,e)}function gm(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.D(r)<<1|e.D(r-1)>>>31;return new tm(n,e.h)}function ym(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],s=0;s<r;s++)i[s]=0<t?e.D(s+n)>>>t|e.D(s+n+1)<<32-t:e.D(s+n);return new tm(i,e.h)}(lh=tm.prototype).ea=function(){if(lm(this))return-hm(this).ea();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.D(n);e+=(0<=r?r:sm+r)*t,t*=sm}return e},lh.toString=function(e){if(2>(e=e||10)||36<e)throw Error("radix out of range: "+e);if(um(this))return"0";if(lm(this))return"-"+hm(this).toString(e);for(var t=im(Math.pow(e,6)),n=this,r="";;){var i=mm(n,t).g,s=((0<(n=dm(n,i.R(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(um(n=i))return s+r;for(;6>s.length;)s="0"+s;r=s+r}},lh.D=function(e){return 0>e?0:e<this.g.length?this.g[e]:this.h},lh.X=function(e){return lm(e=dm(this,e))?-1:um(e)?0:1},lh.abs=function(){return lm(this)?hm(this):this},lh.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,i=0;i<=t;i++){var s=r+(65535&this.D(i))+(65535&e.D(i)),o=(s>>>16)+(this.D(i)>>>16)+(e.D(i)>>>16);r=o>>>16,s&=65535,o&=65535,n[i]=o<<16|s}return new tm(n,-2147483648&n[n.length-1]?-1:0)},lh.R=function(e){if(um(this)||um(e))return om;if(lm(this))return lm(e)?hm(this).R(hm(e)):hm(hm(this).R(e));if(lm(e))return hm(this.R(hm(e)));if(0>this.X(cm)&&0>e.X(cm))return im(this.ea()*e.ea());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var i=0;i<e.g.length;i++){var s=this.D(r)>>>16,o=65535&this.D(r),a=e.D(i)>>>16,c=65535&e.D(i);n[2*r+2*i]+=o*c,fm(n,2*r+2*i),n[2*r+2*i+1]+=s*c,fm(n,2*r+2*i+1),n[2*r+2*i+1]+=o*a,fm(n,2*r+2*i+1),n[2*r+2*i+2]+=s*a,fm(n,2*r+2*i+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new tm(n,0)},lh.gb=function(e){return mm(this,e).h},lh.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)&e.D(r);return new tm(n,this.h&e.h)},lh.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)|e.D(r);return new tm(n,this.h|e.h)},lh.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)^e.D(r);return new tm(n,this.h^e.h)},Gp.prototype.createWebChannel=Gp.prototype.g,Kp.prototype.send=Kp.prototype.u,Kp.prototype.open=Kp.prototype.m,Kp.prototype.close=Kp.prototype.close,Zd.NO_ERROR=0,Zd.TIMEOUT=8,Zd.HTTP_ERROR=6,ef.COMPLETE="complete",rf.EventType=of,of.OPEN="a",of.CLOSE="b",of.ERROR="c",of.MESSAGE="d",_d.prototype.listen=_d.prototype.O,pp.prototype.listenOnce=pp.prototype.P,pp.prototype.getLastError=pp.prototype.Sa,pp.prototype.getLastErrorCode=pp.prototype.Ia,pp.prototype.getStatus=pp.prototype.da,pp.prototype.getResponseJson=pp.prototype.Wa,pp.prototype.getResponseText=pp.prototype.ja,pp.prototype.send=pp.prototype.ha,pp.prototype.setWithCredentials=pp.prototype.Oa,Zp.prototype.digest=Zp.prototype.l,Zp.prototype.reset=Zp.prototype.reset,Zp.prototype.update=Zp.prototype.j,tm.prototype.add=tm.prototype.add,tm.prototype.multiply=tm.prototype.R,tm.prototype.modulo=tm.prototype.gb,tm.prototype.compare=tm.prototype.X,tm.prototype.toNumber=tm.prototype.ea,tm.prototype.toString=tm.prototype.toString,tm.prototype.getBits=tm.prototype.D,tm.fromNumber=im,tm.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if(2>(n=n||10)||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return hm(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=im(Math.pow(n,8)),i=om,s=0;s<t.length;s+=8){var o=Math.min(8,t.length-s),a=parseInt(t.substring(s,s+o),n);8>o?(o=im(Math.pow(n,o)),i=i.R(o).add(im(a))):i=(i=i.R(r)).add(im(a))}return i};var vm=Zd,_m=ef,wm=$d,bm=10,Im=11,Em=ap,Tm=rf,Sm=pp,km=Zp,Cm=tm;const xm="@firebase/firestore";
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Am{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}}Am.UNAUTHENTICATED=new Am(null),Am.GOOGLE_CREDENTIALS=new Am("google-credentials-uid"),Am.FIRST_PARTY=new Am("first-party-uid"),Am.MOCK_USER=new Am("mock-user");
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
let Nm="9.23.0";
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Dm=new mc("@firebase/firestore");function Rm(){return Dm.logLevel}function Om(e,...t){if(Dm.logLevel<=lc.DEBUG){const n=t.map(Lm);Dm.debug(`Firestore (${Nm}): ${e}`,...n)}}function Pm(e,...t){if(Dm.logLevel<=lc.ERROR){const n=t.map(Lm);Dm.error(`Firestore (${Nm}): ${e}`,...n)}}function Mm(e,...t){if(Dm.logLevel<=lc.WARN){const n=t.map(Lm);Dm.warn(`Firestore (${Nm}): ${e}`,...n)}}function Lm(e){if("string"==typeof e)return e;try{return t=e,JSON.stringify(t)}catch(t){return e}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var t}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Fm(e="Unexpected state"){const t=`FIRESTORE (${Nm}) INTERNAL ASSERTION FAILED: `+e;throw Pm(t),new Error(t)}function jm(e,t){e||Fm()}function qm(e,t){return e}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Vm={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 Um extends Pa{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Bm{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class zm{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class $m{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(Am.UNAUTHENTICATED)))}shutdown(){}}class Wm{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 Qm{constructor(e){this.t=e,this.currentUser=Am.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){let n=this.i;const r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve();let i=new Bm;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new Bm,e.enqueueRetryable((()=>r(this.currentUser)))};const s=()=>{const t=i;e.enqueueRetryable((async()=>{await t.promise,await r(this.currentUser)}))},o=e=>{Om("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),s()};this.t.onInit((e=>o(e))),setTimeout((()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?o(e):(Om("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new Bm)}}),0),s()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((t=>this.i!==e?(Om("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(jm("string"==typeof t.accessToken),new zm(t.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){const e=this.auth&&this.auth.getUid();return jm(null===e||"string"==typeof e),new Am(e)}}class Hm{constructor(e,t,n){this.h=e,this.l=t,this.m=n,this.type="FirstParty",this.user=Am.FIRST_PARTY,this.g=new Map}p(){return this.m?this.m():null}get headers(){this.g.set("X-Goog-AuthUser",this.h);const e=this.p();return e&&this.g.set("Authorization",e),this.l&&this.g.set("X-Goog-Iam-Authorization-Token",this.l),this.g}}class Gm{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new Hm(this.h,this.l,this.m))}start(e,t){e.enqueueRetryable((()=>t(Am.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class Km{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class Ym{constructor(e){this.I=e,this.forceRefresh=!1,this.appCheck=null,this.T=null}start(e,t){const n=e=>{null!=e.error&&Om("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);const n=e.token!==this.T;return this.T=e.token,Om("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable((()=>n(t)))};const r=e=>{Om("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.I.onInit((e=>r(e))),setTimeout((()=>{if(!this.appCheck){const e=this.I.getImmediate({optional:!0});e?r(e):Om("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((e=>e?(jm("string"==typeof e.token),this.T=e.token,new Km(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Jm(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let t=0;t<e;t++)n[t]=Math.floor(256*Math.random());return n}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Xm{static A(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(256/62);let n="";for(;n.length<20;){const r=Jm(40);for(let i=0;i<r.length;++i)n.length<20&&r[i]<t&&(n+=e.charAt(r[i]%62))}return n}}function Zm(e,t){return e<t?-1:e>t?1:0}function eg(e,t,n){return e.length===t.length&&e.every(((e,r)=>n(e,t[r])))}function tg(e){return e+"\0"}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ng{constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new Um(Vm.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new Um(Vm.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new Um(Vm.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new Um(Vm.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return ng.fromMillis(Date.now())}static fromDate(e){return ng.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new ng(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Zm(this.nanoseconds,e.nanoseconds):Zm(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(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class rg{constructor(e){this.timestamp=e}static fromTimestamp(e){return new rg(e)}static min(){return new rg(new ng(0,0))}static max(){return new rg(new ng(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ig{constructor(e,t,n){void 0===t?t=0:t>e.length&&Fm(),void 0===n?n=e.length-t:n>e.length-t&&Fm(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===ig.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof ig?e.forEach((e=>{t.push(e)})):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class sg extends ig{construct(e,t,n){return new sg(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(n.indexOf("//")>=0)throw new Um(Vm.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter((e=>e.length>0)))}return new sg(t)}static emptyPath(){return new sg([])}}const og=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class ag extends ig{construct(e,t,n){return new ag(e,t,n)}static isValidIdentifier(e){return og.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),ag.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new ag(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;const i=()=>{if(0===n.length)throw new Um(Vm.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new Um(Vm.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new Um(Vm.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?(s=!s,r++):"."!==t||s?(n+=t,r++):(i(),r++)}if(i(),s)throw new Um(Vm.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new ag(t)}static emptyPath(){return new ag([])}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class cg{constructor(e){this.path=e}static fromPath(e){return new cg(sg.fromString(e))}static fromName(e){return new cg(sg.fromString(e).popFirst(5))}static empty(){return new cg(sg.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===sg.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return sg.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new cg(new sg(e.slice()))}}
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ug{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function lg(e){return e.fields.find((e=>2===e.kind))}function hg(e){return e.fields.filter((e=>2!==e.kind))}ug.UNKNOWN_ID=-1;class dg{constructor(e,t){this.fieldPath=e,this.kind=t}}class fg{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new fg(0,gg.min())}}function pg(e,t){const n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,i=rg.fromTimestamp(1e9===r?new ng(n+1,0):new ng(n,r));return new gg(i,cg.empty(),t)}function mg(e){return new gg(e.readTime,e.key,-1)}class gg{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new gg(rg.min(),cg.empty(),-1)}static max(){return new gg(rg.max(),cg.empty(),-1)}}function yg(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=cg.comparator(e.documentKey,t.documentKey),0!==n?n:Zm(e.largestBatchId,t.largestBatchId))}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const vg="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class _g{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function wg(e){if(e.code!==Vm.FAILED_PRECONDITION||e.message!==vg)throw e;Om("LocalStore","Unexpectedly lost primary lease")}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class bg{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(e,t){return this.callbackAttached&&Fm(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new bg(((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}}))}toPromise(){return new Promise(((e,t)=>{this.next(e,t)}))}wrapUserFunction(e){try{const t=e();return t instanceof bg?t:bg.resolve(t)}catch(e){return bg.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction((()=>e(t))):bg.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction((()=>e(t))):bg.reject(t)}static resolve(e){return new bg(((t,n)=>{t(e)}))}static reject(e){return new bg(((t,n)=>{n(e)}))}static waitFor(e){return new bg(((t,n)=>{let r=0,i=0,s=!1;e.forEach((e=>{++r,e.next((()=>{++i,s&&i===r&&t()}),(e=>n(e)))})),s=!0,i===r&&t()}))}static or(e){let t=bg.resolve(!1);for(const n of e)t=t.next((e=>e?bg.resolve(e):n()));return t}static forEach(e,t){const n=[];return e.forEach(((e,r)=>{n.push(t.call(this,e,r))})),this.waitFor(n)}static mapArray(e,t){return new bg(((n,r)=>{const i=e.length,s=new Array(i);let o=0;for(let a=0;a<i;a++){const c=a;t(e[c]).next((e=>{s[c]=e,++o,o===i&&n(s)}),(e=>r(e)))}}))}static doWhile(e,t){return new bg(((n,r)=>{const i=()=>{!0===e()?t().next((()=>{i()}),r):n()};i()}))}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Ig{constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.v=new Bm,this.transaction.oncomplete=()=>{this.v.resolve()},this.transaction.onabort=()=>{t.error?this.v.reject(new Sg(e,t.error)):this.v.resolve()},this.transaction.onerror=t=>{const n=Ng(t.target.error);this.v.reject(new Sg(e,n))}}static open(e,t,n,r){try{return new Ig(t,e.transaction(r,n))}catch(e){throw new Sg(t,e)}}get R(){return this.v.promise}abort(e){e&&this.v.reject(e),this.aborted||(Om("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}P(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){const t=this.transaction.objectStore(e);return new Cg(t)}}class Eg{constructor(e,t,n){this.name=e,this.version=t,this.V=n,12.2===Eg.S(ka())&&Pm("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 Om("SimpleDb","Removing database:",e),xg(window.indexedDB.deleteDatabase(e)).toPromise()}static D(){if(!Oa())return!1;if(Eg.C())return!0;const e=ka(),t=Eg.S(e),n=0<t&&t<10,r=Eg.N(e),i=0<r&&r<4.5;return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||n||i)}static C(){var e;return void 0!==M&&"YES"===(null===(e=M.env)||void 0===e?void 0:e.k)}static M(e,t){return e.store(t)}static S(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 N(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async $(e){return this.db||(Om("SimpleDb","Opening database:",this.name),this.db=await new Promise(((t,n)=>{const r=indexedDB.open(this.name,this.version);r.onsuccess=e=>{const n=e.target.result;t(n)},r.onblocked=()=>{n(new Sg(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},r.onerror=t=>{const r=t.target.error;"VersionError"===r.name?n(new Um(Vm.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"===r.name?n(new Um(Vm.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: "+r)):n(new Sg(e,r))},r.onupgradeneeded=e=>{Om("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);const t=e.target.result;this.V.O(t,r.transaction,e.oldVersion,this.version).next((()=>{Om("SimpleDb","Database upgrade to version "+this.version+" complete")}))}}))),this.F&&(this.db.onversionchange=e=>this.F(e)),this.db}B(e){this.F=e,this.db&&(this.db.onversionchange=t=>e(t))}async runTransaction(e,t,n,r){const i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.$(e);const t=Ig.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next((e=>(t.P(),e))).catch((e=>(t.abort(e),bg.reject(e)))).toPromise();return s.catch((()=>{})),await t.R,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(Om("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}class Tg{constructor(e){this.L=e,this.q=!1,this.U=null}get isDone(){return this.q}get K(){return this.U}set cursor(e){this.L=e}done(){this.q=!0}G(e){this.U=e}delete(){return xg(this.L.delete())}}class Sg extends Um{constructor(e,t){super(Vm.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function kg(e){return"IndexedDbTransactionError"===e.name}class Cg{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(Om("SimpleDb","PUT",this.store.name,e,t),n=this.store.put(t,e)):(Om("SimpleDb","PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),xg(n)}add(e){return Om("SimpleDb","ADD",this.store.name,e,e),xg(this.store.add(e))}get(e){return xg(this.store.get(e)).next((t=>(void 0===t&&(t=null),Om("SimpleDb","GET",this.store.name,e,t),t)))}delete(e){return Om("SimpleDb","DELETE",this.store.name,e),xg(this.store.delete(e))}count(){return Om("SimpleDb","COUNT",this.store.name),xg(this.store.count())}j(e,t){const n=this.options(e,t);if(n.index||"function"!=typeof this.store.getAll){const e=this.cursor(n),t=[];return this.W(e,((e,n)=>{t.push(n)})).next((()=>t))}{const e=this.store.getAll(n.range);return new bg(((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}}))}}H(e,t){const n=this.store.getAll(e,null===t?void 0:t);return new bg(((e,t)=>{n.onerror=e=>{t(e.target.error)},n.onsuccess=t=>{e(t.target.result)}}))}J(e,t){Om("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.Y=!1;const r=this.cursor(n);return this.W(r,((e,t,n)=>n.delete()))}X(e,t){let n;t?n=e:(n={},t=e);const r=this.cursor(n);return this.W(r,t)}Z(e){const t=this.cursor({});return new bg(((n,r)=>{t.onerror=e=>{const t=Ng(e.target.error);r(t)},t.onsuccess=t=>{const r=t.target.result;r?e(r.primaryKey,r.value).next((e=>{e?r.continue():n()})):n()}}))}W(e,t){const n=[];return new bg(((r,i)=>{e.onerror=e=>{i(e.target.error)},e.onsuccess=e=>{const i=e.target.result;if(!i)return void r();const s=new Tg(i),o=t(i.primaryKey,i.value,s);if(o instanceof bg){const e=o.catch((e=>(s.done(),bg.reject(e))));n.push(e)}s.isDone?r():null===s.K?i.continue():i.continue(s.K)}})).next((()=>bg.waitFor(n)))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.Y?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function xg(e){return new bg(((t,n)=>{e.onsuccess=e=>{const n=e.target.result;t(n)},e.onerror=e=>{const t=Ng(e.target.error);n(t)}}))}let Ag=!1;function Ng(e){const t=Eg.S(ka());if(t>=12.2&&t<13){const t="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(t)>=0){const e=new Um("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 Ag||(Ag=!0,setTimeout((()=>{throw e}),0)),e}}return e}class Dg{constructor(e,t){this.asyncQueue=e,this.tt=t,this.task=null}start(){this.et(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}et(e){Om("IndexBackiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,(async()=>{this.task=null;try{Om("IndexBackiller",`Documents written: ${await this.tt.nt()}`)}catch(e){kg(e)?Om("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e):await wg(e)}await this.et(6e4)}))}}class Rg{constructor(e,t){this.localStore=e,this.persistence=t}async nt(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",(t=>this.st(t,e)))}st(e,t){const n=new Set;let r=t,i=!0;return bg.doWhile((()=>!0===i&&r>0),(()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t=>{if(null!==t&&!n.has(t))return Om("IndexBackiller",`Processing collection: ${t}`),this.it(e,t,r).next((e=>{r-=e,n.add(t)}));i=!1})))).next((()=>t-r))}it(e,t,n){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next((r=>this.localStore.localDocuments.getNextDocuments(e,t,r,n).next((n=>{const i=n.changes;return this.localStore.indexManager.updateIndexEntries(e,i).next((()=>this.rt(r,n))).next((n=>(Om("IndexBackiller",`Updating offset: ${n}`),this.localStore.indexManager.updateCollectionGroup(e,t,n)))).next((()=>i.size))}))))}rt(e,t){let n=e;return t.changes.forEach(((e,t)=>{const r=mg(t);yg(r,n)>0&&(n=r)})),new gg(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}
/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Og{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ot(e),this.ut=e=>t.writeSequenceNumber(e))}ot(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.ut&&this.ut(e),e}}function Pg(e){return null==e}function Mg(e){return 0===e&&1/e==-1/0}function Lg(e){return"number"==typeof e&&Number.isInteger(e)&&!Mg(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Fg(e){let t="";for(let n=0;n<e.length;n++)t.length>0&&(t=qg(t)),t=jg(e.get(n),t);return qg(t)}function jg(e,t){let n=t;const r=e.length;for(let t=0;t<r;t++){const r=e.charAt(t);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}function qg(e){return e+""}function Vg(e){const t=e.length;if(jm(t>=2),2===t)return jm(""===e.charAt(0)&&""===e.charAt(1)),sg.emptyPath();const n=t-2,r=[];let i="";for(let s=0;s<t;){const t=e.indexOf("",s);switch((t<0||t>n)&&Fm(),e.charAt(t+1)){case"":const n=e.substring(s,t);let o;0===i.length?o=n:(i+=n,o=i,i=""),r.push(o);break;case"":i+=e.substring(s,t),i+="\0";break;case"":i+=e.substring(s,t+1);break;default:Fm()}s=t+2}return new sg(r)}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */Og.ct=-1;const Ug=["userId","batchId"];
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Bg(e,t){return[e,Fg(t)]}function zg(e,t,n){return[e,Fg(t),n]}const $g={},Wg=["prefixPath","collectionGroup","readTime","documentId"],Qg=["prefixPath","collectionGroup","documentId"],Hg=["collectionGroup","readTime","prefixPath","documentId"],Gg=["canonicalId","targetId"],Kg=["targetId","path"],Yg=["path","targetId"],Jg=["collectionId","parent"],Xg=["indexId","uid"],Zg=["uid","sequenceNumber"],ey=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],ty=["indexId","uid","orderedDocumentKey"],ny=["userId","collectionPath","documentId"],ry=["userId","collectionPath","largestBatchId"],iy=["userId","collectionGroup","largestBatchId"],sy=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],oy=[...sy,"documentOverlays"],ay=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],cy=ay,uy=[...cy,"indexConfiguration","indexState","indexEntries"];
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ly extends _g{constructor(e,t){super(),this.ht=e,this.currentSequenceNumber=t}}function hy(e,t){const n=qm(e);return Eg.M(n.ht,t)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function dy(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function fy(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function py(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class my{constructor(e,t){this.comparator=e,this.root=t||yy.EMPTY}insert(e,t){return new my(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,yy.BLACK,null,null))}remove(e){return new my(this.comparator,this.root.remove(e,this.comparator).copy(null,null,yy.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){const n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){const r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=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(e){this.inorderTraversal(((t,n)=>(e(t,n),!1)))}toString(){const e=[];return this.inorderTraversal(((t,n)=>(e.push(`${t}:${n}`),!1))),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new gy(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new gy(this.root,e,this.comparator,!1)}getReverseIterator(){return new gy(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new gy(this.root,e,this.comparator,!0)}}class gy{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const 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 this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class yy{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:yy.RED,this.left=null!=r?r:yy.EMPTY,this.right=null!=i?i:yy.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new yy(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;const i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return yy.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 yy.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(){const e=this.copy(null,null,yy.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,yy.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const 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(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw Fm();if(this.right.isRed())throw Fm();const e=this.left.check();if(e!==this.right.check())throw Fm();return e+(this.isRed()?0:1)}}yy.EMPTY=null,yy.RED=!0,yy.BLACK=!1,yy.EMPTY=new class{constructor(){this.size=0}get key(){throw Fm()}get value(){throw Fm()}get color(){throw Fm()}get left(){throw Fm()}get right(){throw Fm()}copy(e,t,n,r,i){return this}insert(e,t,n){return new yy(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}};
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class vy{constructor(e){this.comparator=e,this.data=new my(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(e){this.data.inorderTraversal(((t,n)=>(e(t),!1)))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){const r=n.getNext();if(this.comparator(r.key,e[1])>=0)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 _y(this.data.getIterator())}getIteratorFrom(e){return new _y(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 vy))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 e=[];return this.forEach((t=>{e.push(t)})),e}toString(){const e=[];return this.forEach((t=>e.push(t))),"SortedSet("+e.toString()+")"}copy(e){const t=new vy(this.comparator);return t.data=e,t}}class _y{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function wy(e){return e.hasNext()?e.getNext():void 0}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class by{constructor(e){this.fields=e,e.sort(ag.comparator)}static empty(){return new by([])}unionWith(e){let t=new vy(ag.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new by(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return eg(this.fields,e.fields,((e,t)=>e.isEqual(t)))}}
/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Iy extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class Ey{constructor(e){this.binaryString=e}static fromBase64String(e){const t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new Iy("Invalid base64 string: "+e):e}}(e);return new Ey(t)}static fromUint8Array(e){const t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new Ey(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}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return Zm(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}Ey.EMPTY_BYTE_STRING=new Ey("");const Ty=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Sy(e){if(jm(!!e),"string"==typeof e){let t=0;const n=Ty.exec(e);if(jm(!!n),n[1]){let e=n[1];e=(e+"000000000").substr(0,9),t=Number(e)}const r=new Date(e);return{seconds:Math.floor(r.getTime()/1e3),nanos:t}}return{seconds:ky(e.seconds),nanos:ky(e.nanos)}}function ky(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Cy(e){return"string"==typeof e?Ey.fromBase64String(e):Ey.fromUint8Array(e)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function xy(e){var t,n;return"server_timestamp"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function Ay(e){const t=e.mapValue.fields.__previous_value__;return xy(t)?Ay(t):t}function Ny(e){const t=Sy(e.mapValue.fields.__local_write_time__.timestampValue);return new ng(t.seconds,t.nanos)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Dy{constructor(e,t,n,r,i,s,o,a,c){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=o,this.longPollingOptions=a,this.useFetchStreams=c}}class Ry{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Ry("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Ry&&e.projectId===this.projectId&&e.database===this.database}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Oy={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Py={nullValue:"NULL_VALUE"};function My(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?xy(e)?4:Ky(e)?9007199254740991:10:Fm()}function Ly(e,t){if(e===t)return!0;const n=My(e);if(n!==My(t))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return Ny(e).isEqual(Ny(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;const n=Sy(e.timestampValue),r=Sy(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return function(e,t){return Cy(e.bytesValue).isEqual(Cy(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return ky(e.geoPointValue.latitude)===ky(t.geoPointValue.latitude)&&ky(e.geoPointValue.longitude)===ky(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return ky(e.integerValue)===ky(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const n=ky(e.doubleValue),r=ky(t.doubleValue);return n===r?Mg(n)===Mg(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return eg(e.arrayValue.values||[],t.arrayValue.values||[],Ly);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(dy(n)!==dy(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!Ly(n[e],r[e])))return!1;return!0}(e,t);default:return Fm()}}function Fy(e,t){return void 0!==(e.values||[]).find((e=>Ly(e,t)))}function jy(e,t){if(e===t)return 0;const n=My(e),r=My(t);if(n!==r)return Zm(n,r);switch(n){case 0:case 9007199254740991:return 0;case 1:return Zm(e.booleanValue,t.booleanValue);case 2:return function(e,t){const n=ky(e.integerValue||e.doubleValue),r=ky(t.integerValue||t.doubleValue);return n<r?-1:n>r?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return qy(e.timestampValue,t.timestampValue);case 4:return qy(Ny(e),Ny(t));case 5:return Zm(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Cy(e),r=Cy(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){const n=e.split("/"),r=t.split("/");for(let e=0;e<n.length&&e<r.length;e++){const t=Zm(n[e],r[e]);if(0!==t)return t}return Zm(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){const n=Zm(ky(e.latitude),ky(t.latitude));return 0!==n?n:Zm(ky(e.longitude),ky(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return function(e,t){const n=e.values||[],r=t.values||[];for(let e=0;e<n.length&&e<r.length;++e){const t=jy(n[e],r[e]);if(t)return t}return Zm(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Oy.mapValue&&t===Oy.mapValue)return 0;if(e===Oy.mapValue)return 1;if(t===Oy.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let e=0;e<r.length&&e<s.length;++e){const t=Zm(r[e],s[e]);if(0!==t)return t;const o=jy(n[r[e]],i[s[e]]);if(0!==o)return o}return Zm(r.length,s.length)}(e.mapValue,t.mapValue);default:throw Fm()}}function qy(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Zm(e,t);const n=Sy(e),r=Sy(t),i=Zm(n.seconds,r.seconds);return 0!==i?i:Zm(n.nanos,r.nanos)}function Vy(e){return Uy(e)}function Uy(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=Sy(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?Cy(e.bytesValue).toBase64():"referenceValue"in e?(n=e.referenceValue,cg.fromName(n).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+=Uy(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${Uy(e.fields[i])}`;return n+"}"}(e.mapValue):Fm();var t,n}function By(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function zy(e){return!!e&&"integerValue"in e}function $y(e){return!!e&&"arrayValue"in e}function Wy(e){return!!e&&"nullValue"in e}function Qy(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Hy(e){return!!e&&"mapValue"in e}function Gy(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){const t={mapValue:{fields:{}}};return fy(e.mapValue.fields,((e,n)=>t.mapValue.fields[e]=Gy(n))),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=Gy(e.arrayValue.values[n]);return t}return Object.assign({},e)}function Ky(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Yy(e){return"nullValue"in e?Py:"booleanValue"in e?{booleanValue:!1}:"integerValue"in e||"doubleValue"in e?{doubleValue:NaN}:"timestampValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in e?{stringValue:""}:"bytesValue"in e?{bytesValue:""}:"referenceValue"in e?By(Ry.empty(),cg.empty()):"geoPointValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in e?{arrayValue:{}}:"mapValue"in e?{mapValue:{}}:Fm()}function Jy(e){return"nullValue"in e?{booleanValue:!1}:"booleanValue"in e?{doubleValue:NaN}:"integerValue"in e||"doubleValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in e?{stringValue:""}:"stringValue"in e?{bytesValue:""}:"bytesValue"in e?By(Ry.empty(),cg.empty()):"referenceValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in e?{arrayValue:{}}:"arrayValue"in e?{mapValue:{}}:"mapValue"in e?Oy:Fm()}function Xy(e,t){const n=jy(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Zy(e,t){const n=jy(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ev{constructor(e){this.value=e}static empty(){return new ev({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(t=(t.mapValue.fields||{})[e.get(n)],!Hy(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Gy(t)}setAll(e){let t=ag.emptyPath(),n={},r=[];e.forEach(((e,i)=>{if(!t.isImmediateParentOf(i)){const e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=i.popLast()}e?n[i.lastSegment()]=Gy(e):r.push(i.lastSegment())}));const i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){const t=this.field(e.popLast());Hy(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Ly(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let r=t.mapValue.fields[e.get(n)];Hy(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}applyChanges(e,t,n){fy(t,((t,n)=>e[t]=n));for(const t of n)delete e[t]}clone(){return new ev(Gy(this.value))}}function tv(e){const t=[];return fy(e.fields,((e,n)=>{const r=new ag([e]);if(Hy(n)){const e=tv(n.mapValue).fields;if(0===e.length)t.push(r);else for(const n of e)t.push(r.child(n))}else t.push(r)})),new by(t)
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */}class nv{constructor(e,t,n,r,i,s,o){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=o}static newInvalidDocument(e){return new nv(e,0,rg.min(),rg.min(),rg.min(),ev.empty(),0)}static newFoundDocument(e,t,n,r){return new nv(e,1,t,rg.min(),n,r,0)}static newNoDocument(e,t){return new nv(e,2,t,rg.min(),rg.min(),ev.empty(),0)}static newUnknownDocument(e,t){return new nv(e,3,t,rg.min(),rg.min(),ev.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(rg.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=ev.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=ev.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=rg.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof nv&&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 nv(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class rv{constructor(e,t){this.position=e,this.inclusive=t}}function iv(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],o=e.position[i];if(r=s.field.isKeyField()?cg.comparator(cg.fromName(o.referenceValue),n.key):jy(o,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function sv(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Ly(e.position[n],t.position[n]))return!1;return!0}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ov{constructor(e,t="asc"){this.field=e,this.dir=t}}function av(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class cv{}class uv extends cv{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new _v(e,t,n):"array-contains"===t?new Ev(e,n):"in"===t?new Tv(e,n):"not-in"===t?new Sv(e,n):"array-contains-any"===t?new kv(e,n):new uv(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new wv(e,n):new bv(e,n)}matches(e){const t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(jy(t,this.value)):null!==t&&My(this.value)===My(t)&&this.matchesComparison(jy(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return Fm()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}getFirstInequalityField(){return this.isInequality()?this.field:null}}class lv extends cv{constructor(e,t){super(),this.filters=e,this.op=t,this.lt=null}static create(e,t){return new lv(e,t)}matches(e){return hv(this)?void 0===this.filters.find((t=>!t.matches(e))):void 0!==this.filters.find((t=>t.matches(e)))}getFlattenedFilters(){return null!==this.lt||(this.lt=this.filters.reduce(((e,t)=>e.concat(t.getFlattenedFilters())),[])),this.lt}getFilters(){return Object.assign([],this.filters)}getFirstInequalityField(){const e=this.ft((e=>e.isInequality()));return null!==e?e.field:null}ft(e){for(const t of this.getFlattenedFilters())if(e(t))return t;return null}}function hv(e){return"and"===e.op}function dv(e){return"or"===e.op}function fv(e){return pv(e)&&hv(e)}function pv(e){for(const t of e.filters)if(t instanceof lv)return!1;return!0}function mv(e){if(e instanceof uv)return e.field.canonicalString()+e.op.toString()+Vy(e.value);if(fv(e))return e.filters.map((e=>mv(e))).join(",");{const t=e.filters.map((e=>mv(e))).join(",");return`${e.op}(${t})`}}function gv(e,t){return e instanceof uv?function(e,t){return t instanceof uv&&e.op===t.op&&e.field.isEqual(t.field)&&Ly(e.value,t.value)}(e,t):e instanceof lv?function(e,t){return t instanceof lv&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce(((e,n,r)=>e&&gv(n,t.filters[r])),!0)}(e,t):void Fm()}function yv(e,t){const n=e.filters.concat(t);return lv.create(n,e.op)}function vv(e){return e instanceof uv?function(e){return`${e.field.canonicalString()} ${e.op} ${Vy(e.value)}`}(e):e instanceof lv?function(e){return e.op.toString()+" {"+e.getFilters().map(vv).join(" ,")+"}"}(e):"Filter"}class _v extends uv{constructor(e,t,n){super(e,t,n),this.key=cg.fromName(n.referenceValue)}matches(e){const t=cg.comparator(e.key,this.key);return this.matchesComparison(t)}}class wv extends uv{constructor(e,t){super(e,"in",t),this.keys=Iv("in",t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}}class bv extends uv{constructor(e,t){super(e,"not-in",t),this.keys=Iv("not-in",t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function Iv(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map((e=>cg.fromName(e.referenceValue)))}class Ev extends uv{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return $y(t)&&Fy(t.arrayValue,this.value)}}class Tv extends uv{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&Fy(this.value.arrayValue,t)}}class Sv extends uv{constructor(e,t){super(e,"not-in",t)}matches(e){if(Fy(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!Fy(this.value.arrayValue,t)}}class kv extends uv{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!$y(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>Fy(this.value.arrayValue,e)))}}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Cv{constructor(e,t=null,n=[],r=[],i=null,s=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=o,this.dt=null}}function xv(e,t=null,n=[],r=[],i=null,s=null,o=null){return new Cv(e,t,n,r,i,s,o)}function Av(e){const t=qm(e);if(null===t.dt){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map((e=>mv(e))).join(","),e+="|ob:",e+=t.orderBy.map((e=>function(e){return e.field.canonicalString()+e.dir}(e))).join(","),Pg(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map((e=>Vy(e))).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map((e=>Vy(e))).join(",")),t.dt=e}return t.dt}function Nv(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let n=0;n<e.orderBy.length;n++)if(!av(e.orderBy[n],t.orderBy[n]))return!1;if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!gv(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!sv(e.startAt,t.startAt)&&sv(e.endAt,t.endAt)}function Dv(e){return cg.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Rv(e,t){return e.filters.filter((e=>e instanceof uv&&e.field.isEqual(t)))}function Ov(e,t,n){let r=Py,i=!0;for(const n of Rv(e,t)){let e=Py,t=!0;switch(n.op){case"<":case"<=":e=Yy(n.value);break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=Py}Xy({value:r,inclusive:i},{value:e,inclusive:t})<0&&(r=e,i=t)}if(null!==n)for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){const e=n.position[s];Xy({value:r,inclusive:i},{value:e,inclusive:n.inclusive})<0&&(r=e,i=n.inclusive);break}return{value:r,inclusive:i}}function Pv(e,t,n){let r=Oy,i=!0;for(const n of Rv(e,t)){let e=Oy,t=!0;switch(n.op){case">=":case">":e=Jy(n.value),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=Oy}Zy({value:r,inclusive:i},{value:e,inclusive:t})>0&&(r=e,i=t)}if(null!==n)for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){const e=n.position[s];Zy({value:r,inclusive:i},{value:e,inclusive:n.inclusive})>0&&(r=e,i=n.inclusive);break}return{value:r,inclusive:i}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Mv{constructor(e,t=null,n=[],r=[],i=null,s="F",o=null,a=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=o,this.endAt=a,this.wt=null,this._t=null,this.startAt,this.endAt}}function Lv(e,t,n,r,i,s,o,a){return new Mv(e,t,n,r,i,s,o,a)}function Fv(e){return new Mv(e)}function jv(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function qv(e){return e.explicitOrderBy.length>0?e.explicitOrderBy[0].field:null}function Vv(e){for(const t of e.filters){const e=t.getFirstInequalityField();if(null!==e)return e}return null}function Uv(e){return null!==e.collectionGroup}function Bv(e){const t=qm(e);if(null===t.wt){t.wt=[];const e=Vv(t),n=qv(t);if(null!==e&&null===n)e.isKeyField()||t.wt.push(new ov(e)),t.wt.push(new ov(ag.keyField(),"asc"));else{let e=!1;for(const n of t.explicitOrderBy)t.wt.push(n),n.field.isKeyField()&&(e=!0);if(!e){const e=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc";t.wt.push(new ov(ag.keyField(),e))}}}return t.wt}function zv(e){const t=qm(e);if(!t._t)if("F"===t.limitType)t._t=xv(t.path,t.collectionGroup,Bv(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const n of Bv(t)){const t="desc"===n.dir?"asc":"desc";e.push(new ov(n.field,t))}const n=t.endAt?new rv(t.endAt.position,t.endAt.inclusive):null,r=t.startAt?new rv(t.startAt.position,t.startAt.inclusive):null;t._t=xv(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t._t}function $v(e,t){t.getFirstInequalityField(),Vv(e);const n=e.filters.concat([t]);return new Mv(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function Wv(e,t,n){return new Mv(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Qv(e,t){return Nv(zv(e),zv(t))&&e.limitType===t.limitType}function Hv(e){return`${Av(zv(e))}|lt:${e.limitType}`}function Gv(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=`, filters: [${e.filters.map((e=>vv(e))).join(", ")}]`),Pg(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(t+=`, orderBy: [${e.orderBy.map((e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e))).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map((e=>Vy(e))).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map((e=>Vy(e))).join(",")),`Target(${t})`}(zv(e))}; limitType=${e.limitType})`}function Kv(e,t){return t.isFoundDocument()&&function(e,t){const n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):cg.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(const n of Bv(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&function(e,t){return!(e.startAt&&!function(e,t,n){const r=iv(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,Bv(e),t))&&!(e.endAt&&!function(e,t,n){const r=iv(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,Bv(e),t))}(e,t)}function Yv(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Jv(e){return(t,n)=>{let r=!1;for(const i of Bv(e)){const e=Xv(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}function Xv(e,t,n){const r=e.field.isKeyField()?cg.comparator(t.key,n.key):function(e,t,n){const r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?jy(r,i):Fm()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return Fm()}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Zv=class{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let n=0;n<r.length;n++)if(this.equalsFn(r[n][0],e))return void(r[n]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(e){fy(this.inner,((t,n)=>{for(const[t,r]of n)e(t,r)}))}isEmpty(){return py(this.inner)}size(){return this.innerSize}};
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const e_=new my(cg.comparator);function t_(){return e_}const n_=new my(cg.comparator);function r_(...e){let t=n_;for(const n of e)t=t.insert(n.key,n);return t}function i_(e){let t=n_;return e.forEach(((e,n)=>t=t.insert(e,n.overlayedDocument))),t}function s_(){return a_()}function o_(){return a_()}function a_(){return new Zv((e=>e.toString()),((e,t)=>e.isEqual(t)))}const c_=new my(cg.comparator),u_=new vy(cg.comparator);function l_(...e){let t=u_;for(const n of e)t=t.add(n);return t}const h_=new vy(Zm);function d_(){return h_}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function f_(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Mg(t)?"-0":t}}function p_(e){return{integerValue:""+e}}function m_(e,t){return Lg(t)?p_(t):f_(e,t)}
/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class g_{constructor(){this._=void 0}}function y_(e,t,n){return e instanceof w_?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&xy(t)&&(t=Ay(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof b_?I_(e,t):e instanceof E_?T_(e,t):function(e,t){const n=__(e,t),r=k_(n)+k_(e.gt);return zy(n)&&zy(e.gt)?p_(r):f_(e.serializer,r)}(e,t)}function v_(e,t,n){return e instanceof b_?I_(e,t):e instanceof E_?T_(e,t):n}function __(e,t){return e instanceof S_?zy(n=t)||function(e){return!!e&&"doubleValue"in e}(n)?t:{integerValue:0}:null;var n}class w_ extends g_{}class b_ extends g_{constructor(e){super(),this.elements=e}}function I_(e,t){const n=C_(t);for(const t of e.elements)n.some((e=>Ly(e,t)))||n.push(t);return{arrayValue:{values:n}}}class E_ extends g_{constructor(e){super(),this.elements=e}}function T_(e,t){let n=C_(t);for(const t of e.elements)n=n.filter((e=>!Ly(e,t)));return{arrayValue:{values:n}}}class S_ extends g_{constructor(e,t){super(),this.serializer=e,this.gt=t}}function k_(e){return ky(e.integerValue||e.doubleValue)}function C_(e){return $y(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class x_{constructor(e,t){this.field=e,this.transform=t}}class A_{constructor(e,t){this.version=e,this.transformResults=t}}class N_{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new N_}static exists(e){return new N_(void 0,e)}static updateTime(e){return new N_(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 D_(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class R_{}function O_(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new z_(e.key,N_.none()):new j_(e.key,e.data,N_.none());{const n=e.data,r=ev.empty();let i=new vy(ag.comparator);for(let e of t.fields)if(!i.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?r.delete(e):r.set(e,t),i=i.add(e)}return new q_(e.key,r,new by(i.toArray()),N_.none())}}function P_(e,t,n){e instanceof j_?function(e,t,n){const r=e.value.clone(),i=U_(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof q_?function(e,t,n){if(!D_(e.precondition,t))return void t.convertToUnknownDocument(n.version);const r=U_(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(V_(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function M_(e,t,n,r){return e instanceof j_?function(e,t,n,r){if(!D_(e.precondition,t))return n;const i=e.value.clone(),s=B_(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof q_?function(e,t,n,r){if(!D_(e.precondition,t))return n;const i=B_(e.fieldTransforms,r,t),s=t.data;return s.setAll(V_(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e=>e.field)))}(e,t,n,r):function(e,t,n){return D_(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}(e,t,n)}function L_(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=__(r.transform,e||null);null!=i&&(null===n&&(n=ev.empty()),n.set(r.field,i))}return n||null}function F_(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&!!function(e,t){return void 0===e&&void 0===t||!(!e||!t)&&eg(e,t,((e,t)=>function(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof b_&&t instanceof b_||e instanceof E_&&t instanceof E_?eg(e.elements,t.elements,Ly):e instanceof S_&&t instanceof S_?Ly(e.gt,t.gt):e instanceof w_&&t instanceof w_}(e.transform,t.transform)}(e,t)))}(e.fieldTransforms,t.fieldTransforms)&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class j_ extends R_{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class q_ extends R_{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function V_(e){const t=new Map;return e.fieldMask.fields.forEach((n=>{if(!n.isEmpty()){const r=e.data.field(n);t.set(n,r)}})),t}function U_(e,t,n){const r=new Map;jm(e.length===n.length);for(let i=0;i<n.length;i++){const s=e[i],o=s.transform,a=t.data.field(s.field);r.set(s.field,v_(o,a,n[i]))}return r}function B_(e,t,n){const r=new Map;for(const i of e){const e=i.transform,s=n.data.field(i.field);r.set(i.field,y_(e,s,t))}return r}class z_ extends R_{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class $_ extends R_{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class W_{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){const n=t.mutationResults;for(let t=0;t<this.mutations.length;t++){const r=this.mutations[t];r.key.isEqual(e.key)&&P_(r,e,n[t])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=M_(n,e,t,this.localWriteTime));for(const n of this.mutations)n.key.isEqual(e.key)&&(t=M_(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){const n=o_();return this.mutations.forEach((r=>{const i=e.get(r.key),s=i.overlayedDocument;let o=this.applyToLocalView(s,i.mutatedFields);o=t.has(r.key)?null:o;const a=O_(s,o);null!==a&&n.set(r.key,a),s.isValidDocument()||s.convertToNoDocument(rg.min())})),n}keys(){return this.mutations.reduce(((e,t)=>e.add(t.key)),l_())}isEqual(e){return this.batchId===e.batchId&&eg(this.mutations,e.mutations,((e,t)=>F_(e,t)))&&eg(this.baseMutations,e.baseMutations,((e,t)=>F_(e,t)))}}class Q_{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){jm(e.mutations.length===n.length);let r=c_;const i=e.mutations;for(let e=0;e<i.length;e++)r=r.insert(i[e].key,n[e].version);return new Q_(e,t,n,r)}}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class H_{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n      largestBatchId: ${this.largestBatchId},\n      mutation: ${this.mutation.toString()}\n    }`}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class G_{constructor(e,t){this.count=e,this.unchangedNames=t}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var K_,Y_;function J_(e){switch(e){default:return Fm();case Vm.CANCELLED:case Vm.UNKNOWN:case Vm.DEADLINE_EXCEEDED:case Vm.RESOURCE_EXHAUSTED:case Vm.INTERNAL:case Vm.UNAVAILABLE:case Vm.UNAUTHENTICATED:return!1;case Vm.INVALID_ARGUMENT:case Vm.NOT_FOUND:case Vm.ALREADY_EXISTS:case Vm.PERMISSION_DENIED:case Vm.FAILED_PRECONDITION:case Vm.ABORTED:case Vm.OUT_OF_RANGE:case Vm.UNIMPLEMENTED:case Vm.DATA_LOSS:return!0}}function X_(e){if(void 0===e)return Pm("GRPC error has no .code"),Vm.UNKNOWN;switch(e){case K_.OK:return Vm.OK;case K_.CANCELLED:return Vm.CANCELLED;case K_.UNKNOWN:return Vm.UNKNOWN;case K_.DEADLINE_EXCEEDED:return Vm.DEADLINE_EXCEEDED;case K_.RESOURCE_EXHAUSTED:return Vm.RESOURCE_EXHAUSTED;case K_.INTERNAL:return Vm.INTERNAL;case K_.UNAVAILABLE:return Vm.UNAVAILABLE;case K_.UNAUTHENTICATED:return Vm.UNAUTHENTICATED;case K_.INVALID_ARGUMENT:return Vm.INVALID_ARGUMENT;case K_.NOT_FOUND:return Vm.NOT_FOUND;case K_.ALREADY_EXISTS:return Vm.ALREADY_EXISTS;case K_.PERMISSION_DENIED:return Vm.PERMISSION_DENIED;case K_.FAILED_PRECONDITION:return Vm.FAILED_PRECONDITION;case K_.ABORTED:return Vm.ABORTED;case K_.OUT_OF_RANGE:return Vm.OUT_OF_RANGE;case K_.UNIMPLEMENTED:return Vm.UNIMPLEMENTED;case K_.DATA_LOSS:return Vm.DATA_LOSS;default:return Fm()}}(Y_=K_||(K_={}))[Y_.OK=0]="OK",Y_[Y_.CANCELLED=1]="CANCELLED",Y_[Y_.UNKNOWN=2]="UNKNOWN",Y_[Y_.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",Y_[Y_.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",Y_[Y_.NOT_FOUND=5]="NOT_FOUND",Y_[Y_.ALREADY_EXISTS=6]="ALREADY_EXISTS",Y_[Y_.PERMISSION_DENIED=7]="PERMISSION_DENIED",Y_[Y_.UNAUTHENTICATED=16]="UNAUTHENTICATED",Y_[Y_.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",Y_[Y_.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",Y_[Y_.ABORTED=10]="ABORTED",Y_[Y_.OUT_OF_RANGE=11]="OUT_OF_RANGE",Y_[Y_.UNIMPLEMENTED=12]="UNIMPLEMENTED",Y_[Y_.INTERNAL=13]="INTERNAL",Y_[Y_.UNAVAILABLE=14]="UNAVAILABLE",Y_[Y_.DATA_LOSS=15]="DATA_LOSS";
/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class Z_{constructor(){this.onExistenceFilterMismatchCallbacks=new Map}static get instance(){return ew}static getOrCreateInstance(){return null===ew&&(ew=new Z_),ew}onExistenceFilterMismatch(e){const t=Symbol();return this.onExistenceFilterMismatchCallbacks.set(t,e),()=>this.onExistenceFilterMismatchCallbacks.delete(t)}notifyOnExistenceFilterMismatch(e){this.onExistenceFilterMismatchCallbacks.forEach((t=>t(e)))}}let ew=null;
/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function tw(){return new TextEncoder}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const nw=new Cm([4294967295,4294967295],0);function rw(e){const t=tw().encode(e),n=new km;return n.update(t),new Uint8Array(n.digest())}function iw(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new Cm([n,r],0),new Cm([i,s],0)]}class sw{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new ow(`Invalid padding: ${t}`);if(n<0)throw new ow(`Invalid hash count: ${n}`);if(e.length>0&&0===this.hashCount)throw new ow(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new ow(`Invalid padding when bitmap length is 0: ${t}`);this.It=8*e.length-t,this.Tt=Cm.fromNumber(this.It)}Et(e,t,n){let r=e.add(t.multiply(Cm.fromNumber(n)));return 1===r.compare(nw)&&(r=new Cm([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Tt).toNumber()}At(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}vt(e){if(0===this.It)return!1;const t=rw(e),[n,r]=iw(t);for(let e=0;e<this.hashCount;e++){const t=this.Et(n,r,e);if(!this.At(t))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new sw(i,r,t);return n.forEach((e=>s.insert(e))),s}insert(e){if(0===this.It)return;const t=rw(e),[n,r]=iw(t);for(let e=0;e<this.hashCount;e++){const t=this.Et(n,r,e);this.Rt(t)}}Rt(e){const t=Math.floor(e/8),n=e%8;this.bitmap[t]|=1<<n}}class ow extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class aw{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,cw.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new aw(rg.min(),r,new my(Zm),t_(),l_())}}class cw{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new cw(n,t,l_(),l_(),l_())}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class uw{constructor(e,t,n,r){this.Pt=e,this.removedTargetIds=t,this.key=n,this.bt=r}}class lw{constructor(e,t){this.targetId=e,this.Vt=t}}class hw{constructor(e,t,n=Ey.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class dw{constructor(){this.St=0,this.Dt=mw(),this.Ct=Ey.EMPTY_BYTE_STRING,this.xt=!1,this.Nt=!0}get current(){return this.xt}get resumeToken(){return this.Ct}get kt(){return 0!==this.St}get Mt(){return this.Nt}$t(e){e.approximateByteSize()>0&&(this.Nt=!0,this.Ct=e)}Ot(){let e=l_(),t=l_(),n=l_();return this.Dt.forEach(((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:Fm()}})),new cw(this.Ct,this.xt,e,t,n)}Ft(){this.Nt=!1,this.Dt=mw()}Bt(e,t){this.Nt=!0,this.Dt=this.Dt.insert(e,t)}Lt(e){this.Nt=!0,this.Dt=this.Dt.remove(e)}qt(){this.St+=1}Ut(){this.St-=1}Kt(){this.Nt=!0,this.xt=!0}}class fw{constructor(e){this.Gt=e,this.Qt=new Map,this.jt=t_(),this.zt=pw(),this.Wt=new my(Zm)}Ht(e){for(const t of e.Pt)e.bt&&e.bt.isFoundDocument()?this.Jt(t,e.bt):this.Yt(t,e.key,e.bt);for(const t of e.removedTargetIds)this.Yt(t,e.key,e.bt)}Xt(e){this.forEachTarget(e,(t=>{const n=this.Zt(t);switch(e.state){case 0:this.te(t)&&n.$t(e.resumeToken);break;case 1:n.Ut(),n.kt||n.Ft(),n.$t(e.resumeToken);break;case 2:n.Ut(),n.kt||this.removeTarget(t);break;case 3:this.te(t)&&(n.Kt(),n.$t(e.resumeToken));break;case 4:this.te(t)&&(this.ee(t),n.$t(e.resumeToken));break;default:Fm()}}))}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.Qt.forEach(((e,n)=>{this.te(n)&&t(n)}))}ne(e){var t;const n=e.targetId,r=e.Vt.count,i=this.se(n);if(i){const s=i.target;if(Dv(s))if(0===r){const e=new cg(s.path);this.Yt(n,e,nv.newNoDocument(e,rg.min()))}else jm(1===r);else{const i=this.ie(n);if(i!==r){const r=this.re(e,i);if(0!==r){this.ee(n);const e=2===r?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Wt=this.Wt.insert(n,e)}null===(t=Z_.instance)||void 0===t||t.notifyOnExistenceFilterMismatch(function(e,t,n){var r,i,s,o,a,c;const u={localCacheCount:t,existenceFilterCount:n.count},l=n.unchangedNames;return l&&(u.bloomFilter={applied:0===e,hashCount:null!==(r=null==l?void 0:l.hashCount)&&void 0!==r?r:0,bitmapLength:null!==(o=null===(s=null===(i=null==l?void 0:l.bits)||void 0===i?void 0:i.bitmap)||void 0===s?void 0:s.length)&&void 0!==o?o:0,padding:null!==(c=null===(a=null==l?void 0:l.bits)||void 0===a?void 0:a.padding)&&void 0!==c?c:0}),u}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(r,i,e.Vt))}}}}re(e,t){const{unchangedNames:n,count:r}=e.Vt;if(!n||!n.bits)return 1;const{bits:{bitmap:i="",padding:s=0},hashCount:o=0}=n;let a,c;try{a=Cy(i).toUint8Array()}catch(e){if(e instanceof Iy)return Mm("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),1;throw e}try{c=new sw(a,s,o)}catch(e){return Mm(e instanceof ow?"BloomFilter error: ":"Applying bloom filter failed: ",e),1}return 0===c.It?1:r!==t-this.oe(e.targetId,c)?2:0}oe(e,t){const n=this.Gt.getRemoteKeysForTarget(e);let r=0;return n.forEach((n=>{const i=this.Gt.ue(),s=`projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;t.vt(s)||(this.Yt(e,n,null),r++)})),r}ce(e){const t=new Map;this.Qt.forEach(((n,r)=>{const i=this.se(r);if(i){if(n.current&&Dv(i.target)){const t=new cg(i.target.path);null!==this.jt.get(t)||this.ae(r,t)||this.Yt(r,t,nv.newNoDocument(t,e))}n.Mt&&(t.set(r,n.Ot()),n.Ft())}}));let n=l_();this.zt.forEach(((e,t)=>{let r=!0;t.forEachWhile((e=>{const t=this.se(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)})),r&&(n=n.add(e))})),this.jt.forEach(((t,n)=>n.setReadTime(e)));const r=new aw(e,t,this.Wt,this.jt,n);return this.jt=t_(),this.zt=pw(),this.Wt=new my(Zm),r}Jt(e,t){if(!this.te(e))return;const n=this.ae(e,t.key)?2:0;this.Zt(e).Bt(t.key,n),this.jt=this.jt.insert(t.key,t),this.zt=this.zt.insert(t.key,this.he(t.key).add(e))}Yt(e,t,n){if(!this.te(e))return;const r=this.Zt(e);this.ae(e,t)?r.Bt(t,1):r.Lt(t),this.zt=this.zt.insert(t,this.he(t).delete(e)),n&&(this.jt=this.jt.insert(t,n))}removeTarget(e){this.Qt.delete(e)}ie(e){const t=this.Zt(e).Ot();return this.Gt.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}qt(e){this.Zt(e).qt()}Zt(e){let t=this.Qt.get(e);return t||(t=new dw,this.Qt.set(e,t)),t}he(e){let t=this.zt.get(e);return t||(t=new vy(Zm),this.zt=this.zt.insert(e,t)),t}te(e){const t=null!==this.se(e);return t||Om("WatchChangeAggregator","Detected inactive target",e),t}se(e){const t=this.Qt.get(e);return t&&t.kt?null:this.Gt.le(e)}ee(e){this.Qt.set(e,new dw),this.Gt.getRemoteKeysForTarget(e).forEach((t=>{this.Yt(e,t,null)}))}ae(e,t){return this.Gt.getRemoteKeysForTarget(e).has(t)}}function pw(){return new my(cg.comparator)}function mw(){return new my(cg.comparator)}const gw={asc:"ASCENDING",desc:"DESCENDING"},yw={"<":"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"},vw={and:"AND",or:"OR"};class _w{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function ww(e,t){return e.useProto3Json||Pg(t)?t:{value:t}}function bw(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function Iw(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function Ew(e,t){return bw(e,t.toTimestamp())}function Tw(e){return jm(!!e),rg.fromTimestamp(function(e){const t=Sy(e);return new ng(t.seconds,t.nanos)}(e))}function Sw(e,t){return function(e){return new sg(["projects",e.projectId,"databases",e.database])}(e).child("documents").child(t).canonicalString()}function kw(e){const t=sg.fromString(e);return jm(Gw(t)),t}function Cw(e,t){return Sw(e.databaseId,t.path)}function xw(e,t){const n=kw(t);if(n.get(1)!==e.databaseId.projectId)throw new Um(Vm.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 Um(Vm.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new cg(Rw(n))}function Aw(e,t){return Sw(e.databaseId,t)}function Nw(e){const t=kw(e);return 4===t.length?sg.emptyPath():Rw(t)}function Dw(e){return new sg(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function Rw(e){return jm(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function Ow(e,t,n){return{name:Cw(e,t),fields:n.value.mapValue.fields}}function Pw(e,t,n){const r=xw(e,t.name),i=Tw(t.updateTime),s=t.createTime?Tw(t.createTime):rg.min(),o=new ev({mapValue:{fields:t.fields}}),a=nv.newFoundDocument(r,i,s,o);return n&&a.setHasCommittedMutations(),n?a.setHasCommittedMutations():a}function Mw(e,t){let n;if(t instanceof j_)n={update:Ow(e,t.key,t.value)};else if(t instanceof z_)n={delete:Cw(e,t.key)};else if(t instanceof q_)n={update:Ow(e,t.key,t.data),updateMask:Hw(t.fieldMask)};else{if(!(t instanceof $_))return Fm();n={verify:Cw(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map((e=>function(e,t){const n=t.transform;if(n instanceof w_)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof b_)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof E_)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof S_)return{fieldPath:t.field.canonicalString(),increment:n.gt};throw Fm()}(0,e)))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:Ew(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:Fm()}(e,t.precondition)),n}function Lw(e,t){const n=t.currentDocument?function(e){return void 0!==e.updateTime?N_.updateTime(Tw(e.updateTime)):void 0!==e.exists?N_.exists(e.exists):N_.none()}(t.currentDocument):N_.none(),r=t.updateTransforms?t.updateTransforms.map((t=>function(e,t){let n=null;if("setToServerValue"in t)jm("REQUEST_TIME"===t.setToServerValue),n=new w_;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new b_(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new E_(e)}else"increment"in t?n=new S_(e,t.increment):Fm();const r=ag.fromServerFormat(t.fieldPath);return new x_(r,n)}(e,t))):[];if(t.update){t.update.name;const i=xw(e,t.update.name),s=new ev({mapValue:{fields:t.update.fields}});if(t.updateMask){const e=function(e){const t=e.fieldPaths||[];return new by(t.map((e=>ag.fromServerFormat(e))))}(t.updateMask);return new q_(i,s,e,n,r)}return new j_(i,s,n,r)}if(t.delete){const r=xw(e,t.delete);return new z_(r,n)}if(t.verify){const r=xw(e,t.verify);return new $_(r,n)}return Fm()}function Fw(e,t){return{documents:[Aw(e,t.path)]}}function jw(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=Aw(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=Aw(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);const i=function(e){if(0!==e.length)return Qw(lv.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);const s=function(e){if(0!==e.length)return e.map((e=>function(e){return{field:$w(e.field),direction:Uw(e.dir)}}(e)))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);const o=ww(e,t.limit);var a;return null!==o&&(n.structuredQuery.limit=o),t.startAt&&(n.structuredQuery.startAt={before:(a=t.startAt).inclusive,values:a.position}),t.endAt&&(n.structuredQuery.endAt=function(e){return{before:!e.inclusive,values:e.position}}(t.endAt)),n}function qw(e){let t=Nw(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(r>0){jm(1===r);const e=n.from[0];e.allDescendants?i=e.collectionId:t=t.child(e.collectionId)}let s=[];n.where&&(s=function(e){const t=Vw(e);return t instanceof lv&&fv(t)?t.getFilters():[t]}(n.where));let o=[];n.orderBy&&(o=n.orderBy.map((e=>function(e){return new ov(Ww(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e))));let a=null;n.limit&&(a=function(e){let t;return t="object"==typeof e?e.value:e,Pg(t)?null:t}(n.limit));let c=null;n.startAt&&(c=function(e){const t=!!e.before,n=e.values||[];return new rv(n,t)}(n.startAt));let u=null;return n.endAt&&(u=function(e){const t=!e.before,n=e.values||[];return new rv(n,t)}(n.endAt)),Lv(t,i,o,s,a,"F",c,u)}function Vw(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=Ww(e.unaryFilter.field);return uv.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=Ww(e.unaryFilter.field);return uv.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=Ww(e.unaryFilter.field);return uv.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=Ww(e.unaryFilter.field);return uv.create(i,"!=",{nullValue:"NULL_VALUE"});default:return Fm()}}(e):void 0!==e.fieldFilter?function(e){return uv.create(Ww(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return Fm()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return lv.create(e.compositeFilter.filters.map((e=>Vw(e))),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return Fm()}}(e.compositeFilter.op))}(e):Fm()}function Uw(e){return gw[e]}function Bw(e){return yw[e]}function zw(e){return vw[e]}function $w(e){return{fieldPath:e.canonicalString()}}function Ww(e){return ag.fromServerFormat(e.fieldPath)}function Qw(e){return e instanceof uv?function(e){if("=="===e.op){if(Qy(e.value))return{unaryFilter:{field:$w(e.field),op:"IS_NAN"}};if(Wy(e.value))return{unaryFilter:{field:$w(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Qy(e.value))return{unaryFilter:{field:$w(e.field),op:"IS_NOT_NAN"}};if(Wy(e.value))return{unaryFilter:{field:$w(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:$w(e.field),op:Bw(e.op),value:e.value}}}(e):e instanceof lv?function(e){const t=e.getFilters().map((e=>Qw(e)));return 1===t.length?t[0]:{compositeFilter:{op:zw(e.op),filters:t}}}(e):Fm()}function Hw(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function Gw(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Kw{constructor(e,t,n,r,i=rg.min(),s=rg.min(),o=Ey.EMPTY_BYTE_STRING,a=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=o,this.expectedCount=a}withSequenceNumber(e){return new Kw(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new Kw(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new Kw(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new Kw(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Yw{constructor(e){this.fe=e}}function Jw(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:Xw(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document=function(e,t){return{name:Cw(e,t.key),fields:t.data.value.mapValue.fields,updateTime:bw(e,t.version.toTimestamp()),createTime:bw(e,t.createTime.toTimestamp())}}(e.fe,t);else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Zw(t.version)};else{if(!t.isUnknownDocument())return Fm();r.unknownDocument={path:n.path.toArray(),version:Zw(t.version)}}return r}function Xw(e){const t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Zw(e){const t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function eb(e){const t=new ng(e.seconds,e.nanoseconds);return rg.fromTimestamp(t)}function tb(e,t){const n=(t.baseMutations||[]).map((t=>Lw(e.fe,t)));for(let e=0;e<t.mutations.length-1;++e){const n=t.mutations[e];if(e+1<t.mutations.length&&void 0!==t.mutations[e+1].transform){const r=t.mutations[e+1];n.updateTransforms=r.transform.fieldTransforms,t.mutations.splice(e+1,1),++e}}const r=t.mutations.map((t=>Lw(e.fe,t))),i=ng.fromMillis(t.localWriteTimeMs);return new W_(t.batchId,i,n,r)}function nb(e){const t=eb(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?eb(e.lastLimboFreeSnapshotVersion):rg.min();let r;var i;return void 0!==e.query.documents?(jm(1===(i=e.query).documents.length),r=zv(Fv(Nw(i.documents[0])))):r=function(e){return zv(qw(e))}(e.query),new Kw(r,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,t,n,Ey.fromBase64String(e.resumeToken))}function rb(e,t){const n=Zw(t.snapshotVersion),r=Zw(t.lastLimboFreeSnapshotVersion);let i;i=Dv(t.target)?Fw(e.fe,t.target):jw(e.fe,t.target);const s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Av(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function ib(e){const t=qw({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Wv(t,t.limit,"L"):t}function sb(e,t){return new H_(t.largestBatchId,Lw(e.fe,t.overlayMutation))}function ob(e,t){const n=t.path.lastSegment();return[e,Fg(t.path.popLast()),n]}function ab(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:Zw(r.readTime),documentKey:Fg(r.documentKey.path),largestBatchId:r.largestBatchId}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class cb{getBundleMetadata(e,t){return ub(e).get(t).next((e=>{if(e)return{id:(t=e).bundleId,createTime:eb(t.createTime),version:t.version};var t}))}saveBundleMetadata(e,t){return ub(e).put({bundleId:(n=t).id,createTime:Zw(Tw(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return lb(e).get(t).next((e=>{if(e)return{name:(t=e).name,query:ib(t.bundledQuery),readTime:eb(t.readTime)};var t}))}saveNamedQuery(e,t){return lb(e).put(function(e){return{name:e.name,readTime:Zw(Tw(e.readTime)),bundledQuery:e.bundledQuery}}(t))}}function ub(e){return hy(e,"bundles")}function lb(e){return hy(e,"namedQueries")}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class hb{constructor(e,t){this.serializer=e,this.userId=t}static de(e,t){const n=t.uid||"";return new hb(e,n)}getOverlay(e,t){return db(e).get(ob(this.userId,t)).next((e=>e?sb(this.serializer,e):null))}getOverlays(e,t){const n=s_();return bg.forEach(t,(t=>this.getOverlay(e,t).next((e=>{null!==e&&n.set(t,e)})))).next((()=>n))}saveOverlays(e,t,n){const r=[];return n.forEach(((n,i)=>{const s=new H_(t,i);r.push(this.we(e,s))})),bg.waitFor(r)}removeOverlaysForBatchId(e,t,n){const r=new Set;t.forEach((e=>r.add(Fg(e.getCollectionPath()))));const i=[];return r.forEach((t=>{const r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,n+1],!1,!0);i.push(db(e).J("collectionPathOverlayIndex",r))})),bg.waitFor(i)}getOverlaysForCollection(e,t,n){const r=s_(),i=Fg(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return db(e).j("collectionPathOverlayIndex",s).next((e=>{for(const t of e){const e=sb(this.serializer,t);r.set(e.getKey(),e)}return r}))}getOverlaysForCollectionGroup(e,t,n,r){const i=s_();let s;const o=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return db(e).X({index:"collectionGroupOverlayIndex",range:o},((e,t,n)=>{const o=sb(this.serializer,t);i.size()<r||o.largestBatchId===s?(i.set(o.getKey(),o),s=o.largestBatchId):n.done()})).next((()=>i))}we(e,t){return db(e).put(function(e,t,n){const[r,i,s]=ob(t,n.mutation.key);return{userId:t,collectionPath:i,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:Mw(e.fe,n.mutation)}}(this.serializer,this.userId,t))}}function db(e){return hy(e,"documentOverlays")}
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class fb{constructor(){}_e(e,t){this.me(e,t),t.ge()}me(e,t){if("nullValue"in e)this.ye(t,5);else if("booleanValue"in e)this.ye(t,10),t.pe(e.booleanValue?1:0);else if("integerValue"in e)this.ye(t,15),t.pe(ky(e.integerValue));else if("doubleValue"in e){const n=ky(e.doubleValue);isNaN(n)?this.ye(t,13):(this.ye(t,15),Mg(n)?t.pe(0):t.pe(n))}else if("timestampValue"in e){const n=e.timestampValue;this.ye(t,20),"string"==typeof n?t.Ie(n):(t.Ie(`${n.seconds||""}`),t.pe(n.nanos||0))}else if("stringValue"in e)this.Te(e.stringValue,t),this.Ee(t);else if("bytesValue"in e)this.ye(t,30),t.Ae(Cy(e.bytesValue)),this.Ee(t);else if("referenceValue"in e)this.ve(e.referenceValue,t);else if("geoPointValue"in e){const n=e.geoPointValue;this.ye(t,45),t.pe(n.latitude||0),t.pe(n.longitude||0)}else"mapValue"in e?Ky(e)?this.ye(t,Number.MAX_SAFE_INTEGER):(this.Re(e.mapValue,t),this.Ee(t)):"arrayValue"in e?(this.Pe(e.arrayValue,t),this.Ee(t)):Fm()}Te(e,t){this.ye(t,25),this.be(e,t)}be(e,t){t.Ie(e)}Re(e,t){const n=e.fields||{};this.ye(t,55);for(const e of Object.keys(n))this.Te(e,t),this.me(n[e],t)}Pe(e,t){const n=e.values||[];this.ye(t,50);for(const e of n)this.me(e,t)}ve(e,t){this.ye(t,37),cg.fromName(e).path.forEach((e=>{this.ye(t,60),this.be(e,t)}))}ye(e,t){e.pe(t)}Ee(e){e.pe(2)}}function pb(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}function mb(e){const t=64-function(e){let t=0;for(let n=0;n<8;++n){const r=pb(255&e[n]);if(t+=r,8!==r)break}return t}(e);return Math.ceil(t/8)}fb.Ve=new fb;class gb{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Se(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.De(n.value),n=t.next();this.Ce()}xe(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ne(n.value),n=t.next();this.ke()}Me(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.De(e);else if(e<2048)this.De(960|e>>>6),this.De(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.De(480|e>>>12),this.De(128|63&e>>>6),this.De(128|63&e);else{const e=t.codePointAt(0);this.De(240|e>>>18),this.De(128|63&e>>>12),this.De(128|63&e>>>6),this.De(128|63&e)}}this.Ce()}$e(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ne(e);else if(e<2048)this.Ne(960|e>>>6),this.Ne(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ne(480|e>>>12),this.Ne(128|63&e>>>6),this.Ne(128|63&e);else{const e=t.codePointAt(0);this.Ne(240|e>>>18),this.Ne(128|63&e>>>12),this.Ne(128|63&e>>>6),this.Ne(128|63&e)}}this.ke()}Oe(e){const t=this.Fe(e),n=mb(t);this.Be(1+n),this.buffer[this.position++]=255&n;for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=255&t[e]}Le(e){const t=this.Fe(e),n=mb(t);this.Be(1+n),this.buffer[this.position++]=~(255&n);for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=~(255&t[e])}qe(){this.Ue(255),this.Ue(255)}Ke(){this.Ge(255),this.Ge(255)}reset(){this.position=0}seed(e){this.Be(e.length),this.buffer.set(e,this.position),this.position+=e.length}Qe(){return this.buffer.slice(0,this.position)}Fe(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let e=1;e<t.length;++e)t[e]^=n?255:0;return t}De(e){const t=255&e;0===t?(this.Ue(0),this.Ue(255)):255===t?(this.Ue(255),this.Ue(0)):this.Ue(t)}Ne(e){const t=255&e;0===t?(this.Ge(0),this.Ge(255)):255===t?(this.Ge(255),this.Ge(0)):this.Ge(e)}Ce(){this.Ue(0),this.Ue(1)}ke(){this.Ge(0),this.Ge(1)}Ue(e){this.Be(1),this.buffer[this.position++]=e}Ge(e){this.Be(1),this.buffer[this.position++]=~e}Be(e){const t=e+this.position;if(t<=this.buffer.length)return;let n=2*this.buffer.length;n<t&&(n=t);const r=new Uint8Array(n);r.set(this.buffer),this.buffer=r}}class yb{constructor(e){this.je=e}Ae(e){this.je.Se(e)}Ie(e){this.je.Me(e)}pe(e){this.je.Oe(e)}ge(){this.je.qe()}}class vb{constructor(e){this.je=e}Ae(e){this.je.xe(e)}Ie(e){this.je.$e(e)}pe(e){this.je.Le(e)}ge(){this.je.Ke()}}class _b{constructor(){this.je=new gb,this.ze=new yb(this.je),this.We=new vb(this.je)}seed(e){this.je.seed(e)}He(e){return 0===e?this.ze:this.We}Qe(){return this.je.Qe()}reset(){this.je.reset()}}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class wb{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Je(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new wb(this.indexId,this.documentKey,this.arrayValue,n)}}function bb(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=Ib(e.arrayValue,t.arrayValue),0!==n?n:(n=Ib(e.directionalValue,t.directionalValue),0!==n?n:cg.comparator(e.documentKey,t.documentKey)))}function Ib(e,t){for(let n=0;n<e.length&&n<t.length;++n){const r=e[n]-t[n];if(0!==r)return r}return e.length-t.length}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Eb{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Ye=e.orderBy,this.Xe=[];for(const t of e.filters){const e=t;e.isInequality()?this.Ze=e:this.Xe.push(e)}}tn(e){jm(e.collectionGroup===this.collectionId);const t=lg(e);if(void 0!==t&&!this.en(t))return!1;const n=hg(e);let r=new Set,i=0,s=0;for(;i<n.length&&this.en(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(void 0!==this.Ze){if(!r.has(this.Ze.field.canonicalString())){const e=n[i];if(!this.nn(this.Ze,e)||!this.sn(this.Ye[s++],e))return!1}++i}for(;i<n.length;++i){const e=n[i];if(s>=this.Ye.length||!this.sn(this.Ye[s++],e))return!1}return!0}en(e){for(const t of this.Xe)if(this.nn(t,e))return!0;return!1}nn(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;const n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind===n}sn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Tb(e){var t,n;if(jm(e instanceof uv||e instanceof lv),e instanceof uv){if(e instanceof Tv){const r=(null===(n=null===(t=e.value.arrayValue)||void 0===t?void 0:t.values)||void 0===n?void 0:n.map((t=>uv.create(e.field,"==",t))))||[];return lv.create(r,"or")}return e}const r=e.filters.map((e=>Tb(e)));return lv.create(r,e.op)}function Sb(e){if(0===e.getFilters().length)return[];const t=Ab(Tb(e));return jm(xb(t)),kb(t)||Cb(t)?[t]:t.getFilters()}function kb(e){return e instanceof uv}function Cb(e){return e instanceof lv&&fv(e)}function xb(e){return kb(e)||Cb(e)||function(e){if(e instanceof lv&&dv(e)){for(const t of e.getFilters())if(!kb(t)&&!Cb(t))return!1;return!0}return!1}(e)}function Ab(e){if(jm(e instanceof uv||e instanceof lv),e instanceof uv)return e;if(1===e.filters.length)return Ab(e.filters[0]);const t=e.filters.map((e=>Ab(e)));let n=lv.create(t,e.op);return n=Rb(n),xb(n)?n:(jm(n instanceof lv),jm(hv(n)),jm(n.filters.length>1),n.filters.reduce(((e,t)=>Nb(e,t))))}function Nb(e,t){let n;return jm(e instanceof uv||e instanceof lv),jm(t instanceof uv||t instanceof lv),n=e instanceof uv?t instanceof uv?function(e,t){return lv.create([e,t],"and")}(e,t):Db(e,t):t instanceof uv?Db(t,e):function(e,t){if(jm(e.filters.length>0&&t.filters.length>0),hv(e)&&hv(t))return yv(e,t.getFilters());const n=dv(e)?e:t,r=dv(e)?t:e,i=n.filters.map((e=>Nb(e,r)));return lv.create(i,"or")}(e,t),Rb(n)}function Db(e,t){if(hv(t))return yv(t,e.getFilters());{const n=t.filters.map((t=>Nb(e,t)));return lv.create(n,"or")}}function Rb(e){if(jm(e instanceof uv||e instanceof lv),e instanceof uv)return e;const t=e.getFilters();if(1===t.length)return Rb(t[0]);if(pv(e))return e;const n=t.map((e=>Rb(e))),r=[];return n.forEach((t=>{t instanceof uv?r.push(t):t instanceof lv&&(t.op===e.op?r.push(...t.filters):r.push(t))})),1===r.length?r[0]:lv.create(r,e.op)
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */}class Ob{constructor(){this.rn=new Pb}addToCollectionParentIndex(e,t){return this.rn.add(t),bg.resolve()}getCollectionParents(e,t){return bg.resolve(this.rn.getEntries(t))}addFieldIndex(e,t){return bg.resolve()}deleteFieldIndex(e,t){return bg.resolve()}getDocumentsMatchingTarget(e,t){return bg.resolve(null)}getIndexType(e,t){return bg.resolve(0)}getFieldIndexes(e,t){return bg.resolve([])}getNextCollectionGroupToUpdate(e){return bg.resolve(null)}getMinOffset(e,t){return bg.resolve(gg.min())}getMinOffsetFromCollectionGroup(e,t){return bg.resolve(gg.min())}updateCollectionGroup(e,t,n){return bg.resolve()}updateIndexEntries(e,t){return bg.resolve()}}class Pb{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new vy(sg.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new vy(sg.comparator)).toArray()}}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Mb=new Uint8Array(0);class Lb{constructor(e,t){this.user=e,this.databaseId=t,this.on=new Pb,this.un=new Zv((e=>Av(e)),((e,t)=>Nv(e,t))),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(!this.on.has(t)){const n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener((()=>{this.on.add(t)}));const i={collectionId:n,parent:Fg(r)};return Fb(e).put(i)}return bg.resolve()}getCollectionParents(e,t){const n=[],r=IDBKeyRange.bound([t,""],[tg(t),""],!1,!0);return Fb(e).j(r).next((e=>{for(const r of e){if(r.collectionId!==t)break;n.push(Vg(r.parent))}return n}))}addFieldIndex(e,t){const n=qb(e),r=function(e){return{indexId:e.indexId,collectionGroup:e.collectionGroup,fields:e.fields.map((e=>[e.fieldPath.canonicalString(),e.kind]))}}(t);delete r.indexId;const i=n.add(r);if(t.indexState){const n=Vb(e);return i.next((e=>{n.put(ab(e,this.user,t.indexState.sequenceNumber,t.indexState.offset))}))}return i.next()}deleteFieldIndex(e,t){const n=qb(e),r=Vb(e),i=jb(e);return n.delete(t.indexId).next((()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))).next((()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))))}getDocumentsMatchingTarget(e,t){const n=jb(e);let r=!0;const i=new Map;return bg.forEach(this.cn(t),(t=>this.an(e,t).next((e=>{r&&(r=!!e),i.set(t,e)})))).next((()=>{if(r){let e=l_();const r=[];return bg.forEach(i,((i,s)=>{var o;Om("IndexedDbIndexManager",`Using index ${o=i,`id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map((e=>`${e.fieldPath}:${e.kind}`)).join(",")}`} to execute ${Av(t)}`);const a=function(e,t){const n=lg(t);if(void 0===n)return null;for(const t of Rv(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(s,i),c=function(e,t){const n=new Map;for(const r of hg(t))for(const t of Rv(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(s,i),u=function(e,t){const n=[];let r=!0;for(const i of hg(t)){const t=0===i.kind?Ov(e,i.fieldPath,e.startAt):Pv(e,i.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new rv(n,r)}(s,i),l=function(e,t){const n=[];let r=!0;for(const i of hg(t)){const t=0===i.kind?Pv(e,i.fieldPath,e.endAt):Ov(e,i.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new rv(n,r)}(s,i),h=this.hn(i,s,u),d=this.hn(i,s,l),f=this.ln(i,s,c),p=this.fn(i.indexId,a,h,u.inclusive,d,l.inclusive,f);return bg.forEach(p,(i=>n.H(i,t.limit).next((t=>{t.forEach((t=>{const n=cg.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),r.push(n))}))}))))})).next((()=>r))}return bg.resolve(null)}))}cn(e){let t=this.un.get(e);return t||(t=0===e.filters.length?[e]:Sb(lv.create(e.filters,"and")).map((t=>xv(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt))),this.un.set(e,t),t)}fn(e,t,n,r,i,s,o){const a=(null!=t?t.length:1)*Math.max(n.length,i.length),c=a/(null!=t?t.length:1),u=[];for(let l=0;l<a;++l){const a=t?this.dn(t[l/c]):Mb,h=this.wn(e,a,n[l%c],r),d=this._n(e,a,i[l%c],s),f=o.map((t=>this.wn(e,a,t,!0)));u.push(...this.createRange(h,d,f))}return u}wn(e,t,n,r){const i=new wb(e,cg.empty(),t,n);return r?i:i.Je()}_n(e,t,n,r){const i=new wb(e,cg.empty(),t,n);return r?i.Je():i}an(e,t){const n=new Eb(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next((e=>{let t=null;for(const r of e)n.tn(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t}))}getIndexType(e,t){let n=2;const r=this.cn(t);return bg.forEach(r,(t=>this.an(e,t).next((e=>{e?0!==n&&e.fields.length<function(e){let t=new vy(ag.comparator),n=!1;for(const r of e.filters)for(const e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(const n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})))).next((()=>function(e){return null!==e.limit}(t)&&r.length>1&&2===n?1:n))}mn(e,t){const n=new _b;for(const r of hg(e)){const e=t.data.field(r.fieldPath);if(null==e)return null;const i=n.He(r.kind);fb.Ve._e(e,i)}return n.Qe()}dn(e){const t=new _b;return fb.Ve._e(e,t.He(0)),t.Qe()}gn(e,t){const n=new _b;return fb.Ve._e(By(this.databaseId,t),n.He(function(e){const t=hg(e);return 0===t.length?0:t[t.length-1].kind}(e))),n.Qe()}ln(e,t,n){if(null===n)return[];let r=[];r.push(new _b);let i=0;for(const s of hg(e)){const e=n[i++];for(const n of r)if(this.yn(t,s.fieldPath)&&$y(e))r=this.pn(r,s,e);else{const t=n.He(s.kind);fb.Ve._e(e,t)}}return this.In(r)}hn(e,t,n){return this.ln(e,t,n.position)}In(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Qe();return t}pn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new _b;r.seed(n.Qe()),fb.Ve._e(e,r.He(t.kind)),i.push(r)}return i}yn(e,t){return!!e.filters.find((e=>e instanceof uv&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op)))}getFieldIndexes(e,t){const n=qb(e),r=Vb(e);return(t?n.j("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.j()).next((e=>{const t=[];return bg.forEach(e,(e=>r.get([e.indexId,this.uid]).next((n=>{t.push(function(e,t){const n=t?new fg(t.sequenceNumber,new gg(eb(t.readTime),new cg(Vg(t.documentKey)),t.largestBatchId)):fg.empty(),r=e.fields.map((([e,t])=>new dg(ag.fromServerFormat(e),t)));return new ug(e.indexId,e.collectionGroup,r,n)}(e,n))})))).next((()=>t))}))}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next((e=>0===e.length?null:(e.sort(((e,t)=>{const n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!==n?n:Zm(e.collectionGroup,t.collectionGroup)})),e[0].collectionGroup)))}updateCollectionGroup(e,t,n){const r=qb(e),i=Vb(e);return this.Tn(e).next((e=>r.j("collectionGroupIndex",IDBKeyRange.bound(t,t)).next((t=>bg.forEach(t,(t=>i.put(ab(t.indexId,this.user,e,n))))))))}updateIndexEntries(e,t){const n=new Map;return bg.forEach(t,((t,r)=>{const i=n.get(t.collectionGroup);return(i?bg.resolve(i):this.getFieldIndexes(e,t.collectionGroup)).next((i=>(n.set(t.collectionGroup,i),bg.forEach(i,(n=>this.En(e,t,n).next((t=>{const i=this.An(r,n);return t.isEqual(i)?bg.resolve():this.vn(e,r,n,t,i)})))))))}))}Rn(e,t,n,r){return jb(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.gn(n,t.key),documentKey:t.key.path.toArray()})}Pn(e,t,n,r){return jb(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.gn(n,t.key),t.key.path.toArray()])}En(e,t,n){const r=jb(e);let i=new vy(bb);return r.X({index:"documentKeyIndex",range:IDBKeyRange.only([n.indexId,this.uid,this.gn(n,t)])},((e,r)=>{i=i.add(new wb(n.indexId,t,r.arrayValue,r.directionalValue))})).next((()=>i))}An(e,t){let n=new vy(bb);const r=this.mn(t,e);if(null==r)return n;const i=lg(t);if(null!=i){const s=e.data.field(i.fieldPath);if($y(s))for(const i of s.arrayValue.values||[])n=n.add(new wb(t.indexId,e.key,this.dn(i),r))}else n=n.add(new wb(t.indexId,e.key,Mb,r));return n}vn(e,t,n,r,i){Om("IndexedDbIndexManager","Updating index entries for document '%s'",t.key);const s=[];return function(e,t,n,r,i){const s=e.getIterator(),o=t.getIterator();let a=wy(s),c=wy(o);for(;a||c;){let e=!1,t=!1;if(a&&c){const r=n(a,c);r<0?t=!0:r>0&&(e=!0)}else null!=a?t=!0:e=!0;e?(r(c),c=wy(o)):t?(i(a),a=wy(s)):(a=wy(s),c=wy(o))}}(r,i,bb,(r=>{s.push(this.Rn(e,t,n,r))}),(r=>{s.push(this.Pn(e,t,n,r))})),bg.waitFor(s)}Tn(e){let t=1;return Vb(e).X({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},((e,n,r)=>{r.done(),t=n.sequenceNumber+1})).next((()=>t))}createRange(e,t,n){n=n.sort(((e,t)=>bb(e,t))).filter(((e,t,n)=>!t||0!==bb(e,n[t-1])));const r=[];r.push(e);for(const i of n){const n=bb(i,e),s=bb(i,t);if(0===n)r[0]=e.Je();else if(n>0&&s<0)r.push(i),r.push(i.Je());else if(s>0)break}r.push(t);const i=[];for(let e=0;e<r.length;e+=2){if(this.bn(r[e],r[e+1]))return[];const t=[r[e].indexId,this.uid,r[e].arrayValue,r[e].directionalValue,Mb,[]],n=[r[e+1].indexId,this.uid,r[e+1].arrayValue,r[e+1].directionalValue,Mb,[]];i.push(IDBKeyRange.bound(t,n))}return i}bn(e,t){return bb(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(Ub)}getMinOffset(e,t){return bg.mapArray(this.cn(t),(t=>this.an(e,t).next((e=>e||Fm())))).next(Ub)}}function Fb(e){return hy(e,"collectionParents")}function jb(e){return hy(e,"indexEntries")}function qb(e){return hy(e,"indexConfiguration")}function Vb(e){return hy(e,"indexState")}function Ub(e){jm(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let r=1;r<e.length;r++){const i=e[r].indexState.offset;yg(i,t)<0&&(t=i),n<i.largestBatchId&&(n=i.largestBatchId)}return new gg(t.readTime,t.documentKey,n)}
/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Bb={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class zb{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new zb(e,zb.DEFAULT_COLLECTION_PERCENTILE,zb.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function $b(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],o=IDBKeyRange.only(n.batchId);let a=0;const c=r.X({range:o},((e,t,n)=>(a++,n.delete())));s.push(c.next((()=>{jm(1===a)})));const u=[];for(const e of n.mutations){const r=zg(t,e.key.path,n.batchId);s.push(i.delete(r)),u.push(e.key)}return bg.waitFor(s).next((()=>u))}function Wb(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 Fm();t=e.noDocument}return JSON.stringify(t).length}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */zb.DEFAULT_COLLECTION_PERCENTILE=10,zb.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,zb.DEFAULT=new zb(41943040,zb.DEFAULT_COLLECTION_PERCENTILE,zb.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),zb.DISABLED=new zb(-1,0,0);class Qb{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.Vn={}}static de(e,t,n,r){jm(""!==e.uid);const i=e.isAuthenticated()?e.uid:"";return new Qb(i,t,n,r)}checkEmpty(e){let t=!0;const n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Gb(e).X({index:"userMutationsIndex",range:n},((e,n,r)=>{t=!1,r.done()})).next((()=>t))}addMutationBatch(e,t,n,r){const i=Kb(e),s=Gb(e);return s.add({}).next((o=>{jm("number"==typeof o);const a=new W_(o,t,n,r),c=function(e,t,n){const r=n.baseMutations.map((t=>Mw(e.fe,t))),i=n.mutations.map((t=>Mw(e.fe,t)));return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:i}}(this.serializer,this.userId,a),u=[];let l=new vy(((e,t)=>Zm(e.canonicalString(),t.canonicalString())));for(const e of r){const t=zg(this.userId,e.key.path,o);l=l.add(e.key.path.popLast()),u.push(s.put(c)),u.push(i.put(t,$g))}return l.forEach((t=>{u.push(this.indexManager.addToCollectionParentIndex(e,t))})),e.addOnCommittedListener((()=>{this.Vn[o]=a.keys()})),bg.waitFor(u).next((()=>a))}))}lookupMutationBatch(e,t){return Gb(e).get(t).next((e=>e?(jm(e.userId===this.userId),tb(this.serializer,e)):null))}Sn(e,t){return this.Vn[t]?bg.resolve(this.Vn[t]):this.lookupMutationBatch(e,t).next((e=>{if(e){const n=e.keys();return this.Vn[t]=n,n}return null}))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]);let i=null;return Gb(e).X({index:"userMutationsIndex",range:r},((e,t,r)=>{t.userId===this.userId&&(jm(t.batchId>=n),i=tb(this.serializer,t)),r.done()})).next((()=>i))}getHighestUnacknowledgedBatchId(e){const t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let n=-1;return Gb(e).X({index:"userMutationsIndex",range:t,reverse:!0},((e,t,r)=>{n=t.batchId,r.done()})).next((()=>n))}getAllMutationBatches(e){const t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return Gb(e).j("userMutationsIndex",t).next((e=>e.map((e=>tb(this.serializer,e)))))}getAllMutationBatchesAffectingDocumentKey(e,t){const n=Bg(this.userId,t.path),r=IDBKeyRange.lowerBound(n),i=[];return Kb(e).X({range:r},((n,r,s)=>{const[o,a,c]=n,u=Vg(a);if(o===this.userId&&t.path.isEqual(u))return Gb(e).get(c).next((e=>{if(!e)throw Fm();jm(e.userId===this.userId),i.push(tb(this.serializer,e))}));s.done()})).next((()=>i))}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new vy(Zm);const r=[];return t.forEach((t=>{const i=Bg(this.userId,t.path),s=IDBKeyRange.lowerBound(i),o=Kb(e).X({range:s},((e,r,i)=>{const[s,o,a]=e,c=Vg(o);s===this.userId&&t.path.isEqual(c)?n=n.add(a):i.done()}));r.push(o)})),bg.waitFor(r).next((()=>this.Dn(e,n)))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1,i=Bg(this.userId,n),s=IDBKeyRange.lowerBound(i);let o=new vy(Zm);return Kb(e).X({range:s},((e,t,i)=>{const[s,a,c]=e,u=Vg(a);s===this.userId&&n.isPrefixOf(u)?u.length===r&&(o=o.add(c)):i.done()})).next((()=>this.Dn(e,o)))}Dn(e,t){const n=[],r=[];return t.forEach((t=>{r.push(Gb(e).get(t).next((e=>{if(null===e)throw Fm();jm(e.userId===this.userId),n.push(tb(this.serializer,e))})))})),bg.waitFor(r).next((()=>n))}removeMutationBatch(e,t){return $b(e.ht,this.userId,t).next((n=>(e.addOnCommittedListener((()=>{this.Cn(t.batchId)})),bg.forEach(n,(t=>this.referenceDelegate.markPotentiallyOrphaned(e,t))))))}Cn(e){delete this.Vn[e]}performConsistencyCheck(e){return this.checkEmpty(e).next((t=>{if(!t)return bg.resolve();const n=IDBKeyRange.lowerBound([this.userId]),r=[];return Kb(e).X({range:n},((e,t,n)=>{if(e[0]===this.userId){const t=Vg(e[1]);r.push(t)}else n.done()})).next((()=>{jm(0===r.length)}))}))}containsKey(e,t){return Hb(e,this.userId,t)}xn(e){return Yb(e).get(this.userId).next((e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""}))}}function Hb(e,t,n){const r=Bg(t,n.path),i=r[1],s=IDBKeyRange.lowerBound(r);let o=!1;return Kb(e).X({range:s,Y:!0},((e,n,r)=>{const[s,a,c]=e;s===t&&a===i&&(o=!0),r.done()})).next((()=>o))}function Gb(e){return hy(e,"mutations")}function Kb(e){return hy(e,"documentMutations")}function Yb(e){return hy(e,"mutationQueues")}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Jb{constructor(e){this.Nn=e}next(){return this.Nn+=2,this.Nn}static kn(){return new Jb(0)}static Mn(){return new Jb(-1)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Xb{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.$n(e).next((t=>{const n=new Jb(t.highestTargetId);return t.highestTargetId=n.next(),this.On(e,t).next((()=>t.highestTargetId))}))}getLastRemoteSnapshotVersion(e){return this.$n(e).next((e=>rg.fromTimestamp(new ng(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds))))}getHighestSequenceNumber(e){return this.$n(e).next((e=>e.highestListenSequenceNumber))}setTargetsMetadata(e,t,n){return this.$n(e).next((r=>(r.highestListenSequenceNumber=t,n&&(r.lastRemoteSnapshotVersion=n.toTimestamp()),t>r.highestListenSequenceNumber&&(r.highestListenSequenceNumber=t),this.On(e,r))))}addTargetData(e,t){return this.Fn(e,t).next((()=>this.$n(e).next((n=>(n.targetCount+=1,this.Bn(t,n),this.On(e,n))))))}updateTargetData(e,t){return this.Fn(e,t)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next((()=>Zb(e).delete(t.targetId))).next((()=>this.$n(e))).next((t=>(jm(t.targetCount>0),t.targetCount-=1,this.On(e,t))))}removeTargets(e,t,n){let r=0;const i=[];return Zb(e).X(((s,o)=>{const a=nb(o);a.sequenceNumber<=t&&null===n.get(a.targetId)&&(r++,i.push(this.removeTargetData(e,a)))})).next((()=>bg.waitFor(i))).next((()=>r))}forEachTarget(e,t){return Zb(e).X(((e,n)=>{const r=nb(n);t(r)}))}$n(e){return eI(e).get("targetGlobalKey").next((e=>(jm(null!==e),e)))}On(e,t){return eI(e).put("targetGlobalKey",t)}Fn(e,t){return Zb(e).put(rb(this.serializer,t))}Bn(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.$n(e).next((e=>e.targetCount))}getTargetData(e,t){const n=Av(t),r=IDBKeyRange.bound([n,Number.NEGATIVE_INFINITY],[n,Number.POSITIVE_INFINITY]);let i=null;return Zb(e).X({range:r,index:"queryTargetsIndex"},((e,n,r)=>{const s=nb(n);Nv(t,s.target)&&(i=s,r.done())})).next((()=>i))}addMatchingKeys(e,t,n){const r=[],i=tI(e);return t.forEach((t=>{const s=Fg(t.path);r.push(i.put({targetId:n,path:s})),r.push(this.referenceDelegate.addReference(e,n,t))})),bg.waitFor(r)}removeMatchingKeys(e,t,n){const r=tI(e);return bg.forEach(t,(t=>{const i=Fg(t.path);return bg.waitFor([r.delete([n,i]),this.referenceDelegate.removeReference(e,n,t)])}))}removeMatchingKeysForTargetId(e,t){const n=tI(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=tI(e);let i=l_();return r.X({range:n,Y:!0},((e,t,n)=>{const r=Vg(e[1]),s=new cg(r);i=i.add(s)})).next((()=>i))}containsKey(e,t){const n=Fg(t.path),r=IDBKeyRange.bound([n],[tg(n)],!1,!0);let i=0;return tI(e).X({index:"documentTargetsIndex",Y:!0,range:r},(([e,t],n,r)=>{0!==e&&(i++,r.done())})).next((()=>i>0))}le(e,t){return Zb(e).get(t).next((e=>e?nb(e):null))}}function Zb(e){return hy(e,"targets")}function eI(e){return hy(e,"targetGlobal")}function tI(e){return hy(e,"targetDocuments")}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function nI([e,t],[n,r]){const i=Zm(e,n);return 0===i?Zm(t,r):i}class rI{constructor(e){this.Ln=e,this.buffer=new vy(nI),this.qn=0}Un(){return++this.qn}Kn(e){const t=[e,this.Un()];if(this.buffer.size<this.Ln)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();nI(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class iI{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Gn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Qn(6e4)}stop(){this.Gn&&(this.Gn.cancel(),this.Gn=null)}get started(){return null!==this.Gn}Qn(e){Om("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Gn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,(async()=>{this.Gn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){kg(e)?Om("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await wg(e)}await this.Qn(3e5)}))}}class sI{constructor(e,t){this.jn=e,this.params=t}calculateTargetCount(e,t){return this.jn.zn(e).next((e=>Math.floor(t/100*e)))}nthSequenceNumber(e,t){if(0===t)return bg.resolve(Og.ct);const n=new rI(t);return this.jn.forEachTarget(e,(e=>n.Kn(e.sequenceNumber))).next((()=>this.jn.Wn(e,(e=>n.Kn(e))))).next((()=>n.maxValue))}removeTargets(e,t,n){return this.jn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.jn.removeOrphanedDocuments(e,t)}collect(e,t){return-1===this.params.cacheSizeCollectionThreshold?(Om("LruGarbageCollector","Garbage collection skipped; disabled"),bg.resolve(Bb)):this.getCacheSize(e).next((n=>n<this.params.cacheSizeCollectionThreshold?(Om("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),Bb):this.Hn(e,t)))}getCacheSize(e){return this.jn.getCacheSize(e)}Hn(e,t){let n,r,i,s,o,a,c;const u=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next((t=>(t>this.params.maximumSequenceNumbersToCollect?(Om("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),r=this.params.maximumSequenceNumbersToCollect):r=t,s=Date.now(),this.nthSequenceNumber(e,r)))).next((r=>(n=r,o=Date.now(),this.removeTargets(e,n,t)))).next((t=>(i=t,a=Date.now(),this.removeOrphanedDocuments(e,n)))).next((e=>(c=Date.now(),Rm()<=lc.DEBUG&&Om("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${s-u}ms\n\tDetermined least recently used ${r} in `+(o-s)+"ms\n"+`\tRemoved ${i} targets in `+(a-o)+"ms\n"+`\tRemoved ${e} documents in `+(c-a)+"ms\n"+`Total Duration: ${c-u}ms`),bg.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:i,documentsRemoved:e}))))}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class oI{constructor(e,t){this.db=e,this.garbageCollector=function(e,t){return new sI(e,t)}(this,t)}zn(e){const t=this.Jn(e);return this.db.getTargetCache().getTargetCount(e).next((e=>t.next((t=>e+t))))}Jn(e){let t=0;return this.Wn(e,(e=>{t++})).next((()=>t))}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Wn(e,t){return this.Yn(e,((e,n)=>t(n)))}addReference(e,t,n){return aI(e,n)}removeReference(e,t,n){return aI(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return aI(e,t)}Xn(e,t){return function(e,t){let n=!1;return Yb(e).Z((r=>Hb(e,r,t).next((e=>(e&&(n=!0),bg.resolve(!e)))))).next((()=>n))}(e,t)}removeOrphanedDocuments(e,t){const n=this.db.getRemoteDocumentCache().newChangeBuffer(),r=[];let i=0;return this.Yn(e,((s,o)=>{if(o<=t){const t=this.Xn(e,s).next((t=>{if(!t)return i++,n.getEntry(e,s).next((()=>(n.removeEntry(s,rg.min()),tI(e).delete([0,Fg(s.path)]))))}));r.push(t)}})).next((()=>bg.waitFor(r))).next((()=>n.apply(e))).next((()=>i))}removeTarget(e,t){const n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return aI(e,t)}Yn(e,t){const n=tI(e);let r,i=Og.ct;return n.X({index:"documentTargetsIndex"},(([e,n],{path:s,sequenceNumber:o})=>{0===e?(i!==Og.ct&&t(new cg(Vg(r)),i),i=o,r=s):i=Og.ct})).next((()=>{i!==Og.ct&&t(new cg(Vg(r)),i)}))}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function aI(e,t){return tI(e).put(function(e,t){return{targetId:0,path:Fg(e.path),sequenceNumber:t}}(t,e.currentSequenceNumber))}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class cI{constructor(){this.changes=new Zv((e=>e.toString()),((e,t)=>e.isEqual(t))),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,nv.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();const n=this.changes.get(t);return void 0!==n?bg.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class uI{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return fI(e).put(n)}removeEntry(e,t,n){return fI(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],Xw(t),n[n.length-1]]}(t,n))}updateMetadata(e,t){return this.getMetadata(e).next((n=>(n.byteSize+=t,this.Zn(e,n))))}getEntry(e,t){let n=nv.newInvalidDocument(t);return fI(e).X({index:"documentKeyIndex",range:IDBKeyRange.only(pI(t))},((e,r)=>{n=this.ts(t,r)})).next((()=>n))}es(e,t){let n={size:0,document:nv.newInvalidDocument(t)};return fI(e).X({index:"documentKeyIndex",range:IDBKeyRange.only(pI(t))},((e,r)=>{n={document:this.ts(t,r),size:Wb(r)}})).next((()=>n))}getEntries(e,t){let n=t_();return this.ns(e,t,((e,t)=>{const r=this.ts(e,t);n=n.insert(e,r)})).next((()=>n))}ss(e,t){let n=t_(),r=new my(cg.comparator);return this.ns(e,t,((e,t)=>{const i=this.ts(e,t);n=n.insert(e,i),r=r.insert(e,Wb(t))})).next((()=>({documents:n,rs:r})))}ns(e,t,n){if(t.isEmpty())return bg.resolve();let r=new vy(gI);t.forEach((e=>r=r.add(e)));const i=IDBKeyRange.bound(pI(r.first()),pI(r.last())),s=r.getIterator();let o=s.getNext();return fI(e).X({index:"documentKeyIndex",range:i},((e,t,r)=>{const i=cg.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;o&&gI(o,i)<0;)n(o,null),o=s.getNext();o&&o.isEqual(i)&&(n(o,t),o=s.hasNext()?s.getNext():null),o?r.G(pI(o)):r.done()})).next((()=>{for(;o;)n(o,null),o=s.hasNext()?s.getNext():null}))}getDocumentsMatchingQuery(e,t,n,r){const i=t.path,s=[i.popLast().toArray(),i.lastSegment(),Xw(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],o=[i.popLast().toArray(),i.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return fI(e).j(IDBKeyRange.bound(s,o,!0)).next((e=>{let n=t_();for(const i of e){const e=this.ts(cg.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(Kv(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n}))}getAllFromCollectionGroup(e,t,n,r){let i=t_();const s=mI(t,n),o=mI(t,gg.max());return fI(e).X({index:"collectionGroupIndex",range:IDBKeyRange.bound(s,o,!0)},((e,t,n)=>{const s=this.ts(cg.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);i=i.insert(s.key,s),i.size===r&&n.done()})).next((()=>i))}newChangeBuffer(e){return new hI(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next((e=>e.byteSize))}getMetadata(e){return dI(e).get("remoteDocumentGlobalKey").next((e=>(jm(!!e),e)))}Zn(e,t){return dI(e).put("remoteDocumentGlobalKey",t)}ts(e,t){if(t){const e=function(e,t){let n;if(t.document)n=Pw(e.fe,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=cg.fromSegments(t.noDocument.path),r=eb(t.noDocument.readTime);n=nv.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return Fm();{const e=cg.fromSegments(t.unknownDocument.path),r=eb(t.unknownDocument.version);n=nv.newUnknownDocument(e,r)}}return t.readTime&&n.setReadTime(function(e){const t=new ng(e[0],e[1]);return rg.fromTimestamp(t)}(t.readTime)),n}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(rg.min()))return e}return nv.newInvalidDocument(e)}}function lI(e){return new uI(e)}class hI extends cI{constructor(e,t){super(),this.os=e,this.trackRemovals=t,this.us=new Zv((e=>e.toString()),((e,t)=>e.isEqual(t)))}applyChanges(e){const t=[];let n=0,r=new vy(((e,t)=>Zm(e.canonicalString(),t.canonicalString())));return this.changes.forEach(((i,s)=>{const o=this.us.get(i);if(t.push(this.os.removeEntry(e,i,o.readTime)),s.isValidDocument()){const a=Jw(this.os.serializer,s);r=r.add(i.path.popLast());const c=Wb(a);n+=c-o.size,t.push(this.os.addEntry(e,i,a))}else if(n-=o.size,this.trackRemovals){const n=Jw(this.os.serializer,s.convertToNoDocument(rg.min()));t.push(this.os.addEntry(e,i,n))}})),r.forEach((n=>{t.push(this.os.indexManager.addToCollectionParentIndex(e,n))})),t.push(this.os.updateMetadata(e,n)),bg.waitFor(t)}getFromCache(e,t){return this.os.es(e,t).next((e=>(this.us.set(t,{size:e.size,readTime:e.document.readTime}),e.document)))}getAllFromCache(e,t){return this.os.ss(e,t).next((({documents:e,rs:t})=>(t.forEach(((t,n)=>{this.us.set(t,{size:n,readTime:e.get(t).readTime})})),e)))}}function dI(e){return hy(e,"remoteDocumentGlobal")}function fI(e){return hy(e,"remoteDocumentsV14")}function pI(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function mI(e,t){const n=t.documentKey.path.toArray();return[e,Xw(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function gI(e,t){const n=e.path.toArray(),r=t.path.toArray();let i=0;for(let e=0;e<n.length-2&&e<r.length-2;++e)if(i=Zm(n[e],r[e]),i)return i;return i=Zm(n.length,r.length),i||(i=Zm(n[n.length-2],r[r.length-2]),i||Zm(n[n.length-1],r[r.length-1]))
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */}class yI{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class vI{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next((r=>(n=r,this.remoteDocumentCache.getEntry(e,t)))).next((e=>(null!==n&&M_(n.mutation,e,by.empty(),ng.now()),e)))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.getLocalViewOfDocuments(e,t,l_()).next((()=>t))))}getLocalViewOfDocuments(e,t,n=l_()){const r=s_();return this.populateOverlays(e,r,t).next((()=>this.computeViews(e,t,r,n).next((e=>{let t=r_();return e.forEach(((e,n)=>{t=t.insert(e,n.overlayedDocument)})),t}))))}getOverlayedDocuments(e,t){const n=s_();return this.populateOverlays(e,n,t).next((()=>this.computeViews(e,t,n,l_())))}populateOverlays(e,t,n){const r=[];return n.forEach((e=>{t.has(e)||r.push(e)})),this.documentOverlayCache.getOverlays(e,r).next((e=>{e.forEach(((e,n)=>{t.set(e,n)}))}))}computeViews(e,t,n,r){let i=t_();const s=a_(),o=a_();return t.forEach(((e,t)=>{const o=n.get(t.key);r.has(t.key)&&(void 0===o||o.mutation instanceof q_)?i=i.insert(t.key,t):void 0!==o?(s.set(t.key,o.mutation.getFieldMask()),M_(o.mutation,t,o.mutation.getFieldMask(),ng.now())):s.set(t.key,by.empty())})),this.recalculateAndSaveOverlays(e,i).next((e=>(e.forEach(((e,t)=>s.set(e,t))),t.forEach(((e,t)=>{var n;return o.set(e,new yI(t,null!==(n=s.get(e))&&void 0!==n?n:null))})),o)))}recalculateAndSaveOverlays(e,t){const n=a_();let r=new my(((e,t)=>e-t)),i=l_();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next((e=>{for(const i of e)i.keys().forEach((e=>{const s=t.get(e);if(null===s)return;let o=n.get(e)||by.empty();o=i.applyToLocalView(s,o),n.set(e,o);const a=(r.get(i.batchId)||l_()).add(e);r=r.insert(i.batchId,a)}))})).next((()=>{const s=[],o=r.getReverseIterator();for(;o.hasNext();){const r=o.getNext(),a=r.key,c=r.value,u=o_();c.forEach((e=>{if(!i.has(e)){const r=O_(t.get(e),n.get(e));null!==r&&u.set(e,r),i=i.add(e)}})),s.push(this.documentOverlayCache.saveOverlays(e,a,u))}return bg.waitFor(s)})).next((()=>n))}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.recalculateAndSaveOverlays(e,t)))}getDocumentsMatchingQuery(e,t,n){return function(e){return cg.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):Uv(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n)}getNextDocuments(e,t,n,r){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next((i=>{const s=r-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-i.size):bg.resolve(s_());let o=-1,a=i;return s.next((t=>bg.forEach(t,((t,n)=>(o<n.largestBatchId&&(o=n.largestBatchId),i.get(t)?bg.resolve():this.remoteDocumentCache.getEntry(e,t).next((e=>{a=a.insert(t,e)}))))).next((()=>this.populateOverlays(e,t,i))).next((()=>this.computeViews(e,a,t,l_()))).next((e=>({batchId:o,changes:i_(e)})))))}))}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new cg(t)).next((e=>{let t=r_();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t}))}getDocumentsMatchingCollectionGroupQuery(e,t,n){const r=t.collectionGroup;let i=r_();return this.indexManager.getCollectionParents(e,r).next((s=>bg.forEach(s,(s=>{const o=function(e,t){return new Mv(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,s.child(r));return this.getDocumentsMatchingCollectionQuery(e,o,n).next((e=>{e.forEach(((e,t)=>{i=i.insert(e,t)}))}))})).next((()=>i))))}getDocumentsMatchingCollectionQuery(e,t,n){let r;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next((i=>(r=i,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,r)))).next((e=>{r.forEach(((t,n)=>{const r=n.getKey();null===e.get(r)&&(e=e.insert(r,nv.newInvalidDocument(r)))}));let n=r_();return e.forEach(((e,i)=>{const s=r.get(e);void 0!==s&&M_(s.mutation,i,by.empty(),ng.now()),Kv(t,i)&&(n=n.insert(e,i))})),n}))}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class _I{constructor(e){this.serializer=e,this.cs=new Map,this.hs=new Map}getBundleMetadata(e,t){return bg.resolve(this.cs.get(t))}saveBundleMetadata(e,t){var n;return this.cs.set(t.id,{id:(n=t).id,version:n.version,createTime:Tw(n.createTime)}),bg.resolve()}getNamedQuery(e,t){return bg.resolve(this.hs.get(t))}saveNamedQuery(e,t){return this.hs.set(t.name,function(e){return{name:e.name,query:ib(e.bundledQuery),readTime:Tw(e.readTime)}}(t)),bg.resolve()}}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class wI{constructor(){this.overlays=new my(cg.comparator),this.ls=new Map}getOverlay(e,t){return bg.resolve(this.overlays.get(t))}getOverlays(e,t){const n=s_();return bg.forEach(t,(t=>this.getOverlay(e,t).next((e=>{null!==e&&n.set(t,e)})))).next((()=>n))}saveOverlays(e,t,n){return n.forEach(((n,r)=>{this.we(e,t,r)})),bg.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.ls.get(n);return void 0!==r&&(r.forEach((e=>this.overlays=this.overlays.remove(e))),this.ls.delete(n)),bg.resolve()}getOverlaysForCollection(e,t,n){const r=s_(),i=t.length+1,s=new cg(t.child("")),o=this.overlays.getIteratorFrom(s);for(;o.hasNext();){const e=o.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return bg.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let i=new my(((e,t)=>e-t));const s=this.overlays.getIterator();for(;s.hasNext();){const e=s.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=i.get(e.largestBatchId);null===t&&(t=s_(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const o=s_(),a=i.getIterator();for(;a.hasNext()&&(a.getNext().value.forEach(((e,t)=>o.set(e,t))),!(o.size()>=r)););return bg.resolve(o)}we(e,t,n){const r=this.overlays.get(n.key);if(null!==r){const e=this.ls.get(r.largestBatchId).delete(n.key);this.ls.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new H_(t,n));let i=this.ls.get(t);void 0===i&&(i=l_(),this.ls.set(t,i)),this.ls.set(t,i.add(n.key))}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class bI{constructor(){this.fs=new vy(II.ds),this.ws=new vy(II._s)}isEmpty(){return this.fs.isEmpty()}addReference(e,t){const n=new II(e,t);this.fs=this.fs.add(n),this.ws=this.ws.add(n)}gs(e,t){e.forEach((e=>this.addReference(e,t)))}removeReference(e,t){this.ys(new II(e,t))}ps(e,t){e.forEach((e=>this.removeReference(e,t)))}Is(e){const t=new cg(new sg([])),n=new II(t,e),r=new II(t,e+1),i=[];return this.ws.forEachInRange([n,r],(e=>{this.ys(e),i.push(e.key)})),i}Ts(){this.fs.forEach((e=>this.ys(e)))}ys(e){this.fs=this.fs.delete(e),this.ws=this.ws.delete(e)}Es(e){const t=new cg(new sg([])),n=new II(t,e),r=new II(t,e+1);let i=l_();return this.ws.forEachInRange([n,r],(e=>{i=i.add(e.key)})),i}containsKey(e){const t=new II(e,0),n=this.fs.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class II{constructor(e,t){this.key=e,this.As=t}static ds(e,t){return cg.comparator(e.key,t.key)||Zm(e.As,t.As)}static _s(e,t){return Zm(e.As,t.As)||cg.comparator(e.key,t.key)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class EI{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.vs=1,this.Rs=new vy(II.ds)}checkEmpty(e){return bg.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){const i=this.vs;this.vs++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const s=new W_(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.Rs=this.Rs.add(new II(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return bg.resolve(s)}lookupMutationBatch(e,t){return bg.resolve(this.Ps(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=this.bs(n),i=r<0?0:r;return bg.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return bg.resolve(0===this.mutationQueue.length?-1:this.vs-1)}getAllMutationBatches(e){return bg.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new II(t,0),r=new II(t,Number.POSITIVE_INFINITY),i=[];return this.Rs.forEachInRange([n,r],(e=>{const t=this.Ps(e.As);i.push(t)})),bg.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new vy(Zm);return t.forEach((e=>{const t=new II(e,0),r=new II(e,Number.POSITIVE_INFINITY);this.Rs.forEachInRange([t,r],(e=>{n=n.add(e.As)}))})),bg.resolve(this.Vs(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;cg.isDocumentKey(i)||(i=i.child(""));const s=new II(new cg(i),0);let o=new vy(Zm);return this.Rs.forEachWhile((e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.As)),!0)}),s),bg.resolve(this.Vs(o))}Vs(e){const t=[];return e.forEach((e=>{const n=this.Ps(e);null!==n&&t.push(n)})),t}removeMutationBatch(e,t){jm(0===this.Ss(t.batchId,"removed")),this.mutationQueue.shift();let n=this.Rs;return bg.forEach(t.mutations,(r=>{const i=new II(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)})).next((()=>{this.Rs=n}))}Cn(e){}containsKey(e,t){const n=new II(t,0),r=this.Rs.firstAfterOrEqual(n);return bg.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,bg.resolve()}Ss(e,t){return this.bs(e)}bs(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Ps(e){const t=this.bs(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class TI{constructor(e){this.Ds=e,this.docs=new my(cg.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Ds(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){const 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 bg.resolve(n?n.document.mutableCopy():nv.newInvalidDocument(t))}getEntries(e,t){let n=t_();return t.forEach((e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():nv.newInvalidDocument(e))})),bg.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=t_();const s=t.path,o=new cg(s.child("")),a=this.docs.getIteratorFrom(o);for(;a.hasNext();){const{key:e,value:{document:o}}=a.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||yg(mg(o),n)<=0||(r.has(o.key)||Kv(t,o))&&(i=i.insert(o.key,o.mutableCopy()))}return bg.resolve(i)}getAllFromCollectionGroup(e,t,n,r){Fm()}Cs(e,t){return bg.forEach(this.docs,(e=>t(e)))}newChangeBuffer(e){return new SI(this)}getSize(e){return bg.resolve(this.size)}}class SI extends cI{constructor(e){super(),this.os=e}applyChanges(e){const t=[];return this.changes.forEach(((n,r)=>{r.isValidDocument()?t.push(this.os.addEntry(e,r)):this.os.removeEntry(n)})),bg.waitFor(t)}getFromCache(e,t){return this.os.getEntry(e,t)}getAllFromCache(e,t){return this.os.getEntries(e,t)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class kI{constructor(e){this.persistence=e,this.xs=new Zv((e=>Av(e)),Nv),this.lastRemoteSnapshotVersion=rg.min(),this.highestTargetId=0,this.Ns=0,this.ks=new bI,this.targetCount=0,this.Ms=Jb.kn()}forEachTarget(e,t){return this.xs.forEach(((e,n)=>t(n))),bg.resolve()}getLastRemoteSnapshotVersion(e){return bg.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return bg.resolve(this.Ns)}allocateTargetId(e){return this.highestTargetId=this.Ms.next(),bg.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Ns&&(this.Ns=t),bg.resolve()}Fn(e){this.xs.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.Ms=new Jb(t),this.highestTargetId=t),e.sequenceNumber>this.Ns&&(this.Ns=e.sequenceNumber)}addTargetData(e,t){return this.Fn(t),this.targetCount+=1,bg.resolve()}updateTargetData(e,t){return this.Fn(t),bg.resolve()}removeTargetData(e,t){return this.xs.delete(t.target),this.ks.Is(t.targetId),this.targetCount-=1,bg.resolve()}removeTargets(e,t,n){let r=0;const i=[];return this.xs.forEach(((s,o)=>{o.sequenceNumber<=t&&null===n.get(o.targetId)&&(this.xs.delete(s),i.push(this.removeMatchingKeysForTargetId(e,o.targetId)),r++)})),bg.waitFor(i).next((()=>r))}getTargetCount(e){return bg.resolve(this.targetCount)}getTargetData(e,t){const n=this.xs.get(t)||null;return bg.resolve(n)}addMatchingKeys(e,t,n){return this.ks.gs(t,n),bg.resolve()}removeMatchingKeys(e,t,n){this.ks.ps(t,n);const r=this.persistence.referenceDelegate,i=[];return r&&t.forEach((t=>{i.push(r.markPotentiallyOrphaned(e,t))})),bg.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.ks.Is(t),bg.resolve()}getMatchingKeysForTargetId(e,t){const n=this.ks.Es(t);return bg.resolve(n)}containsKey(e,t){return bg.resolve(this.ks.containsKey(t))}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class CI{constructor(e,t){this.$s={},this.overlays={},this.Os=new Og(0),this.Fs=!1,this.Fs=!0,this.referenceDelegate=e(this),this.Bs=new kI(this),this.indexManager=new Ob,this.remoteDocumentCache=function(e){return new TI(e)}((e=>this.referenceDelegate.Ls(e))),this.serializer=new Yw(t),this.qs=new _I(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.Fs=!1,Promise.resolve()}get started(){return this.Fs}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new wI,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.$s[e.toKey()];return n||(n=new EI(t,this.referenceDelegate),this.$s[e.toKey()]=n),n}getTargetCache(){return this.Bs}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.qs}runTransaction(e,t,n){Om("MemoryPersistence","Starting transaction:",e);const r=new xI(this.Os.next());return this.referenceDelegate.Us(),n(r).next((e=>this.referenceDelegate.Ks(r).next((()=>e)))).toPromise().then((e=>(r.raiseOnCommittedEvent(),e)))}Gs(e,t){return bg.or(Object.values(this.$s).map((n=>()=>n.containsKey(e,t))))}}class xI extends _g{constructor(e){super(),this.currentSequenceNumber=e}}class AI{constructor(e){this.persistence=e,this.Qs=new bI,this.js=null}static zs(e){return new AI(e)}get Ws(){if(this.js)return this.js;throw Fm()}addReference(e,t,n){return this.Qs.addReference(n,t),this.Ws.delete(n.toString()),bg.resolve()}removeReference(e,t,n){return this.Qs.removeReference(n,t),this.Ws.add(n.toString()),bg.resolve()}markPotentiallyOrphaned(e,t){return this.Ws.add(t.toString()),bg.resolve()}removeTarget(e,t){this.Qs.Is(t.targetId).forEach((e=>this.Ws.add(e.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next((e=>{e.forEach((e=>this.Ws.add(e.toString())))})).next((()=>n.removeTargetData(e,t)))}Us(){this.js=new Set}Ks(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return bg.forEach(this.Ws,(n=>{const r=cg.fromPath(n);return this.Hs(e,r).next((e=>{e||t.removeEntry(r,rg.min())}))})).next((()=>(this.js=null,t.apply(e))))}updateLimboDocument(e,t){return this.Hs(e,t).next((e=>{e?this.Ws.delete(t.toString()):this.Ws.add(t.toString())}))}Ls(e){return 0}Hs(e,t){return bg.or([()=>bg.resolve(this.Qs.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Gs(e,t)])}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class NI{constructor(e){this.serializer=e}O(e,t,n,r){const i=new Ig("createOrUpgrade",t);n<1&&r>=1&&(function(e){e.createObjectStore("owner")}(e),function(e){e.createObjectStore("mutationQueues",{keyPath:"userId"}),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Ug,{unique:!0}),e.createObjectStore("documentMutations")}(e),DI(e),function(e){e.createObjectStore("remoteDocuments")}(e));let s=bg.resolve();return n<3&&r>=3&&(0!==n&&(function(e){e.deleteObjectStore("targetDocuments"),e.deleteObjectStore("targets"),e.deleteObjectStore("targetGlobal")}(e),DI(e)),s=s.next((()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:rg.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(i)))),n<4&&r>=4&&(0!==n&&(s=s.next((()=>function(e,t){return t.store("mutations").j().next((n=>{e.deleteObjectStore("mutations"),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Ug,{unique:!0});const r=t.store("mutations"),i=n.map((e=>r.put(e)));return bg.waitFor(i)}))}(e,i)))),s=s.next((()=>{!function(e){e.createObjectStore("clientMetadata",{keyPath:"clientId"})}(e)}))),n<5&&r>=5&&(s=s.next((()=>this.Ys(i)))),n<6&&r>=6&&(s=s.next((()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(e),this.Xs(i))))),n<7&&r>=7&&(s=s.next((()=>this.Zs(i)))),n<8&&r>=8&&(s=s.next((()=>this.ti(e,i)))),n<9&&r>=9&&(s=s.next((()=>{!function(e){e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")}(e)}))),n<10&&r>=10&&(s=s.next((()=>this.ei(i)))),n<11&&r>=11&&(s=s.next((()=>{!function(e){e.createObjectStore("bundles",{keyPath:"bundleId"})}(e),function(e){e.createObjectStore("namedQueries",{keyPath:"name"})}(e)}))),n<12&&r>=12&&(s=s.next((()=>{!function(e){const t=e.createObjectStore("documentOverlays",{keyPath:ny});t.createIndex("collectionPathOverlayIndex",ry,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",iy,{unique:!1})}(e)}))),n<13&&r>=13&&(s=s.next((()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:Wg});t.createIndex("documentKeyIndex",Qg),t.createIndex("collectionGroupIndex",Hg)}(e))).next((()=>this.ni(e,i))).next((()=>e.deleteObjectStore("remoteDocuments")))),n<14&&r>=14&&(s=s.next((()=>this.si(e,i)))),n<15&&r>=15&&(s=s.next((()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Xg}).createIndex("sequenceNumberIndex",Zg,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:ey}).createIndex("documentKeyIndex",ty,{unique:!1})}(e)))),s}Xs(e){let t=0;return e.store("remoteDocuments").X(((e,n)=>{t+=Wb(n)})).next((()=>{const n={byteSize:t};return e.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",n)}))}Ys(e){const t=e.store("mutationQueues"),n=e.store("mutations");return t.j().next((t=>bg.forEach(t,(t=>{const r=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return n.j("userMutationsIndex",r).next((n=>bg.forEach(n,(n=>{jm(n.userId===t.userId);const r=tb(this.serializer,n);return $b(e,t.userId,r).next((()=>{}))}))))}))))}Zs(e){const t=e.store("targetDocuments"),n=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next((e=>{const r=[];return n.X(((n,i)=>{const s=new sg(n),o=function(e){return[0,Fg(e)]}(s);r.push(t.get(o).next((n=>n?bg.resolve():(n=>t.put({targetId:0,path:Fg(n),sequenceNumber:e.highestListenSequenceNumber}))(s))))})).next((()=>bg.waitFor(r)))}))}ti(e,t){e.createObjectStore("collectionParents",{keyPath:Jg});const n=t.store("collectionParents"),r=new Pb,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Fg(r)})}};return t.store("remoteDocuments").X({Y:!0},((e,t)=>{const n=new sg(e);return i(n.popLast())})).next((()=>t.store("documentMutations").X({Y:!0},(([e,t,n],r)=>{const s=Vg(t);return i(s.popLast())}))))}ei(e){const t=e.store("targets");return t.X(((e,n)=>{const r=nb(n),i=rb(this.serializer,r);return t.put(i)}))}ni(e,t){const n=t.store("remoteDocuments"),r=[];return n.X(((e,n)=>{const i=t.store("remoteDocumentsV14"),s=(o=n,o.document?new cg(sg.fromString(o.document.name).popFirst(5)):o.noDocument?cg.fromSegments(o.noDocument.path):o.unknownDocument?cg.fromSegments(o.unknownDocument.path):Fm()).path.toArray();var o;
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const a={prefixPath:s.slice(0,s.length-2),collectionGroup:s[s.length-2],documentId:s[s.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(i.put(a))})).next((()=>bg.waitFor(r)))}si(e,t){const n=t.store("mutations"),r=lI(this.serializer),i=new CI(AI.zs,this.serializer.fe);return n.j().next((e=>{const n=new Map;return e.forEach((e=>{var t;let r=null!==(t=n.get(e.userId))&&void 0!==t?t:l_();tb(this.serializer,e).keys().forEach((e=>r=r.add(e))),n.set(e.userId,r)})),bg.forEach(n,((e,n)=>{const s=new Am(n),o=hb.de(this.serializer,s),a=i.getIndexManager(s),c=Qb.de(s,this.serializer,a,i.referenceDelegate);return new vI(r,c,o,a).recalculateAndSaveOverlaysForDocumentKeys(new ly(t,Og.ct),e).next()}))}))}}function DI(e){e.createObjectStore("targetDocuments",{keyPath:Kg}).createIndex("documentTargetsIndex",Yg,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",Gg,{unique:!0}),e.createObjectStore("targetGlobal")}const RI="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 OI{constructor(e,t,n,r,i,s,o,a,c,u,l=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.ii=i,this.window=s,this.document=o,this.ri=c,this.oi=u,this.ui=l,this.Os=null,this.Fs=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ci=null,this.inForeground=!1,this.ai=null,this.hi=null,this.li=Number.NEGATIVE_INFINITY,this.fi=e=>Promise.resolve(),!OI.D())throw new Um(Vm.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new oI(this,r),this.di=t+"main",this.serializer=new Yw(a),this.wi=new Eg(this.di,this.ui,new NI(this.serializer)),this.Bs=new Xb(this.referenceDelegate,this.serializer),this.remoteDocumentCache=lI(this.serializer),this.qs=new cb,this.window&&this.window.localStorage?this._i=this.window.localStorage:(this._i=null,!1===u&&Pm("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.mi().then((()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new Um(Vm.FAILED_PRECONDITION,RI);return this.gi(),this.yi(),this.pi(),this.runTransaction("getHighestListenSequenceNumber","readonly",(e=>this.Bs.getHighestSequenceNumber(e)))})).then((e=>{this.Os=new Og(e,this.ri)})).then((()=>{this.Fs=!0})).catch((e=>(this.wi&&this.wi.close(),Promise.reject(e))))}Ii(e){return this.fi=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.wi.B((async t=>{null===t.newVersion&&await e()}))}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.ii.enqueueAndForget((async()=>{this.started&&await this.mi()})))}mi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",(e=>MI(e).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next((()=>{if(this.isPrimary)return this.Ti(e).next((e=>{e||(this.isPrimary=!1,this.ii.enqueueRetryable((()=>this.fi(!1))))}))})).next((()=>this.Ei(e))).next((t=>this.isPrimary&&!t?this.Ai(e).next((()=>!1)):!!t&&this.vi(e).next((()=>!0)))))).catch((e=>{if(kg(e))return Om("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return Om("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1})).then((e=>{this.isPrimary!==e&&this.ii.enqueueRetryable((()=>this.fi(e))),this.isPrimary=e}))}Ti(e){return PI(e).get("owner").next((e=>bg.resolve(this.Ri(e))))}Pi(e){return MI(e).delete(this.clientId)}async bi(){if(this.isPrimary&&!this.Vi(this.li,18e5)){this.li=Date.now();const e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",(e=>{const t=hy(e,"clientMetadata");return t.j().next((e=>{const n=this.Si(e,18e5),r=e.filter((e=>-1===n.indexOf(e)));return bg.forEach(r,(e=>t.delete(e.clientId))).next((()=>r))}))})).catch((()=>[]));if(this._i)for(const t of e)this._i.removeItem(this.Di(t.clientId))}}pi(){this.hi=this.ii.enqueueAfterDelay("client_metadata_refresh",4e3,(()=>this.mi().then((()=>this.bi())).then((()=>this.pi()))))}Ri(e){return!!e&&e.ownerId===this.clientId}Ei(e){return this.oi?bg.resolve(!0):PI(e).get("owner").next((t=>{if(null!==t&&this.Vi(t.leaseTimestampMs,5e3)&&!this.Ci(t.ownerId)){if(this.Ri(t)&&this.networkEnabled)return!0;if(!this.Ri(t)){if(!t.allowTabSynchronization)throw new Um(Vm.FAILED_PRECONDITION,RI);return!1}}return!(!this.networkEnabled||!this.inForeground)||MI(e).j().next((e=>void 0===this.Si(e,5e3).find((e=>{if(this.clientId!==e.clientId){const 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&&Om("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e)))}async shutdown(){this.Fs=!1,this.xi(),this.hi&&(this.hi.cancel(),this.hi=null),this.Ni(),this.ki(),await this.wi.runTransaction("shutdown","readwrite",["owner","clientMetadata"],(e=>{const t=new ly(e,Og.ct);return this.Ai(t).next((()=>this.Pi(t)))})),this.wi.close(),this.Mi()}Si(e,t){return e.filter((e=>this.Vi(e.updateTimeMs,t)&&!this.Ci(e.clientId)))}$i(){return this.runTransaction("getActiveClients","readonly",(e=>MI(e).j().next((e=>this.Si(e,18e5).map((e=>e.clientId))))))}get started(){return this.Fs}getMutationQueue(e,t){return Qb.de(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Bs}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new Lb(e,this.serializer.fe.databaseId)}getDocumentOverlayCache(e){return hb.de(this.serializer,e)}getBundleCache(){return this.qs}runTransaction(e,t,n){Om("IndexedDbPersistence","Starting transaction:",e);const r="readonly"===t?"readonly":"readwrite",i=15===(s=this.ui)?uy:14===s?cy:13===s?ay:12===s?oy:11===s?sy:void Fm();var s;let o;return this.wi.runTransaction(e,r,i,(r=>(o=new ly(r,this.Os?this.Os.next():Og.ct),"readwrite-primary"===t?this.Ti(o).next((e=>!!e||this.Ei(o))).next((t=>{if(!t)throw Pm(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.ii.enqueueRetryable((()=>this.fi(!1))),new Um(Vm.FAILED_PRECONDITION,vg);return n(o)})).next((e=>this.vi(o).next((()=>e)))):this.Oi(o).next((()=>n(o)))))).then((e=>(o.raiseOnCommittedEvent(),e)))}Oi(e){return PI(e).get("owner").next((e=>{if(null!==e&&this.Vi(e.leaseTimestampMs,5e3)&&!this.Ci(e.ownerId)&&!this.Ri(e)&&!(this.oi||this.allowTabSynchronization&&e.allowTabSynchronization))throw new Um(Vm.FAILED_PRECONDITION,RI)}))}vi(e){const t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return PI(e).put("owner",t)}static D(){return Eg.D()}Ai(e){const t=PI(e);return t.get("owner").next((e=>this.Ri(e)?(Om("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):bg.resolve()))}Vi(e,t){const n=Date.now();return!(e<n-t||e>n&&(Pm(`Detected an update time that is in the future: ${e} > ${n}`),1))}gi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ai=()=>{this.ii.enqueueAndForget((()=>(this.inForeground="visible"===this.document.visibilityState,this.mi())))},this.document.addEventListener("visibilitychange",this.ai),this.inForeground="visible"===this.document.visibilityState)}Ni(){this.ai&&(this.document.removeEventListener("visibilitychange",this.ai),this.ai=null)}yi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ci=()=>{this.xi();const e=/(?:Version|Mobile)\/1[456]/;!xa()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.ii.enterRestrictedMode(!0),this.ii.enqueueAndForget((()=>this.shutdown()))},this.window.addEventListener("pagehide",this.ci))}ki(){this.ci&&(this.window.removeEventListener("pagehide",this.ci),this.ci=null)}Ci(e){var t;try{const n=null!==(null===(t=this._i)||void 0===t?void 0:t.getItem(this.Di(e)));return Om("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return Pm("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}xi(){if(this._i)try{this._i.setItem(this.Di(this.clientId),String(Date.now()))}catch(e){Pm("Failed to set zombie client id.",e)}}Mi(){if(this._i)try{this._i.removeItem(this.Di(this.clientId))}catch(e){}}Di(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function PI(e){return hy(e,"owner")}function MI(e){return hy(e,"clientMetadata")}function LI(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */}class FI{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Fi=n,this.Bi=r}static Li(e,t){let n=l_(),r=l_();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 FI(e,t.fromCache,n,r)}}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class jI{constructor(){this.qi=!1}initialize(e,t){this.Ui=e,this.indexManager=t,this.qi=!0}getDocumentsMatchingQuery(e,t,n,r){return this.Ki(e,t).next((i=>i||this.Gi(e,t,r,n))).next((n=>n||this.Qi(e,t)))}Ki(e,t){if(jv(t))return bg.resolve(null);let n=zv(t);return this.indexManager.getIndexType(e,n).next((r=>0===r?null:(null!==t.limit&&1===r&&(t=Wv(t,null,"F"),n=zv(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next((r=>{const i=l_(...r);return this.Ui.getDocuments(e,i).next((r=>this.indexManager.getMinOffset(e,n).next((n=>{const s=this.ji(t,r);return this.zi(t,s,i,n.readTime)?this.Ki(e,Wv(t,null,"F")):this.Wi(e,s,t,n)}))))})))))}Gi(e,t,n,r){return jv(t)||r.isEqual(rg.min())?this.Qi(e,t):this.Ui.getDocuments(e,n).next((i=>{const s=this.ji(t,i);return this.zi(t,s,n,r)?this.Qi(e,t):(Rm()<=lc.DEBUG&&Om("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),Gv(t)),this.Wi(e,s,t,pg(r,-1)))}))}ji(e,t){let n=new vy(Jv(e));return t.forEach(((t,r)=>{Kv(e,r)&&(n=n.add(r))})),n}zi(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}Qi(e,t){return Rm()<=lc.DEBUG&&Om("QueryEngine","Using full collection scan to execute query:",Gv(t)),this.Ui.getDocumentsMatchingQuery(e,t,gg.min())}Wi(e,t,n,r){return this.Ui.getDocumentsMatchingQuery(e,n,r).next((e=>(t.forEach((t=>{e=e.insert(t.key,t)})),e)))}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class qI{constructor(e,t,n,r){this.persistence=e,this.Hi=t,this.serializer=r,this.Ji=new my(Zm),this.Yi=new Zv((e=>Av(e)),Nv),this.Xi=new Map,this.Zi=e.getRemoteDocumentCache(),this.Bs=e.getTargetCache(),this.qs=e.getBundleCache(),this.tr(n)}tr(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new vI(this.Zi,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Zi.setIndexManager(this.indexManager),this.Hi.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(t=>e.collect(t,this.Ji)))}}function VI(e,t,n,r){return new qI(e,t,n,r)}async function UI(e,t){const n=qm(e);return await n.persistence.runTransaction("Handle user change","readonly",(e=>{let r;return n.mutationQueue.getAllMutationBatches(e).next((i=>(r=i,n.tr(t),n.mutationQueue.getAllMutationBatches(e)))).next((t=>{const i=[],s=[];let o=l_();for(const e of r){i.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}for(const e of t){s.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}return n.localDocuments.getDocuments(e,o).next((e=>({er:e,removedBatchIds:i,addedBatchIds:s})))}))}))}function BI(e){const t=qm(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.Bs.getLastRemoteSnapshotVersion(e)))}function zI(e,t,n){let r=l_(),i=l_();return n.forEach((e=>r=r.add(e))),t.getEntries(e,r).next((e=>{let r=t_();return n.forEach(((n,s)=>{const o=e.get(n);s.isFoundDocument()!==o.isFoundDocument()&&(i=i.add(n)),s.isNoDocument()&&s.version.isEqual(rg.min())?(t.removeEntry(n,s.readTime),r=r.insert(n,s)):!o.isValidDocument()||s.version.compareTo(o.version)>0||0===s.version.compareTo(o.version)&&o.hasPendingWrites?(t.addEntry(s),r=r.insert(n,s)):Om("LocalStore","Ignoring outdated watch update for ",n,". Current version:",o.version," Watch version:",s.version)})),{nr:r,sr:i}}))}function $I(e,t){const n=qm(e);return n.persistence.runTransaction("Get next mutation batch","readonly",(e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t))))}function WI(e,t){const n=qm(e);return n.persistence.runTransaction("Allocate target","readwrite",(e=>{let r;return n.Bs.getTargetData(e,t).next((i=>i?(r=i,bg.resolve(r)):n.Bs.allocateTargetId(e).next((i=>(r=new Kw(t,i,"TargetPurposeListen",e.currentSequenceNumber),n.Bs.addTargetData(e,r).next((()=>r)))))))})).then((e=>{const r=n.Ji.get(e.targetId);return(null===r||e.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(n.Ji=n.Ji.insert(e.targetId,e),n.Yi.set(t,e.targetId)),e}))}async function QI(e,t,n){const r=qm(e),i=r.Ji.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,(e=>r.persistence.referenceDelegate.removeTarget(e,i)))}catch(e){if(!kg(e))throw e;Om("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.Ji=r.Ji.remove(t),r.Yi.delete(i.target)}function HI(e,t,n){const r=qm(e);let i=rg.min(),s=l_();return r.persistence.runTransaction("Execute query","readonly",(e=>function(e,t,n){const r=qm(e),i=r.Yi.get(n);return void 0!==i?bg.resolve(r.Ji.get(i)):r.Bs.getTargetData(t,n)}(r,e,zv(t)).next((t=>{if(t)return i=t.lastLimboFreeSnapshotVersion,r.Bs.getMatchingKeysForTargetId(e,t.targetId).next((e=>{s=e}))})).next((()=>r.Hi.getDocumentsMatchingQuery(e,t,n?i:rg.min(),n?s:l_()))).next((e=>(YI(r,Yv(t),e),{documents:e,ir:s})))))}function GI(e,t){const n=qm(e),r=qm(n.Bs),i=n.Ji.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",(e=>r.le(e,t).next((e=>e?e.target:null))))}function KI(e,t){const n=qm(e),r=n.Xi.get(t)||rg.min();return n.persistence.runTransaction("Get new document changes","readonly",(e=>n.Zi.getAllFromCollectionGroup(e,t,pg(r,-1),Number.MAX_SAFE_INTEGER))).then((e=>(YI(n,t,e),e)))}function YI(e,t,n){let r=e.Xi.get(t)||rg.min();n.forEach(((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)})),e.Xi.set(t,r)}async function JI(e,t,n=l_()){const r=await WI(e,zv(ib(t.bundledQuery))),i=qm(e);return i.persistence.runTransaction("Save named query","readwrite",(e=>{const s=Tw(t.readTime);if(r.snapshotVersion.compareTo(s)>=0)return i.qs.saveNamedQuery(e,t);const o=r.withResumeToken(Ey.EMPTY_BYTE_STRING,s);return i.Ji=i.Ji.insert(o.targetId,o),i.Bs.updateTargetData(e,o).next((()=>i.Bs.removeMatchingKeysForTargetId(e,r.targetId))).next((()=>i.Bs.addMatchingKeys(e,n,r.targetId))).next((()=>i.qs.saveNamedQuery(e,t)))}))}function XI(e,t){return`firestore_clients_${e}_${t}`}function ZI(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function eE(e,t){return`firestore_targets_${e}_${t}`}class tE{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static ar(e,t,n){const r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new Um(r.error.code,r.error.message))),s?new tE(e,t,r.state,i):(Pm("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}hr(){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 nE{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static ar(e,t){const n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new Um(n.error.code,n.error.message))),i?new nE(e,n.state,r):(Pm("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}hr(){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 rE{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static ar(e,t){const n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=d_();for(let e=0;r&&e<n.activeTargetIds.length;++e)r=Lg(n.activeTargetIds[e]),i=i.add(n.activeTargetIds[e]);return r?new rE(e,i):(Pm("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class iE{constructor(e,t){this.clientId=e,this.onlineState=t}static ar(e){const t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new iE(t.clientId,t.onlineState):(Pm("SharedClientState",`Failed to parse online state: ${e}`),null)}}class sE{constructor(){this.activeTargetIds=d_()}lr(e){this.activeTargetIds=this.activeTargetIds.add(e)}dr(e){this.activeTargetIds=this.activeTargetIds.delete(e)}hr(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class oE{constructor(e,t,n,r,i){this.window=e,this.ii=t,this.persistenceKey=n,this.wr=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this._r=this.mr.bind(this),this.gr=new my(Zm),this.started=!1,this.yr=[];const s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.pr=XI(this.persistenceKey,this.wr),this.Ir=function(e){return`firestore_sequence_number_${e}`}
/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(this.persistenceKey),this.gr=this.gr.insert(this.wr,new sE),this.Tr=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.Er=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.Ar=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.vr=function(e){return`firestore_online_state_${e}`}(this.persistenceKey),this.Rr=function(e){return`firestore_bundle_loaded_v2_${e}`}(this.persistenceKey),this.window.addEventListener("storage",this._r)}static D(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.$i();for(const t of e){if(t===this.wr)continue;const e=this.getItem(XI(this.persistenceKey,t));if(e){const n=rE.ar(t,e);n&&(this.gr=this.gr.insert(n.clientId,n))}}this.Pr();const t=this.storage.getItem(this.vr);if(t){const e=this.br(t);e&&this.Vr(e)}for(const e of this.yr)this.mr(e);this.yr=[],this.window.addEventListener("pagehide",(()=>this.shutdown())),this.started=!0}writeSequenceNumber(e){this.setItem(this.Ir,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Sr(this.gr)}isActiveQueryTarget(e){let t=!1;return this.gr.forEach(((n,r)=>{r.activeTargetIds.has(e)&&(t=!0)})),t}addPendingMutation(e){this.Dr(e,"pending")}updateMutationState(e,t,n){this.Dr(e,t,n),this.Cr(e)}addLocalQueryTarget(e){let t="not-current";if(this.isActiveQueryTarget(e)){const n=this.storage.getItem(eE(this.persistenceKey,e));if(n){const r=nE.ar(e,n);r&&(t=r.state)}}return this.Nr.lr(e),this.Pr(),t}removeLocalQueryTarget(e){this.Nr.dr(e),this.Pr()}isLocalQueryTarget(e){return this.Nr.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(eE(this.persistenceKey,e))}updateQueryState(e,t,n){this.kr(e,t,n)}handleUserChange(e,t,n){t.forEach((e=>{this.Cr(e)})),this.currentUser=e,n.forEach((e=>{this.addPendingMutation(e)}))}setOnlineState(e){this.Mr(e)}notifyBundleLoaded(e){this.$r(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this._r),this.removeItem(this.pr),this.started=!1)}getItem(e){const t=this.storage.getItem(e);return Om("SharedClientState","READ",e,t),t}setItem(e,t){Om("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){Om("SharedClientState","REMOVE",e),this.storage.removeItem(e)}mr(e){const t=e;if(t.storageArea===this.storage){if(Om("SharedClientState","EVENT",t.key,t.newValue),t.key===this.pr)return void Pm("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.ii.enqueueRetryable((async()=>{if(this.started){if(null!==t.key)if(this.Tr.test(t.key)){if(null==t.newValue){const e=this.Or(t.key);return this.Fr(e,null)}{const e=this.Br(t.key,t.newValue);if(e)return this.Fr(e.clientId,e)}}else if(this.Er.test(t.key)){if(null!==t.newValue){const e=this.Lr(t.key,t.newValue);if(e)return this.qr(e)}}else if(this.Ar.test(t.key)){if(null!==t.newValue){const e=this.Ur(t.key,t.newValue);if(e)return this.Kr(e)}}else if(t.key===this.vr){if(null!==t.newValue){const e=this.br(t.newValue);if(e)return this.Vr(e)}}else if(t.key===this.Ir){const e=function(e){let t=Og.ct;if(null!=e)try{const n=JSON.parse(e);jm("number"==typeof n),t=n}catch(e){Pm("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(t.newValue);e!==Og.ct&&this.sequenceNumberHandler(e)}else if(t.key===this.Rr){const e=this.Gr(t.newValue);await Promise.all(e.map((e=>this.syncEngine.Qr(e))))}}else this.yr.push(t)}))}}get Nr(){return this.gr.get(this.wr)}Pr(){this.setItem(this.pr,this.Nr.hr())}Dr(e,t,n){const r=new tE(this.currentUser,e,t,n),i=ZI(this.persistenceKey,this.currentUser,e);this.setItem(i,r.hr())}Cr(e){const t=ZI(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Mr(e){const t={clientId:this.wr,onlineState:e};this.storage.setItem(this.vr,JSON.stringify(t))}kr(e,t,n){const r=eE(this.persistenceKey,e),i=new nE(e,t,n);this.setItem(r,i.hr())}$r(e){const t=JSON.stringify(Array.from(e));this.setItem(this.Rr,t)}Or(e){const t=this.Tr.exec(e);return t?t[1]:null}Br(e,t){const n=this.Or(e);return rE.ar(n,t)}Lr(e,t){const n=this.Er.exec(e),r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return tE.ar(new Am(i),r,t)}Ur(e,t){const n=this.Ar.exec(e),r=Number(n[1]);return nE.ar(r,t)}br(e){return iE.ar(e)}Gr(e){return JSON.parse(e)}async qr(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.jr(e.batchId,e.state,e.error);Om("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Kr(e){return this.syncEngine.zr(e.targetId,e.state,e.error)}Fr(e,t){const n=t?this.gr.insert(e,t):this.gr.remove(e),r=this.Sr(this.gr),i=this.Sr(n),s=[],o=[];return i.forEach((e=>{r.has(e)||s.push(e)})),r.forEach((e=>{i.has(e)||o.push(e)})),this.syncEngine.Wr(s,o).then((()=>{this.gr=n}))}Vr(e){this.gr.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Sr(e){let t=d_();return e.forEach(((e,n)=>{t=t.unionWith(n.activeTargetIds)})),t}}class aE{constructor(){this.Hr=new sE,this.Jr={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Hr.lr(e),this.Jr[e]||"not-current"}updateQueryState(e,t,n){this.Jr[e]=t}removeLocalQueryTarget(e){this.Hr.dr(e)}isLocalQueryTarget(e){return this.Hr.activeTargetIds.has(e)}clearQueryState(e){delete this.Jr[e]}getAllActiveQueryTargets(){return this.Hr.activeTargetIds}isActiveQueryTarget(e){return this.Hr.activeTargetIds.has(e)}start(){return this.Hr=new sE,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class cE{Yr(e){}shutdown(){}}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class uE{constructor(){this.Xr=()=>this.Zr(),this.eo=()=>this.no(),this.so=[],this.io()}Yr(e){this.so.push(e)}shutdown(){window.removeEventListener("online",this.Xr),window.removeEventListener("offline",this.eo)}io(){window.addEventListener("online",this.Xr),window.addEventListener("offline",this.eo)}Zr(){Om("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.so)e(0)}no(){Om("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.so)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}
/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let lE=null;function hE(){return null===lE?lE=268435456+Math.round(2147483648*Math.random()):lE++,"0x"+lE.toString(16)
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */}const dE={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class fE{constructor(e){this.ro=e.ro,this.oo=e.oo}uo(e){this.co=e}ao(e){this.ho=e}onMessage(e){this.lo=e}close(){this.oo()}send(e){this.ro(e)}fo(){this.co()}wo(e){this.ho(e)}_o(e){this.lo(e)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const pE="WebChannelConnection";class mE extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http";this.mo=t+"://"+e.host,this.yo="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}get po(){return!1}Io(e,t,n,r,i){const s=hE(),o=this.To(e,t);Om("RestConnection",`Sending RPC '${e}' ${s}:`,o,n);const a={};return this.Eo(a,r,i),this.Ao(e,o,a,n).then((t=>(Om("RestConnection",`Received RPC '${e}' ${s}: `,t),t)),(t=>{throw Mm("RestConnection",`RPC '${e}' ${s} failed with error: `,t,"url: ",o,"request:",n),t}))}vo(e,t,n,r,i,s){return this.Io(e,t,n,r,i)}Eo(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+Nm,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach(((t,n)=>e[n]=t)),n&&n.headers.forEach(((t,n)=>e[n]=t))}To(e,t){const n=dE[e];return`${this.mo}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Ao(e,t,n,r){const i=hE();return new Promise(((s,o)=>{const a=new Sm;a.setWithCredentials(!0),a.listenOnce(_m.COMPLETE,(()=>{try{switch(a.getLastErrorCode()){case vm.NO_ERROR:const t=a.getResponseJson();Om(pE,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(t)),s(t);break;case vm.TIMEOUT:Om(pE,`RPC '${e}' ${i} timed out`),o(new Um(Vm.DEADLINE_EXCEEDED,"Request time out"));break;case vm.HTTP_ERROR:const n=a.getStatus();if(Om(pE,`RPC '${e}' ${i} failed with status:`,n,"response text:",a.getResponseText()),n>0){let e=a.getResponseJson();Array.isArray(e)&&(e=e[0]);const t=null==e?void 0:e.error;if(t&&t.status&&t.message){const e=function(e){const t=e.toLowerCase().replace(/_/g,"-");return Object.values(Vm).indexOf(t)>=0?t:Vm.UNKNOWN}(t.status);o(new Um(e,t.message))}else o(new Um(Vm.UNKNOWN,"Server responded with status "+a.getStatus()))}else o(new Um(Vm.UNAVAILABLE,"Connection failed."));break;default:Fm()}}finally{Om(pE,`RPC '${e}' ${i} completed.`)}}));const c=JSON.stringify(r);Om(pE,`RPC '${e}' ${i} sending request:`,r),a.send(t,"POST",c,n,15)}))}Ro(e,t,n){const r=hE(),i=[this.mo,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=new Gp,o=Qd(),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},c=this.longPollingOptions.timeoutSeconds;void 0!==c&&(a.longPollingTimeout=Math.round(1e3*c)),this.useFetchStreams&&(a.xmlHttpFactory=new Em({})),this.Eo(a.initMessageHeaders,t,n),a.encodeInitMessageHeaders=!0;const u=i.join("");Om(pE,`Creating RPC '${e}' stream ${r}: ${u}`,a);const l=s.createWebChannel(u,a);let h=!1,d=!1;const f=new fE({ro:t=>{d?Om(pE,`Not sending because RPC '${e}' stream ${r} is closed:`,t):(h||(Om(pE,`Opening RPC '${e}' stream ${r} transport.`),l.open(),h=!0),Om(pE,`RPC '${e}' stream ${r} sending:`,t),l.send(t))},oo:()=>l.close()}),p=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return p(l,Tm.EventType.OPEN,(()=>{d||Om(pE,`RPC '${e}' stream ${r} transport opened.`)})),p(l,Tm.EventType.CLOSE,(()=>{d||(d=!0,Om(pE,`RPC '${e}' stream ${r} transport closed`),f.wo())})),p(l,Tm.EventType.ERROR,(t=>{d||(d=!0,Mm(pE,`RPC '${e}' stream ${r} transport errored:`,t),f.wo(new Um(Vm.UNAVAILABLE,"The operation could not be completed")))})),p(l,Tm.EventType.MESSAGE,(t=>{var n;if(!d){const i=t.data[0];jm(!!i);const s=i,o=s.error||(null===(n=s[0])||void 0===n?void 0:n.error);if(o){Om(pE,`RPC '${e}' stream ${r} received error:`,o);const t=o.status;let n=function(e){const t=K_[e];if(void 0!==t)return X_(t)}(t),i=o.message;void 0===n&&(n=Vm.INTERNAL,i="Unknown error status: "+t+" with message "+o.message),d=!0,f.wo(new Um(n,i)),l.close()}else Om(pE,`RPC '${e}' stream ${r} received:`,i),f._o(i)}})),p(o,wm.STAT_EVENT,(t=>{t.stat===bm?Om(pE,`RPC '${e}' stream ${r} detected buffering proxy`):t.stat===Im&&Om(pE,`RPC '${e}' stream ${r} detected no buffering proxy`)})),setTimeout((()=>{f.fo()}),0),f}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function gE(){return"undefined"!=typeof window?window:null}function yE(){return"undefined"!=typeof document?document:null}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function vE(e){return new _w(e,!0)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class _E{constructor(e,t,n=1e3,r=1.5,i=6e4){this.ii=e,this.timerId=t,this.Po=n,this.bo=r,this.Vo=i,this.So=0,this.Do=null,this.Co=Date.now(),this.reset()}reset(){this.So=0}xo(){this.So=this.Vo}No(e){this.cancel();const t=Math.floor(this.So+this.ko()),n=Math.max(0,Date.now()-this.Co),r=Math.max(0,t-n);r>0&&Om("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.So} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Do=this.ii.enqueueAfterDelay(this.timerId,r,(()=>(this.Co=Date.now(),e()))),this.So*=this.bo,this.So<this.Po&&(this.So=this.Po),this.So>this.Vo&&(this.So=this.Vo)}Mo(){null!==this.Do&&(this.Do.skipDelay(),this.Do=null)}cancel(){null!==this.Do&&(this.Do.cancel(),this.Do=null)}ko(){return(Math.random()-.5)*this.So}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class wE{constructor(e,t,n,r,i,s,o,a){this.ii=e,this.$o=n,this.Oo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.Fo=0,this.Bo=null,this.Lo=null,this.stream=null,this.qo=new _E(e,t)}Uo(){return 1===this.state||5===this.state||this.Ko()}Ko(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Go()}async stop(){this.Uo()&&await this.close(0)}Qo(){this.state=0,this.qo.reset()}jo(){this.Ko()&&null===this.Bo&&(this.Bo=this.ii.enqueueAfterDelay(this.$o,6e4,(()=>this.zo())))}Wo(e){this.Ho(),this.stream.send(e)}async zo(){if(this.Ko())return this.close(0)}Ho(){this.Bo&&(this.Bo.cancel(),this.Bo=null)}Jo(){this.Lo&&(this.Lo.cancel(),this.Lo=null)}async close(e,t){this.Ho(),this.Jo(),this.qo.cancel(),this.Fo++,4!==e?this.qo.reset():t&&t.code===Vm.RESOURCE_EXHAUSTED?(Pm(t.toString()),Pm("Using maximum backoff delay to prevent overloading the backend."),this.qo.xo()):t&&t.code===Vm.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Yo(),this.stream.close(),this.stream=null),this.state=e,await this.listener.ao(t)}Yo(){}auth(){this.state=1;const e=this.Xo(this.Fo),t=this.Fo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([e,n])=>{this.Fo===t&&this.Zo(e,n)}),(t=>{e((()=>{const e=new Um(Vm.UNKNOWN,"Fetching auth token failed: "+t.message);return this.tu(e)}))}))}Zo(e,t){const n=this.Xo(this.Fo);this.stream=this.eu(e,t),this.stream.uo((()=>{n((()=>(this.state=2,this.Lo=this.ii.enqueueAfterDelay(this.Oo,1e4,(()=>(this.Ko()&&(this.state=3),Promise.resolve()))),this.listener.uo())))})),this.stream.ao((e=>{n((()=>this.tu(e)))})),this.stream.onMessage((e=>{n((()=>this.onMessage(e)))}))}Go(){this.state=5,this.qo.No((async()=>{this.state=0,this.start()}))}tu(e){return Om("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Xo(e){return t=>{this.ii.enqueueAndForget((()=>this.Fo===e?t():(Om("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class bE extends wE{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}eu(e,t){return this.connection.Ro("Listen",e,t)}onMessage(e){this.qo.reset();const t=function(e,t){let n;if("targetChange"in t){t.targetChange;const r=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:Fm()}(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],s=function(e,t){return e.useProto3Json?(jm(void 0===t||"string"==typeof t),Ey.fromBase64String(t||"")):(jm(void 0===t||t instanceof Uint8Array),Ey.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),o=t.targetChange.cause,a=o&&function(e){const t=void 0===e.code?Vm.UNKNOWN:X_(e.code);return new Um(t,e.message||"")}(o);n=new hw(r,i,s,a||null)}else if("documentChange"in t){t.documentChange;const r=t.documentChange;r.document,r.document.name,r.document.updateTime;const i=xw(e,r.document.name),s=Tw(r.document.updateTime),o=r.document.createTime?Tw(r.document.createTime):rg.min(),a=new ev({mapValue:{fields:r.document.fields}}),c=nv.newFoundDocument(i,s,o,a),u=r.targetIds||[],l=r.removedTargetIds||[];n=new uw(u,l,c.key,c)}else if("documentDelete"in t){t.documentDelete;const r=t.documentDelete;r.document;const i=xw(e,r.document),s=r.readTime?Tw(r.readTime):rg.min(),o=nv.newNoDocument(i,s),a=r.removedTargetIds||[];n=new uw([],a,o.key,o)}else if("documentRemove"in t){t.documentRemove;const r=t.documentRemove;r.document;const i=xw(e,r.document),s=r.removedTargetIds||[];n=new uw([],s,i,null)}else{if(!("filter"in t))return Fm();{t.filter;const e=t.filter;e.targetId;const{count:r=0,unchangedNames:i}=e,s=new G_(r,i),o=e.targetId;n=new lw(o,s)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return rg.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?rg.min():t.readTime?Tw(t.readTime):rg.min()}(e);return this.listener.nu(t,n)}su(e){const t={};t.database=Dw(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=Dv(r)?{documents:Fw(e,r)}:{query:jw(e,r)},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=Iw(e,t.resumeToken);const r=ww(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(rg.min())>0){n.readTime=bw(e,t.snapshotVersion.toTimestamp());const r=ww(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);const n=function(e,t){const n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return Fm()}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.Wo(t)}iu(e){const t={};t.database=Dw(this.serializer),t.removeTarget=e,this.Wo(t)}}class IE extends wE{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i,this.ru=!1}get ou(){return this.ru}start(){this.ru=!1,this.lastStreamToken=void 0,super.start()}Yo(){this.ru&&this.uu([])}eu(e,t){return this.connection.Ro("Write",e,t)}onMessage(e){if(jm(!!e.streamToken),this.lastStreamToken=e.streamToken,this.ru){this.qo.reset();const t=function(e,t){return e&&e.length>0?(jm(void 0!==t),e.map((e=>function(e,t){let n=e.updateTime?Tw(e.updateTime):Tw(t);return n.isEqual(rg.min())&&(n=Tw(t)),new A_(n,e.transformResults||[])}(e,t)))):[]}(e.writeResults,e.commitTime),n=Tw(e.commitTime);return this.listener.cu(n,t)}return jm(!e.writeResults||0===e.writeResults.length),this.ru=!0,this.listener.au()}hu(){const e={};e.database=Dw(this.serializer),this.Wo(e)}uu(e){const t={streamToken:this.lastStreamToken,writes:e.map((e=>Mw(this.serializer,e)))};this.Wo(t)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class EE extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.lu=!1}fu(){if(this.lu)throw new Um(Vm.FAILED_PRECONDITION,"The client has already been terminated.")}Io(e,t,n){return this.fu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([r,i])=>this.connection.Io(e,t,n,r,i))).catch((e=>{throw"FirebaseError"===e.name?(e.code===Vm.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new Um(Vm.UNKNOWN,e.toString())}))}vo(e,t,n,r){return this.fu(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([i,s])=>this.connection.vo(e,t,n,i,s,r))).catch((e=>{throw"FirebaseError"===e.name?(e.code===Vm.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new Um(Vm.UNKNOWN,e.toString())}))}terminate(){this.lu=!0}}class TE{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.wu=0,this._u=null,this.mu=!0}gu(){0===this.wu&&(this.yu("Unknown"),this._u=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this._u=null,this.pu("Backend didn't respond within 10 seconds."),this.yu("Offline"),Promise.resolve()))))}Iu(e){"Online"===this.state?this.yu("Unknown"):(this.wu++,this.wu>=1&&(this.Tu(),this.pu(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.yu("Offline")))}set(e){this.Tu(),this.wu=0,"Online"===e&&(this.mu=!1),this.yu(e)}yu(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}pu(e){const 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.mu?(Pm(t),this.mu=!1):Om("OnlineStateTracker",t)}Tu(){null!==this._u&&(this._u.cancel(),this._u=null)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class SE{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Eu=[],this.Au=new Map,this.vu=new Set,this.Ru=[],this.Pu=i,this.Pu.Yr((e=>{n.enqueueAndForget((async()=>{PE(this)&&(Om("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=qm(e);t.vu.add(4),await CE(t),t.bu.set("Unknown"),t.vu.delete(4),await kE(t)}(this))}))})),this.bu=new TE(n,r)}}async function kE(e){if(PE(e))for(const t of e.Ru)await t(!0)}async function CE(e){for(const t of e.Ru)await t(!1)}function xE(e,t){const n=qm(e);n.Au.has(t.targetId)||(n.Au.set(t.targetId,t),OE(n)?RE(n):XE(n).Ko()&&NE(n,t))}function AE(e,t){const n=qm(e),r=XE(n);n.Au.delete(t),r.Ko()&&DE(n,t),0===n.Au.size&&(r.Ko()?r.jo():PE(n)&&n.bu.set("Unknown"))}function NE(e,t){if(e.Vu.qt(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(rg.min())>0){const n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}XE(e).su(t)}function DE(e,t){e.Vu.qt(t),XE(e).iu(t)}function RE(e){e.Vu=new fw({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),le:t=>e.Au.get(t)||null,ue:()=>e.datastore.serializer.databaseId}),XE(e).start(),e.bu.gu()}function OE(e){return PE(e)&&!XE(e).Uo()&&e.Au.size>0}function PE(e){return 0===qm(e).vu.size}function ME(e){e.Vu=void 0}async function LE(e){e.Au.forEach(((t,n)=>{NE(e,t)}))}async function FE(e,t){ME(e),OE(e)?(e.bu.Iu(t),RE(e)):e.bu.set("Unknown")}async function jE(e,t,n){if(e.bu.set("Online"),t instanceof hw&&2===t.state&&t.cause)try{await async function(e,t){const n=t.cause;for(const r of t.targetIds)e.Au.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.Au.delete(r),e.Vu.removeTarget(r))}(e,t)}catch(n){Om("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await qE(e,n)}else if(t instanceof uw?e.Vu.Ht(t):t instanceof lw?e.Vu.ne(t):e.Vu.Xt(t),!n.isEqual(rg.min()))try{const t=await BI(e.localStore);n.compareTo(t)>=0&&await function(e,t){const n=e.Vu.ce(t);return n.targetChanges.forEach(((n,r)=>{if(n.resumeToken.approximateByteSize()>0){const i=e.Au.get(r);i&&e.Au.set(r,i.withResumeToken(n.resumeToken,t))}})),n.targetMismatches.forEach(((t,n)=>{const r=e.Au.get(t);if(!r)return;e.Au.set(t,r.withResumeToken(Ey.EMPTY_BYTE_STRING,r.snapshotVersion)),DE(e,t);const i=new Kw(r.target,t,n,r.sequenceNumber);NE(e,i)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){Om("RemoteStore","Failed to raise snapshot:",t),await qE(e,t)}}async function qE(e,t,n){if(!kg(t))throw t;e.vu.add(1),await CE(e),e.bu.set("Offline"),n||(n=()=>BI(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{Om("RemoteStore","Retrying IndexedDB access"),await n(),e.vu.delete(1),await kE(e)}))}function VE(e,t){return t().catch((n=>qE(e,n,t)))}async function UE(e){const t=qm(e),n=ZE(t);let r=t.Eu.length>0?t.Eu[t.Eu.length-1].batchId:-1;for(;BE(t);)try{const e=await $I(t.localStore,r);if(null===e){0===t.Eu.length&&n.jo();break}r=e.batchId,zE(t,e)}catch(e){await qE(t,e)}$E(t)&&WE(t)}function BE(e){return PE(e)&&e.Eu.length<10}function zE(e,t){e.Eu.push(t);const n=ZE(e);n.Ko()&&n.ou&&n.uu(t.mutations)}function $E(e){return PE(e)&&!ZE(e).Uo()&&e.Eu.length>0}function WE(e){ZE(e).start()}async function QE(e){ZE(e).hu()}async function HE(e){const t=ZE(e);for(const n of e.Eu)t.uu(n.mutations)}async function GE(e,t,n){const r=e.Eu.shift(),i=Q_.from(r,t,n);await VE(e,(()=>e.remoteSyncer.applySuccessfulWrite(i))),await UE(e)}async function KE(e,t){t&&ZE(e).ou&&await async function(e,t){if(J_(n=t.code)&&n!==Vm.ABORTED){const n=e.Eu.shift();ZE(e).Qo(),await VE(e,(()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t))),await UE(e)}var n}(e,t),$E(e)&&WE(e)}async function YE(e,t){const n=qm(e);n.asyncQueue.verifyOperationInProgress(),Om("RemoteStore","RemoteStore received new credentials");const r=PE(n);n.vu.add(3),await CE(n),r&&n.bu.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.vu.delete(3),await kE(n)}async function JE(e,t){const n=qm(e);t?(n.vu.delete(2),await kE(n)):t||(n.vu.add(2),await CE(n),n.bu.set("Unknown"))}function XE(e){return e.Su||(e.Su=function(e,t,n){const r=qm(e);return r.fu(),new bE(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)
/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */}(e.datastore,e.asyncQueue,{uo:LE.bind(null,e),ao:FE.bind(null,e),nu:jE.bind(null,e)}),e.Ru.push((async t=>{t?(e.Su.Qo(),OE(e)?RE(e):e.bu.set("Unknown")):(await e.Su.stop(),ME(e))}))),e.Su}function ZE(e){return e.Du||(e.Du=function(e,t,n){const r=qm(e);return r.fu(),new IE(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{uo:QE.bind(null,e),ao:KE.bind(null,e),au:HE.bind(null,e),cu:GE.bind(null,e)}),e.Ru.push((async t=>{t?(e.Du.Qo(),await UE(e)):(await e.Du.stop(),e.Eu.length>0&&(Om("RemoteStore",`Stopping write stream with ${e.Eu.length} pending writes`),e.Eu=[]))}))),e.Du
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */}class eT{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new Bm,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,o=new eT(e,t,s,r,i);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 Um(Vm.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 tT(e,t){if(Pm("AsyncQueue",`${t}: ${e}`),kg(e))return new Um(Vm.UNAVAILABLE,`${t}: ${e}`);throw e}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class nT{constructor(e){this.comparator=e?(t,n)=>e(t,n)||cg.comparator(t.key,n.key):(e,t)=>cg.comparator(e.key,t.key),this.keyedMap=r_(),this.sortedSet=new my(this.comparator)}static emptySet(e){return new nT(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){const t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal(((t,n)=>(e(t),!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){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof nT))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 e=[];return this.forEach((t=>{e.push(t.toString())})),0===e.length?"DocumentSet ()":"DocumentSet (\n  "+e.join("  \n")+"\n)"}copy(e,t){const n=new nT;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class rT{constructor(){this.Cu=new my(cg.comparator)}track(e){const t=e.doc.key,n=this.Cu.get(t);n?0!==e.type&&3===n.type?this.Cu=this.Cu.insert(t,e):3===e.type&&1!==n.type?this.Cu=this.Cu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Cu=this.Cu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Cu=this.Cu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Cu=this.Cu.remove(t):1===e.type&&2===n.type?this.Cu=this.Cu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Cu=this.Cu.insert(t,{type:2,doc:e.doc}):Fm():this.Cu=this.Cu.insert(t,e)}xu(){const e=[];return this.Cu.inorderTraversal(((t,n)=>{e.push(n)})),e}}class iT{constructor(e,t,n,r,i,s,o,a,c){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=o,this.excludesMetadataChanges=a,this.hasCachedResults=c}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach((e=>{s.push({type:0,doc:e})})),new iT(e,t,nT.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&Qv(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 e=0;e<t.length;e++)if(t[e].type!==n[e].type||!t[e].doc.isEqual(n[e].doc))return!1;return!0}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class sT{constructor(){this.Nu=void 0,this.listeners=[]}}class oT{constructor(){this.queries=new Zv((e=>Hv(e)),Qv),this.onlineState="Unknown",this.ku=new Set}}async function aT(e,t){const n=qm(e),r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new sT),i)try{s.Nu=await n.onListen(r)}catch(e){const n=tT(e,`Initialization of query '${Gv(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.Mu(n.onlineState),s.Nu&&t.$u(s.Nu)&&hT(n)}async function cT(e,t){const n=qm(e),r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);e>=0&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function uT(e,t){const n=qm(e);let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.$u(e)&&(r=!0);i.Nu=e}}r&&hT(n)}function lT(e,t,n){const r=qm(e),i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}function hT(e){e.ku.forEach((e=>{e.next()}))}class dT{constructor(e,t,n){this.query=e,this.Ou=t,this.Fu=!1,this.Bu=null,this.onlineState="Unknown",this.options=n||{}}$u(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new iT(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Fu?this.Lu(e)&&(this.Ou.next(e),t=!0):this.qu(e,this.onlineState)&&(this.Uu(e),t=!0),this.Bu=e,t}onError(e){this.Ou.error(e)}Mu(e){this.onlineState=e;let t=!1;return this.Bu&&!this.Fu&&this.qu(this.Bu,e)&&(this.Uu(this.Bu),t=!0),t}qu(e,t){if(!e.fromCache)return!0;const n="Offline"!==t;return(!this.options.Ku||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Lu(e){if(e.docChanges.length>0)return!0;const t=this.Bu&&this.Bu.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}Uu(e){e=iT.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Fu=!0,this.Ou.next(e)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class fT{constructor(e,t){this.Gu=e,this.byteLength=t}Qu(){return"metadata"in this.Gu}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class pT{constructor(e){this.serializer=e}rr(e){return xw(this.serializer,e)}ur(e){return e.metadata.exists?Pw(this.serializer,e.document,!1):nv.newNoDocument(this.rr(e.metadata.name),this.cr(e.metadata.readTime))}cr(e){return Tw(e)}}class mT{constructor(e,t,n){this.ju=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=gT(e)}zu(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.Gu.namedQuery)this.queries.push(e.Gu.namedQuery);else if(e.Gu.documentMetadata){this.documents.push({metadata:e.Gu.documentMetadata}),e.Gu.documentMetadata.exists||++t;const n=sg.fromString(e.Gu.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.Gu.document&&(this.documents[this.documents.length-1].document=e.Gu.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Wu(e){const t=new Map,n=new pT(this.serializer);for(const r of e)if(r.metadata.queries){const e=n.rr(r.metadata.name);for(const n of r.metadata.queries){const r=(t.get(n)||l_()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=qm(e);let s=l_(),o=t_();for(const e of n){const n=t.rr(e.metadata.name);e.document&&(s=s.add(n));const r=t.ur(e);r.setReadTime(t.cr(e.metadata.readTime)),o=o.insert(n,r)}const a=i.Zi.newChangeBuffer({trackRemovals:!0}),c=await WI(i,function(e){return zv(Fv(sg.fromString(`__bundle__/docs/${e}`)))}(r));return i.persistence.runTransaction("Apply bundle documents","readwrite",(e=>zI(e,a,o).next((t=>(a.apply(e),t))).next((t=>i.Bs.removeMatchingKeysForTargetId(e,c.targetId).next((()=>i.Bs.addMatchingKeys(e,s,c.targetId))).next((()=>i.localDocuments.getLocalViewOfDocuments(e,t.nr,t.sr))).next((()=>t.nr))))))}(this.localStore,new pT(this.serializer),this.documents,this.ju.id),t=this.Wu(this.documents);for(const e of this.queries)await JI(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Hu:this.collectionGroups,Ju:e}}}function gT(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class yT{constructor(e){this.key=e}}class vT{constructor(e){this.key=e}}class _T{constructor(e,t){this.query=e,this.Yu=t,this.Xu=null,this.hasCachedResults=!1,this.current=!1,this.Zu=l_(),this.mutatedKeys=l_(),this.tc=Jv(e),this.ec=new nT(this.tc)}get nc(){return this.Yu}sc(e,t){const n=t?t.ic:new rT,r=t?t.ec:this.ec;let i=t?t.mutatedKeys:this.mutatedKeys,s=r,o=!1;const a="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,c="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal(((e,t)=>{const u=r.get(e),l=Kv(this.query,t)?t:null,h=!!u&&this.mutatedKeys.has(u.key),d=!!l&&(l.hasLocalMutations||this.mutatedKeys.has(l.key)&&l.hasCommittedMutations);let f=!1;u&&l?u.data.isEqual(l.data)?h!==d&&(n.track({type:3,doc:l}),f=!0):this.rc(u,l)||(n.track({type:2,doc:l}),f=!0,(a&&this.tc(l,a)>0||c&&this.tc(l,c)<0)&&(o=!0)):!u&&l?(n.track({type:0,doc:l}),f=!0):u&&!l&&(n.track({type:1,doc:u}),f=!0,(a||c)&&(o=!0)),f&&(l?(s=s.add(l),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))})),null!==this.query.limit)for(;s.size>this.query.limit;){const e="F"===this.query.limitType?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{ec:s,ic:n,zi:o,mutatedKeys:i}}rc(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){const r=this.ec;this.ec=e.ec,this.mutatedKeys=e.mutatedKeys;const i=e.ic.xu();i.sort(((e,t)=>function(e,t){const n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Fm()}};return n(e)-n(t)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e.type,t.type)||this.tc(e.doc,t.doc))),this.oc(n);const s=t?this.uc():[],o=0===this.Zu.size&&this.current?1:0,a=o!==this.Xu;return this.Xu=o,0!==i.length||a?{snapshot:new iT(this.query,e.ec,r,i,e.mutatedKeys,0===o,a,!1,!!n&&n.resumeToken.approximateByteSize()>0),cc:s}:{cc:s}}Mu(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({ec:this.ec,ic:new rT,mutatedKeys:this.mutatedKeys,zi:!1},!1)):{cc:[]}}ac(e){return!this.Yu.has(e)&&!!this.ec.has(e)&&!this.ec.get(e).hasLocalMutations}oc(e){e&&(e.addedDocuments.forEach((e=>this.Yu=this.Yu.add(e))),e.modifiedDocuments.forEach((e=>{})),e.removedDocuments.forEach((e=>this.Yu=this.Yu.delete(e))),this.current=e.current)}uc(){if(!this.current)return[];const e=this.Zu;this.Zu=l_(),this.ec.forEach((e=>{this.ac(e.key)&&(this.Zu=this.Zu.add(e.key))}));const t=[];return e.forEach((e=>{this.Zu.has(e)||t.push(new vT(e))})),this.Zu.forEach((n=>{e.has(n)||t.push(new yT(n))})),t}hc(e){this.Yu=e.ir,this.Zu=l_();const t=this.sc(e.documents);return this.applyChanges(t,!0)}lc(){return iT.fromInitialDocuments(this.query,this.ec,this.mutatedKeys,0===this.Xu,this.hasCachedResults)}}class wT{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class bT{constructor(e){this.key=e,this.fc=!1}}class IT{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.dc={},this.wc=new Zv((e=>Hv(e)),Qv),this._c=new Map,this.mc=new Set,this.gc=new my(cg.comparator),this.yc=new Map,this.Ic=new bI,this.Tc={},this.Ec=new Map,this.Ac=Jb.Mn(),this.onlineState="Unknown",this.vc=void 0}get isPrimaryClient(){return!0===this.vc}}async function ET(e,t){const n=KT(e);let r,i;const s=n.wc.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.lc();else{const e=await WI(n.localStore,zv(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await TT(n,t,r,"current"===s,e.resumeToken),n.isPrimaryClient&&xE(n.remoteStore,e)}return i}async function TT(e,t,n,r,i){e.Rc=(t,n,r)=>async function(e,t,n,r){let i=t.view.sc(n);i.zi&&(i=await HI(e.localStore,t.query,!1).then((({documents:e})=>t.view.sc(e,i))));const s=r&&r.targetChanges.get(t.targetId),o=t.view.applyChanges(i,e.isPrimaryClient,s);return MT(e,t.targetId,o.cc),o.snapshot}(e,t,n,r);const s=await HI(e.localStore,t,!0),o=new _T(t,s.ir),a=o.sc(s.documents),c=cw.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),u=o.applyChanges(a,e.isPrimaryClient,c);MT(e,n,u.cc);const l=new wT(t,n,o);return e.wc.set(t,l),e._c.has(n)?e._c.get(n).push(t):e._c.set(n,[t]),u.snapshot}async function ST(e,t){const n=qm(e),r=n.wc.get(t),i=n._c.get(r.targetId);if(i.length>1)return n._c.set(r.targetId,i.filter((e=>!Qv(e,t)))),void n.wc.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await QI(n.localStore,r.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(r.targetId),AE(n.remoteStore,r.targetId),OT(n,r.targetId)})).catch(wg)):(OT(n,r.targetId),await QI(n.localStore,r.targetId,!0))}async function kT(e,t){const n=qm(e);try{const e=await function(e,t){const n=qm(e),r=t.snapshotVersion;let i=n.Ji;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(e=>{const s=n.Zi.newChangeBuffer({trackRemovals:!0});i=n.Ji;const o=[];t.targetChanges.forEach(((s,a)=>{const c=i.get(a);if(!c)return;o.push(n.Bs.removeMatchingKeys(e,s.removedDocuments,a).next((()=>n.Bs.addMatchingKeys(e,s.addedDocuments,a))));let u=c.withSequenceNumber(e.currentSequenceNumber);null!==t.targetMismatches.get(a)?u=u.withResumeToken(Ey.EMPTY_BYTE_STRING,rg.min()).withLastLimboFreeSnapshotVersion(rg.min()):s.resumeToken.approximateByteSize()>0&&(u=u.withResumeToken(s.resumeToken,r)),i=i.insert(a,u),function(e,t,n){return 0===e.resumeToken.approximateByteSize()||t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(c,u,s)&&o.push(n.Bs.updateTargetData(e,u))}));let a=t_(),c=l_();if(t.documentUpdates.forEach((r=>{t.resolvedLimboDocuments.has(r)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))})),o.push(zI(e,s,t.documentUpdates).next((e=>{a=e.nr,c=e.sr}))),!r.isEqual(rg.min())){const t=n.Bs.getLastRemoteSnapshotVersion(e).next((t=>n.Bs.setTargetsMetadata(e,e.currentSequenceNumber,r)));o.push(t)}return bg.waitFor(o).next((()=>s.apply(e))).next((()=>n.localDocuments.getLocalViewOfDocuments(e,a,c))).next((()=>a))})).then((e=>(n.Ji=i,e)))}(n.localStore,t);t.targetChanges.forEach(((e,t)=>{const r=n.yc.get(t);r&&(jm(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?r.fc=!0:e.modifiedDocuments.size>0?jm(r.fc):e.removedDocuments.size>0&&(jm(r.fc),r.fc=!1))})),await jT(n,e,t)}catch(e){await wg(e)}}function CT(e,t,n){const r=qm(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){const e=[];r.wc.forEach(((n,r)=>{const i=r.view.Mu(t);i.snapshot&&e.push(i.snapshot)})),function(e,t){const n=qm(e);n.onlineState=t;let r=!1;n.queries.forEach(((e,n)=>{for(const e of n.listeners)e.Mu(t)&&(r=!0)})),r&&hT(n)}(r.eventManager,t),e.length&&r.dc.nu(e),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}async function xT(e,t,n){const r=qm(e);r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.yc.get(t),s=i&&i.key;if(s){let e=new my(cg.comparator);e=e.insert(s,nv.newNoDocument(s,rg.min()));const n=l_().add(s),i=new aw(rg.min(),new Map,new my(Zm),e,n);await kT(r,i),r.gc=r.gc.remove(s),r.yc.delete(t),FT(r)}else await QI(r.localStore,t,!1).then((()=>OT(r,t,n))).catch(wg)}async function AT(e,t){const n=qm(e),r=t.batch.batchId;try{const e=await function(e,t){const n=qm(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",(e=>{const r=t.batch.keys(),i=n.Zi.newChangeBuffer({trackRemovals:!0});return function(e,t,n,r){const i=n.batch,s=i.keys();let o=bg.resolve();return s.forEach((e=>{o=o.next((()=>r.getEntry(t,e))).next((t=>{const s=n.docVersions.get(e);jm(null!==s),t.version.compareTo(s)<0&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))}))})),o.next((()=>e.mutationQueue.removeMutationBatch(t,i)))}(n,e,t,i).next((()=>i.apply(e))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=l_();for(let n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t)))).next((()=>n.localDocuments.getDocuments(e,r)))}))}(n.localStore,t);RT(n,r,null),DT(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await jT(n,e)}catch(e){await wg(e)}}async function NT(e,t,n){const r=qm(e);try{const e=await function(e,t){const n=qm(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",(e=>{let r;return n.mutationQueue.lookupMutationBatch(e,t).next((t=>(jm(null!==t),r=t.keys(),n.mutationQueue.removeMutationBatch(e,t)))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,r))).next((()=>n.localDocuments.getDocuments(e,r)))}))}(r.localStore,t);RT(r,t,n),DT(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await jT(r,e)}catch(n){await wg(n)}}function DT(e,t){(e.Ec.get(t)||[]).forEach((e=>{e.resolve()})),e.Ec.delete(t)}function RT(e,t,n){const r=qm(e);let i=r.Tc[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.Tc[r.currentUser.toKey()]=i}}function OT(e,t,n=null){e.sharedClientState.removeLocalQueryTarget(t);for(const r of e._c.get(t))e.wc.delete(r),n&&e.dc.Pc(r,n);e._c.delete(t),e.isPrimaryClient&&e.Ic.Is(t).forEach((t=>{e.Ic.containsKey(t)||PT(e,t)}))}function PT(e,t){e.mc.delete(t.path.canonicalString());const n=e.gc.get(t);null!==n&&(AE(e.remoteStore,n),e.gc=e.gc.remove(t),e.yc.delete(n),FT(e))}function MT(e,t,n){for(const r of n)r instanceof yT?(e.Ic.addReference(r.key,t),LT(e,r)):r instanceof vT?(Om("SyncEngine","Document no longer in limbo: "+r.key),e.Ic.removeReference(r.key,t),e.Ic.containsKey(r.key)||PT(e,r.key)):Fm()}function LT(e,t){const n=t.key,r=n.path.canonicalString();e.gc.get(n)||e.mc.has(r)||(Om("SyncEngine","New document in limbo: "+n),e.mc.add(r),FT(e))}function FT(e){for(;e.mc.size>0&&e.gc.size<e.maxConcurrentLimboResolutions;){const t=e.mc.values().next().value;e.mc.delete(t);const n=new cg(sg.fromString(t)),r=e.Ac.next();e.yc.set(r,new bT(n)),e.gc=e.gc.insert(n,r),xE(e.remoteStore,new Kw(zv(Fv(n.path)),r,"TargetPurposeLimboResolution",Og.ct))}}async function jT(e,t,n){const r=qm(e),i=[],s=[],o=[];r.wc.isEmpty()||(r.wc.forEach(((e,a)=>{o.push(r.Rc(a,t,n).then((e=>{if((e||n)&&r.isPrimaryClient&&r.sharedClientState.updateQueryState(a.targetId,(null==e?void 0:e.fromCache)?"not-current":"current"),e){i.push(e);const t=FI.Li(a.targetId,e);s.push(t)}})))})),await Promise.all(o),r.dc.nu(i),await async function(e,t){const n=qm(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(e=>bg.forEach(t,(t=>bg.forEach(t.Fi,(r=>n.persistence.referenceDelegate.addReference(e,t.targetId,r))).next((()=>bg.forEach(t.Bi,(r=>n.persistence.referenceDelegate.removeReference(e,t.targetId,r)))))))))}catch(e){if(!kg(e))throw e;Om("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=n.Ji.get(t),r=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(r);n.Ji=n.Ji.insert(t,i)}}}(r.localStore,s))}async function qT(e,t){const n=qm(e);if(!n.currentUser.isEqual(t)){Om("SyncEngine","User change. New user:",t.toKey());const e=await UI(n.localStore,t);n.currentUser=t,function(e,t){e.Ec.forEach((e=>{e.forEach((e=>{e.reject(new Um(Vm.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))}))})),e.Ec.clear()}(n),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await jT(n,e.er)}}function VT(e,t){const n=qm(e),r=n.yc.get(t);if(r&&r.fc)return l_().add(r.key);{let e=l_();const r=n._c.get(t);if(!r)return e;for(const t of r){const r=n.wc.get(t);e=e.unionWith(r.view.nc)}return e}}async function UT(e,t){const n=qm(e),r=await HI(n.localStore,t.query,!0),i=t.view.hc(r);return n.isPrimaryClient&&MT(n,t.targetId,i.cc),i}async function BT(e,t){const n=qm(e);return KI(n.localStore,t).then((e=>jT(n,e)))}async function zT(e,t,n,r){const i=qm(e),s=await function(e,t){const n=qm(e),r=qm(n.mutationQueue);return n.persistence.runTransaction("Lookup mutation documents","readonly",(e=>r.Sn(e,t).next((t=>t?n.localDocuments.getDocuments(e,t):bg.resolve(null)))))}(i.localStore,t);null!==s?("pending"===n?await UE(i.remoteStore):"acknowledged"===n||"rejected"===n?(RT(i,t,r||null),DT(i,t),function(e,t){qm(qm(e).mutationQueue).Cn(t)}(i.localStore,t)):Fm(),await jT(i,s)):Om("SyncEngine","Cannot apply mutation batch with id: "+t)}async function $T(e,t,n){const r=qm(e),i=[],s=[];for(const e of t){let t;const n=r._c.get(e);if(n&&0!==n.length){t=await WI(r.localStore,zv(n[0]));for(const e of n){const t=r.wc.get(e),n=await UT(r,t);n.snapshot&&s.push(n.snapshot)}}else{const n=await GI(r.localStore,e);t=await WI(r.localStore,n),await TT(r,WT(n),e,!1,t.resumeToken)}i.push(t)}return r.dc.nu(s),i}function WT(e){return Lv(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function QT(e){const t=qm(e);return qm(qm(t.localStore).persistence).$i()}async function HT(e,t,n,r){const i=qm(e);if(i.vc)return void Om("SyncEngine","Ignoring unexpected query state notification.");const s=i._c.get(t);if(s&&s.length>0)switch(n){case"current":case"not-current":{const e=await KI(i.localStore,Yv(s[0])),r=aw.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,Ey.EMPTY_BYTE_STRING);await jT(i,e,r);break}case"rejected":await QI(i.localStore,t,!0),OT(i,t,r);break;default:Fm()}}async function GT(e,t,n){const r=KT(e);if(r.vc){for(const e of t){if(r._c.has(e)){Om("SyncEngine","Adding an already active target "+e);continue}const t=await GI(r.localStore,e),n=await WI(r.localStore,t);await TT(r,WT(t),n.targetId,!1,n.resumeToken),xE(r.remoteStore,n)}for(const e of n)r._c.has(e)&&await QI(r.localStore,e,!1).then((()=>{AE(r.remoteStore,e),OT(r,e)})).catch(wg)}}function KT(e){const t=qm(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=kT.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=VT.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=xT.bind(null,t),t.dc.nu=uT.bind(null,t.eventManager),t.dc.Pc=lT.bind(null,t.eventManager),t}function YT(e){const t=qm(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=AT.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=NT.bind(null,t),t}class JT{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=vE(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return VI(this.persistence,new jI,e.initialUser,this.serializer)}createPersistence(e){return new CI(AI.zs,this.serializer)}createSharedClientState(e){return new aE}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class XT extends JT{constructor(e,t,n){super(),this.Vc=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Vc.initialize(this,e),await YT(this.Vc.syncEngine),await UE(this.Vc.remoteStore),await this.persistence.Ii((()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve())))}createLocalStore(e){return VI(this.persistence,new jI,e.initialUser,this.serializer)}createGarbageCollectionScheduler(e,t){const n=this.persistence.referenceDelegate.garbageCollector;return new iI(n,e.asyncQueue,t)}createIndexBackfillerScheduler(e,t){const n=new Rg(t,this.persistence);return new Dg(e.asyncQueue,n)}createPersistence(e){const t=LI(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?zb.withCacheSize(this.cacheSizeBytes):zb.DEFAULT;return new OI(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,gE(),yE(),this.serializer,this.sharedClientState,!!this.forceOwnership)}createSharedClientState(e){return new aE}}class ZT extends XT{constructor(e,t){super(e,t,!1),this.Vc=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);const t=this.Vc.syncEngine;this.sharedClientState instanceof oE&&(this.sharedClientState.syncEngine={jr:zT.bind(null,t),zr:HT.bind(null,t),Wr:GT.bind(null,t),$i:QT.bind(null,t),Qr:BT.bind(null,t)},await this.sharedClientState.start()),await this.persistence.Ii((async e=>{await async function(e,t){const n=qm(e);if(KT(n),YT(n),!0===t&&!0!==n.vc){const e=n.sharedClientState.getAllActiveQueryTargets(),t=await $T(n,e.toArray());n.vc=!0,await JE(n.remoteStore,!0);for(const e of t)xE(n.remoteStore,e)}else if(!1===t&&!1!==n.vc){const e=[];let t=Promise.resolve();n._c.forEach(((r,i)=>{n.sharedClientState.isLocalQueryTarget(i)?e.push(i):t=t.then((()=>(OT(n,i),QI(n.localStore,i,!0)))),AE(n.remoteStore,i)})),await t,await $T(n,e),function(e){const t=qm(e);t.yc.forEach(((e,n)=>{AE(t.remoteStore,n)})),t.Ic.Ts(),t.yc=new Map,t.gc=new my(cg.comparator)}(n),n.vc=!1,await JE(n.remoteStore,!1)}}(this.Vc.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())}))}createSharedClientState(e){const t=gE();if(!oE.D(t))throw new Um(Vm.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");const n=LI(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new oE(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class eS{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=>CT(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=qT.bind(null,this.syncEngine),await JE(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new oT}createDatastore(e){const t=vE(e.databaseInfo.databaseId),n=(r=e.databaseInfo,new mE(r));var r;return function(e,t,n,r){return new EE(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>CT(this.syncEngine,e,0),s=uE.D()?new uE:new cE,new SE(t,n,r,i,s);var t,n,r,i,s}createSyncEngine(e,t){return function(e,t,n,r,i,s,o){const a=new IT(e,t,n,r,i,s);return o&&(a.vc=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=qm(e);Om("RemoteStore","RemoteStore shutting down."),t.vu.add(5),await CE(t),t.Pu.shutdown(),t.bu.set("Unknown")}(this.remoteStore)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function tS(e,t=10240){let n=0;return{async read(){if(n<e.byteLength){const r={value:e.slice(n,n+t),done:!1};return n+=t,r}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class nS{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Sc(this.observer.next,e)}error(e){this.observer.error?this.Sc(this.observer.error,e):Pm("Uncaught Error in snapshot listener:",e.toString())}Dc(){this.muted=!0}Sc(e,t){this.muted||setTimeout((()=>{this.muted||e(t)}),0)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class rS{constructor(e,t){this.Cc=e,this.serializer=t,this.metadata=new Bm,this.buffer=new Uint8Array,this.xc=new TextDecoder("utf-8"),this.Nc().then((e=>{e&&e.Qu()?this.metadata.resolve(e.Gu.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.Gu)}`))}),(e=>this.metadata.reject(e)))}close(){return this.Cc.cancel()}async getMetadata(){return this.metadata.promise}async bc(){return await this.getMetadata(),this.Nc()}async Nc(){const e=await this.kc();if(null===e)return null;const t=this.xc.decode(e),n=Number(t);isNaN(n)&&this.Mc(`length string (${t}) is not valid number`);const r=await this.$c(n);return new fT(JSON.parse(r),e.length+n)}Oc(){return this.buffer.findIndex((e=>e==="{".charCodeAt(0)))}async kc(){for(;this.Oc()<0&&!await this.Fc(););if(0===this.buffer.length)return null;const e=this.Oc();e<0&&this.Mc("Reached the end of bundle when a length string is expected.");const t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async $c(e){for(;this.buffer.length<e;)await this.Fc()&&this.Mc("Reached the end of bundle when more is expected.");const t=this.xc.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}Mc(e){throw this.Cc.cancel(),new Error(`Invalid bundle format: ${e}`)}async Fc(){const e=await this.Cc.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}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class iS{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(),this.mutations.length>0)throw new Um(Vm.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const n=qm(e),r=Dw(n.serializer)+"/documents",i={documents:t.map((e=>Cw(n.serializer,e)))},s=await n.vo("BatchGetDocuments",r,i,t.length),o=new Map;s.forEach((e=>{const t=function(e,t){return"found"in t?function(e,t){jm(!!t.found),t.found.name,t.found.updateTime;const n=xw(e,t.found.name),r=Tw(t.found.updateTime),i=t.found.createTime?Tw(t.found.createTime):rg.min(),s=new ev({mapValue:{fields:t.found.fields}});return nv.newFoundDocument(n,r,i,s)}(e,t):"missing"in t?function(e,t){jm(!!t.missing),jm(!!t.readTime);const n=xw(e,t.missing),r=Tw(t.readTime);return nv.newNoDocument(n,r)}(e,t):Fm()}(n.serializer,e);o.set(t.key.toString(),t)}));const a=[];return t.forEach((e=>{const t=o.get(e.toString());jm(!!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 z_(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const e=this.readVersions;this.mutations.forEach((t=>{e.delete(t.key.toString())})),e.forEach(((e,t)=>{const n=cg.fromPath(t);this.mutations.push(new $_(n,this.precondition(n)))})),await async function(e,t){const n=qm(e),r=Dw(n.serializer)+"/documents",i={writes:t.map((e=>Mw(n.serializer,e)))};await n.Io("Commit",r,i)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw Fm();t=rg.min()}const n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new Um(Vm.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(rg.min())?N_.exists(!1):N_.updateTime(t):N_.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual(rg.min()))throw new Um(Vm.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return N_.updateTime(t)}return N_.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class sS{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.Bc=n.maxAttempts,this.qo=new _E(this.asyncQueue,"transaction_retry")}run(){this.Bc-=1,this.Lc()}Lc(){this.qo.No((async()=>{const e=new iS(this.datastore),t=this.qc(e);t&&t.then((t=>{this.asyncQueue.enqueueAndForget((()=>e.commit().then((()=>{this.deferred.resolve(t)})).catch((e=>{this.Uc(e)}))))})).catch((e=>{this.Uc(e)}))}))}qc(e){try{const t=this.updateFunction(e);return!Pg(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}}Uc(e){this.Bc>0&&this.Kc(e)?(this.Bc-=1,this.asyncQueue.enqueueAndForget((()=>(this.Lc(),Promise.resolve())))):this.deferred.reject(e)}Kc(e){if("FirebaseError"===e.name){const t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!J_(t)}return!1}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class oS{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=Am.UNAUTHENTICATED,this.clientId=Xm.A(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,(async e=>{Om("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(e=>(Om("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user))))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new Um(Vm.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const e=new Bm;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){const n=tT(t,"Failed to shutdown persistence");e.reject(n)}})),e.promise}}async function aS(e,t){e.asyncQueue.verifyOperationInProgress(),Om("FirestoreClient","Initializing OfflineComponentProvider");const n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener((async e=>{r.isEqual(e)||(await UI(t.localStore,e),r=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e._offlineComponents=t}async function cS(e,t){e.asyncQueue.verifyOperationInProgress();const n=await lS(e);Om("FirestoreClient","Initializing OnlineComponentProvider");const r=await e.getConfiguration();await t.initialize(n,r),e.setCredentialChangeListener((e=>YE(t.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,n)=>YE(t.remoteStore,n))),e._onlineComponents=t}function uS(e){return"FirebaseError"===e.name?e.code===Vm.FAILED_PRECONDITION||e.code===Vm.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function lS(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){Om("FirestoreClient","Using user provided OfflineComponentProvider");try{await aS(e,e._uninitializedComponentsProvider._offline)}catch(t){const n=t;if(!uS(n))throw n;Mm("Error using user provided cache. Falling back to memory cache: "+n),await aS(e,new JT)}}else Om("FirestoreClient","Using default OfflineComponentProvider"),await aS(e,new JT);return e._offlineComponents}async function hS(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(Om("FirestoreClient","Using user provided OnlineComponentProvider"),await cS(e,e._uninitializedComponentsProvider._online)):(Om("FirestoreClient","Using default OnlineComponentProvider"),await cS(e,new eS))),e._onlineComponents}function dS(e){return lS(e).then((e=>e.persistence))}function fS(e){return lS(e).then((e=>e.localStore))}function pS(e){return hS(e).then((e=>e.remoteStore))}function mS(e){return hS(e).then((e=>e.syncEngine))}async function gS(e){const t=await hS(e),n=t.eventManager;return n.onListen=ET.bind(null,t.syncEngine),n.onUnlisten=ST.bind(null,t.syncEngine),n}function yS(e,t,n={}){const r=new Bm;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new nS({next:s=>{t.enqueueAndForget((()=>cT(e,o)));const a=s.docs.has(n);!a&&s.fromCache?i.reject(new Um(Vm.UNAVAILABLE,"Failed to get document because the client is offline.")):a&&s.fromCache&&r&&"server"===r.source?i.reject(new Um(Vm.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.)')):i.resolve(s)},error:e=>i.reject(e)}),o=new dT(Fv(n.path),s,{includeMetadataChanges:!0,Ku:!0});return aT(e,o)}(await gS(e),e.asyncQueue,t,n,r))),r.promise}function vS(e,t,n={}){const r=new Bm;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new nS({next:n=>{t.enqueueAndForget((()=>cT(e,o))),n.fromCache&&"server"===r.source?i.reject(new Um(Vm.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(n)},error:e=>i.reject(e)}),o=new dT(n,s,{includeMetadataChanges:!0,Ku:!0});return aT(e,o)}(await gS(e),e.asyncQueue,t,n,r))),r.promise}function _S(e,t,n,r){const i=function(e,t){let n;return n="string"==typeof e?tw().encode(e):e,function(e,t){return new rS(e,t)}(function(e,t){if(e instanceof Uint8Array)return tS(e,t);if(e instanceof ArrayBuffer)return tS(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(n),t)}(n,vE(t));e.asyncQueue.enqueueAndForget((async()=>{!function(e,t,n){const r=qm(e);(async function(e,t,n){try{const r=await t.getMetadata();if(await function(e,t){const n=qm(e),r=Tw(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",(e=>n.qs.getBundleMetadata(e,t.id))).then((e=>!!e&&e.createTime.compareTo(r)>=0))}(e.localStore,r))return await t.close(),n._completeWith(function(e){return{taskState:"Success",documentsLoaded:e.totalDocuments,bytesLoaded:e.totalBytes,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}(r)),Promise.resolve(new Set);n._updateProgress(gT(r));const i=new mT(r,e.localStore,t.serializer);let s=await t.bc();for(;s;){const e=await i.zu(s);e&&n._updateProgress(e),s=await t.bc()}const o=await i.complete();return await jT(e,o.Ju,void 0),await function(e,t){const n=qm(e);return n.persistence.runTransaction("Save bundle","readwrite",(e=>n.qs.saveBundleMetadata(e,t)))}(e.localStore,r),n._completeWith(o.progress),Promise.resolve(o.Hu)}catch(e){return Mm("SyncEngine",`Loading bundle failed with ${e}`),n._failWith(e),Promise.resolve(new Set)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */)(r,t,n).then((e=>{r.sharedClientState.notifyBundleLoaded(e)}))}(await mS(e),i,r)}))}
/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function wS(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */}const bS=new Map;
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function IS(e,t,n){if(!n)throw new Um(Vm.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function ES(e,t,n,r){if(!0===t&&!0===r)throw new Um(Vm.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function TS(e){if(!cg.isDocumentKey(e))throw new Um(Vm.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function SS(e){if(cg.isDocumentKey(e))throw new Um(Vm.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function kS(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const t=function(e){return e.constructor?e.constructor.name:null}(e);return t?`a custom ${t} object`:"an object"}}return"function"==typeof e?"a function":Fm()}function CS(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new Um(Vm.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=kS(e);throw new Um(Vm.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function xS(e,t){if(t<=0)throw new Um(Vm.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class AS{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new Um(Vm.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.cache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new Um(Vm.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}ES("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=wS(null!==(n=e.experimentalLongPollingOptions)&&void 0!==n?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new Um(Vm.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new Um(Vm.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new Um(Vm.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams;var t,n}}class NS{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new AS({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new Um(Vm.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 Um(Vm.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 AS(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new $m;switch(e.type){case"firstParty":return new Gm(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new Um(Vm.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=bS.get(e);t&&(Om("ComponentProvider","Removing Datastore"),bS.delete(e),t.terminate())}(this),Promise.resolve()}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class DS{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 OS(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new DS(this.firestore,e,this._key)}}class RS{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new RS(this.firestore,e,this._query)}}class OS extends RS{constructor(e,t,n){super(e,t,Fv(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 DS(this.firestore,null,new cg(e))}withConverter(e){return new OS(this.firestore,e,this._path)}}function PS(e,t,...n){if(e=ic(e),IS("collection","path",t),e instanceof NS){const r=sg.fromString(t,...n);return SS(r),new OS(e,null,r)}{if(!(e instanceof DS||e instanceof OS))throw new Um(Vm.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(sg.fromString(t,...n));return SS(r),new OS(e.firestore,null,r)}}function MS(e,t,...n){if(e=ic(e),1===arguments.length&&(t=Xm.A()),IS("doc","path",t),e instanceof NS){const r=sg.fromString(t,...n);return TS(r),new DS(e,null,new cg(r))}{if(!(e instanceof DS||e instanceof OS))throw new Um(Vm.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(sg.fromString(t,...n));return TS(r),new DS(e.firestore,e instanceof OS?e.converter:null,new cg(r))}}function LS(e,t){return e=ic(e),t=ic(t),(e instanceof DS||e instanceof OS)&&(t instanceof DS||t instanceof OS)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function FS(e,t){return e=ic(e),t=ic(t),e instanceof RS&&t instanceof RS&&e.firestore===t.firestore&&Qv(e._query,t._query)&&e.converter===t.converter
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */}class jS{constructor(){this.Gc=Promise.resolve(),this.Qc=[],this.jc=!1,this.zc=[],this.Wc=null,this.Hc=!1,this.Jc=!1,this.Yc=[],this.qo=new _E(this,"async_queue_retry"),this.Xc=()=>{const e=yE();e&&Om("AsyncQueue","Visibility state changed to "+e.visibilityState),this.qo.Mo()};const e=yE();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Xc)}get isShuttingDown(){return this.jc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Zc(),this.ta(e)}enterRestrictedMode(e){if(!this.jc){this.jc=!0,this.Jc=e||!1;const t=yE();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Xc)}}enqueue(e){if(this.Zc(),this.jc)return new Promise((()=>{}));const t=new Bm;return this.ta((()=>this.jc&&this.Jc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.Qc.push(e),this.ea())))}async ea(){if(0!==this.Qc.length){try{await this.Qc[0](),this.Qc.shift(),this.qo.reset()}catch(e){if(!kg(e))throw e;Om("AsyncQueue","Operation failed with retryable error: "+e)}this.Qc.length>0&&this.qo.No((()=>this.ea()))}}ta(e){const t=this.Gc.then((()=>(this.Hc=!0,e().catch((e=>{this.Wc=e,this.Hc=!1;const t=function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e);throw Pm("INTERNAL UNHANDLED ERROR: ",t),e})).then((e=>(this.Hc=!1,e))))));return this.Gc=t,t}enqueueAfterDelay(e,t,n){this.Zc(),this.Yc.indexOf(e)>-1&&(t=0);const r=eT.createAndSchedule(this,e,t,n,(e=>this.na(e)));return this.zc.push(r),r}Zc(){this.Wc&&Fm()}verifyOperationInProgress(){}async sa(){let e;do{e=this.Gc,await e}while(e!==this.Gc)}ia(e){for(const t of this.zc)if(t.timerId===e)return!0;return!1}ra(e){return this.sa().then((()=>{this.zc.sort(((e,t)=>e.targetTimeMs-t.targetTimeMs));for(const t of this.zc)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.sa()}))}oa(e){this.Yc.push(e)}na(e){const t=this.zc.indexOf(e);this.zc.splice(t,1)}}function qS(e){return function(e,t){if("object"!=typeof e||null===e)return!1;const n=e;for(const e of["next","error","complete"])if(e in n&&"function"==typeof n[e])return!0;return!1}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e)}class VS{constructor(){this._progressObserver={},this._taskCompletionResolver=new Bm,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)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class US extends NS{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new jS,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||zS(this),this._firestoreClient.terminate()}}function BS(e){return e._firestoreClient||zS(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function zS(e){var t,n,r;const i=e._freezeSettings(),s=function(e,t,n,r){return new Dy(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,wS(r.experimentalLongPollingOptions),r.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,i);e._firestoreClient=new oS(e._authCredentials,e._appCheckCredentials,e._queue,s),(null===(n=i.cache)||void 0===n?void 0:n._offlineComponentProvider)&&(null===(r=i.cache)||void 0===r?void 0:r._onlineComponentProvider)&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:i.cache.kind,_offline:i.cache._offlineComponentProvider,_online:i.cache._onlineComponentProvider})}function $S(e,t,n){const r=new Bm;return e.asyncQueue.enqueue((async()=>{try{await aS(e,n),await cS(e,t),r.resolve()}catch(e){const t=e;if(!uS(t))throw t;Mm("Error enabling indexeddb cache. Falling back to memory cache: "+t),r.reject(t)}})).then((()=>r.promise))}function WS(e){return function(e){const t=new Bm;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t){const n=qm(e);PE(n.remoteStore)||Om("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(e){const t=qm(e);return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",(e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e)))}(n.localStore);if(-1===e)return void t.resolve();const r=n.Ec.get(e)||[];r.push(t),n.Ec.set(e,r)}catch(e){const n=tT(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await mS(e),t))),t.promise}(BS(e=CS(e,US)))}function QS(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await dS(e),n=await pS(e);return t.setNetworkEnabled(!0),function(e){const t=qm(e);return t.vu.delete(0),kE(t)}(n)}))}(BS(e=CS(e,US)))}function HS(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await dS(e),n=await pS(e);return t.setNetworkEnabled(!1),async function(e){const t=qm(e);t.vu.add(0),await CE(t),t.bu.set("Offline")}(n)}))}(BS(e=CS(e,US)))}function GS(e,t){return function(e,t){return e.asyncQueue.enqueue((async()=>function(e,t){const n=qm(e);return n.persistence.runTransaction("Get named query","readonly",(e=>n.qs.getNamedQuery(e,t)))}(await fS(e),t)))}(BS(e=CS(e,US)),t).then((t=>t?new RS(e,null,t.query):null))}function KS(e){if(e._initialized||e._terminated)throw new Um(Vm.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.")}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class YS{constructor(e){this._byteString=e}static fromBase64String(e){try{return new YS(Ey.fromBase64String(e))}catch(e){throw new Um(Vm.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new YS(Ey.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)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class JS{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new Um(Vm.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new ag(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class XS{constructor(e){this._methodName=e}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ZS{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new Um(Vm.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new Um(Vm.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 Zm(this._lat,e._lat)||Zm(this._long,e._long)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const ek=/^__.*__$/;class tk{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new q_(e,this.data,this.fieldMask,t,this.fieldTransforms):new j_(e,this.data,t,this.fieldTransforms)}}class nk{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new q_(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function rk(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw Fm()}}class ik{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.ua(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get ca(){return this.settings.ca}aa(e){return new ik(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}ha(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.aa({path:n,la:!1});return r.fa(e),r}da(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.aa({path:n,la:!1});return r.ua(),r}wa(e){return this.aa({path:void 0,la:!0})}_a(e){return Tk(e,this.settings.methodName,this.settings.ma||!1,this.path,this.settings.ga)}contains(e){return void 0!==this.fieldMask.find((t=>e.isPrefixOf(t)))||void 0!==this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))}ua(){if(this.path)for(let e=0;e<this.path.length;e++)this.fa(this.path.get(e))}fa(e){if(0===e.length)throw this._a("Document fields must not be empty");if(rk(this.ca)&&ek.test(e))throw this._a('Document fields cannot begin and end with "__"')}}class sk{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||vE(e)}ya(e,t,n,r=!1){return new ik({ca:e,methodName:t,ga:n,path:ag.emptyPath(),la:!1,ma:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function ok(e){const t=e._freezeSettings(),n=vE(e._databaseId);return new sk(e._databaseId,!!t.ignoreUndefinedProperties,n)}function ak(e,t,n,r,i,s={}){const o=e.ya(s.merge||s.mergeFields?2:0,t,n,i);wk("Data must be an object, but it was:",o,r);const a=vk(r,o);let c,u;if(s.merge)c=new by(o.fieldMask),u=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=bk(t,r,n);if(!o.contains(i))throw new Um(Vm.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);Sk(e,i)||e.push(i)}c=new by(e),u=o.fieldTransforms.filter((e=>c.covers(e.field)))}else c=null,u=o.fieldTransforms;return new tk(new ev(a),c,u)}class ck extends XS{_toFieldTransform(e){if(2!==e.ca)throw 1===e.ca?e._a(`${this._methodName}() can only appear at the top level of your update data`):e._a(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof ck}}function uk(e,t,n){return new ik({ca:3,ga:t.settings.ga,methodName:e._methodName,la:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class lk extends XS{_toFieldTransform(e){return new x_(e.path,new w_)}isEqual(e){return e instanceof lk}}class hk extends XS{constructor(e,t){super(e),this.pa=t}_toFieldTransform(e){const t=uk(this,e,!0),n=this.pa.map((e=>yk(e,t))),r=new b_(n);return new x_(e.path,r)}isEqual(e){return this===e}}class dk extends XS{constructor(e,t){super(e),this.pa=t}_toFieldTransform(e){const t=uk(this,e,!0),n=this.pa.map((e=>yk(e,t))),r=new E_(n);return new x_(e.path,r)}isEqual(e){return this===e}}class fk extends XS{constructor(e,t){super(e),this.Ia=t}_toFieldTransform(e){const t=new S_(e.serializer,m_(e.serializer,this.Ia));return new x_(e.path,t)}isEqual(e){return this===e}}function pk(e,t,n,r){const i=e.ya(1,t,n);wk("Data must be an object, but it was:",i,r);const s=[],o=ev.empty();fy(r,((e,r)=>{const a=Ek(t,e,n);r=ic(r);const c=i.da(a);if(r instanceof ck)s.push(a);else{const e=yk(r,c);null!=e&&(s.push(a),o.set(a,e))}}));const a=new by(s);return new nk(o,a,i.fieldTransforms)}function mk(e,t,n,r,i,s){const o=e.ya(1,t,n),a=[bk(t,r,n)],c=[i];if(s.length%2!=0)throw new Um(Vm.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<s.length;e+=2)a.push(bk(t,s[e])),c.push(s[e+1]);const u=[],l=ev.empty();for(let e=a.length-1;e>=0;--e)if(!Sk(u,a[e])){const t=a[e];let n=c[e];n=ic(n);const r=o.da(t);if(n instanceof ck)u.push(t);else{const e=yk(n,r);null!=e&&(u.push(t),l.set(t,e))}}const h=new by(u);return new nk(l,h,o.fieldTransforms)}function gk(e,t,n,r=!1){return yk(n,e.ya(r?4:3,t))}function yk(e,t){if(_k(e=ic(e)))return wk("Unsupported field value:",t,e),vk(e,t);if(e instanceof XS)return function(e,t){if(!rk(t.ca))throw t._a(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t._a(`${e._methodName}() is not currently supported inside arrays`);const n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.la&&4!==t.ca)throw t._a("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=yk(i,t.wa(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=ic(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return m_(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const n=ng.fromDate(e);return{timestampValue:bw(t.serializer,n)}}if(e instanceof ng){const n=new ng(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:bw(t.serializer,n)}}if(e instanceof ZS)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof YS)return{bytesValue:Iw(t.serializer,e._byteString)};if(e instanceof DS){const n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t._a(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:Sw(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t._a(`Unsupported field value: ${kS(e)}`)}(e,t)}function vk(e,t){const n={};return py(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):fy(e,((e,r)=>{const i=yk(r,t.ha(e));null!=i&&(n[e]=i)})),{mapValue:{fields:n}}}function _k(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof ng||e instanceof ZS||e instanceof YS||e instanceof DS||e instanceof XS)}function wk(e,t,n){if(!_k(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const r=kS(n);throw"an object"===r?t._a(e+" a custom object"):t._a(e+" "+r)}}function bk(e,t,n){if((t=ic(t))instanceof JS)return t._internalPath;if("string"==typeof t)return Ek(e,t);throw Tk("Field path arguments must be of type string or ",e,!1,void 0,n)}const Ik=new RegExp("[~\\*/\\[\\]]");function Ek(e,t,n){if(t.search(Ik)>=0)throw Tk(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new JS(...t.split("."))._internalPath}catch(r){throw Tk(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function Tk(e,t,n,r,i){const s=r&&!r.isEmpty(),o=void 0!==i;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(s||o)&&(c+=" (found",s&&(c+=` in field ${r}`),o&&(c+=` in document ${i}`),c+=")"),new Um(Vm.INVALID_ARGUMENT,a+e+c)}function Sk(e,t){return e.some((e=>e.isEqual(t)))}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class kk{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new DS(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new Ck(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){const t=this._document.data.field(xk("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Ck extends kk{data(){return super.data()}}function xk(e,t){return"string"==typeof t?Ek(e,t):t instanceof JS?t._internalPath:t._delegate._internalPath}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Ak(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new Um(Vm.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class Nk{}class Dk extends Nk{}function Rk(e,t,...n){let r=[];t instanceof Nk&&r.push(t),r=r.concat(n),function(e){const t=e.filter((e=>e instanceof Pk)).length,n=e.filter((e=>e instanceof Ok)).length;if(t>1||t>0&&n>0)throw new Um(Vm.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(r);for(const t of r)e=t._apply(e);return e}class Ok extends Dk{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new Ok(e,t,n)}_apply(e){const t=this._parse(e);return Bk(e._query,t),new RS(e.firestore,e.converter,$v(e._query,t))}_parse(e){const t=ok(e.firestore),n=function(e,t,n,r,i,s,o){let a;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new Um(Vm.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){Uk(o,s);const t=[];for(const n of o)t.push(Vk(r,e,n));a={arrayValue:{values:t}}}else a=Vk(r,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||Uk(o,s),a=gk(n,"where",o,"in"===s||"not-in"===s);return uv.create(i,s,a)}(e._query,0,t,e.firestore._databaseId,this._field,this._op,this._value);return n}}class Pk extends Nk{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new Pk(e,t)}_parse(e){const t=this._queryConstraints.map((t=>t._parse(e))).filter((e=>e.getFilters().length>0));return 1===t.length?t[0]:lv.create(t,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;const r=t.getFlattenedFilters();for(const e of r)Bk(n,e),n=$v(n,e)}(e._query,t),new RS(e.firestore,e.converter,$v(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class Mk extends Dk{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new Mk(e,t)}_apply(e){const t=function(e,t,n){if(null!==e.startAt)throw new Um(Vm.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new Um(Vm.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");const r=new ov(t,n);return function(e,t){if(null===qv(e)){const n=Vv(e);null!==n&&zk(e,n,t.field)}}(e,r),r}(e._query,this._field,this._direction);return new RS(e.firestore,e.converter,function(e,t){const n=e.explicitOrderBy.concat([t]);return new Mv(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}class Lk extends Dk{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new Lk(e,t,n)}_apply(e){return new RS(e.firestore,e.converter,Wv(e._query,this._limit,this._limitType))}}class Fk extends Dk{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Fk(e,t,n)}_apply(e){const t=qk(e,this.type,this._docOrFields,this._inclusive);return new RS(e.firestore,e.converter,function(e,t){return new Mv(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,t,e.endAt)}(e._query,t))}}class jk extends Dk{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new jk(e,t,n)}_apply(e){const t=qk(e,this.type,this._docOrFields,this._inclusive);return new RS(e.firestore,e.converter,function(e,t){return new Mv(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,t)}(e._query,t))}}function qk(e,t,n,r){if(n[0]=ic(n[0]),n[0]instanceof kk)return function(e,t,n,r,i){if(!r)throw new Um(Vm.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of Bv(e))if(n.field.isKeyField())s.push(By(t,r.key));else{const e=r.data.field(n.field);if(xy(e))throw new Um(Vm.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 Um(Vm.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new rv(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);{const i=ok(e.firestore);return function(e,t,n,r,i,s){const o=e.explicitOrderBy;if(i.length>o.length)throw new Um(Vm.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 s=0;s<i.length;s++){const c=i[s];if(o[s].field.isKeyField()){if("string"!=typeof c)throw new Um(Vm.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);if(!Uv(e)&&-1!==c.indexOf("/"))throw new Um(Vm.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(sg.fromString(c));if(!cg.isDocumentKey(n))throw new Um(Vm.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new cg(n);a.push(By(t,i))}else{const e=gk(n,r,c);a.push(e)}}return new rv(a,s)}(e._query,e.firestore._databaseId,i,t,n,r)}}function Vk(e,t,n){if("string"==typeof(n=ic(n))){if(""===n)throw new Um(Vm.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!Uv(t)&&-1!==n.indexOf("/"))throw new Um(Vm.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);const r=t.path.child(sg.fromString(n));if(!cg.isDocumentKey(r))throw new Um(Vm.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 By(e,new cg(r))}if(n instanceof DS)return By(e,n._key);throw new Um(Vm.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${kS(n)}.`)}function Uk(e,t){if(!Array.isArray(e)||0===e.length)throw new Um(Vm.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function Bk(e,t){if(t.isInequality()){const n=Vv(e),r=t.field;if(null!==n&&!n.isEqual(r))throw new Um(Vm.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 '${n.toString()}' and '${r.toString()}'`);const i=qv(e);null!==i&&zk(e,r,i)}const n=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(t.indexOf(e.op)>=0)return e.op;return null}(e.filters,function(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(t.op));if(null!==n)throw n===t.op?new Um(Vm.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new Um(Vm.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}function zk(e,t,n){if(!n.isEqual(t))throw new Um(Vm.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 $k{convertValue(e,t="none"){switch(My(e)){case 0:return null;case 1:return e.booleanValue;case 2:return ky(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(Cy(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 Fm()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){const n={};return fy(e,((e,r)=>{n[e]=this.convertValue(r,t)})),n}convertGeoPoint(e){return new ZS(ky(e.latitude),ky(e.longitude))}convertArray(e,t){return(e.values||[]).map((e=>this.convertValue(e,t)))}convertServerTimestamp(e,t){switch(t){case"previous":const n=Ay(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Ny(e));default:return null}}convertTimestamp(e){const t=Sy(e);return new ng(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=sg.fromString(e);jm(Gw(n));const r=new Ry(n.get(1),n.get(3)),i=new cg(n.popFirst(5));return r.isEqual(t)||Pm(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Wk(e,t,n){let r;return r=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,r}class Qk extends $k{constructor(e){super(),this.firestore=e}convertBytes(e){return new YS(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new DS(this.firestore,null,t)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Hk{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Gk extends kk{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const t=new Kk(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){const n=this._document.data.field(xk("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Kk extends Gk{data(e={}){return super.data(e)}}class Yk{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new Hk(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const e=[];return this.forEach((t=>e.push(t))),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach((n=>{e.call(t,new Kk(this._firestore,this._userDataWriter,n.key,n,new Hk(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(e={}){const t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new Um(Vm.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(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map((n=>{const r=new Kk(e._firestore,e._userDataWriter,n.doc.key,n.doc,new Hk(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:r,oldIndex:-1,newIndex:t++}}))}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter((e=>t||3!==e.type)).map((t=>{const r=new Kk(e._firestore,e._userDataWriter,t.doc.key,t.doc,new Hk(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let i=-1,s=-1;return 0!==t.type&&(i=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(n=n.add(t.doc),s=n.indexOf(t.doc.key)),{type:Jk(t.type),doc:r,oldIndex:i,newIndex:s}}))}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function Jk(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Fm()}}function Xk(e,t){return e instanceof Gk&&t instanceof Gk?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 Yk&&t instanceof Yk&&e._firestore===t._firestore&&FS(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Zk extends $k{constructor(e){super(),this.firestore=e}convertBytes(e){return new YS(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new DS(this.firestore,null,t)}}function eC(e){e=CS(e,DS);const t=CS(e.firestore,US),n=BS(t),r=new Zk(t);return function(e,t){const n=new Bm;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){try{const r=await function(e,t){const n=qm(e);return n.persistence.runTransaction("read document","readonly",(e=>n.localDocuments.getDocument(e,t)))}(e,t);r.isFoundDocument()?n.resolve(r):r.isNoDocument()?n.resolve(null):n.reject(new Um(Vm.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){const r=tT(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await fS(e),t,n))),n.promise}(n,e._key).then((n=>new Gk(t,r,e._key,n,new Hk(null!==n&&n.hasLocalMutations,!0),e.converter)))}function tC(e){e=CS(e,RS);const t=CS(e.firestore,US),n=BS(t),r=new Zk(t);return function(e,t){const n=new Bm;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){try{const r=await HI(e,t,!0),i=new _T(t,r.ir),s=i.sc(r.documents),o=i.applyChanges(s,!1);n.resolve(o.snapshot)}catch(e){const r=tT(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await fS(e),t,n))),n.promise}(n,e._query).then((n=>new Yk(t,r,e,n)))}function nC(e,t,n){e=CS(e,DS);const r=CS(e.firestore,US),i=Wk(e.converter,t,n);return oC(r,[ak(ok(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,N_.none())])}function rC(e,t,n,...r){e=CS(e,DS);const i=CS(e.firestore,US),s=ok(i);let o;return o="string"==typeof(t=ic(t))||t instanceof JS?mk(s,"updateDoc",e._key,t,n,r):pk(s,"updateDoc",e._key,t),oC(i,[o.toMutation(e._key,N_.exists(!0))])}function iC(e,...t){var n,r,i;e=ic(e);let s={includeMetadataChanges:!1},o=0;"object"!=typeof t[o]||qS(t[o])||(s=t[o],o++);const a={includeMetadataChanges:s.includeMetadataChanges};if(qS(t[o])){const e=t[o];t[o]=null===(n=e.next)||void 0===n?void 0:n.bind(e),t[o+1]=null===(r=e.error)||void 0===r?void 0:r.bind(e),t[o+2]=null===(i=e.complete)||void 0===i?void 0:i.bind(e)}let c,u,l;if(e instanceof DS)u=CS(e.firestore,US),l=Fv(e._key.path),c={next:n=>{t[o]&&t[o](aC(u,e,n))},error:t[o+1],complete:t[o+2]};else{const n=CS(e,RS);u=CS(n.firestore,US),l=n._query;const r=new Zk(u);c={next:e=>{t[o]&&t[o](new Yk(u,r,n,e))},error:t[o+1],complete:t[o+2]},Ak(e._query)}return function(e,t,n,r){const i=new nS(r),s=new dT(t,i,n);return e.asyncQueue.enqueueAndForget((async()=>aT(await gS(e),s))),()=>{i.Dc(),e.asyncQueue.enqueueAndForget((async()=>cT(await gS(e),s)))}}(BS(u),l,a,c)}function sC(e,t){return function(e,t){const n=new nS(t);return e.asyncQueue.enqueueAndForget((async()=>function(e,t){qm(e).ku.add(t),t.next()}(await gS(e),n))),()=>{n.Dc(),e.asyncQueue.enqueueAndForget((async()=>function(e,t){qm(e).ku.delete(t)}(await gS(e),n)))}}(BS(e=CS(e,US)),qS(t)?t:{next:t})}function oC(e,t){return function(e,t){const n=new Bm;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){const r=YT(e);try{const e=await function(e,t){const n=qm(e),r=ng.now(),i=t.reduce(((e,t)=>e.add(t.key)),l_());let s,o;return n.persistence.runTransaction("Locally write mutations","readwrite",(e=>{let a=t_(),c=l_();return n.Zi.getEntries(e,i).next((e=>{a=e,a.forEach(((e,t)=>{t.isValidDocument()||(c=c.add(e))}))})).next((()=>n.localDocuments.getOverlayedDocuments(e,a))).next((i=>{s=i;const o=[];for(const e of t){const t=L_(e,s.get(e.key).overlayedDocument);null!=t&&o.push(new q_(e.key,t,tv(t.value.mapValue),N_.exists(!0)))}return n.mutationQueue.addMutationBatch(e,r,o,t)})).next((t=>{o=t;const r=t.applyToLocalDocumentSet(s,c);return n.documentOverlayCache.saveOverlays(e,t.batchId,r)}))})).then((()=>({batchId:o.batchId,changes:i_(s)})))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Tc[e.currentUser.toKey()];r||(r=new my(Zm)),r=r.insert(t,n),e.Tc[e.currentUser.toKey()]=r}(r,e.batchId,n),await jT(r,e.changes),await UE(r.remoteStore)}catch(e){const t=tT(e,"Failed to persist write");n.reject(t)}}(await mS(e),t,n))),n.promise}(BS(e),t)}function aC(e,t,n){const r=n.docs.get(t._key),i=new Zk(e);return new Gk(e,i,t._key,r,new Hk(n.hasPendingWrites,n.fromCache),t.converter)}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const cC={maxAttempts:5};
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class uC{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=ok(e)}set(e,t,n){this._verifyNotCommitted();const r=lC(e,this._firestore),i=Wk(r.converter,t,n),s=ak(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,N_.none())),this}update(e,t,n,...r){this._verifyNotCommitted();const i=lC(e,this._firestore);let s;return s="string"==typeof(t=ic(t))||t instanceof JS?mk(this._dataReader,"WriteBatch.update",i._key,t,n,r):pk(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,N_.exists(!0))),this}delete(e){this._verifyNotCommitted();const t=lC(e,this._firestore);return this._mutations=this._mutations.concat(new z_(t._key,N_.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new Um(Vm.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function lC(e,t){if((e=ic(e)).firestore!==t)throw new Um(Vm.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class hC extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=ok(e)}get(e){const t=lC(e,this._firestore),n=new Qk(this._firestore);return this._transaction.lookup([t._key]).then((e=>{if(!e||1!==e.length)return Fm();const r=e[0];if(r.isFoundDocument())return new kk(this._firestore,n,r.key,r,t.converter);if(r.isNoDocument())return new kk(this._firestore,n,t._key,null,t.converter);throw Fm()}))}set(e,t,n){const r=lC(e,this._firestore),i=Wk(r.converter,t,n),s=ak(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,s),this}update(e,t,n,...r){const i=lC(e,this._firestore);let s;return s="string"==typeof(t=ic(t))||t instanceof JS?mk(this._dataReader,"Transaction.update",i._key,t,n,r):pk(this._dataReader,"Transaction.update",i._key,t),this._transaction.update(i._key,s),this}delete(e){const t=lC(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=lC(e,this._firestore),n=new Zk(this._firestore);return super.get(e).then((e=>new Gk(this._firestore,n,t._key,e._document,new Hk(!1,!1),t.converter)))}}function dC(e,t,n){e=CS(e,US);const r=Object.assign(Object.assign({},cC),n);return function(e){if(e.maxAttempts<1)throw new Um(Vm.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(e,t,n){const r=new Bm;return e.asyncQueue.enqueueAndForget((async()=>{const i=await function(e){return hS(e).then((e=>e.datastore))}(e);new sS(e.asyncQueue,i,n,t,r).run()})),r.promise}(BS(e),(n=>t(new hC(e,n))),r)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */!function(e,t=!0){Nm=Hc,zc(new sc("firestore",((e,{instanceIdentifier:n,options:r})=>{const i=e.getProvider("app").getImmediate(),s=new US(new Qm(e.getProvider("auth-internal")),new Ym(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new Um(Vm.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Ry(e.options.projectId,t)}(i,n),i);return r=Object.assign({useFetchStreams:t},r),s._setSettings(r),s}),"PUBLIC").setMultipleInstances(!0)),Yc(xm,"3.13.0",e),Yc(xm,"3.13.0","esm2017")}();
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function fC(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new Um("invalid-argument",`Invalid options passed to function ${e}(): You cannot specify both "merge" and "mergeFields".`);return t}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function pC(){if("undefined"==typeof Uint8Array)throw new Um("unimplemented","Uint8Arrays are not available in this environment.")}function mC(){if("undefined"==typeof atob)throw new Um("unimplemented","Blobs are unavailable in Firestore in this environment.")}let gC=class e{constructor(e){this._delegate=e}static fromBase64String(t){return mC(),new e(YS.fromBase64String(t))}static fromUint8Array(t){return pC(),new e(YS.fromUint8Array(t))}toBase64(){return mC(),this._delegate.toBase64()}toUint8Array(){return pC(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}};
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function yC(e){return function(e,t){if("object"!=typeof e||null===e)return!1;const n=e;for(const e of t)if(e in n&&"function"==typeof n[e])return!0;return!1}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e,["next","error","complete"])}class vC{enableIndexedDbPersistence(e,t){return function(e,t){KS(e=CS(e,US));const n=BS(e);if(n._uninitializedComponentsProvider)throw new Um(Vm.FAILED_PRECONDITION,"SDK cache is already specified.");Mm("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const r=e._freezeSettings(),i=new eS;return $S(n,i,new XT(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){KS(e=CS(e,US));const t=BS(e);if(t._uninitializedComponentsProvider)throw new Um(Vm.FAILED_PRECONDITION,"SDK cache is already specified.");Mm("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const n=e._freezeSettings(),r=new eS;return $S(t,r,new ZT(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new Um(Vm.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new Bm;return e._queue.enqueueAndForgetEvenWhileRestricted((async()=>{try{await async function(e){if(!Eg.D())return Promise.resolve();const t=e+"main";await Eg.delete(t)}(LI(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}})),t.promise}(e._delegate)}}class _C{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Ry||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){const t=this._delegate._getSettings();e.merge||t.host===e.host||Mm("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={}){!function(e,t,n,r={}){var i;const s=(e=CS(e,NS))._getSettings(),o=`${t}:${n}`;if("firestore.googleapis.com"!==s.host&&s.host!==o&&Mm("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},s),{host:o,ssl:!1})),r.mockUserToken){let t,n;if("string"==typeof r.mockUserToken)t=r.mockUserToken,n=Am.MOCK_USER;else{t=Sa(r.mockUserToken,null===(i=e._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new Um(Vm.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new Am(s)}e._authCredentials=new Wm(new zm(t,n))}}(this._delegate,e,t,n)}enableNetwork(){return QS(this._delegate)}disableNetwork(){return HS(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,ES("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 WS(this._delegate)}onSnapshotsInSync(e){return sC(this._delegate,e)}get app(){if(!this._appCompat)throw new Um("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new OC(this,PS(this._delegate,e))}catch(e){throw SC(e,"collection()","Firestore.collection()")}}doc(e){try{return new TC(this,MS(this._delegate,e))}catch(e){throw SC(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new NC(this,function(e,t){if(e=CS(e,NS),IS("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new Um(Vm.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new RS(e,null,function(e){return new Mv(sg.emptyPath(),e)}(t))}(this._delegate,e))}catch(e){throw SC(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(e){return dC(this._delegate,(t=>e(new bC(this,t))))}batch(){return BS(this._delegate),new IC(new uC(this._delegate,(e=>oC(this._delegate,e))))}loadBundle(e){return function(e,t){const n=BS(e=CS(e,US)),r=new VS;return _S(n,e._databaseId,t,r),r}(this._delegate,e)}namedQuery(e){return GS(this._delegate,e).then((e=>e?new NC(this,e):null))}}class wC extends $k{constructor(e){super(),this.firestore=e}convertBytes(e){return new gC(new YS(e))}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return TC.forKey(t,this.firestore,null)}}class bC{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new wC(e)}get(e){const t=PC(e);return this._delegate.get(t).then((e=>new xC(this._firestore,new Gk(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter))))}set(e,t,n){const r=PC(e);return n?(fC("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){const i=PC(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){const t=PC(e);return this._delegate.delete(t),this}}class IC{constructor(e){this._delegate=e}set(e,t,n){const r=PC(e);return n?(fC("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){const i=PC(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){const t=PC(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class EC{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){const n=new Kk(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new AC(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=EC.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new EC(e,new wC(e),t),r.set(t,i)),i}}EC.INSTANCES=new WeakMap;class TC{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new wC(e)}static forPath(e,t,n){if(e.length%2!=0)throw new Um("invalid-argument",`Invalid document reference. Document references must have an even number of segments, but ${e.canonicalString()} has ${e.length}`);return new TC(t,new DS(t._delegate,n,new cg(e)))}static forKey(e,t,n){return new TC(t,new DS(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new OC(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new OC(this.firestore,PS(this._delegate,e))}catch(e){throw SC(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=ic(e))instanceof DS&&LS(this._delegate,e)}set(e,t){t=fC("DocumentReference.set",t);try{return t?nC(this._delegate,e,t):nC(this._delegate,e)}catch(e){throw SC(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?rC(this._delegate,e):rC(this._delegate,e,t,...n)}catch(e){throw SC(e,"updateDoc()","DocumentReference.update()")}}delete(){return oC(CS((e=this._delegate).firestore,US),[new z_(e._key,N_.none())]);var e}onSnapshot(...e){const t=kC(e),n=CC(e,(e=>new xC(this.firestore,new Gk(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter))));return iC(this._delegate,t,n)}get(e){let t;return t="cache"===(null==e?void 0:e.source)?eC(this._delegate):"server"===(null==e?void 0:e.source)?function(e){e=CS(e,DS);const t=CS(e.firestore,US);return yS(BS(t),e._key,{source:"server"}).then((n=>aC(t,e,n)))}(this._delegate):function(e){e=CS(e,DS);const t=CS(e.firestore,US);return yS(BS(t),e._key).then((n=>aC(t,e,n)))}(this._delegate),t.then((e=>new xC(this.firestore,new Gk(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter))))}withConverter(e){return new TC(this.firestore,e?this._delegate.withConverter(EC.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function SC(e,t,n){return e.message=e.message.replace(t,n),e}function kC(e){for(const t of e)if("object"==typeof t&&!yC(t))return t;return{}}function CC(e,t){var n,r;let i;return i=yC(e[0])?e[0]:yC(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=>{i.next&&i.next(t(e))},error:null===(n=i.error)||void 0===n?void 0:n.bind(i),complete:null===(r=i.complete)||void 0===r?void 0:r.bind(i)}}class xC{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new TC(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 Xk(this._delegate,e._delegate)}}class AC extends xC{data(e){const t=this._delegate.data(e);return void 0!==t||Fm(),t}}let NC=class e{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new wC(e)}where(t,n,r){try{return new e(this.firestore,Rk(this._delegate,function(e,t,n){const r=t,i=xk("where",e);return Ok._create(i,r,n)}(t,n,r)))}catch(e){throw SC(e,/(orderBy|where)\(\)/,"Query.$1()")}}orderBy(t,n){try{return new e(this.firestore,Rk(this._delegate,function(e,t="asc"){const n=t,r=xk("orderBy",e);return Mk._create(r,n)}(t,n)))}catch(e){throw SC(e,/(orderBy|where)\(\)/,"Query.$1()")}}limit(t){try{return new e(this.firestore,Rk(this._delegate,(xS("limit",n=t),Lk._create("limit",n,"F"))))}catch(e){throw SC(e,"limit()","Query.limit()")}var n}limitToLast(t){try{return new e(this.firestore,Rk(this._delegate,(xS("limitToLast",n=t),Lk._create("limitToLast",n,"L"))))}catch(e){throw SC(e,"limitToLast()","Query.limitToLast()")}var n}startAt(...t){try{return new e(this.firestore,Rk(this._delegate,function(...e){return Fk._create("startAt",e,!0)}(...t)))}catch(e){throw SC(e,"startAt()","Query.startAt()")}}startAfter(...t){try{return new e(this.firestore,Rk(this._delegate,function(...e){return Fk._create("startAfter",e,!1)}(...t)))}catch(e){throw SC(e,"startAfter()","Query.startAfter()")}}endBefore(...t){try{return new e(this.firestore,Rk(this._delegate,function(...e){return jk._create("endBefore",e,!1)}(...t)))}catch(e){throw SC(e,"endBefore()","Query.endBefore()")}}endAt(...t){try{return new e(this.firestore,Rk(this._delegate,function(...e){return jk._create("endAt",e,!0)}(...t)))}catch(e){throw SC(e,"endAt()","Query.endAt()")}}isEqual(e){return FS(this._delegate,e._delegate)}get(e){let t;return t="cache"===(null==e?void 0:e.source)?tC(this._delegate):"server"===(null==e?void 0:e.source)?function(e){e=CS(e,RS);const t=CS(e.firestore,US),n=BS(t),r=new Zk(t);return vS(n,e._query,{source:"server"}).then((n=>new Yk(t,r,e,n)))}(this._delegate):function(e){e=CS(e,RS);const t=CS(e.firestore,US),n=BS(t),r=new Zk(t);return Ak(e._query),vS(n,e._query).then((n=>new Yk(t,r,e,n)))}(this._delegate),t.then((e=>new RC(this.firestore,new Yk(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot))))}onSnapshot(...e){const t=kC(e),n=CC(e,(e=>new RC(this.firestore,new Yk(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot))));return iC(this._delegate,t,n)}withConverter(t){return new e(this.firestore,t?this._delegate.withConverter(EC.getInstance(this.firestore,t)):this._delegate.withConverter(null))}};class DC{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new AC(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class RC{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new NC(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 AC(this._firestore,e)))}docChanges(e){return this._delegate.docChanges(e).map((e=>new DC(this._firestore,e)))}forEach(e,t){this._delegate.forEach((n=>{e.call(t,new AC(this._firestore,n))}))}isEqual(e){return Xk(this._delegate,e._delegate)}}class OC extends NC{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(){const e=this._delegate.parent;return e?new TC(this.firestore,e):null}doc(e){try{return new TC(this.firestore,void 0===e?MS(this._delegate):MS(this._delegate,e))}catch(e){throw SC(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=CS(e.firestore,US),r=MS(e),i=Wk(e.converter,t);return oC(n,[ak(ok(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,N_.exists(!1))]).then((()=>r))}(this._delegate,e).then((e=>new TC(this.firestore,e)))}isEqual(e){return LS(this._delegate,e._delegate)}withConverter(e){return new OC(this.firestore,e?this._delegate.withConverter(EC.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function PC(e){return CS(e,DS)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class MC{constructor(...e){this._delegate=new JS(...e)}static documentId(){return new MC(ag.keyField().canonicalString())}isEqual(e){return(e=ic(e))instanceof JS&&this._delegate._internalPath.isEqual(e._internalPath)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class LC{constructor(e){this._delegate=e}static serverTimestamp(){const e=new lk("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new LC(e)}static delete(){const e=new ck("deleteField");return e._methodName="FieldValue.delete",new LC(e)}static arrayUnion(...e){const t=function(...e){return new hk("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new LC(t)}static arrayRemove(...e){const t=function(...e){return new dk("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new LC(t)}static increment(e){const t=new fk("increment",e);return t._methodName="FieldValue.increment",new LC(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}}
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const FC={Firestore:_C,GeoPoint:ZS,Timestamp:ng,Blob:gC,Transaction:bC,WriteBatch:IC,DocumentReference:TC,DocumentSnapshot:xC,Query:NC,QueryDocumentSnapshot:AC,QuerySnapshot:RC,CollectionReference:OC,FieldPath:MC,FieldValue:LC,setLogLevel:function(e){var t;t=e,Dm.setLogLevel(t)},CACHE_SIZE_UNLIMITED:-1};
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var jC;(function(e,t){e.INTERNAL.registerComponent(new sc("firestore-compat",(e=>{const n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("firestore").getImmediate();return t(n,r)}),"PUBLIC").setServiceProps(Object.assign({},FC)))})(jC=uh,((e,t)=>new _C(e,t,new vC))),jC.registerVersion("@firebase/firestore-compat","0.3.12");const qC={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},VC="EMAIL_SIGNIN",UC="PASSWORD_RESET",BC="RECOVER_EMAIL",zC="REVERT_SECOND_FACTOR_ADDITION",$C="VERIFY_AND_CHANGE_EMAIL",WC="VERIFY_EMAIL";function QC(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}const HC=
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registed for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","login-blocked":"Login blocked by user-provided method: {$originalMessage}","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-password":"A non-empty password must be provided","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted.  Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance.","missing-recaptcha-token":"The reCAPTCHA token is missing when sending request to the backend.","invalid-recaptcha-token":"The reCAPTCHA token is invalid when sending request to the backend.","invalid-recaptcha-action":"The reCAPTCHA action is invalid when sending request to the backend.","recaptcha-not-enabled":"reCAPTCHA Enterprise integration is not enabled for this project.","missing-client-type":"The reCAPTCHA client type is missing when sending request to the backend.","missing-recaptcha-version":"The reCAPTCHA version is missing when sending request to the backend.","invalid-req-type":"Invalid request parameters.","invalid-recaptcha-version":"The reCAPTCHA version is invalid when sending request to the backend."}},GC=QC,KC=new Ma("auth","Firebase",{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}),YC=new mc("@firebase/auth");function JC(e,...t){YC.logLevel<=lc.ERROR&&YC.error(`Auth (${Hc}): ${e}`,...t)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function XC(e,...t){throw nx(e,...t)}function ZC(e,...t){return nx(e,...t)}function ex(e,t,n){const r=Object.assign(Object.assign({},GC()),{[t]:n});return new Ma("auth","Firebase",r).create(t,{appName:e.name})}function tx(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&XC(e,"argument-error"),ex(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`)}function nx(e,...t){if("string"!=typeof e){const n=t[0],r=[...t.slice(1)];return r[0]&&(r[0].appName=e.name),e._errorFactory.create(n,...r)}return KC.create(e,...t)}function rx(e,t,...n){if(!e)throw nx(t,...n)}function ix(e){const t="INTERNAL ASSERTION FAILED: "+e;throw JC(t),new Error(t)}function sx(e,t){e||ix(t)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function ox(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function ax(){return"http:"===cx()||"https:"===cx()}function cx(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class ux{constructor(e,t){this.shortDelay=e,this.longDelay=t,sx(t>e,"Short delay should be less than long delay!"),this.isMobile=Ca()||Na()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(ax()||Aa()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function lx(e,t){sx(e.emulator,"Emulator should always be set here");const{url:n}=e.emulator;return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class hx{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl?this.fetchImpl:"undefined"!=typeof self&&"fetch"in self?self.fetch:void ix("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){return this.headersImpl?this.headersImpl:"undefined"!=typeof self&&"Headers"in self?self.Headers:void ix("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){return this.responseImpl?this.responseImpl:"undefined"!=typeof self&&"Response"in self?self.Response:void ix("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const dx={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"},fx=new ux(3e4,6e4);
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function px(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function mx(e,t,n,r,i={}){return gx(e,i,(async()=>{let i={},s={};r&&("GET"===t?s=r:i={body:JSON.stringify(r)});const o=Qa(Object.assign({key:e.config.apiKey},s)).slice(1),a=await e._getAdditionalHeaders();return a["Content-Type"]="application/json",e.languageCode&&(a["X-Firebase-Locale"]=e.languageCode),hx.fetch()(vx(e,e.config.apiHost,n,o),Object.assign({method:t,headers:a,referrerPolicy:"no-referrer"},i))}))}async function gx(e,t,n){e._canInitEmulator=!1;const r=Object.assign(Object.assign({},dx),t);try{const t=new _x(e),i=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();const s=await i.json();if("needConfirmation"in s)throw wx(e,"account-exists-with-different-credential",s);if(i.ok&&!("errorMessage"in s))return s;{const t=i.ok?s.errorMessage:s.error.message,[n,o]=t.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===n)throw wx(e,"credential-already-in-use",s);if("EMAIL_EXISTS"===n)throw wx(e,"email-already-in-use",s);if("USER_DISABLED"===n)throw wx(e,"user-disabled",s);const a=r[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(o)throw ex(e,a,o);XC(e,a)}}catch(t){if(t instanceof Pa)throw t;XC(e,"network-request-failed",{message:String(t)})}}async function yx(e,t,n,r,i={}){const s=await mx(e,t,n,r,i);return"mfaPendingCredential"in s&&XC(e,"multi-factor-auth-required",{_serverResponse:s}),s}function vx(e,t,n,r){const i=`${t}${n}?${r}`;return e.config.emulator?lx(e.config,i):`${e.config.apiScheme}://${i}`}class _x{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(ZC(this.auth,"network-request-failed"))),fx.get())}))}clearNetworkTimeout(){clearTimeout(this.timer)}}function wx(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=ZC(e,t,r);return i.customData._tokenResponse=n,i}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function bx(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function Ix(e){return 1e3*Number(e)}function Ex(e){const[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return JC("JWT malformed, contained fewer than 3 sections"),null;try{const e=_a(n);return e?JSON.parse(e):(JC("Failed to decode base64 JWT payload"),null)}catch(e){return JC("Caught error parsing JWT payload as JSON",null==e?void 0:e.toString()),null}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
async function Tx(e,t,n=!1){if(n)return t;try{return await t}catch(t){throw t instanceof Pa&&function({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class Sx{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){var t;if(e){const e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;const e=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,e)}}schedule(e=!1){if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout((async()=>{await this.iteration()}),t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===(null==e?void 0:e.code)&&this.schedule(!0))}this.schedule()}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class kx{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=bx(this.lastLoginAt),this.creationTime=bx(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function Cx(e){var t;const n=e.auth,r=await e.getIdToken(),i=await Tx(e,async function(e,t){return mx(e,"POST","/v1/accounts:lookup",t)}(n,{idToken:r}));rx(null==i?void 0:i.users.length,n,"internal-error");const s=i.users[0];e._notifyReloadListener(s);const o=(null===(t=s.providerUserInfo)||void 0===t?void 0:t.length)?s.providerUserInfo.map((e=>{var{providerId:t}=e,n=ft(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}})):[];const a=(c=e.providerData,u=o,[...c.filter((e=>!u.some((t=>t.providerId===e.providerId)))),...u]);var c,u;const l=e.isAnonymous,h=!(e.email&&s.passwordHash||(null==a?void 0:a.length)),d=!!l&&h,f={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:a,metadata:new kx(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(e,f)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class xx{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){rx(e.idToken,"internal-error"),rx(void 0!==e.idToken,"internal-error"),rx(void 0!==e.refreshToken,"internal-error");const t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):function(e){const t=Ex(e);return rx(t,"internal-error"),rx(void 0!==t.exp,"internal-error"),rx(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}async getToken(e,t=!1){return rx(!this.accessToken||this.refreshToken,e,"user-token-expired"),t||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:n,refreshToken:r,expiresIn:i}=
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */await async function(e,t){const n=await gx(e,{},(async()=>{const n=Qa({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:r,apiKey:i}=e.config,s=vx(e,r,"/v1/token",`key=${i}`),o=await e._getAdditionalHeaders();return o["Content-Type"]="application/x-www-form-urlencoded",hx.fetch()(s,{method:"POST",headers:o,body:n})}));return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}(e,t);this.updateTokensAndExpiration(n,r,Number(i))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){const{refreshToken:n,accessToken:r,expirationTime:i}=t,s=new xx;return n&&(rx("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(rx("string"==typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(rx("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new xx,this.toJSON())}_performRefresh(){return ix("not implemented")}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Ax(e,t){rx("string"==typeof e||void 0===e,"internal-error",{appName:t})}class Nx{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=ft(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new Sx(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new kx(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){const t=await Tx(this,this.stsTokenManager.getToken(this.auth,e));return rx(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return async function(e,t=!1){const n=ic(e),r=await n.getIdToken(t),i=Ex(r);rx(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");const s="object"==typeof i.firebase?i.firebase:void 0,o=null==s?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:bx(Ix(i.auth_time)),issuedAtTime:bx(Ix(i.iat)),expirationTime:bx(Ix(i.exp)),signInProvider:o||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=ic(e);await Cx(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(rx(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map((e=>Object.assign({},e))),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new Nx(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){rx(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),t&&await Cx(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){const e=await this.getIdToken();return await Tx(this,async function(e,t){return mx(e,"POST","/v1/accounts:delete",t)}(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map((e=>Object.assign({},e))),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var n,r,i,s,o,a,c,u;const l=null!==(n=t.displayName)&&void 0!==n?n:void 0,h=null!==(r=t.email)&&void 0!==r?r:void 0,d=null!==(i=t.phoneNumber)&&void 0!==i?i:void 0,f=null!==(s=t.photoURL)&&void 0!==s?s:void 0,p=null!==(o=t.tenantId)&&void 0!==o?o:void 0,m=null!==(a=t._redirectEventId)&&void 0!==a?a:void 0,g=null!==(c=t.createdAt)&&void 0!==c?c:void 0,y=null!==(u=t.lastLoginAt)&&void 0!==u?u:void 0,{uid:v,emailVerified:_,isAnonymous:w,providerData:b,stsTokenManager:I}=t;rx(v&&I,e,"internal-error");const E=xx.fromJSON(this.name,I);rx("string"==typeof v,e,"internal-error"),Ax(l,e.name),Ax(h,e.name),rx("boolean"==typeof _,e,"internal-error"),rx("boolean"==typeof w,e,"internal-error"),Ax(d,e.name),Ax(f,e.name),Ax(p,e.name),Ax(m,e.name),Ax(g,e.name),Ax(y,e.name);const T=new Nx({uid:v,auth:e,email:h,emailVerified:_,displayName:l,isAnonymous:w,photoURL:f,phoneNumber:d,tenantId:p,stsTokenManager:E,createdAt:g,lastLoginAt:y});return b&&Array.isArray(b)&&(T.providerData=b.map((e=>Object.assign({},e)))),m&&(T._redirectEventId=m),T}static async _fromIdTokenResponse(e,t,n=!1){const r=new xx;r.updateFromServerResponse(t);const i=new Nx({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await Cx(i),i}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Dx=new Map;function Rx(e){sx(e instanceof Function,"Expected a class definition");let t=Dx.get(e);return t?(sx(t instanceof e,"Instance stored in cache mismatched with class"),t):(t=new e,Dx.set(e,t),t)}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Ox{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Ox.type="NONE";const Px=Ox;
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Mx(e,t,n){return`firebase:${e}:${t}:${n}`}class Lx{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;const{config:r,name:i}=this.auth;this.fullUserKey=Mx(this.userKey,r.apiKey,i),this.fullPersistenceKey=Mx("persistence",r.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);return e?Nx._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,n="authUser"){if(!t.length)return new Lx(Rx(Px),e,n);const r=(await Promise.all(t.map((async e=>{if(await e._isAvailable())return e})))).filter((e=>e));let i=r[0]||Rx(Px);const s=Mx(n,e.config.apiKey,e.name);let o=null;for(const n of t)try{const t=await n._get(s);if(t){const r=Nx._fromJSON(e,t);n!==i&&(o=r),i=n;break}}catch(e){}const a=r.filter((e=>e._shouldAllowMigration));return i._shouldAllowMigration&&a.length?(i=a[0],o&&await i._set(s,o.toJSON()),await Promise.all(t.map((async e=>{if(e!==i)try{await e._remove(s)}catch(e){}}))),new Lx(i,e,n)):new Lx(i,e,n)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Fx(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(Ux(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(jx(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(zx(t))return"Blackberry";if($x(t))return"Webos";if(qx(t))return"Safari";if((t.includes("chrome/")||Vx(t))&&!t.includes("edge/"))return"Chrome";if(Bx(t))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,n=e.match(t);if(2===(null==n?void 0:n.length))return n[1]}return"Other"}function jx(e=ka()){return/firefox\//i.test(e)}function qx(e=ka()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function Vx(e=ka()){return/crios\//i.test(e)}function Ux(e=ka()){return/iemobile/i.test(e)}function Bx(e=ka()){return/android/i.test(e)}function zx(e=ka()){return/blackberry/i.test(e)}function $x(e=ka()){return/webos/i.test(e)}function Wx(e=ka()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function Qx(e=ka()){return Wx(e)||Bx(e)||$x(e)||zx(e)||/windows phone/i.test(e)||Ux(e)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function Hx(e,t=[]){let n;switch(e){case"Browser":n=Fx(ka());break;case"Worker":n=`${Fx(ka())}-${e}`;break;default:n=e}const r=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${Hc}/${r}`}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function Gx(e,t){return mx(e,"GET","/v2/recaptchaConfig",px(e,t))}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Kx(e){return void 0!==e&&void 0!==e.getResponse}function Yx(e){return void 0!==e&&void 0!==e.enterprise}class Jx{constructor(e){if(this.siteKey="",this.emailPasswordEnabled=!1,void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.emailPasswordEnabled=e.recaptchaEnforcementState.some((e=>"EMAIL_PASSWORD_PROVIDER"===e.provider&&"OFF"!==e.enforcementState))}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function Xx(e){return new Promise(((t,n)=>{const r=document.createElement("script");r.setAttribute("src",e),r.onload=t,r.onerror=e=>{const t=ZC("internal-error");t.customData=e,n(t)},r.type="text/javascript",r.charset="UTF-8",function(){var e,t;return null!==(t=null===(e=document.getElementsByTagName("head"))||void 0===e?void 0:e[0])&&void 0!==t?t:document}().appendChild(r)}))}function Zx(e){return`__${e}${Math.floor(1e6*Math.random())}`}class eA{constructor(e){this.type="recaptcha-enterprise",this.auth=iA(e)}async verify(e="verify",t=!1){function n(t,n,r){const i=window.grecaptcha;Yx(i)?i.enterprise.ready((()=>{i.enterprise.execute(t,{action:e}).then((e=>{n(e)})).catch((()=>{n("NO_RECAPTCHA")}))})):r(Error("No reCAPTCHA enterprise script loaded."))}return new Promise(((e,r)=>{(async function(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise((async(t,n)=>{Gx(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then((r=>{if(void 0!==r.recaptchaKey){const n=new Jx(r);return null==e.tenantId?e._agentRecaptchaConfig=n:e._tenantRecaptchaConfigs[e.tenantId]=n,t(n.siteKey)}n(new Error("recaptcha Enterprise site key undefined"))})).catch((e=>{n(e)}))}))})(this.auth).then((i=>{if(!t&&Yx(window.grecaptcha))n(i,e,r);else{if("undefined"==typeof window)return void r(new Error("RecaptchaVerifier is only supported in browser"));Xx("https://www.google.com/recaptcha/enterprise.js?render="+i).then((()=>{n(i,e,r)})).catch((e=>{r(e)}))}})).catch((e=>{r(e)}))}))}}async function tA(e,t,n,r=!1){const i=new eA(e);let s;try{s=await i.verify(n)}catch(e){s=await i.verify(n,!0)}const o=Object.assign({},t);return r?Object.assign(o,{captchaResp:s}):Object.assign(o,{captchaResponse:s}),Object.assign(o,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(o,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),o}
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class nA{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const n=t=>new Promise(((n,r)=>{try{n(e(t))}catch(e){r(e)}}));n.onAbort=t,this.queue.push(n);const r=this.queue.length-1;return()=>{this.queue[r]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(e){t.reverse();for(const e of t)try{e()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null==e?void 0:e.message})}}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class rA{constructor(e,t,n,r){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=n,this.config=r,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new sA(this),this.idTokenSubscription=new sA(this),this.beforeStateQueue=new nA(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=KC,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=r.sdkClientVersion}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=Rx(t)),this._initializationPromise=this.queue((async()=>{var n,r;if(!this._deleted&&(this.persistenceManager=await Lx.create(this,e),!this._deleted)){if(null===(n=this._popupRedirectResolver)||void 0===n?void 0:n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=(null===(r=this.currentUser)||void 0===r?void 0:r.uid)||null,this._deleted||(this._isInitialized=!0)}})),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();return this.currentUser||e?this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0):void 0}async initializeCurrentUser(e){var t;const n=await this.assertedPersistence.getCurrentUser();let r=n,i=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const n=null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId,s=null==r?void 0:r._redirectEventId,o=await this.tryRedirectSignIn(e);n&&n!==s||!(null==o?void 0:o.user)||(r=o.user,i=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(r)}catch(e){r=n,this._popupRedirectResolver._overrideRedirectResult(this,(()=>Promise.reject(e)))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return rx(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await Cx(e)}catch(e){if("auth/network-request-failed"!==(null==e?void 0:e.code))return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("undefined"==typeof navigator)return null;const e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){const t=e?ic(e):null;return t&&rx(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&rx(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue((async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()}))}async signOut(){return await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0)}setPersistence(e){return this.queue((async()=>{await this.assertedPersistence.setPersistence(Rx(e))}))}async initializeRecaptchaConfig(){const e=await Gx(this,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}),t=new Jx(e);if(null==this.tenantId?this._agentRecaptchaConfig=t:this._tenantRecaptchaConfigs[this.tenantId]=t,t.emailPasswordEnabled){new eA(this).verify()}}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new Ma("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&Rx(e)||this._popupRedirectResolver;rx(t,this,"argument-error"),this.redirectPersistenceManager=await Lx.create(this,[Rx(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var t,n;return this._isInitialized&&await this.queue((async()=>{})),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(n=this.redirectUser)||void 0===n?void 0:n._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue((async()=>this.directlySetCurrentUser(e)))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e,t;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const n=null!==(t=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==t?t:null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,n,r){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t),s=this._isInitialized?Promise.resolve():this._initializationPromise;return rx(s,this,"internal-error"),s.then((()=>i(this.currentUser))),"function"==typeof t?e.addObserver(t,n,r):e.addObserver(t)}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return rx(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Hx(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;const t={"X-Client-Version":this.clientVersion};this.app.options.appId&&(t["X-Firebase-gmpid"]=this.app.options.appId);const n=await(null===(e=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getHeartbeatsHeader());n&&(t["X-Firebase-Client"]=n);const r=await this._getAppCheckToken();return r&&(t["X-Firebase-AppCheck"]=r),t}async _getAppCheckToken(){var e;const t=await(null===(e=this.appCheckServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getToken());return(null==t?void 0:t.error)&&function(e,...t){YC.logLevel<=lc.WARN&&YC.warn(`Auth (${Hc}): ${e}`,...t)}(`Error while retrieving App Check token: ${t.error}`),null==t?void 0:t.token}}function iA(e){return ic(e)}class sA{constructor(e){this.auth=e,this.observer=null,this.addObserver=Ya((e=>this.observer=e))}get next(){return rx(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function oA(e,t,n){const r=iA(e);rx(r._canInitEmulator,r,"emulator-config-failed"),rx(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");const i=!!(null==n?void 0:n.disableWarnings),s=aA(t),{host:o,port:a}=function(e){const t=aA(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const r=n[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(r);if(i){const e=i[1];return{host:e,port:cA(r.substr(e.length+1))}}{const[e,t]=r.split(":");return{host:e,port:cA(t)}}}(t),c=null===a?"":`:${a}`;r.config.emulator={url:`${s}//${o}${c}/`},r.settings.appVerificationDisabledForTesting=!0,r.emulatorConfig=Object.freeze({host:o,port:a,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),i||function(){function e(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"undefined"!=typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only.  Do not use with production credentials.");"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */()}function aA(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function cA(e){if(!e)return null;const t=Number(e);return isNaN(t)?null:t}class uA{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return ix("not implemented")}_getIdTokenResponse(e){return ix("not implemented")}_linkToIdToken(e,t){return ix("not implemented")}_getReauthenticationResolver(e){return ix("not implemented")}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function lA(e,t){return mx(e,"POST","/v1/accounts:resetPassword",px(e,t))}async function hA(e,t){return mx(e,"POST","/v1/accounts:update",t)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
async function dA(e,t){return yx(e,"POST","/v1/accounts:signInWithPassword",px(e,t))}async function fA(e,t){return mx(e,"POST","/v1/accounts:sendOobCode",px(e,t))}async function pA(e,t){return fA(e,t)}async function mA(e,t){return fA(e,t)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class gA extends uA{constructor(e,t,n,r=null){super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new gA(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new gA(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e;if((null==t?void 0:t.email)&&(null==t?void 0:t.password)){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){var t;switch(this.signInMethod){case"password":const n={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};if(null===(t=e._getRecaptchaConfig())||void 0===t?void 0:t.emailPasswordEnabled){const t=await tA(e,n,"signInWithPassword");return dA(e,t)}return dA(e,n).catch((async t=>{if("auth/missing-recaptcha-token"===t.code){console.log("Sign-in with email address and password is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.");const t=await tA(e,n,"signInWithPassword");return dA(e,t)}return Promise.reject(t)}));case"emailLink":
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
return async function(e,t){return yx(e,"POST","/v1/accounts:signInWithEmailLink",px(e,t))}(e,{email:this._email,oobCode:this._password});default:XC(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return hA(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return yx(e,"POST","/v1/accounts:signInWithEmailLink",px(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:XC(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function yA(e,t){return yx(e,"POST","/v1/accounts:signInWithIdp",px(e,t))}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class vA extends uA{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new vA(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):XC("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:r}=t,i=ft(t,["providerId","signInMethod"]);if(!n||!r)return null;const s=new vA(n,r);return s.idToken=i.idToken||void 0,s.accessToken=i.accessToken||void 0,s.secret=i.secret,s.nonce=i.nonce,s.pendingToken=i.pendingToken||null,s}_getIdTokenResponse(e){return yA(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,yA(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,yA(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=Qa(t)}return e}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const _A={USER_NOT_FOUND:"user-not-found"};
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class wA extends uA{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new wA({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new wA({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return yx(e,"POST","/v1/accounts:signInWithPhoneNumber",px(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){const n=await yx(e,"POST","/v1/accounts:signInWithPhoneNumber",px(e,t));if(n.temporaryProof)throw wx(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return yx(e,"POST","/v1/accounts:signInWithPhoneNumber",px(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),_A)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}=e;return n||t||r||i?new wA({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class bA{constructor(e){var t,n,r,i,s,o;const a=Ha(Ga(e)),c=null!==(t=a.apiKey)&&void 0!==t?t:null,u=null!==(n=a.oobCode)&&void 0!==n?n:null,l=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(r=a.mode)&&void 0!==r?r:null);rx(c&&u&&l,"argument-error"),this.apiKey=c,this.operation=l,this.code=u,this.continueUrl=null!==(i=a.continueUrl)&&void 0!==i?i:null,this.languageCode=null!==(s=a.languageCode)&&void 0!==s?s:null,this.tenantId=null!==(o=a.tenantId)&&void 0!==o?o:null}static parseLink(e){const t=function(e){const t=Ha(Ga(e)).link,n=t?Ha(Ga(t)).deep_link_id:null,r=Ha(Ga(e)).deep_link_id;return(r?Ha(Ga(r)).link:null)||r||n||t||e}(e);try{return new bA(t)}catch(e){return null}}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class IA{constructor(){this.providerId=IA.PROVIDER_ID}static credential(e,t){return gA._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const n=bA.parseLink(t);return rx(n,"argument-error"),gA._fromEmailAndCode(e,n.code,n.tenantId)}}IA.PROVIDER_ID="password",IA.EMAIL_PASSWORD_SIGN_IN_METHOD="password",IA.EMAIL_LINK_SIGN_IN_METHOD="emailLink";
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class EA{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class TA extends EA{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class SA extends TA{static credentialFromJSON(e){const t="string"==typeof e?JSON.parse(e):e;return rx("providerId"in t&&"signInMethod"in t,"argument-error"),vA._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return rx(e.idToken||e.accessToken,"argument-error"),vA._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return SA.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return SA.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:r,pendingToken:i,nonce:s,providerId:o}=e;if(!(n||r||t||i))return null;if(!o)return null;try{return new SA(o)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:i})}catch(e){return null}}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class kA extends TA{constructor(){super("facebook.com")}static credential(e){return vA._fromParams({providerId:kA.PROVIDER_ID,signInMethod:kA.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return kA.credentialFromTaggedObject(e)}static credentialFromError(e){return kA.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return kA.credential(e.oauthAccessToken)}catch(e){return null}}}kA.FACEBOOK_SIGN_IN_METHOD="facebook.com",kA.PROVIDER_ID="facebook.com";
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class CA extends TA{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return vA._fromParams({providerId:CA.PROVIDER_ID,signInMethod:CA.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return CA.credentialFromTaggedObject(e)}static credentialFromError(e){return CA.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return CA.credential(t,n)}catch(e){return null}}}CA.GOOGLE_SIGN_IN_METHOD="google.com",CA.PROVIDER_ID="google.com";
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class xA extends TA{constructor(){super("github.com")}static credential(e){return vA._fromParams({providerId:xA.PROVIDER_ID,signInMethod:xA.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return xA.credentialFromTaggedObject(e)}static credentialFromError(e){return xA.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return xA.credential(e.oauthAccessToken)}catch(e){return null}}}xA.GITHUB_SIGN_IN_METHOD="github.com",xA.PROVIDER_ID="github.com";class AA extends uA{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return yA(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,yA(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,yA(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:r,pendingToken:i}=t;return n&&r&&i&&n===r?new AA(n,i):null}static _create(e,t){return new AA(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class NA extends EA{constructor(e){rx(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return NA.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return NA.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){const t=AA.fromJSON(e);return rx(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{pendingToken:t,providerId:n}=e;if(!t||!n)return null;try{return AA._create(n,t)}catch(e){return null}}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class DA extends TA{constructor(){super("twitter.com")}static credential(e,t){return vA._fromParams({providerId:DA.PROVIDER_ID,signInMethod:DA.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return DA.credentialFromTaggedObject(e)}static credentialFromError(e){return DA.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return DA.credential(t,n)}catch(e){return null}}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
async function RA(e,t){return yx(e,"POST","/v1/accounts:signUp",px(e,t))}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */DA.TWITTER_SIGN_IN_METHOD="twitter.com",DA.PROVIDER_ID="twitter.com";class OA{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,r=!1){const i=await Nx._fromIdTokenResponse(e,n,r),s=PA(n);return new OA({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);const r=PA(n);return new OA({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function PA(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class MA extends Pa{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,MA.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new MA(e,t,n,r)}}function LA(e,t,n,r){return("reauthenticate"===t?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch((n=>{if("auth/multi-factor-auth-required"===n.code)throw MA._fromErrorAndOperation(e,n,t,r);throw n}))}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function FA(e){return new Set(e.map((({providerId:e})=>e)).filter((e=>!!e)))}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function jA(e,t){const n=ic(e);await VA(!0,n,t);const{providerUserInfo:r}=await async function(e,t){return mx(e,"POST","/v1/accounts:update",t)}(n.auth,{idToken:await n.getIdToken(),deleteProvider:[t]}),i=FA(r||[]);return n.providerData=n.providerData.filter((e=>i.has(e.providerId))),i.has("phone")||(n.phoneNumber=null),await n.auth._persistUserIfCurrent(n),n}async function qA(e,t,n=!1){const r=await Tx(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return OA._forOperation(e,"link",r)}async function VA(e,t,n){await Cx(t);const r=!1===e?"provider-already-linked":"no-such-provider";rx(FA(t.providerData).has(n)===e,t.auth,r)}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function UA(e,t,n=!1){const{auth:r}=e,i="reauthenticate";try{const s=await Tx(e,LA(r,i,t,e),n);rx(s.idToken,r,"internal-error");const o=Ex(s.idToken);rx(o,r,"internal-error");const{sub:a}=o;return rx(e.uid===a,r,"user-mismatch"),OA._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&XC(r,"user-mismatch"),e}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function BA(e,t,n=!1){const r="signIn",i=await LA(e,r,t),s=await OA._fromIdTokenResponse(e,r,i);return n||await e._updateCurrentUser(s.user),s}async function zA(e,t){return BA(iA(e),t)}async function $A(e,t){const n=ic(e);return await VA(!1,n,t.providerId),qA(n,t)}async function WA(e,t){return UA(ic(e),t)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
async function QA(e,t){const n=iA(e),r=await async function(e,t){return yx(e,"POST","/v1/accounts:signInWithCustomToken",px(e,t))}(n,{token:t,returnSecureToken:!0}),i=await OA._fromIdTokenResponse(n,"signIn",r);return await n._updateCurrentUser(i.user),i}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class HA{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?GA._fromServerResponse(e,t):"totpInfo"in t?KA._fromServerResponse(e,t):XC(e,"internal-error")}}class GA extends HA{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new GA(t)}}class KA extends HA{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new KA(t)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function YA(e,t,n){var r;rx((null===(r=n.url)||void 0===r?void 0:r.length)>0,e,"invalid-continue-uri"),rx(void 0===n.dynamicLinkDomain||n.dynamicLinkDomain.length>0,e,"invalid-dynamic-link-domain"),t.continueUrl=n.url,t.dynamicLinkDomain=n.dynamicLinkDomain,t.canHandleCodeInApp=n.handleCodeInApp,n.iOS&&(rx(n.iOS.bundleId.length>0,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(rx(n.android.packageName.length>0,e,"missing-android-pkg-name"),t.androidInstallApp=n.android.installApp,t.androidMinimumVersionCode=n.android.minimumVersion,t.androidPackageName=n.android.packageName)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function JA(e,t){await async function(e,t){return mx(e,"POST","/v1/accounts:update",px(e,t))}(ic(e),{oobCode:t})}async function XA(e,t){const n=ic(e),r=await lA(n,{oobCode:t}),i=r.requestType;switch(rx(i,n,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":rx(r.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":rx(r.mfaInfo,n,"internal-error");default:rx(r.email,n,"internal-error")}let s=null;return r.mfaInfo&&(s=HA._fromServerResponse(iA(n),r.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.newEmail:r.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.email:r.newEmail)||null,multiFactorInfo:s},operation:i}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
async function ZA(e,t){const n={identifier:t,continueUri:ax()?ox():"http://localhost"},{signinMethods:r}=
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */await async function(e,t){return mx(e,"POST","/v1/accounts:createAuthUri",px(e,t))}(ic(e),n);return r||[]}async function eN(e,t){const n=ic(e),r={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&YA(n.auth,r,t);const{email:i}=await async function(e,t){return fA(e,t)}(n.auth,r);i!==e.email&&await e.reload()}async function tN(e,t,n){const r=ic(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};n&&YA(r.auth,i,n);const{email:s}=await async function(e,t){return fA(e,t)}(r.auth,i);s!==e.email&&await e.reload()}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
async function nN(e,{displayName:t,photoURL:n}){if(void 0===t&&void 0===n)return;const r=ic(e),i={idToken:await r.getIdToken(),displayName:t,photoUrl:n,returnSecureToken:!0},s=await Tx(r,async function(e,t){return mx(e,"POST","/v1/accounts:update",t)}(r.auth,i));r.displayName=s.displayName||null,r.photoURL=s.photoUrl||null;const o=r.providerData.find((({providerId:e})=>"password"===e));o&&(o.displayName=r.displayName,o.photoURL=r.photoURL),await r._updateTokensIfNecessary(s)}async function rN(e,t,n){const{auth:r}=e,i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),n&&(i.password=n);const s=await Tx(e,hA(r,i));await e._updateTokensIfNecessary(s,!0)}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class iN{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class sN extends iN{constructor(e,t,n,r){super(e,t,n),this.username=r}}class oN extends iN{constructor(e,t){super(e,"facebook.com",t)}}class aN extends sN{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class cN extends iN{constructor(e,t){super(e,"google.com",t)}}class uN extends sN{constructor(e,t,n){super(e,"twitter.com",t,n)}}function lN(e){const{user:t,_tokenResponse:n}=e;return t.isAnonymous&&!n?{providerId:null,isNewUser:!1,profile:null}:function(e){var t,n;if(!e)return null;const{providerId:r}=e,i=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},s=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!r&&(null==e?void 0:e.idToken)){const r=null===(n=null===(t=Ex(e.idToken))||void 0===t?void 0:t.firebase)||void 0===n?void 0:n.sign_in_provider;if(r)return new iN(s,"anonymous"!==r&&"custom"!==r?r:null)}if(!r)return null;switch(r){case"facebook.com":return new oN(s,i);case"github.com":return new aN(s,i);case"google.com":return new cN(s,i);case"twitter.com":return new uN(s,i,e.screenName||null);case"custom":case"anonymous":return new iN(s,null);default:return new iN(s,r,i)}}(n)}class hN{constructor(e,t,n){this.type=e,this.credential=t,this.auth=n}static _fromIdtoken(e,t){return new hN("enroll",e,t)}static _fromMfaPendingCredential(e){return new hN("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){var t,n;if(null==e?void 0:e.multiFactorSession){if(null===(t=e.multiFactorSession)||void 0===t?void 0:t.pendingCredential)return hN._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null===(n=e.multiFactorSession)||void 0===n?void 0:n.idToken)return hN._fromIdtoken(e.multiFactorSession.idToken)}return null}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class dN{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,t){const n=iA(e),r=t.customData._serverResponse,i=(r.mfaInfo||[]).map((e=>HA._fromServerResponse(n,e)));rx(r.mfaPendingCredential,n,"internal-error");const s=hN._fromMfaPendingCredential(r.mfaPendingCredential);return new dN(s,i,(async e=>{const i=await e._process(n,s);delete r.mfaInfo,delete r.mfaPendingCredential;const o=Object.assign(Object.assign({},r),{idToken:i.idToken,refreshToken:i.refreshToken});switch(t.operationType){case"signIn":const e=await OA._fromIdTokenResponse(n,t.operationType,o);return await n._updateCurrentUser(e.user),e;case"reauthenticate":return rx(t.user,n,"internal-error"),OA._forOperation(t.user,t.operationType,o);default:XC(n,"internal-error")}}))}async resolveSignIn(e){const t=e;return this.signInResolver(t)}}class fN{constructor(e){this.user=e,this.enrolledFactors=[],e._onReload((t=>{t.mfaInfo&&(this.enrolledFactors=t.mfaInfo.map((t=>HA._fromServerResponse(e.auth,t))))}))}static _fromUser(e){return new fN(e)}async getSession(){return hN._fromIdtoken(await this.user.getIdToken(),this.user.auth)}async enroll(e,t){const n=e,r=await this.getSession(),i=await Tx(this.user,n._process(this.user.auth,r,t));return await this.user._updateTokensIfNecessary(i),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid,n=await this.user.getIdToken();try{const e=await Tx(this.user,(r=this.user.auth,i={idToken:n,mfaEnrollmentId:t},mx(r,"POST","/v2/accounts/mfaEnrollment:withdraw",px(r,i))));this.enrolledFactors=this.enrolledFactors.filter((({uid:e})=>e!==t)),await this.user._updateTokensIfNecessary(e),await this.user.reload()}catch(e){throw e}var r,i}}const pN=new WeakMap;const mN="__sak";
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class gN{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(mN,"1"),this.storage.removeItem(mN),Promise.resolve(!0)):Promise.resolve(!1)}catch(e){return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){const t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class yN extends gN{constructor(){super((()=>window.localStorage),"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=function(){const e=ka();return qx(e)||Wx(e)}()&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=Qx(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const n=this.storage.getItem(t),r=this.localCache[t];n!==r&&e(t,r,n)}}onStorageEvent(e,t=!1){if(!e.key)return void this.forAllChangedKeys(((e,t,n)=>{this.notifyListeners(e,n)}));const n=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const r=this.storage.getItem(n);if(e.newValue!==r)null!==e.newValue?this.storage.setItem(n,e.newValue):this.storage.removeItem(n);else if(this.localCache[n]===e.newValue&&!t)return}const r=()=>{const e=this.storage.getItem(n);(t||this.localCache[n]!==e)&&this.notifyListeners(n,e)},i=this.storage.getItem(n);Da()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(r,10):r()}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const e of Array.from(n))e(t?JSON.parse(t):t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),!0)}))}),1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}yN.type="LOCAL";const vN=yN;
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class _N extends gN{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(e,t){}_removeListener(e,t){}}_N.type="SESSION";const wN=_N;
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class bN{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find((t=>t.isListeningto(e)));if(t)return t;const n=new bN(e);return this.receivers.push(n),n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:r,data:i}=t.data,s=this.handlersMap[r];if(!(null==s?void 0:s.size))return;t.ports[0].postMessage({status:"ack",eventId:n,eventType:r});const o=Array.from(s).map((async e=>e(t.origin,i))),a=await function(e){return Promise.all(e.map((async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})))}(o);t.ports[0].postMessage({status:"done",eventId:n,eventType:r,response:a})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function IN(e="",t=10){let n="";for(let e=0;e<t;e++)n+=Math.floor(10*Math.random());return e+n}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */bN.receivers=[];class EN{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,n=50){const r="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!r)throw new Error("connection_unavailable");let i,s;return new Promise(((o,a)=>{const c=IN("",20);r.port1.start();const u=setTimeout((()=>{a(new Error("unsupported_event"))}),n);s={messageChannel:r,onMessage(e){const t=e;if(t.data.eventId===c)switch(t.data.status){case"ack":clearTimeout(u),i=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(i),o(t.data.response);break;default:clearTimeout(u),clearTimeout(i),a(new Error("invalid_response"))}}},this.handlers.add(s),r.port1.addEventListener("message",s.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[r.port2])})).finally((()=>{s&&this.removeMessageHandler(s)}))}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function TN(){return window}
/**
 * @license
 * Copyright 2020 Google LLC.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function SN(){return void 0!==TN().WorkerGlobalScope&&"function"==typeof TN().importScripts}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const kN="firebaseLocalStorageDb",CN="firebaseLocalStorage",xN="fbase_key";class AN{constructor(e){this.request=e}toPromise(){return new Promise(((e,t)=>{this.request.addEventListener("success",(()=>{e(this.request.result)})),this.request.addEventListener("error",(()=>{t(this.request.error)}))}))}}function NN(e,t){return e.transaction([CN],t?"readwrite":"readonly").objectStore(CN)}function DN(){const e=indexedDB.open(kN,1);return new Promise(((t,n)=>{e.addEventListener("error",(()=>{n(e.error)})),e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(CN,{keyPath:xN})}catch(e){n(e)}})),e.addEventListener("success",(async()=>{const n=e.result;n.objectStoreNames.contains(CN)?t(n):(n.close(),await function(){const e=indexedDB.deleteDatabase(kN);return new AN(e).toPromise()}(),t(await DN()))}))}))}async function RN(e,t,n){const r=NN(e,!0).put({[xN]:t,value:n});return new AN(r).toPromise()}function ON(e,t){const n=NN(e,!0).delete(t);return new AN(n).toPromise()}class PN{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then((()=>{}),(()=>{}))}async _openDb(){return this.db||(this.db=await DN()),this.db}async _withRetries(e){let t=0;for(;;)try{const t=await this._openDb();return await e(t)}catch(e){if(t++>3)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return SN()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=bN._getInstance(SN()?self:null),this.receiver._subscribe("keyChanged",(async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)}))),this.receiver._subscribe("ping",(async(e,t)=>["keyChanged"]))}async initializeSender(){var e,t;if(this.activeServiceWorker=await async function(){if(!(null===navigator||void 0===navigator?void 0:navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),!this.activeServiceWorker)return;this.sender=new EN(this.activeServiceWorker);const n=await this.sender._send("ping",{},800);n&&(null===(e=n[0])||void 0===e?void 0:e.fulfilled)&&(null===(t=n[0])||void 0===t?void 0:t.value.includes("keyChanged"))&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(this.sender&&this.activeServiceWorker&&function(){var e;return(null===(e=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===e?void 0:e.controller)||null}()===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await DN();return await RN(e,mN,"1"),await ON(e,mN),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite((async()=>(await this._withRetries((n=>RN(n,e,t))),this.localCache[e]=t,this.notifyServiceWorker(e))))}async _get(e){const t=await this._withRetries((t=>async function(e,t){const n=NN(e,!1).get(t),r=await new AN(n).toPromise();return void 0===r?null:r.value}(t,e)));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite((async()=>(await this._withRetries((t=>ON(t,e))),delete this.localCache[e],this.notifyServiceWorker(e))))}async _poll(){const e=await this._withRetries((e=>{const t=NN(e,!1).getAll();return new AN(t).toPromise()}));if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],n=new Set;for(const{fbase_key:r,value:i}of e)n.add(r),JSON.stringify(this.localCache[r])!==JSON.stringify(i)&&(this.notifyListeners(r,i),t.push(r));for(const e of Object.keys(this.localCache))this.localCache[e]&&!n.has(e)&&(this.notifyListeners(e,null),t.push(e));return t}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const e of Array.from(n))e(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((async()=>this._poll()),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}PN.type="LOCAL";const MN=PN;
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const LN=1e12;class FN{constructor(e){this.auth=e,this.counter=LN,this._widgets=new Map}render(e,t){const n=this.counter;return this._widgets.set(n,new jN(e,this.auth.name,t||{})),this.counter++,n}reset(e){var t;const n=e||LN;null===(t=this._widgets.get(n))||void 0===t||t.delete(),this._widgets.delete(n)}getResponse(e){var t;const n=e||LN;return(null===(t=this._widgets.get(n))||void 0===t?void 0:t.getResponse())||""}async execute(e){var t;const n=e||LN;return null===(t=this._widgets.get(n))||void 0===t||t.execute(),""}}class jN{constructor(e,t,n){this.params=n,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};const r="string"==typeof e?document.getElementById(e):e;rx(r,"argument-error",{appName:t}),this.container=r,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout((()=>{this.responseToken=function(e){const t=[],n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<e;r++)t.push(n.charAt(Math.floor(Math.random()*n.length)));return t.join("")}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(50);const{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(e){}this.timerId=window.setTimeout((()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()}),6e4)}),500))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}const qN=Zx("rcb"),VN=new ux(3e4,6e4);class UN{constructor(){var e;this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!(null===(e=TN().grecaptcha)||void 0===e?void 0:e.render)}load(e,t=""){return rx(function(e){return e.length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e)}(t),e,"argument-error"),this.shouldResolveImmediately(t)&&Kx(TN().grecaptcha)?Promise.resolve(TN().grecaptcha):new Promise(((n,r)=>{const i=TN().setTimeout((()=>{r(ZC(e,"network-request-failed"))}),VN.get());TN()[qN]=()=>{TN().clearTimeout(i),delete TN()[qN];const s=TN().grecaptcha;if(!s||!Kx(s))return void r(ZC(e,"internal-error"));const o=s.render;s.render=(e,t)=>{const n=o(e,t);return this.counter++,n},this.hostLanguage=t,n(s)};Xx(`https://www.google.com/recaptcha/api.js??${Qa({onload:qN,render:"explicit",hl:t})}`).catch((()=>{clearTimeout(i),r(ZC(e,"internal-error"))}))}))}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){var t;return!!(null===(t=TN().grecaptcha)||void 0===t?void 0:t.render)&&(e===this.hostLanguage||this.counter>0||this.librarySeparatelyLoaded)}}class BN{async load(e){return new FN(e)}clearedOneInstance(){}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const zN="recaptcha",$N={theme:"light",type:"image"};
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class WN{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){const t=wA._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function QN(e,t,n){var r;const i=await n.verify();try{let s;if(rx("string"==typeof i,e,"argument-error"),rx(n.type===zN,e,"argument-error"),s="string"==typeof t?{phoneNumber:t}:t,"session"in s){const t=s.session;if("phoneNumber"in s){rx("enroll"===t.type,e,"internal-error");const n=
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */await function(e,t){return mx(e,"POST","/v2/accounts/mfaEnrollment:start",px(e,t))}(e,{idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:s.phoneNumber,recaptchaToken:i}});return n.phoneSessionInfo.sessionInfo}{rx("signin"===t.type,e,"internal-error");const n=(null===(r=s.multiFactorHint)||void 0===r?void 0:r.uid)||s.multiFactorUid;rx(n,e,"missing-multi-factor-info");const o=await function(e,t){return mx(e,"POST","/v2/accounts/mfaSignIn:start",px(e,t))}(e,{mfaPendingCredential:t.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:i}});return o.phoneResponseInfo.sessionInfo}}{const{sessionInfo:t}=await async function(e,t){return mx(e,"POST","/v1/accounts:sendVerificationCode",px(e,t))}(e,{phoneNumber:s.phoneNumber,recaptchaToken:i});return t}}finally{n._reset()}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
let HN=class e{constructor(t){this.providerId=e.PROVIDER_ID,this.auth=iA(t)}verifyPhoneNumber(e,t){return QN(this.auth,e,ic(t))}static credential(e,t){return wA._fromVerification(e,t)}static credentialFromResult(t){const n=t;return e.credentialFromTaggedObject(n)}static credentialFromError(t){return e.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{phoneNumber:t,temporaryProof:n}=e;return t&&n?wA._fromTokenResponse(t,n):null}};
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function GN(e,t){return t?Rx(t):(rx(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */HN.PROVIDER_ID="phone",HN.PHONE_SIGN_IN_METHOD="phone";class KN extends uA{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return yA(e,this._buildIdpRequest())}_linkToIdToken(e,t){return yA(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return yA(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function YN(e){return BA(e.auth,new KN(e),e.bypassAuthState)}function JN(e){const{auth:t,user:n}=e;return rx(n,t,"internal-error"),UA(n,new KN(e),e.bypassAuthState)}async function XN(e){const{auth:t,user:n}=e;return rx(n,t,"internal-error"),qA(n,new KN(e),e.bypassAuthState)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ZN{constructor(e,t,n,r,i=!1){this.auth=e,this.resolver=n,this.user=r,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise((async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}}))}async onAuthEvent(e){const{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:s,type:o}=e;if(s)return void this.reject(s);const a={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return YN;case"linkViaPopup":case"linkViaRedirect":return XN;case"reauthViaPopup":case"reauthViaRedirect":return JN;default:XC(this.auth,"internal-error")}}resolve(e){sx(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){sx(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const eD=new ux(2e3,1e4);class tD extends ZN{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,tD.currentPopupAction&&tD.currentPopupAction.cancel(),tD.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return rx(e,this.auth,"internal-error"),e}async onExecution(){sx(1===this.filter.length,"Popup operations only handle one event");const e=IN();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch((e=>{this.reject(e)})),this.resolver._isIframeWebStorageSupported(this.auth,(e=>{e||this.reject(ZC(this.auth,"web-storage-unsupported"))})),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(ZC(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,tD.currentPopupAction=null}pollUserCancellation(){const e=()=>{var t,n;(null===(n=null===(t=this.authWindow)||void 0===t?void 0:t.window)||void 0===n?void 0:n.closed)?this.pollId=window.setTimeout((()=>{this.pollId=null,this.reject(ZC(this.auth,"popup-closed-by-user"))}),8e3):this.pollId=window.setTimeout(e,eD.get())};e()}}tD.currentPopupAction=null;
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const nD="pendingRedirect",rD=new Map;class iD extends ZN{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let e=rD.get(this.auth._key());if(!e){try{const t=await async function(e,t){const n=cD(t),r=aD(e);if(!await r._isAvailable())return!1;const i="true"===await r._get(n);return await r._remove(n),i}(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(t)}catch(t){e=()=>Promise.reject(t)}rD.set(this.auth._key(),e)}return this.bypassAuthState||rD.set(this.auth._key(),(()=>Promise.resolve(null))),e()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function sD(e,t){return aD(e)._set(cD(t),"true")}function oD(e,t){rD.set(e._key(),t)}function aD(e){return Rx(e._redirectPersistence)}function cD(e){return Mx(nD,e.config.apiKey,e.name)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function uD(e,t,n){return async function(e,t,n){const r=iA(e);tx(e,t,EA),await r._initializationPromise;const i=GN(r,n);return await sD(i,r),i._openRedirect(r,t,"signInViaRedirect")}(e,t,n)}function lD(e,t,n){return async function(e,t,n){const r=ic(e);tx(r.auth,t,EA),await r.auth._initializationPromise;const i=GN(r.auth,n);await sD(i,r.auth);const s=await fD(r);return i._openRedirect(r.auth,t,"reauthViaRedirect",s)}(e,t,n)}function hD(e,t,n){return async function(e,t,n){const r=ic(e);tx(r.auth,t,EA),await r.auth._initializationPromise;const i=GN(r.auth,n);await VA(!1,r,t.providerId),await sD(i,r.auth);const s=await fD(r);return i._openRedirect(r.auth,t,"linkViaRedirect",s)}(e,t,n)}async function dD(e,t,n=!1){const r=iA(e),i=GN(r,t),s=new iD(r,i,n),o=await s.execute();return o&&!n&&(delete o.user._redirectEventId,await r._persistUserIfCurrent(o.user),await r._setRedirectUser(null,t)),o}async function fD(e){const t=IN(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class pD{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach((n=>{this.isEventForConsumer(e,n)&&(t=!0,this.sendToConsumer(e,n),this.saveEventToCache(e))})),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return gD(e);default:return!1}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){var n;if(e.error&&!gD(e)){const r=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";t.onError(ZC(this.auth,r))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(mD(e))}saveEventToCache(e){this.cachedEventUids.add(mD(e)),this.lastProcessedEventTime=Date.now()}}function mD(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join("-")}function gD({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function yD(e,t={}){return mx(e,"GET","/v1/projects",t)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const vD=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,_D=/^https?/;function wD(e){const t=ox(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){const i=new URL(e);return""===i.hostname&&""===r?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&i.hostname===r}if(!_D.test(n))return!1;if(vD.test(e))return r===e;const i=e.replace(/\./g,"\\.");return new RegExp("^(.+\\."+i+"|"+i+")$","i").test(r)}
/**
 * @license
 * Copyright 2020 Google LLC.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const bD=new ux(3e4,6e4);function ID(){const e=TN().___jsl;if(null==e?void 0:e.H)for(const t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[...e.H[t].L],e.CP)for(let t=0;t<e.CP.length;t++)e.CP[t]=null}let ED=null;function TD(e){return ED=ED||function(e){return new Promise(((t,n)=>{var r,i,s;function o(){ID(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{ID(),n(ZC(e,"network-request-failed"))},timeout:bD.get()})}if(null===(i=null===(r=TN().gapi)||void 0===r?void 0:r.iframes)||void 0===i?void 0:i.Iframe)t(gapi.iframes.getContext());else{if(!(null===(s=TN().gapi)||void 0===s?void 0:s.load)){const t=Zx("iframefcb");return TN()[t]=()=>{gapi.load?o():n(ZC(e,"network-request-failed"))},Xx(`https://apis.google.com/js/api.js?onload=${t}`).catch((e=>n(e)))}o()}})).catch((e=>{throw ED=null,e}))}(e),ED}
/**
 * @license
 * Copyright 2020 Google LLC.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const SD=new ux(5e3,15e3),kD="__/auth/iframe",CD="emulator/auth/iframe",xD={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},AD=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function ND(e){const t=e.config;rx(t.authDomain,e,"auth-domain-config-required");const n=t.emulator?lx(t,CD):`https://${e.config.authDomain}/${kD}`,r={apiKey:t.apiKey,appName:e.name,v:Hc},i=AD.get(e.config.apiHost);i&&(r.eid=i);const s=e._getFrameworks();return s.length&&(r.fw=s.join(",")),`${n}?${Qa(r).slice(1)}`}
/**
 * @license
 * Copyright 2020 Google LLC.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const DD={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class RD{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function OD(e,t,n,r=500,i=600){const s=Math.max((window.screen.availHeight-i)/2,0).toString(),o=Math.max((window.screen.availWidth-r)/2,0).toString();let a="";const c=Object.assign(Object.assign({},DD),{width:r.toString(),height:i.toString(),top:s,left:o}),u=ka().toLowerCase();n&&(a=Vx(u)?"_blank":n),jx(u)&&(t=t||"http://localhost",c.scrollbars="yes");const l=Object.entries(c).reduce(((e,[t,n])=>`${e}${t}=${n},`),"");if(function(e=ka()){var t;return Wx(e)&&!!(null===(t=window.navigator)||void 0===t?void 0:t.standalone)}(u)&&"_self"!==a)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(t||"",a),new RD(null);const h=window.open(t||"",a,l);rx(h,e,"popup-blocked");try{h.focus()}catch(e){}return new RD(h)}const PD="__/auth/handler",MD="emulator/auth/handler",LD=encodeURIComponent("fac");async function FD(e,t,n,r,i,s){rx(e.config.authDomain,e,"auth-domain-config-required"),rx(e.config.apiKey,e,"invalid-api-key");const o={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:Hc,eventId:i};if(t instanceof EA){t.setDefaultLanguage(e.languageCode),o.providerId=t.providerId||"",Ba(t.getCustomParameters())||(o.customParameters=JSON.stringify(t.getCustomParameters()));for(const[e,t]of Object.entries(s||{}))o[e]=t}if(t instanceof TA){const e=t.getScopes().filter((e=>""!==e));e.length>0&&(o.scopes=e.join(","))}e.tenantId&&(o.tid=e.tenantId);const a=o;for(const e of Object.keys(a))void 0===a[e]&&delete a[e];const c=await e._getAppCheckToken(),u=c?`#${LD}=${encodeURIComponent(c)}`:"";return`${function({config:e}){if(!e.emulator)return`https://${e.authDomain}/${PD}`;return lx(e,MD)}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e)}?${Qa(a).slice(1)}${u}`}const jD="webStorageSupport";const qD=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=wN,this._completeRedirectFn=dD,this._overrideRedirectResult=oD}async _openPopup(e,t,n,r){var i;sx(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()");return OD(e,await FD(e,t,n,ox(),r),IN())}async _openRedirect(e,t,n,r){await this._originValidation(e);return function(e){TN().location.href=e}(await FD(e,t,n,ox(),r)),new Promise((()=>{}))}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:n}=this.eventManagers[t];return e?Promise.resolve(e):(sx(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch((()=>{delete this.eventManagers[t]})),n}async initAndGetManager(e){const t=await async function(e){const t=await TD(e),n=TN().gapi;return rx(n,e,"internal-error"),t.open({where:document.body,url:ND(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:xD,dontclear:!0},(t=>new Promise((async(n,r)=>{await t.restyle({setHideOnLeave:!1});const i=ZC(e,"network-request-failed"),s=TN().setTimeout((()=>{r(i)}),SD.get());function o(){TN().clearTimeout(s),n(t)}t.ping(o).then(o,(()=>{r(i)}))}))))}(e),n=new pD(e);return t.register("authEvent",(t=>{rx(null==t?void 0:t.authEvent,e,"invalid-auth-event");return{status:n.onEvent(t.authEvent)?"ACK":"ERROR"}}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:n},this.iframes[e._key()]=t,n}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(jD,{type:jD},(n=>{var r;const i=null===(r=null==n?void 0:n[0])||void 0===r?void 0:r[jD];void 0!==i&&t(!!i),XC(e,"internal-error")}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){if(e.config.emulator)return;const{authorizedDomains:t}=await yD(e);for(const e of t)try{if(wD(e))return}catch(e){}XC(e,"unauthorized-domain")}(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return Qx()||qx()||Wx()}};class VD{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return ix("unexpected MultiFactorSessionType")}}}class UD extends VD{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new UD(e)}_finalizeEnroll(e,t,n){return function(e,t){return mx(e,"POST","/v2/accounts/mfaEnrollment:finalize",px(e,t))}(e,{idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()})}_finalizeSignIn(e,t){return function(e,t){return mx(e,"POST","/v2/accounts/mfaSignIn:finalize",px(e,t))}(e,{mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()})}}class BD{constructor(){}static assertion(e){return UD._fromCredential(e)}}BD.FACTOR_ID="phone";var zD="@firebase/auth",$D="0.23.2";
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class WD{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?void 0:e.uid)||null}async getToken(e){if(this.assertAuthConfigured(),await this.auth._initializationPromise,!this.auth.currentUser)return null;return{accessToken:await this.auth.currentUser.getIdToken(e)}}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged((t=>{e((null==t?void 0:t.stsTokenManager.accessToken)||null)}));this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){rx(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var QD;
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function HD(){return window}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e=>{var t;null===(t=Ia())||void 0===t||t[`_${e}`]})("authIdTokenMaxAge"),QD="Browser",zc(new sc("auth",((e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=e.getProvider("heartbeat"),i=e.getProvider("app-check-internal"),{apiKey:s,authDomain:o}=n.options;rx(s&&!s.includes(":"),"invalid-api-key",{appName:n.name});const a={apiKey:s,authDomain:o,clientPlatform:QD,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Hx(QD)},c=new rA(n,r,i,a);return function(e,t){const n=(null==t?void 0:t.persistence)||[],r=(Array.isArray(n)?n:[n]).map(Rx);(null==t?void 0:t.errorMap)&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null==t?void 0:t.popupRedirectResolver)}(c,t),c}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,n)=>{e.getProvider("auth-internal").initialize()}))),zc(new sc("auth-internal",(e=>(e=>new WD(e))(iA(e.getProvider("auth").getImmediate()))),"PRIVATE").setInstantiationMode("EXPLICIT")),Yc(zD,$D,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(QD)),Yc(zD,$D,"esm2017");async function GD(e,t,n){var r;const{BuildInfo:i}=HD();sx(t.sessionId,"AuthEvent did not contain a session ID");const s=await async function(e){const t=function(e){if(sx(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map((e=>e.toString(16).padStart(2,"0"))).join("")}(t.sessionId),o={};return Wx()?o.ibi=i.packageName:Bx()?o.apn=i.packageName:XC(e,"operation-not-supported-in-this-environment"),i.displayName&&(o.appDisplayName=i.displayName),o.sessionId=s,FD(e,n,t.type,void 0,null!==(r=t.eventId)&&void 0!==r?r:void 0,o)}function KD(e){const{cordova:t}=HD();return new Promise((n=>{t.plugins.browsertab.isAvailable((r=>{let i=null;r?t.plugins.browsertab.openUrl(e):i=t.InAppBrowser.open(e,function(e=ka()){return/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)}()?"_blank":"_system","location=yes"),n(i)}))}))}const YD=20;class JD extends pD{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise((e=>{this.resolveInialized=e}))}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(e){return this.resolveInialized(),this.passiveListeners.forEach((t=>t(e))),super.onEvent(e)}async initialized(){await this.initPromise}}async function XD(e){const t=await tR()._get(nR(e));return t&&await tR()._remove(nR(e)),t}function ZD(e,t){var n,r;const i=function(e){const t=rR(e),n=t.link?decodeURIComponent(t.link):void 0,r=rR(n).link,i=t.deep_link_id?decodeURIComponent(t.deep_link_id):void 0;return rR(i).link||i||r||n||e}(t);if(i.includes("/__/auth/callback")){const t=rR(i),s=t.firebaseError?function(e){try{return JSON.parse(e)}catch(e){return null}}(decodeURIComponent(t.firebaseError)):null,o=null===(r=null===(n=null==s?void 0:s.code)||void 0===n?void 0:n.split("auth/"))||void 0===r?void 0:r[1],a=o?ZC(o):null;return a?{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:a,urlResponse:null,sessionId:null,postBody:null}:{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:i,postBody:null}}return null}function eR(){const e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let n=0;n<YD;n++){const n=Math.floor(62*Math.random());e.push(t.charAt(n))}return e.join("")}function tR(){return Rx(vN)}function nR(e){return Mx("authEvent",e.config.apiKey,e.name)}function rR(e){if(!(null==e?void 0:e.includes("?")))return{};const[t,...n]=e.split("?");return Ha(n.join("?"))}
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const iR=class{constructor(){this._redirectPersistence=wN,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=dD,this._overrideRedirectResult=oD}async _initialize(e){const t=e._key();let n=this.eventManagers.get(t);return n||(n=new JD(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(e){XC(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,n,r){!function(e){var t,n,r,i,s,o,a,c,u,l;const h=HD();rx("function"==typeof(null===(t=null==h?void 0:h.universalLinks)||void 0===t?void 0:t.subscribe),e,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),rx(void 0!==(null===(n=null==h?void 0:h.BuildInfo)||void 0===n?void 0:n.packageName),e,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),rx("function"==typeof(null===(s=null===(i=null===(r=null==h?void 0:h.cordova)||void 0===r?void 0:r.plugins)||void 0===i?void 0:i.browsertab)||void 0===s?void 0:s.openUrl),e,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),rx("function"==typeof(null===(c=null===(a=null===(o=null==h?void 0:h.cordova)||void 0===o?void 0:o.plugins)||void 0===a?void 0:a.browsertab)||void 0===c?void 0:c.isAvailable),e,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),rx("function"==typeof(null===(l=null===(u=null==h?void 0:h.cordova)||void 0===u?void 0:u.InAppBrowser)||void 0===l?void 0:l.open),e,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"})}(e);const i=await this._initialize(e);await i.initialized(),i.resetRedirect(),rD.clear(),await this._originValidation(e);const s=function(e,t,n=null){return{type:t,eventId:n,urlResponse:null,sessionId:eR(),postBody:null,tenantId:e.tenantId,error:ZC(e,"no-auth-event")}}(e,n,r);await function(e,t){return tR()._set(nR(e),t)}(e,s);const o=await GD(e,s,t);return async function(e,t,n){const{cordova:r}=HD();let i=()=>{};try{await new Promise(((s,o)=>{let a=null;function c(){var e;s();const t=null===(e=r.plugins.browsertab)||void 0===e?void 0:e.close;"function"==typeof t&&t(),"function"==typeof(null==n?void 0:n.close)&&n.close()}function u(){a||(a=window.setTimeout((()=>{o(ZC(e,"redirect-cancelled-by-user"))}),2e3))}function l(){"visible"===(null===document||void 0===document?void 0:document.visibilityState)&&u()}t.addPassiveListener(c),document.addEventListener("resume",u,!1),Bx()&&document.addEventListener("visibilitychange",l,!1),i=()=>{t.removePassiveListener(c),document.removeEventListener("resume",u,!1),document.removeEventListener("visibilitychange",l,!1),a&&window.clearTimeout(a)}}))}finally{i()}}(e,i,await KD(o))}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){const{BuildInfo:t}=HD(),n={};Wx()?n.iosBundleId=t.packageName:Bx()?n.androidPackageName=t.packageName:XC(e,"operation-not-supported-in-this-environment"),await yD(e,n)}(e)),this.originValidationPromises[t]}attachCallbackListeners(e,t){const{universalLinks:n,handleOpenURL:r,BuildInfo:i}=HD(),s=setTimeout((async()=>{await XD(e),t.onEvent(sR())}),500),o=async n=>{clearTimeout(s);const r=await XD(e);let i=null;r&&(null==n?void 0:n.url)&&(i=ZD(r,n.url)),t.onEvent(i||sR())};void 0!==n&&"function"==typeof n.subscribe&&n.subscribe(null,o);const a=r,c=`${i.packageName.toLowerCase()}://`;HD().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)&&o({url:e}),"function"==typeof a)try{a(e)}catch(e){console.error(e)}}}};function sR(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:ZC("no-auth-event")}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function oR(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function aR(e=ka()){return!("file:"!==oR()&&"ionic:"!==oR()&&"capacitor:"!==oR()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function cR(e=ka()){return Da()&&11===(null===document||void 0===document?void 0:document.documentMode)||function(e=ka()){return/Edge\/\d+/.test(e)}(e)}function uR(){try{const e=self.localStorage,t=IN();if(e)return e.setItem(t,"1"),e.removeItem(t),!cR()||Oa()}catch(e){return lR()&&Oa()}return!1}function lR(){return void 0!==h&&"WorkerGlobalScope"in h&&"importScripts"in h}function hR(){return("http:"===oR()||"https:"===oR()||Aa()||aR())&&!(Na()||xa())&&uR()&&!lR()}function dR(){return aR()&&"undefined"!=typeof document}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const fR={LOCAL:"local",NONE:"none",SESSION:"session"},pR=rx,mR="persistence";async function gR(e){await e._initializationPromise;const t=yR(),n=Mx(mR,e.config.apiKey,e.name);t&&t.setItem(n,e._getPersistence())}function yR(){var e;try{return(null===(e="undefined"!=typeof window?window:null)||void 0===e?void 0:e.sessionStorage)||null}catch(e){return null}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const vR=rx;class _R{constructor(){this.browserResolver=Rx(qD),this.cordovaResolver=Rx(iR),this.underlyingResolver=null,this._redirectPersistence=wN,this._completeRedirectFn=dD,this._overrideRedirectResult=oD}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,n,r)}async _openRedirect(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,n,r)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return dR()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return vR(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){if(this.underlyingResolver)return;const e=await async function(){return!!dR()&&new Promise((e=>{const t=setTimeout((()=>{e(!1)}),1e3);document.addEventListener("deviceready",(()=>{clearTimeout(t),e(!0)}))}))}();this.underlyingResolver=e?this.cordovaResolver:this.browserResolver}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function wR(e){return e.unwrap()}function bR(e,t){var n;const r=null===(n=t.customData)||void 0===n?void 0:n._tokenResponse;if("auth/multi-factor-auth-required"===(null==t?void 0:t.code)){t.resolver=new SR(e,function(e,t){var n;const r=ic(e),i=t;return rx(t.customData.operationType,r,"argument-error"),rx(null===(n=i.customData._serverResponse)||void 0===n?void 0:n.mfaPendingCredential,r,"argument-error"),dN._fromError(r,i)}(e,t))}else if(r){const e=IR(t),n=t;e&&(n.credential=e,n.tenantId=r.tenantId||void 0,n.email=r.email||void 0,n.phoneNumber=r.phoneNumber||void 0)}}function IR(e){const{_tokenResponse:t}=e instanceof Pa?e.customData:e;if(!t)return null;if(!(e instanceof Pa)&&"temporaryProof"in t&&"phoneNumber"in t)return HN.credentialFromResult(e);const n=t.providerId;if(!n||n===qC.PASSWORD)return null;let r;switch(n){case qC.GOOGLE:r=CA;break;case qC.FACEBOOK:r=kA;break;case qC.GITHUB:r=xA;break;case qC.TWITTER:r=DA;break;default:const{oauthIdToken:e,oauthAccessToken:i,oauthTokenSecret:s,pendingToken:o,nonce:a}=t;return i||s||e||o?o?n.startsWith("saml.")?AA._create(n,o):vA._fromParams({providerId:n,signInMethod:n,pendingToken:o,idToken:e,accessToken:i}):new SA(n).credential({idToken:e,accessToken:i,rawNonce:a}):null}return e instanceof Pa?r.credentialFromError(e):r.credentialFromResult(e)}function ER(e,t){return t.catch((t=>{throw t instanceof Pa&&bR(e,t),t})).then((e=>{const t=e.operationType,n=e.user;return{operationType:t,credential:(r=e,IR(r)),additionalUserInfo:lN(e),user:kR.getOrCreate(n)};
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var r}))}async function TR(e,t){const n=await t;return{verificationId:n.verificationId,confirm:t=>ER(e,n.confirm(t))}}class SR{constructor(e,t){this.resolver=t,this.auth=e.wrapped()}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return ER(wR(this.auth),this.resolver.resolveSignIn(e))}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class kR{constructor(e){this._delegate=e,this.multiFactor=function(e){const t=ic(e);return pN.has(t)||pN.set(t,fN._fromUser(t)),pN.get(t)}(e)}static getOrCreate(e){return kR.USER_MAP.has(e)||kR.USER_MAP.set(e,new kR(e)),kR.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return ER(this.auth,$A(this._delegate,e))}async linkWithPhoneNumber(e,t){return TR(this.auth,async function(e,t,n){const r=ic(e);await VA(!1,r,"phone");const i=await QN(r.auth,t,ic(n));return new WN(i,(e=>$A(r,e)))}(this._delegate,e,t))}async linkWithPopup(e){return ER(this.auth,async function(e,t,n){const r=ic(e);tx(r.auth,t,EA);const i=GN(r.auth,n);return new tD(r.auth,"linkViaPopup",t,i,r).executeNotNull()}(this._delegate,e,_R))}async linkWithRedirect(e){return await gR(iA(this.auth)),hD(this._delegate,e,_R)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return ER(this.auth,WA(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return TR(this.auth,async function(e,t,n){const r=ic(e),i=await QN(r.auth,t,ic(n));return new WN(i,(e=>WA(r,e)))}(this._delegate,e,t))}reauthenticateWithPopup(e){return ER(this.auth,async function(e,t,n){const r=ic(e);tx(r.auth,t,EA);const i=GN(r.auth,n);return new tD(r.auth,"reauthViaPopup",t,i,r).executeNotNull()}(this._delegate,e,_R))}async reauthenticateWithRedirect(e){return await gR(iA(this.auth)),lD(this._delegate,e,_R)}sendEmailVerification(e){return eN(this._delegate,e)}async unlink(e){return await jA(this._delegate,e),this}updateEmail(e){return function(e,t){return rN(ic(e),t,null)}(this._delegate,e)}updatePassword(e){return function(e,t){return rN(ic(e),null,t)}(this._delegate,e)}updatePhoneNumber(e){return async function(e,t){await qA(ic(e),t)}(this._delegate,e)}updateProfile(e){return nN(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return tN(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}kR.USER_MAP=new WeakMap;
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const CR=rx;class xR{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();const{apiKey:n}=e.options;CR(n,"invalid-api-key",{appName:e.name}),CR(n,"invalid-api-key",{appName:e.name});const r="undefined"!=typeof window?_R:void 0;this._delegate=t.initialize({options:{persistence:NR(n,e.name),popupRedirectResolver:r}}),this._delegate._updateErrorMap(HC),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?kR.getOrCreate(this._delegate.currentUser):null}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){oA(this._delegate,e,t)}applyActionCode(e){return JA(this._delegate,e)}checkActionCode(e){return XA(this._delegate,e)}confirmPasswordReset(e,t){return async function(e,t,n){await lA(ic(e),{oobCode:t,newPassword:n})}(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return ER(this._delegate,async function(e,t,n){var r;const i=iA(e),s={returnSecureToken:!0,email:t,password:n,clientType:"CLIENT_TYPE_WEB"};let o;if(null===(r=i._getRecaptchaConfig())||void 0===r?void 0:r.emailPasswordEnabled){const e=await tA(i,s,"signUpPassword");o=RA(i,e)}else o=RA(i,s).catch((async e=>{if("auth/missing-recaptcha-token"===e.code){console.log("Sign-up is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-up flow.");const e=await tA(i,s,"signUpPassword");return RA(i,e)}return Promise.reject(e)}));const a=await o.catch((e=>Promise.reject(e))),c=await OA._fromIdTokenResponse(i,"signIn",a);return await i._updateCurrentUser(c.user),c}(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return ZA(this._delegate,e)}isSignInWithEmailLink(e){return function(e,t){const n=bA.parseLink(t);return"EMAIL_SIGNIN"===(null==n?void 0:n.operation)}(this._delegate,e)}async getRedirectResult(){CR(hR(),this._delegate,"operation-not-supported-in-this-environment");const e=await async function(e,t){return await iA(e)._initializationPromise,dD(e,t,!1)}(this._delegate,_R);return e?ER(this._delegate,Promise.resolve(e)):{credential:null,user:null}}addFrameworkForLogging(e){!function(e,t){iA(e)._logFramework(t)}(this._delegate,e)}onAuthStateChanged(e,t,n){const{next:r,error:i,complete:s}=AR(e,t,n);return this._delegate.onAuthStateChanged(r,i,s)}onIdTokenChanged(e,t,n){const{next:r,error:i,complete:s}=AR(e,t,n);return this._delegate.onIdTokenChanged(r,i,s)}sendSignInLinkToEmail(e,t){
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
return async function(e,t,n){var r;const i=iA(e),s={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};function o(e,t){rx(t.handleCodeInApp,i,"argument-error"),t&&YA(i,e,t)}if(null===(r=i._getRecaptchaConfig())||void 0===r?void 0:r.emailPasswordEnabled){const e=await tA(i,s,"getOobCode",!0);o(e,n),await mA(i,e)}else o(s,n),await mA(i,s).catch((async e=>{if("auth/missing-recaptcha-token"!==e.code)return Promise.reject(e);{console.log("Email link sign-in is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.");const e=await tA(i,s,"getOobCode",!0);o(e,n),await mA(i,e)}}))}(this._delegate,e,t)}sendPasswordResetEmail(e,t){return async function(e,t,n){var r;const i=iA(e),s={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};if(null===(r=i._getRecaptchaConfig())||void 0===r?void 0:r.emailPasswordEnabled){const e=await tA(i,s,"getOobCode",!0);n&&YA(i,e,n),await pA(i,e)}else n&&YA(i,s,n),await pA(i,s).catch((async e=>{if("auth/missing-recaptcha-token"!==e.code)return Promise.reject(e);{console.log("Password resets are protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the password reset flow.");const e=await tA(i,s,"getOobCode",!0);n&&YA(i,e,n),await pA(i,e)}}))}(this._delegate,e,t||void 0)}async setPersistence(e){let t;switch(function(e,t){pR(Object.values(fR).includes(t),e,"invalid-persistence-type"),Na()?pR(t!==fR.SESSION,e,"unsupported-persistence-type"):xa()?pR(t===fR.NONE,e,"unsupported-persistence-type"):lR()?pR(t===fR.NONE||t===fR.LOCAL&&Oa(),e,"unsupported-persistence-type"):pR(t===fR.NONE||uR(),e,"unsupported-persistence-type")}(this._delegate,e),e){case fR.SESSION:t=wN;break;case fR.LOCAL:t=await Rx(MN)._isAvailable()?MN:vN;break;case fR.NONE:t=Px;break;default:return XC("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(t)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return ER(this._delegate,async function(e){var t;const n=iA(e);if(await n._initializationPromise,null===(t=n.currentUser)||void 0===t?void 0:t.isAnonymous)return new OA({user:n.currentUser,providerId:null,operationType:"signIn"});const r=await RA(n,{returnSecureToken:!0}),i=await OA._fromIdTokenResponse(n,"signIn",r,!0);return await n._updateCurrentUser(i.user),i}(this._delegate))}signInWithCredential(e){return ER(this._delegate,zA(this._delegate,e))}signInWithCustomToken(e){return ER(this._delegate,QA(this._delegate,e))}signInWithEmailAndPassword(e,t){return ER(this._delegate,function(e,t,n){return zA(ic(e),IA.credential(t,n))}(this._delegate,e,t))}signInWithEmailLink(e,t){return ER(this._delegate,async function(e,t,n){const r=ic(e),i=IA.credentialWithLink(t,n||ox());return rx(i._tenantId===(r.tenantId||null),r,"tenant-id-mismatch"),zA(r,i)}(this._delegate,e,t))}signInWithPhoneNumber(e,t){return TR(this._delegate,async function(e,t,n){const r=iA(e),i=await QN(r,t,ic(n));return new WN(i,(e=>zA(r,e)))}(this._delegate,e,t))}async signInWithPopup(e){return CR(hR(),this._delegate,"operation-not-supported-in-this-environment"),ER(this._delegate,async function(e,t,n){const r=iA(e);tx(e,t,EA);const i=GN(r,n);return new tD(r,"signInViaPopup",t,i).executeNotNull()}(this._delegate,e,_R))}async signInWithRedirect(e){return CR(hR(),this._delegate,"operation-not-supported-in-this-environment"),await gR(this._delegate),uD(this._delegate,e,_R)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return async function(e,t){const{data:n}=await XA(ic(e),t);return n.email}(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function AR(e,t,n){let r=e;"function"!=typeof e&&({next:r,error:t,complete:n}=e);const i=r;return{next:e=>i(e&&kR.getOrCreate(e)),error:t,complete:n}}function NR(e,t){const n=function(e,t){const n=yR();if(!n)return[];const r=Mx(mR,e,t);switch(n.getItem(r)){case fR.NONE:return[Px];case fR.LOCAL:return[MN,wN];case fR.SESSION:return[wN];default:return[]}}(e,t);if("undefined"==typeof self||n.includes(MN)||n.push(MN),"undefined"!=typeof window)for(const e of[vN,wN])n.includes(e)||n.push(e);return n.includes(Px)||n.push(Px),n}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */xR.Persistence=fR;class DR{constructor(){this.providerId="phone",this._delegate=new HN(wR(uh.auth()))}static credential(e,t){return HN.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}DR.PHONE_SIGN_IN_METHOD=HN.PHONE_SIGN_IN_METHOD,DR.PROVIDER_ID=HN.PROVIDER_ID;
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const RR=rx;class OR{constructor(e,t,n=uh.app()){var r;RR(null===(r=n.options)||void 0===r?void 0:r.apiKey,"invalid-api-key",{appName:n.name}),this._delegate=new class{constructor(e,t=Object.assign({},$N),n){this.parameters=t,this.type=zN,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=iA(n),this.isInvisible="invisible"===this.parameters.size,rx("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");const r="string"==typeof e?document.getElementById(e):e;rx(r,this.auth,"argument-error"),this.container=r,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=this.auth.settings.appVerificationDisabledForTesting?new BN:new UN,this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),t=this.getAssertedRecaptcha();return t.getResponse(e)||new Promise((n=>{const r=e=>{e&&(this.tokenChangeListeners.delete(r),n(e))};this.tokenChangeListeners.add(r),this.isInvisible&&t.execute(e)}))}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch((e=>{throw this.renderPromise=null,e}))),this.renderPromise}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach((e=>{this.container.removeChild(e)}))}validateStartingState(){rx(!this.parameters.sitekey,this.auth,"argument-error"),rx(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),rx("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(e){return t=>{if(this.tokenChangeListeners.forEach((e=>e(t))),"function"==typeof e)e(t);else if("string"==typeof e){const n=TN()[e];"function"==typeof n&&n(t)}}}assertNotDestroyed(){rx(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;if(!this.isInvisible){const t=document.createElement("div");e.appendChild(t),e=t}this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){rx(ax()&&!SN(),this.auth,"internal-error"),await function(){let e=null;return new Promise((t=>{"complete"!==document.readyState?(e=()=>t(),window.addEventListener("load",e)):t()})).catch((t=>{throw e&&window.removeEventListener("load",e),t}))}(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);const e=await async function(e){return(await mx(e,"GET","/v1/recaptchaParams")).recaptchaSiteKey||""}(this.auth);rx(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return rx(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}(e,t,n.auth()),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */!function(e){e.INTERNAL.registerComponent(new sc("auth-compat",(e=>{const t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("auth");return new xR(t,n)}),"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:VC,PASSWORD_RESET:UC,RECOVER_EMAIL:BC,REVERT_SECOND_FACTOR_ADDITION:zC,VERIFY_AND_CHANGE_EMAIL:$C,VERIFY_EMAIL:WC}},EmailAuthProvider:IA,FacebookAuthProvider:kA,GithubAuthProvider:xA,GoogleAuthProvider:CA,OAuthProvider:SA,SAMLAuthProvider:NA,PhoneAuthProvider:DR,PhoneMultiFactorGenerator:BD,RecaptchaVerifier:OR,TwitterAuthProvider:DA,Auth:xR,AuthCredential:uA,Error:Pa}).setInstantiationMode("LAZY").setMultipleInstances(!1)),e.registerVersion("@firebase/auth-compat","0.4.2")}(uh);
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class PR{constructor(e,t,n){this._delegate=e,this.task=t,this.ref=n}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class MR{constructor(e,t){this._delegate=e,this._ref=t,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new PR(this._delegate.snapshot,this,this._ref)}then(e,t){return this._delegate.then((t=>{if(e)return e(new PR(t,this,this._ref))}),t)}on(e,t,n,r){let i;return t&&(i="function"==typeof t?e=>t(new PR(e,this,this._ref)):{next:t.next?e=>t.next(new PR(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,i,n||void 0,r||void 0)}}class LR{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map((e=>new FR(e,this._service)))}get items(){return this._delegate.items.map((e=>new FR(e,this._service)))}get nextPageToken(){return this._delegate.nextPageToken||null}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class FR{constructor(e,t){this._delegate=e,this.storage=t}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){const t=function(e,t){return Fl(e,t)}(this._delegate,e);return new FR(t,this.storage)}get root(){return new FR(this._delegate.root,this.storage)}get parent(){const e=this._delegate.parent;return null==e?null:new FR(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new MR(Ql(this._delegate,e,t),this)}putString(e,t=Uu.RAW,n){this._throwIfRoot("putString");const r=zu(t,e),i=Object.assign({},n);return null==i.contentType&&null!=r.contentType&&(i.contentType=r.contentType),new MR(new xl(this._delegate,new Hu(r.data,!0),i),this)}listAll(){return function(e){return Dl(e=ic(e))}(this._delegate).then((e=>new LR(e,this.storage)))}list(e){return function(e,t){return Ol(e=ic(e),t)}(this._delegate,e||void 0).then((e=>new LR(e,this.storage)))}getMetadata(){return Hl(this._delegate)}updateMetadata(e){return function(e,t){return Pl(e=ic(e),t)}(this._delegate,e)}getDownloadURL(){return Gl(this._delegate)}delete(){return this._throwIfRoot("delete"),function(e){return Ll(e=ic(e))}(this._delegate)}_throwIfRoot(e){if(""===this._delegate._location.path)throw Tu(e)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class jR{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(qR(e))throw Iu("ref() expected a child path but got a URL, use refFromURL instead.");return new FR(Kl(this._delegate,e),this)}refFromURL(e){if(!qR(e))throw Iu("refFromURL() expected a full URL but got a child path, use ref() instead.");try{Cu.makeFromUrl(e,this._delegate.host)}catch(e){throw Iu("refFromUrl() expected a valid full URL but got an invalid one.")}return new FR(Kl(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,n={}){Yl(this._delegate,e,t,n)}}function qR(e){return/^[A-Za-z]+:\/\//.test(e)}function VR(e,{instanceIdentifier:t}){const n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("storage").getImmediate({identifier:t});return new jR(n,r)}!function(e){const t={TaskState:bl,TaskEvent:wl,StringFormat:Uu,Storage:jR,Reference:FR};e.INTERNAL.registerComponent(new sc("storage-compat",VR,"PUBLIC").setServiceProps(t).setMultipleInstances(!0)),e.registerVersion("@firebase/storage-compat","0.3.2")}(uh);const UR="@firebase/database",BR="0.14.4";
/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
let zR="";function $R(e){zR=e}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class WR{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),ja(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:Fa(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class QR{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return Va(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const HR=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new WR(t)}}catch(e){}return new QR},GR=HR("localStorage"),KR=HR("sessionStorage"),YR=new mc("@firebase/database"),JR=function(){let e=1;return function(){return e++}}(),XR=function(e){const t=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>=55296&&i<=56319){const t=i-55296;r++,da(r<e.length,"Surrogate pair missing trail surrogate."),i=65536+(t<<10)+(e.charCodeAt(r)-56320)}i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):i<65536?(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t}(e),n=new Ka;n.update(t);const r=n.digest();return ma.encodeByteArray(r)},ZR=function(...e){let t="";for(let n=0;n<e.length;n++){const r=e[n];Array.isArray(r)||r&&"object"==typeof r&&"number"==typeof r.length?t+=ZR.apply(null,r):t+="object"==typeof r?ja(r):r,t+=" "}return t};let eO=null,tO=!0;const nO=function(e,t){da(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(YR.logLevel=lc.VERBOSE,eO=YR.log.bind(YR),t&&KR.set("logging_enabled",!0)):"function"==typeof e?eO=e:(eO=null,KR.remove("logging_enabled"))},rO=function(...e){if(!0===tO&&(tO=!1,null===eO&&!0===KR.get("logging_enabled")&&nO(!0)),eO){const t=ZR.apply(null,e);eO(t)}},iO=function(e){return function(...t){rO(e,...t)}},sO=function(...e){const t="FIREBASE INTERNAL ERROR: "+ZR(...e);YR.error(t)},oO=function(...e){const t=`FIREBASE FATAL ERROR: ${ZR(...e)}`;throw YR.error(t),new Error(t)},aO=function(...e){const t="FIREBASE WARNING: "+ZR(...e);YR.warn(t)},cO=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},uO="[MIN_NAME]",lO="[MAX_NAME]",hO=function(e,t){if(e===t)return 0;if(e===uO||t===lO)return-1;if(t===uO||e===lO)return 1;{const n=_O(e),r=_O(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null!==r?1:e<t?-1:1}},dO=function(e,t){return e===t?0:e<t?-1:1},fO=function(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+ja(t))},pO=function(e){if("object"!=typeof e||null===e)return ja(e);const t=[];for(const n in e)t.push(n);t.sort();let n="{";for(let r=0;r<t.length;r++)0!==r&&(n+=","),n+=ja(t[r]),n+=":",n+=pO(e[t[r]]);return n+="}",n},mO=function(e,t){const n=e.length;if(n<=t)return[e];const r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r};function gO(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}const yO=function(e){da(!cO(e),"Invalid JSON number");const t=1023;let n,r,i,s,o;0===e?(r=0,i=0,n=1/e==-1/0?1:0):(n=e<0,(e=Math.abs(e))>=Math.pow(2,-1022)?(s=Math.min(Math.floor(Math.log(e)/Math.LN2),t),r=s+t,i=Math.round(e*Math.pow(2,52-s)-Math.pow(2,52))):(r=0,i=Math.round(e/Math.pow(2,-1074))));const a=[];for(o=52;o;o-=1)a.push(i%2?1:0),i=Math.floor(i/2);for(o=11;o;o-=1)a.push(r%2?1:0),r=Math.floor(r/2);a.push(n?1:0),a.reverse();const c=a.join("");let u="";for(o=0;o<64;o+=8){let e=parseInt(c.substr(o,8),2).toString(16);1===e.length&&(e="0"+e),u+=e}return u.toLowerCase()};const vO=new RegExp("^-?(0*)\\d{1,10}$"),_O=function(e){if(vO.test(e)){const t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},wO=function(e){try{e()}catch(e){setTimeout((()=>{const t=e.stack||"";throw aO("Exception was thrown by user callback.",t),e}),Math.floor(0))}},bO=function(e,t){const n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n};
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class IO{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null==t||t.get().then((e=>this.appCheck=e))}getToken(e){return this.appCheck?this.appCheck.getToken(e):new Promise(((t,n)=>{setTimeout((()=>{this.appCheck?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){var t;null===(t=this.appCheckProvider)||void 0===t||t.get().then((t=>t.addTokenListener(e)))}notifyForInvalidToken(){aO(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class EO{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit((e=>this.auth_=e))}getToken(e){return this.auth_?this.auth_.getToken(e).catch((e=>e&&"auth/token-not-initialized"===e.code?(rO("Got auth/token-not-initialized error.  Treating as null token."),null):Promise.reject(e))):new Promise(((t,n)=>{setTimeout((()=>{this.auth_?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then((t=>t.addAuthTokenListener(e)))}removeTokenChangeListener(e){this.authProvider_.get().then((t=>t.removeAuthTokenListener(e)))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',aO(e)}}class TO{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}TO.OWNER="owner";
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const SO=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,kO="ac",CO="websocket",xO="long_polling";
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class AO{constructor(e,t,n,r,i=!1,s="",o=!1,a=!1){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=GR.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&GR.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function NO(e,t,n){let r;if(da("string"==typeof t,"typeof type must == string"),da("object"==typeof n,"typeof params must == object"),t===CO)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==xO)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}(function(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams})(e)&&(n.ns=e.namespace);const i=[];return gO(n,((e,t)=>{i.push(e+"="+t)})),r+i.join("&")}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class DO{constructor(){this.counters_={}}incrementCounter(e,t=1){Va(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return wa(void 0,this.counters_)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const RO={},OO={};function PO(e){const t=e.toString();return RO[t]||(RO[t]=new DO),RO[t]}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class MO{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){const e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&wO((()=>{this.onMessage_(e[t])}));if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const LO="start";class FO{constructor(e,t,n,r,i,s,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=s,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=iO(e),this.stats_=PO(t),this.urlFn=e=>(this.appCheckToken&&(e[kO]=this.appCheckToken),NO(t,xO,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new MO(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout((()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null}),Math.floor(3e4)),function(e){if("complete"===document.readyState)e();else{let t=!1;const n=function(){document.body?t||(t=!0,e()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",(()=>{"complete"===document.readyState&&n()})),window.attachEvent("onload",n))}}((()=>{if(this.isClosed_)return;this.scriptTagHolder=new jO(((...e)=>{const[t,n,r,i,s]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===LO)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,(()=>{this.onClosed_()}))):this.onClosed_()}}),((...e)=>{const[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)}),(()=>{this.onClosed_()}),this.urlFn);const e={};e[LO]="t",e.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v="5",this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e[kO]=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&SO.test(location.hostname)&&(e.r="f");const t=this.urlFn(e);this.log_("Connecting via long-poll to "+t),this.scriptTagHolder.addTag(t,(()=>{}))}))}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){FO.forceAllow_=!0}static forceDisallow(){FO.forceDisallow_=!0}static isAvailable(){return!!FO.forceAllow_||!(FO.forceDisallow_||"undefined"==typeof document||null==document.createElement||"object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href)||"object"==typeof Windows&&"object"==typeof Windows.UI)}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){const t=ja(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=ya(t),r=mO(n,1840);for(let e=0;e<r.length;e++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,r.length,r[e]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");const n={dframe:"t"};n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){const t=ja(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class jO{constructor(e,t,n,r){this.onDisconnect=n,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=JR(),window["pLPCommand"+this.uniqueCallbackIdentifier]=e,window["pRTLPCB"+this.uniqueCallbackIdentifier]=t,this.myIFrame=jO.createIFrame_();let n="";if(this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,11)){n='<script>document.domain="'+document.domain+'";<\/script>'}const r="<html><body>"+n+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(r),this.myIFrame.doc.close()}catch(e){rO("frame writing exception"),e.stack&&rO(e.stack),rO(e)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||rO("No IE domain setting required")}catch(t){const n=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout((()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)}),Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e.id=this.myID,e.pw=this.myPW,e.ser=this.currentSerial;let t=this.urlFn(e),n="",r=0;for(;this.pendingSegs.length>0;){if(!(this.pendingSegs[0].d.length+30+n.length<=1870))break;{const e=this.pendingSegs.shift();n=n+"&seg"+r+"="+e.seg+"&ts"+r+"="+e.ts+"&d"+r+"="+e.d,r++}}return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(25e3));this.addTag(e,(()=>{clearTimeout(r),n()}))}addTag(e,t){setTimeout((()=>{try{if(!this.sendNewPolls)return;const n=this.myIFrame.doc.createElement("script");n.type="text/javascript",n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){const e=n.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{rO("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch(e){}}),Math.floor(1))}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let qO=null;"undefined"!=typeof MozWebSocket?qO=MozWebSocket:"undefined"!=typeof WebSocket&&(qO=WebSocket);class VO{constructor(e,t,n,r,i,s,o){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=iO(this.connId),this.stats_=PO(t),this.connURL=VO.connectionURL_(t,s,o,r,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){const s={v:"5"};return"undefined"!=typeof location&&location.hostname&&SO.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),r&&(s[kO]=r),i&&(s.p=i),NO(e,CO,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,GR.set("previous_websocket_failure",!0);try{let e;Ra(),this.mySock=new qO(this.connURL,[],e)}catch(e){this.log_("Error instantiating WebSocket.");const t=e.message||e.data;return t&&this.log_(t),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error.  Closing connection.");const t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){VO.forceDisallow_=!0}static isAvailable(){let e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,n=navigator.userAgent.match(t);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==qO&&!VO.forceDisallow_}static previouslyFailed(){return GR.isInMemoryStorage||!0===GR.get("previous_websocket_failure")}markConnectionHealthy(){GR.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const e=this.frames.join("");this.frames=null;const t=Fa(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(da(null===this.frames,"We already have a frame buffer"),e.length<=6){const t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{const e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();const t=ja(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=mO(t,16384);n.length>1&&this.sendString_(String(n.length));for(let e=0;e<n.length;e++)this.sendString_(n[e])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval((()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()}),Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}VO.responsesRequiredToBeHealthy=2,VO.healthyTimeout=3e4;
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class UO{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[FO,VO]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){const t=VO&&VO.isAvailable();let n=t&&!VO.previouslyFailed();if(e.webSocketOnly&&(t||aO("wss:// URL used, but browser isn't known to support websockets.  Trying anyway."),n=!0),n)this.transports_=[VO];else{const e=this.transports_=[];for(const t of UO.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t);UO.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}UO.globalTransportInitialized_=!1;class BO{constructor(e,t,n,r,i,s,o,a,c,u){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=s,this.onReady_=o,this.onDisconnect_=a,this.onKill_=c,this.lastSessionId=u,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=iO("c:"+this.id+":"),this.transportManager_=new UO(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout((()=>{this.conn_&&this.conn_.open(t,n)}),Math.floor(0));const r=e.healthyTimeout||0;r>0&&(this.healthyTimeout_=bO((()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>102400?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes.  Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>10240?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes.  Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))}),Math.floor(r)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){const t={t:"d",d:e};this.sendData_(t)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if("t"in e){const t=e.t;"a"===t?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const t=fO("t",e),n=fO("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const t=fO("t",e),n=fO("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){const t=fO("t",e);if("d"in e){const n=e.d;if("h"===t){const e=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?sO("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):sO("Unknown control packet command: "+t)}}onHandshake_(e){const t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&aO("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),bO((()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())}),Math.floor(6e4))}onReset_(e){this.log_("Reset packet received.  New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):bO((()=>{this.sendPingOnPrimaryIfNecessary_()}),Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(GR.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class zO{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class $O{constructor(e){this.allowedEvents_=e,this.listeners_={},da(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,t)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});const r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);const r=this.listeners_[e]||[];for(let e=0;e<r.length;e++)if(r[e].callback===t&&(!n||n===r[e].context))return void r.splice(e,1)}validateEventType_(e){da(this.allowedEvents_.find((t=>t===e)),"Unknown event: "+e)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class WO extends $O{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||Ca()||(window.addEventListener("online",(()=>{this.online_||(this.online_=!0,this.trigger("online",!0))}),!1),window.addEventListener("offline",(()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))}),!1))}static getInstance(){return new WO}getInitialEvent(e){return da("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const QO=32,HO=768;class GO{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e<this.pieces_.length;e++)this.pieces_[e].length>0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function KO(){return new GO("")}function YO(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function JO(e){return e.pieces_.length-e.pieceNum_}function XO(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new GO(e.pieces_,t)}function ZO(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function eP(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function tP(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new GO(t,0)}function nP(e,t){const n=[];for(let t=e.pieceNum_;t<e.pieces_.length;t++)n.push(e.pieces_[t]);if(t instanceof GO)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{const e=t.split("/");for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new GO(n,0)}function rP(e){return e.pieceNum_>=e.pieces_.length}function iP(e,t){const n=YO(e),r=YO(t);if(null===n)return t;if(n===r)return iP(XO(e),XO(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function sP(e,t){const n=eP(e,0),r=eP(t,0);for(let e=0;e<n.length&&e<r.length;e++){const t=hO(n[e],r[e]);if(0!==t)return t}return n.length===r.length?0:n.length<r.length?-1:1}function oP(e,t){if(JO(e)!==JO(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function aP(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(JO(e)>JO(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class cP{constructor(e,t){this.errorPrefix_=t,this.parts_=eP(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let e=0;e<this.parts_.length;e++)this.byteLength_+=rc(this.parts_[e]);uP(this)}}function uP(e){if(e.byteLength_>HO)throw new Error(e.errorPrefix_+"has a key path longer than "+HO+" bytes ("+e.byteLength_+").");if(e.parts_.length>QO)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+QO+") or object contains a cycle "+lP(e))}function lP(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class hP extends $O{constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}static getInstance(){return new hP}getInitialEvent(e){return da("visible"===e,"Unknown event type: "+e),[this.visible_]}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const dP=1e3;class fP extends zO{constructor(e,t,n,r,i,s,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=fP.nextPersistentConnectionId_++,this.log_=iO("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=dP,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a&&!Ra())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");hP.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&WO.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){const r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(ja(i)),da(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();const t=new Ta,n={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{const n=e.d;"ok"===e.s?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;const r=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(r),t.promise}listen(e,t,n,r){this.initConnection_();const i=e._queryIdentifier,s=e._path.toString();this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),da(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),da(!this.listens.get(s).has(i),"listen() called twice for same path/queryId.");const o={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(s).set(i,o),this.connected_&&this.sendListen_(o)}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,(n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)}))}sendListen_(e){const t=e.query,n=t._path.toString(),r=t._queryIdentifier;this.log_("Listen on "+n+" for "+r);const i={p:n};e.tag&&(i.q=t._queryObject,i.t=e.tag),i.h=e.hashFn(),this.sendRequest("q",i,(i=>{const s=i.d,o=i.s;fP.warnOnListenWarnings_(s,t);(this.listens.get(n)&&this.listens.get(n).get(r))===e&&(this.log_("listen response",i),"ok"!==o&&this.removeListen_(n,r),e.onComplete&&e.onComplete(o,s))}))}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&Va(e,"w")){const n=Ua(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){const e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();aO(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${e} at ${n} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},(()=>{})),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&40===e.length||function(e){const t=qa(e).claims;return"object"==typeof t&&!0===t.admin}(e))&&(this.log_("Admin auth credential detected.  Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},(()=>{}))}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_,t=function(e){const t=qa(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")}(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,(t=>{const n=t.s,r=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,r))}))}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},(e=>{const t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)}))}unlisten(e,t){const n=e._path.toString(),r=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+r),da(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query");this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);const i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,r){const i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,(e=>{r&&setTimeout((()=>{r(e.s,e.d)}),Math.floor(0))}))}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();const s={p:t,d:n};void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:r}),this.outstandingPutCount_++;const o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(e){const t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,r=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,(n=>{this.log_(t+" response",n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(n.s,n.d)}))}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,(e=>{if("ok"!==e.s){const t=e.d;this.log_("reportStats","Error sending stats: "+t)}}))}}onDataMessage_(e){if("r"in e){this.log_("from server: "+ja(e));const t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):sO("Unrecognized action received from server: "+ja(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){da(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout((()=>{this.establishConnectionTimer_=null,this.establishConnection_()}),Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible.  Reducing delay."),this.reconnectDelay_=dP,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=dP,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline.  Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){if(this.visible_){if(this.lastConnectionEstablishedTime_){(new Date).getTime()-this.lastConnectionEstablishedTime_>3e4&&(this.reconnectDelay_=dP),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible.  Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime();const e=(new Date).getTime()-this.lastConnectionAttemptTime_;let t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;const e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),n=this.onRealtimeDisconnect_.bind(this),r=this.id+":"+fP.nextConnectionId_++,i=this.lastSessionId;let s=!1,o=null;const a=function(){o?o.close():(s=!0,n())},c=function(e){da(o,"sendRequest call when we're not connected not allowed."),o.sendRequest(e)};this.realtime_={close:a,sendRequest:c};const u=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[a,c]=await Promise.all([this.authTokenProvider_.getToken(u),this.appCheckTokenProvider_.getToken(u)]);s?rO("getToken() completed but was canceled"):(rO("getToken() completed. Creating connection."),this.authToken_=a&&a.accessToken,this.appCheckToken_=c&&c.token,o=new BO(r,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,n,(e=>{aO(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")}),i))}catch(e){this.log_("Failed to get token: "+e),s||(this.repoInfo_.nodeAdmin&&aO(e),a())}}}interrupt(e){rO("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){rO("Resuming connection for reason: "+e),delete this.interruptReasons_[e],Ba(this.interruptReasons_)&&(this.reconnectDelay_=dP,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map((e=>pO(e))).join("$"):"default";const r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){const n=new GO(e).toString();let r;if(this.listens.has(n)){const e=this.listens.get(n);r=e.get(t),e.delete(t),0===e.size&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){rO("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){rO("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=3&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const t of e.values())this.sendListen_(t);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){const e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){const e={};e["sdk.js."+zR.replace(/\./g,"-")]=1,Ca()?e["framework.cordova"]=1:Na()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){const e=WO.getInstance().currentlyOnline();return Ba(this.interruptReasons_)&&e}}fP.nextPersistentConnectionId_=0,fP.nextConnectionId_=0;
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class pP{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new pP(e,t)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class mP{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){const n=new pP(uO,e),r=new pP(uO,t);return 0!==this.compare(n,r)}minPost(){return pP.MIN}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let gP;class yP extends mP{static get __EMPTY_NODE(){return gP}static set __EMPTY_NODE(e){gP=e}compare(e,t){return hO(e.name,t.name)}isDefinedOn(e){throw fa("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return pP.MIN}maxPost(){return new pP(lO,gP)}makePost(e,t){return da("string"==typeof e,"KeyIndex indexValue must always be a string."),new pP(e,gP)}toString(){return".key"}}const vP=new yP;
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class _P{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,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(){if(0===this.nodeStack_.length)return null;let e,t=this.nodeStack_.pop();if(e=this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value},this.isReverse_)for(t=t.left;!t.isEmpty();)this.nodeStack_.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack_.push(t),t=t.left;return e}hasNext(){return this.nodeStack_.length>0}peek(){if(0===this.nodeStack_.length)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class wP{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:wP.RED,this.left=null!=r?r:bP.EMPTY_NODE,this.right=null!=i?i:bP.EMPTY_NODE}copy(e,t,n,r,i){return new wP(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}count(){return this.left.count()+1+this.right.count()}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;const i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp_()}removeMin_(){if(this.left.isEmpty())return bP.EMPTY_NODE;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;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return bP.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.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_(){const e=this.copy(null,null,wP.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,wP.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const 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_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}wP.RED=!0,wP.BLACK=!1;class bP{constructor(e,t=bP.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new bP(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,wP.BLACK,null,null))}remove(e){return new bP(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,wP.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t)return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key.  What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new _P(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new _P(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new _P(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new _P(this.root_,null,this.comparator_,!0,e)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function IP(e,t){return hO(e.name,t.name)}function EP(e,t){return hO(e,t)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let TP;bP.EMPTY_NODE=new class{copy(e,t,n,r,i){return this}insert(e,t,n){return new wP(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};const SP=function(e){return"number"==typeof e?"number:"+yO(e):"string:"+e},kP=function(e){if(e.isLeafNode()){const t=e.val();da("string"==typeof t||"number"==typeof t||"object"==typeof t&&Va(t,".sv"),"Priority must be a string or number.")}else da(e===TP||e.isEmpty(),"priority of unexpected type.");da(e===TP||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
let CP,xP,AP;class NP{constructor(e,t=NP.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,da(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),kP(this.priorityNode_)}static set __childrenNodeConstructor(e){CP=e}static get __childrenNodeConstructor(){return CP}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new NP(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:NP.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return rP(e)?this:".priority"===YO(e)?this.priorityNode_:NP.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:NP.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){const n=YO(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(da(".priority"!==n||1===JO(e),".priority must be the last token in a path"),this.updateImmediateChild(n,NP.__childrenNodeConstructor.EMPTY_NODE.updateChild(XO(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+SP(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",e+="number"===t?yO(this.value_):this.value_,this.lazyHash_=XR(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===NP.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof NP.__childrenNodeConstructor?-1:(da(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const t=typeof e.value_,n=typeof this.value_,r=NP.VALUE_TYPE_ORDER.indexOf(t),i=NP.VALUE_TYPE_ORDER.indexOf(n);return da(r>=0,"Unknown leaf type: "+t),da(i>=0,"Unknown leaf type: "+n),r===i?"object"===n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;if(e.isLeafNode()){const t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}return!1}}NP.VALUE_TYPE_ORDER=["object","boolean","number","string"];const DP=new class extends mP{compare(e,t){const n=e.node.getPriority(),r=t.node.getPriority(),i=n.compareTo(r);return 0===i?hO(e.name,t.name):i}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return pP.MIN}maxPost(){return new pP(lO,new NP("[PRIORITY-POST]",AP))}makePost(e,t){const n=xP(e);return new pP(t,new NP("[PRIORITY-POST]",n))}toString(){return".priority"}},RP=Math.log(2);
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class OP{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/RP,10)),this.current_=this.count-1;const n=(r=this.count,parseInt(Array(r+1).join("1"),2));var r;this.bits_=e+1&n}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);return this.current_--,e}}const PP=function(e,t,n,r){e.sort(t);const i=function(t,r){const s=r-t;let o,a;if(0===s)return null;if(1===s)return o=e[t],a=n?n(o):o,new wP(a,o.node,wP.BLACK,null,null);{const c=parseInt(s/2,10)+t,u=i(t,c),l=i(c+1,r);return o=e[c],a=n?n(o):o,new wP(a,o.node,wP.BLACK,u,l)}},s=function(t){let r=null,s=null,o=e.length;const a=function(t,r){const s=o-t,a=o;o-=t;const u=i(s+1,a),l=e[s],h=n?n(l):l;c(new wP(h,l.node,r,null,u))},c=function(e){r?(r.left=e,r=e):(s=e,r=e)};for(let e=0;e<t.count;++e){const n=t.nextBitIsOne(),r=Math.pow(2,t.count-(e+1));n?a(r,wP.BLACK):(a(r,wP.BLACK),a(r,wP.RED))}return s}(new OP(e.length));return new bP(r||t,s)};
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let MP;const LP={};class FP{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return da(LP&&DP,"ChildrenNode.ts has not been loaded"),MP=MP||new FP({".priority":LP},{".priority":DP}),MP}get(e){const t=Ua(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof bP?t:null}hasIndex(e){return Va(this.indexSet_,e.toString())}addIndex(e,t){da(e!==vP,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=!1;const i=t.getIterator(pP.Wrap);let s,o=i.getNext();for(;o;)r=r||e.isDefinedOn(o.node),n.push(o),o=i.getNext();s=r?PP(n,e.getCompare()):LP;const a=e.toString(),c=Object.assign({},this.indexSet_);c[a]=e;const u=Object.assign({},this.indexes_);return u[a]=s,new FP(u,c)}addToIndexes(e,t){const n=za(this.indexes_,((n,r)=>{const i=Ua(this.indexSet_,r);if(da(i,"Missing index implementation for "+r),n===LP){if(i.isDefinedOn(e.node)){const n=[],r=t.getIterator(pP.Wrap);let s=r.getNext();for(;s;)s.name!==e.name&&n.push(s),s=r.getNext();return n.push(e),PP(n,i.getCompare())}return LP}{const r=t.get(e.name);let i=n;return r&&(i=i.remove(new pP(e.name,r))),i.insert(e,e.node)}}));return new FP(n,this.indexSet_)}removeFromIndexes(e,t){const n=za(this.indexes_,(n=>{if(n===LP)return n;{const r=t.get(e.name);return r?n.remove(new pP(e.name,r)):n}}));return new FP(n,this.indexSet_)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let jP;class qP{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&kP(this.priorityNode_),this.children_.isEmpty()&&da(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return jP||(jP=new qP(new bP(EP),null,FP.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||jP}updatePriority(e){return this.children_.isEmpty()?this:new qP(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{const t=this.children_.get(e);return null===t?jP:t}}getChild(e){const t=YO(e);return null===t?this:this.getImmediateChild(t).getChild(XO(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if(da(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{const n=new pP(e,t);let r,i;t.isEmpty()?(r=this.children_.remove(e),i=this.indexMap_.removeFromIndexes(n,this.children_)):(r=this.children_.insert(e,t),i=this.indexMap_.addToIndexes(n,this.children_));const s=r.isEmpty()?jP:this.priorityNode_;return new qP(r,s,i)}}updateChild(e,t){const n=YO(e);if(null===n)return t;{da(".priority"!==YO(e)||1===JO(e),".priority must be the last token in a path");const r=this.getImmediateChild(n).updateChild(XO(e),t);return this.updateImmediateChild(n,r)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let n=0,r=0,i=!0;if(this.forEachChild(DP,((s,o)=>{t[s]=o.val(e),n++,i&&qP.INTEGER_REGEXP_.test(s)?r=Math.max(r,Number(s)):i=!1})),!e&&i&&r<2*n){const e=[];for(const n in t)e[n]=t[n];return e}return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+SP(this.getPriority().val())+":"),this.forEachChild(DP,((t,n)=>{const r=n.hash();""!==r&&(e+=":"+t+":"+r)})),this.lazyHash_=""===e?"":XR(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){const n=r.getPredecessorKey(new pP(e,t));return n?n.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.minKey();return e&&e.name}return this.children_.minKey()}getFirstChild(e){const t=this.getFirstChildName(e);return t?new pP(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.maxKey();return e&&e.name}return this.children_.maxKey()}getLastChild(e){const t=this.getLastChildName(e);return t?new pP(t,this.children_.get(t)):null}forEachChild(e,t){const n=this.resolveIndex_(e);return n?n.inorderTraversal((e=>t(e.name,e.node))):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,(e=>e));{const n=this.children_.getIteratorFrom(e.name,pP.Wrap);let r=n.peek();for(;null!=r&&t.compare(r,e)<0;)n.getNext(),r=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,(e=>e));{const n=this.children_.getReverseIteratorFrom(e.name,pP.Wrap);let r=n.peek();for(;null!=r&&t.compare(r,e)>0;)n.getNext(),r=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===VP?-1:0}withIndex(e){if(e===vP||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new qP(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===vP||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const t=e;if(this.getPriority().equals(t.getPriority())){if(this.children_.count()===t.children_.count()){const e=this.getIterator(DP),n=t.getIterator(DP);let r=e.getNext(),i=n.getNext();for(;r&&i;){if(r.name!==i.name||!r.node.equals(i.node))return!1;r=e.getNext(),i=n.getNext()}return null===r&&null===i}return!1}return!1}}resolveIndex_(e){return e===vP?null:this.indexMap_.get(e.toString())}}qP.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;const VP=new class extends qP{constructor(){super(new bP(EP),qP.EMPTY_NODE,FP.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return qP.EMPTY_NODE}isEmpty(){return!1}};Object.defineProperties(pP,{MIN:{value:new pP(uO,qP.EMPTY_NODE)},MAX:{value:new pP(lO,VP)}}),yP.__EMPTY_NODE=qP.EMPTY_NODE,NP.__childrenNodeConstructor=qP,TP=VP,function(e){AP=e}(VP);
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const UP=!0;function BP(e,t=null){if(null===e)return qP.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),da(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e){return new NP(e,BP(t))}if(e instanceof Array||!UP){let n=qP.EMPTY_NODE;return gO(e,((t,r)=>{if(Va(e,t)&&"."!==t.substring(0,1)){const e=BP(r);!e.isLeafNode()&&e.isEmpty()||(n=n.updateImmediateChild(t,e))}})),n.updatePriority(BP(t))}{const n=[];let r=!1;if(gO(e,((e,t)=>{if("."!==e.substring(0,1)){const i=BP(t);i.isEmpty()||(r=r||!i.getPriority().isEmpty(),n.push(new pP(e,i)))}})),0===n.length)return qP.EMPTY_NODE;const i=PP(n,IP,(e=>e.name),EP);if(r){const e=PP(n,DP.getCompare());return new qP(i,BP(t),new FP({".priority":e},{".priority":DP}))}return new qP(i,BP(t),FP.Default)}}!function(e){xP=e}(BP);
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class zP extends mP{constructor(e){super(),this.indexPath_=e,da(!rP(e)&&".priority"!==YO(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){const n=this.extractChild(e.node),r=this.extractChild(t.node),i=n.compareTo(r);return 0===i?hO(e.name,t.name):i}makePost(e,t){const n=BP(e),r=qP.EMPTY_NODE.updateChild(this.indexPath_,n);return new pP(t,r)}maxPost(){const e=qP.EMPTY_NODE.updateChild(this.indexPath_,VP);return new pP(lO,e)}toString(){return eP(this.indexPath_,0).join("/")}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const $P=new class extends mP{compare(e,t){const n=e.node.compareTo(t.node);return 0===n?hO(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return pP.MIN}maxPost(){return pP.MAX}makePost(e,t){const n=BP(e);return new pP(t,n)}toString(){return".value"}};
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function WP(e){return{type:"value",snapshotNode:e}}function QP(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function HP(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function GP(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class KP{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){da(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const o=e.getImmediateChild(t);return o.getChild(r).equals(n.getChild(r))&&o.isEmpty()===n.isEmpty()?e:(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(HP(t,o)):da(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):o.isEmpty()?s.trackChildChange(QP(t,n)):s.trackChildChange(GP(t,n,o))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(e,t,n){return null!=n&&(e.isLeafNode()||e.forEachChild(DP,((e,r)=>{t.hasChild(e)||n.trackChildChange(HP(e,r))})),t.isLeafNode()||t.forEachChild(DP,((t,r)=>{if(e.hasChild(t)){const i=e.getImmediateChild(t);i.equals(r)||n.trackChildChange(GP(t,r,i))}else n.trackChildChange(QP(t,r))}))),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?qP.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class YP{constructor(e){this.indexedFilter_=new KP(e.getIndex()),this.index_=e.getIndex(),this.startPost_=YP.getStartPost_(e),this.endPost_=YP.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,r,i,s){return this.matches(new pP(t,n))||(n=qP.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){t.isLeafNode()&&(t=qP.EMPTY_NODE);let r=t.withIndex(this.index_);r=r.updatePriority(qP.EMPTY_NODE);const i=this;return t.forEachChild(DP,((e,t)=>{i.matches(new pP(e,t))||(r=r.updateImmediateChild(e,qP.EMPTY_NODE))})),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class JP{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e),this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e),this.withinStartPost=e=>{const t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{const t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new YP(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,r,i,s){return this.rangedFilter_.matches(new pP(t,n))||(n=qP.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,s):this.fullLimitUpdateChild_(e,t,n,i,s)}updateFullNode(e,t,n){let r;if(t.isLeafNode()||t.isEmpty())r=qP.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<t.numChildren()&&t.isIndexed(this.index_)){let e;r=qP.EMPTY_NODE.withIndex(this.index_),e=this.reverse_?t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;e.hasNext()&&n<this.limit_;){const t=e.getNext();if(this.withinDirectionalStart(t)){if(!this.withinDirectionalEnd(t))break;r=r.updateImmediateChild(t.name,t.node),n++}}}else{let e;r=t.withIndex(this.index_),r=r.updatePriority(qP.EMPTY_NODE),e=this.reverse_?r.getReverseIterator(this.index_):r.getIterator(this.index_);let n=0;for(;e.hasNext();){const t=e.getNext();n<this.limit_&&this.withinDirectionalStart(t)&&this.withinDirectionalEnd(t)?n++:r=r.updateImmediateChild(t.name,qP.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let s;if(this.reverse_){const e=this.index_.getCompare();s=(t,n)=>e(n,t)}else s=this.index_.getCompare();const o=e;da(o.numChildren()===this.limit_,"");const a=new pP(t,n),c=this.reverse_?o.getFirstChild(this.index_):o.getLastChild(this.index_),u=this.rangedFilter_.matches(a);if(o.hasChild(t)){const e=o.getImmediateChild(t);let l=r.getChildAfterChild(this.index_,c,this.reverse_);for(;null!=l&&(l.name===t||o.hasChild(l.name));)l=r.getChildAfterChild(this.index_,l,this.reverse_);const h=null==l?1:s(l,a);if(u&&!n.isEmpty()&&h>=0)return null!=i&&i.trackChildChange(GP(t,n,e)),o.updateImmediateChild(t,n);{null!=i&&i.trackChildChange(HP(t,e));const n=o.updateImmediateChild(t,qP.EMPTY_NODE);return null!=l&&this.rangedFilter_.matches(l)?(null!=i&&i.trackChildChange(QP(l.name,l.node)),n.updateImmediateChild(l.name,l.node)):n}}return n.isEmpty()?e:u&&s(c,a)>=0?(null!=i&&(i.trackChildChange(HP(c.name,c.node)),i.trackChildChange(QP(t,n))),o.updateImmediateChild(t,n).updateImmediateChild(c.name,qP.EMPTY_NODE)):e}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class XP{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=DP}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return da(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return da(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:uO}hasEnd(){return this.endSet_}getIndexEndValue(){return da(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return da(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:lO}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return da(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===DP}copy(){const e=new XP;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function ZP(e,t,n){const r=e.copy();return r.startSet_=!0,void 0===t&&(t=null),r.indexStartValue_=t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function eM(e,t,n){const r=e.copy();return r.endSet_=!0,void 0===t&&(t=null),r.indexEndValue_=t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function tM(e,t){const n=e.copy();return n.index_=t,n}function nM(e){const t={};if(e.isDefault())return t;let n;if(e.index_===DP?n="$priority":e.index_===$P?n="$value":e.index_===vP?n="$key":(da(e.index_ instanceof zP,"Unrecognized index type!"),n=e.index_.toString()),t.orderBy=ja(n),e.startSet_){const n=e.startAfterSet_?"startAfter":"startAt";t[n]=ja(e.indexStartValue_),e.startNameSet_&&(t[n]+=","+ja(e.indexStartName_))}if(e.endSet_){const n=e.endBeforeSet_?"endBefore":"endAt";t[n]=ja(e.indexEndValue_),e.endNameSet_&&(t[n]+=","+ja(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function rM(e){const t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==DP&&(t.i=e.index_.toString()),t}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class iM extends zO{constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=iO("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(da(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,n,r){const i=e._path.toString();this.log_("Listen called for "+i+" "+e._queryIdentifier);const s=iM.getListenId_(e,n),o={};this.listens_[s]=o;const a=nM(e._queryParams);this.restRequest_(i+".json",a,((e,t)=>{let a=t;if(404===e&&(a=null,e=null),null===e&&this.onDataUpdate_(i,a,!1,n),Ua(this.listens_,s)===o){let t;t=e?401===e?"permission_denied":"rest_error:"+e:"ok",r(t,null)}}))}unlisten(e,t){const n=iM.getListenId_(e,t);delete this.listens_[n]}get(e){const t=nM(e._queryParams),n=e._path.toString(),r=new Ta;return this.restRequest_(n+".json",t,((e,t)=>{let i=t;404===e&&(i=null,e=null),null===e?(this.onDataUpdate_(n,i,!1,null),r.resolve(i)):r.reject(new Error(i))})),r.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then((([r,i])=>{r&&r.accessToken&&(t.auth=r.accessToken),i&&i.token&&(t.ac=i.token);const s=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+Qa(t);this.log_("Sending REST request for "+s);const o=new XMLHttpRequest;o.onreadystatechange=()=>{if(n&&4===o.readyState){this.log_("REST Response for "+s+" received. status:",o.status,"response:",o.responseText);let e=null;if(o.status>=200&&o.status<300){try{e=Fa(o.responseText)}catch(e){aO("Failed to parse JSON response for "+s+": "+o.responseText)}n(null,e)}else 401!==o.status&&404!==o.status&&aO("Got unsuccessful REST response for "+s+" Status: "+o.status),n(o.status);n=null}},o.open("GET",s,!0),o.send()}))}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class sM{constructor(){this.rootNode_=qP.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function oM(){return{value:null,children:new Map}}function aM(e,t,n){if(rP(t))e.value=n,e.children.clear();else if(null!==e.value)e.value=e.value.updateChild(t,n);else{const r=YO(t);e.children.has(r)||e.children.set(r,oM());aM(e.children.get(r),t=XO(t),n)}}function cM(e,t){if(rP(t))return e.value=null,e.children.clear(),!0;if(null!==e.value){if(e.value.isLeafNode())return!1;{const n=e.value;return e.value=null,n.forEachChild(DP,((t,n)=>{aM(e,new GO(t),n)})),cM(e,t)}}if(e.children.size>0){const n=YO(t);if(t=XO(t),e.children.has(n)){cM(e.children.get(n),t)&&e.children.delete(n)}return 0===e.children.size}return!0}function uM(e,t,n){null!==e.value?n(t,e.value):function(e,t){e.children.forEach(((e,n)=>{t(n,e)}))}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e,((e,r)=>{uM(r,new GO(t.toString()+"/"+e),n)}))}class lM{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t=Object.assign({},e);return this.last_&&gO(this.last_,((e,n)=>{t[e]=t[e]-n})),this.last_=e,t}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class hM{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new lM(e);const n=1e4+2e4*Math.random();bO(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){const e=this.statsListener_.get(),t={};let n=!1;gO(e,((e,r)=>{r>0&&Va(this.statsToReport_,e)&&(t[e]=r,n=!0)})),n&&this.server_.reportStats(t),bO(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */var dM;function fM(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */!function(e){e[e.OVERWRITE=0]="OVERWRITE",e[e.MERGE=1]="MERGE",e[e.ACK_USER_WRITE=2]="ACK_USER_WRITE",e[e.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(dM||(dM={}));class pM{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=dM.ACK_USER_WRITE,this.source={fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}operationForChild(e){if(rP(this.path)){if(null!=this.affectedTree.value)return da(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new GO(e));return new pM(KO(),t,this.revert)}}return da(YO(this.path)===e,"operationForChild called for unrelated child."),new pM(XO(this.path),this.affectedTree,this.revert)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class mM{constructor(e,t){this.source=e,this.path=t,this.type=dM.LISTEN_COMPLETE}operationForChild(e){return rP(this.path)?new mM(this.source,KO()):new mM(this.source,XO(this.path))}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class gM{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=dM.OVERWRITE}operationForChild(e){return rP(this.path)?new gM(this.source,KO(),this.snap.getImmediateChild(e)):new gM(this.source,XO(this.path),this.snap)}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class yM{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=dM.MERGE}operationForChild(e){if(rP(this.path)){const t=this.children.subtree(new GO(e));return t.isEmpty()?null:t.value?new gM(this.source,KO(),t.value):new yM(this.source,KO(),t)}return da(YO(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new yM(this.source,XO(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class vM{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(rP(e))return this.isFullyInitialized()&&!this.filtered_;const t=YO(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class _M{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function wM(e,t,n,r,i,s){const o=r.filter((e=>e.type===n));o.sort(((t,n)=>function(e,t,n){if(null==t.childName||null==n.childName)throw fa("Should only compare child_ events.");const r=new pP(t.childName,t.snapshotNode),i=new pP(n.childName,n.snapshotNode);return e.index_.compare(r,i)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e,t,n))),o.forEach((n=>{const r=function(e,t,n){return"value"===t.type||"child_removed"===t.type||(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_)),t}(e,n,s);i.forEach((i=>{i.respondsTo(n.type)&&t.push(i.createEvent(r,e.query_))}))}))}function bM(e,t){return{eventCache:e,serverCache:t}}function IM(e,t,n,r){return bM(new vM(t,n,r),e.serverCache)}function EM(e,t,n,r){return bM(e.eventCache,new vM(t,n,r))}function TM(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function SM(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let kM;class CM{constructor(e,t=(()=>(kM||(kM=new bP(dO)),kM))()){this.value=e,this.children=t}static fromObject(e){let t=new CM(null);return gO(e,((e,n)=>{t=t.set(new GO(e),n)})),t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:KO(),value:this.value};if(rP(e))return null;{const n=YO(e),r=this.children.get(n);if(null!==r){const i=r.findRootMostMatchingPathAndValue(XO(e),t);if(null!=i){return{path:nP(new GO(n),i.path),value:i.value}}return null}return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,(()=>!0))}subtree(e){if(rP(e))return this;{const t=YO(e),n=this.children.get(t);return null!==n?n.subtree(XO(e)):new CM(null)}}set(e,t){if(rP(e))return new CM(t,this.children);{const n=YO(e),r=(this.children.get(n)||new CM(null)).set(XO(e),t),i=this.children.insert(n,r);return new CM(this.value,i)}}remove(e){if(rP(e))return this.children.isEmpty()?new CM(null):new CM(null,this.children);{const t=YO(e),n=this.children.get(t);if(n){const r=n.remove(XO(e));let i;return i=r.isEmpty()?this.children.remove(t):this.children.insert(t,r),null===this.value&&i.isEmpty()?new CM(null):new CM(this.value,i)}return this}}get(e){if(rP(e))return this.value;{const t=YO(e),n=this.children.get(t);return n?n.get(XO(e)):null}}setTree(e,t){if(rP(e))return t;{const n=YO(e),r=(this.children.get(n)||new CM(null)).setTree(XO(e),t);let i;return i=r.isEmpty()?this.children.remove(n):this.children.insert(n,r),new CM(this.value,i)}}fold(e){return this.fold_(KO(),e)}fold_(e,t){const n={};return this.children.inorderTraversal(((r,i)=>{n[r]=i.fold_(nP(e,r),t)})),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,KO(),t)}findOnPath_(e,t,n){const r=!!this.value&&n(t,this.value);if(r)return r;if(rP(e))return null;{const r=YO(e),i=this.children.get(r);return i?i.findOnPath_(XO(e),nP(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,KO(),t)}foreachOnPath_(e,t,n){if(rP(e))return this;{this.value&&n(t,this.value);const r=YO(e),i=this.children.get(r);return i?i.foreachOnPath_(XO(e),nP(t,r),n):new CM(null)}}foreach(e){this.foreach_(KO(),e)}foreach_(e,t){this.children.inorderTraversal(((n,r)=>{r.foreach_(nP(e,n),t)})),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal(((t,n)=>{n.value&&e(t,n.value)}))}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class xM{constructor(e){this.writeTree_=e}static empty(){return new xM(new CM(null))}}function AM(e,t,n){if(rP(t))return new xM(new CM(n));{const r=e.writeTree_.findRootMostValueAndPath(t);if(null!=r){const i=r.path;let s=r.value;const o=iP(i,t);return s=s.updateChild(o,n),new xM(e.writeTree_.set(i,s))}{const r=new CM(n),i=e.writeTree_.setTree(t,r);return new xM(i)}}}function NM(e,t,n){let r=e;return gO(n,((e,n)=>{r=AM(r,nP(t,e),n)})),r}function DM(e,t){if(rP(t))return xM.empty();{const n=e.writeTree_.setTree(t,new CM(null));return new xM(n)}}function RM(e,t){return null!=OM(e,t)}function OM(e,t){const n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(iP(n.path,t)):null}function PM(e){const t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(DP,((e,n)=>{t.push(new pP(e,n))})):e.writeTree_.children.inorderTraversal(((e,n)=>{null!=n.value&&t.push(new pP(e,n.value))})),t}function MM(e,t){if(rP(t))return e;{const n=OM(e,t);return new xM(null!=n?new CM(n):e.writeTree_.subtree(t))}}function LM(e){return e.writeTree_.isEmpty()}function FM(e,t){return jM(KO(),e.writeTree_,t)}function jM(e,t,n){if(null!=t.value)return n.updateChild(e,t.value);{let r=null;return t.children.inorderTraversal(((t,i)=>{".priority"===t?(da(null!==i.value,"Priority writes must always be leaf nodes"),r=i.value):n=jM(nP(e,t),i,n)})),n.getChild(e).isEmpty()||null===r||(n=n.updateChild(nP(e,".priority"),r)),n}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function qM(e,t){return XM(t,e)}function VM(e,t){const n=e.allWrites.findIndex((e=>e.writeId===t));da(n>=0,"removeWrite called with nonexistent writeId.");const r=e.allWrites[n];e.allWrites.splice(n,1);let i=r.visible,s=!1,o=e.allWrites.length-1;for(;i&&o>=0;){const t=e.allWrites[o];t.visible&&(o>=n&&UM(t,r.path)?i=!1:aP(r.path,t.path)&&(s=!0)),o--}if(i){if(s)return function(e){e.visibleWrites=zM(e.allWrites,BM,KO()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1}(e),!0;if(r.snap)e.visibleWrites=DM(e.visibleWrites,r.path);else{gO(r.children,(t=>{e.visibleWrites=DM(e.visibleWrites,nP(r.path,t))}))}return!0}return!1}function UM(e,t){if(e.snap)return aP(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&aP(nP(e.path,n),t))return!0;return!1}function BM(e){return e.visible}function zM(e,t,n){let r=xM.empty();for(let i=0;i<e.length;++i){const s=e[i];if(t(s)){const e=s.path;let t;if(s.snap)aP(n,e)?(t=iP(n,e),r=AM(r,t,s.snap)):aP(e,n)&&(t=iP(e,n),r=AM(r,KO(),s.snap.getChild(t)));else{if(!s.children)throw fa("WriteRecord should have .snap or .children");if(aP(n,e))t=iP(n,e),r=NM(r,t,s.children);else if(aP(e,n))if(t=iP(e,n),rP(t))r=NM(r,KO(),s.children);else{const e=Ua(s.children,YO(t));if(e){const n=e.getChild(XO(t));r=AM(r,KO(),n)}}}}}return r}function $M(e,t,n,r,i){if(r||i){const s=MM(e.visibleWrites,t);if(!i&&LM(s))return n;if(i||null!=n||RM(s,KO())){const s=function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(aP(e.path,t)||aP(t,e.path))};return FM(zM(e.allWrites,s,t),n||qP.EMPTY_NODE)}return null}{const r=OM(e.visibleWrites,t);if(null!=r)return r;{const r=MM(e.visibleWrites,t);if(LM(r))return n;if(null!=n||RM(r,KO())){return FM(r,n||qP.EMPTY_NODE)}return null}}}function WM(e,t,n,r){return $M(e.writeTree,e.treePath,t,n,r)}function QM(e,t){return function(e,t,n){let r=qP.EMPTY_NODE;const i=OM(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(DP,((e,t)=>{r=r.updateImmediateChild(e,t)})),r;if(n){const i=MM(e.visibleWrites,t);return n.forEachChild(DP,((e,t)=>{const n=FM(MM(i,new GO(e)),t);r=r.updateImmediateChild(e,n)})),PM(i).forEach((e=>{r=r.updateImmediateChild(e.name,e.node)})),r}return PM(MM(e.visibleWrites,t)).forEach((e=>{r=r.updateImmediateChild(e.name,e.node)})),r}(e.writeTree,e.treePath,t)}function HM(e,t,n,r){return function(e,t,n,r,i){da(r||i,"Either existingEventSnap or existingServerSnap must exist");const s=nP(t,n);if(RM(e.visibleWrites,s))return null;{const t=MM(e.visibleWrites,s);return LM(t)?i.getChild(n):FM(t,i.getChild(n))}}(e.writeTree,e.treePath,t,n,r)}function GM(e,t){return function(e,t){return OM(e.visibleWrites,t)}(e.writeTree,nP(e.treePath,t))}function KM(e,t,n,r,i,s){return function(e,t,n,r,i,s,o){let a;const c=MM(e.visibleWrites,t),u=OM(c,KO());if(null!=u)a=u;else{if(null==n)return[];a=FM(c,n)}if(a=a.withIndex(o),a.isEmpty()||a.isLeafNode())return[];{const e=[],t=o.getCompare(),n=s?a.getReverseIteratorFrom(r,o):a.getIteratorFrom(r,o);let c=n.getNext();for(;c&&e.length<i;)0!==t(c,r)&&e.push(c),c=n.getNext();return e}}(e.writeTree,e.treePath,t,n,r,i,s)}function YM(e,t,n){return function(e,t,n,r){const i=nP(t,n),s=OM(e.visibleWrites,i);if(null!=s)return s;if(r.isCompleteForChild(n))return FM(MM(e.visibleWrites,i),r.getNode().getImmediateChild(n));return null}(e.writeTree,e.treePath,t,n)}function JM(e,t){return XM(nP(e.treePath,t),e.writeTree)}function XM(e,t){return{treePath:e,writeTree:t}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class ZM{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type,n=e.childName;da("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),da(".priority"!==n,"Only non-priority child changes can be tracked.");const r=this.changeMap.get(n);if(r){const i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,GP(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,HP(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,QP(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw fa("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,GP(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const eL=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class tL{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{const t=null!=this.optCompleteServerCache_?new vM(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return YM(this.writes_,e,t)}}getChildAfterChild(e,t,n){const r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:SM(this.viewCache_),i=KM(this.writes_,r,t,1,n,e);return 0===i.length?null:i[0]}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function nL(e,t,n,r,i){const s=new ZM;let o,a;if(n.type===dM.OVERWRITE){const c=n;c.source.fromUser?o=sL(e,t,c.path,c.snap,r,i,s):(da(c.source.fromServer,"Unknown source."),a=c.source.tagged||t.serverCache.isFiltered()&&!rP(c.path),o=iL(e,t,c.path,c.snap,r,i,a,s))}else if(n.type===dM.MERGE){const c=n;c.source.fromUser?o=function(e,t,n,r,i,s,o){let a=t;return r.foreach(((r,c)=>{const u=nP(n,r);oL(t,YO(u))&&(a=sL(e,a,u,c,i,s,o))})),r.foreach(((r,c)=>{const u=nP(n,r);oL(t,YO(u))||(a=sL(e,a,u,c,i,s,o))})),a}(e,t,c.path,c.children,r,i,s):(da(c.source.fromServer,"Unknown source."),a=c.source.tagged||t.serverCache.isFiltered(),o=cL(e,t,c.path,c.children,r,i,a,s))}else if(n.type===dM.ACK_USER_WRITE){const a=n;o=a.revert?function(e,t,n,r,i,s){let o;if(null!=GM(r,n))return t;{const a=new tL(r,t,i),c=t.eventCache.getNode();let u;if(rP(n)||".priority"===YO(n)){let n;if(t.serverCache.isFullyInitialized())n=WM(r,SM(t));else{const e=t.serverCache.getNode();da(e instanceof qP,"serverChildren would be complete if leaf node"),n=QM(r,e)}u=e.filter.updateFullNode(c,n,s)}else{const i=YO(n);let l=YM(r,i,t.serverCache);null==l&&t.serverCache.isCompleteForChild(i)&&(l=c.getImmediateChild(i)),u=null!=l?e.filter.updateChild(c,i,l,XO(n),a,s):t.eventCache.getNode().hasChild(i)?e.filter.updateChild(c,i,qP.EMPTY_NODE,XO(n),a,s):c,u.isEmpty()&&t.serverCache.isFullyInitialized()&&(o=WM(r,SM(t)),o.isLeafNode()&&(u=e.filter.updateFullNode(u,o,s)))}return o=t.serverCache.isFullyInitialized()||null!=GM(r,KO()),IM(t,u,o,e.filter.filtersNodes())}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e,t,a.path,r,i,s):function(e,t,n,r,i,s,o){if(null!=GM(i,n))return t;const a=t.serverCache.isFiltered(),c=t.serverCache;if(null!=r.value){if(rP(n)&&c.isFullyInitialized()||c.isCompleteForPath(n))return iL(e,t,n,c.getNode().getChild(n),i,s,a,o);if(rP(n)){let r=new CM(null);return c.getNode().forEachChild(vP,((e,t)=>{r=r.set(new GO(e),t)})),cL(e,t,n,r,i,s,a,o)}return t}{let u=new CM(null);return r.foreach(((e,t)=>{const r=nP(n,e);c.isCompleteForPath(r)&&(u=u.set(e,c.getNode().getChild(r)))})),cL(e,t,n,u,i,s,a,o)}}(e,t,a.path,a.affectedTree,r,i,s)}else{if(n.type!==dM.LISTEN_COMPLETE)throw fa("Unknown operation type: "+n.type);o=function(e,t,n,r,i){const s=t.serverCache,o=EM(t,s.getNode(),s.isFullyInitialized()||rP(n),s.isFiltered());return rL(e,o,n,r,eL,i)}(e,t,n.path,r,s)}const c=s.getChanges();return function(e,t,n){const r=t.eventCache;if(r.isFullyInitialized()){const i=r.getNode().isLeafNode()||r.getNode().isEmpty(),s=TM(e);(n.length>0||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(WP(TM(t)))}}(t,o,c),{viewCache:o,changes:c}}function rL(e,t,n,r,i,s){const o=t.eventCache;if(null!=GM(r,n))return t;{let a,c;if(rP(n))if(da(t.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t.serverCache.isFiltered()){const n=SM(t),i=QM(r,n instanceof qP?n:qP.EMPTY_NODE);a=e.filter.updateFullNode(t.eventCache.getNode(),i,s)}else{const n=WM(r,SM(t));a=e.filter.updateFullNode(t.eventCache.getNode(),n,s)}else{const u=YO(n);if(".priority"===u){da(1===JO(n),"Can't have a priority with additional path components");const i=o.getNode();c=t.serverCache.getNode();const s=HM(r,n,i,c);a=null!=s?e.filter.updatePriority(i,s):o.getNode()}else{const l=XO(n);let h;if(o.isCompleteForChild(u)){c=t.serverCache.getNode();const e=HM(r,n,o.getNode(),c);h=null!=e?o.getNode().getImmediateChild(u).updateChild(l,e):o.getNode().getImmediateChild(u)}else h=YM(r,u,t.serverCache);a=null!=h?e.filter.updateChild(o.getNode(),u,h,l,i,s):o.getNode()}}return IM(t,a,o.isFullyInitialized()||rP(n),e.filter.filtersNodes())}}function iL(e,t,n,r,i,s,o,a){const c=t.serverCache;let u;const l=o?e.filter:e.filter.getIndexedFilter();if(rP(n))u=l.updateFullNode(c.getNode(),r,null);else if(l.filtersNodes()&&!c.isFiltered()){const e=c.getNode().updateChild(n,r);u=l.updateFullNode(c.getNode(),e,null)}else{const e=YO(n);if(!c.isCompleteForPath(n)&&JO(n)>1)return t;const i=XO(n),s=c.getNode().getImmediateChild(e).updateChild(i,r);u=".priority"===e?l.updatePriority(c.getNode(),s):l.updateChild(c.getNode(),e,s,i,eL,null)}const h=EM(t,u,c.isFullyInitialized()||rP(n),l.filtersNodes());return rL(e,h,n,i,new tL(i,h,s),a)}function sL(e,t,n,r,i,s,o){const a=t.eventCache;let c,u;const l=new tL(i,t,s);if(rP(n))u=e.filter.updateFullNode(t.eventCache.getNode(),r,o),c=IM(t,u,!0,e.filter.filtersNodes());else{const i=YO(n);if(".priority"===i)u=e.filter.updatePriority(t.eventCache.getNode(),r),c=IM(t,u,a.isFullyInitialized(),a.isFiltered());else{const s=XO(n),u=a.getNode().getImmediateChild(i);let h;if(rP(s))h=r;else{const e=l.getCompleteChild(i);h=null!=e?".priority"===ZO(s)&&e.getChild(tP(s)).isEmpty()?e:e.updateChild(s,r):qP.EMPTY_NODE}if(u.equals(h))c=t;else{c=IM(t,e.filter.updateChild(a.getNode(),i,h,s,l,o),a.isFullyInitialized(),e.filter.filtersNodes())}}}return c}function oL(e,t){return e.eventCache.isCompleteForChild(t)}function aL(e,t,n){return n.foreach(((e,n)=>{t=t.updateChild(e,n)})),t}function cL(e,t,n,r,i,s,o,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let c,u=t;c=rP(n)?r:new CM(null).setTree(n,r);const l=t.serverCache.getNode();return c.children.inorderTraversal(((n,r)=>{if(l.hasChild(n)){const c=aL(0,t.serverCache.getNode().getImmediateChild(n),r);u=iL(e,u,new GO(n),c,i,s,o,a)}})),c.children.inorderTraversal(((n,r)=>{const c=!t.serverCache.isCompleteForChild(n)&&null===r.value;if(!l.hasChild(n)&&!c){const c=aL(0,t.serverCache.getNode().getImmediateChild(n),r);u=iL(e,u,new GO(n),c,i,s,o,a)}})),u}class uL{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new KP(n.getIndex()),i=(s=n).loadsAllData()?new KP(s.getIndex()):s.hasLimit()?new JP(s):new YP(s);var s;this.processor_=function(e){return{filter:e}}(i);const o=t.serverCache,a=t.eventCache,c=r.updateFullNode(qP.EMPTY_NODE,o.getNode(),null),u=i.updateFullNode(qP.EMPTY_NODE,a.getNode(),null),l=new vM(c,o.isFullyInitialized(),r.filtersNodes()),h=new vM(u,a.isFullyInitialized(),i.filtersNodes());this.viewCache_=bM(h,l),this.eventGenerator_=new _M(this.query_)}get query(){return this.query_}}function lL(e,t){const n=SM(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!rP(t)&&!n.getImmediateChild(YO(t)).isEmpty())?n.getChild(t):null}function hL(e){return 0===e.eventRegistrations_.length}function dL(e,t,n){const r=[];if(n){da(null==t,"A cancel should cancel all event registrations.");const i=e.query._path;e.eventRegistrations_.forEach((e=>{const t=e.createCancelEvent(n,i);t&&r.push(t)}))}if(t){let n=[];for(let r=0;r<e.eventRegistrations_.length;++r){const i=e.eventRegistrations_[r];if(i.matches(t)){if(t.hasAnyCallback()){n=n.concat(e.eventRegistrations_.slice(r+1));break}}else n.push(i)}e.eventRegistrations_=n}else e.eventRegistrations_=[];return r}function fL(e,t,n,r){t.type===dM.MERGE&&null!==t.source.queryId&&(da(SM(e.viewCache_),"We should always have a full cache before handling merges"),da(TM(e.viewCache_),"Missing event cache, even though we have a server cache"));const i=e.viewCache_,s=nL(e.processor_,i,t,n,r);var o,a;return o=e.processor_,a=s.viewCache,da(a.eventCache.getNode().isIndexed(o.filter.getIndex()),"Event snap not indexed"),da(a.serverCache.getNode().isIndexed(o.filter.getIndex()),"Server snap not indexed"),da(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,pL(e,s.changes,s.viewCache.eventCache.getNode(),null)}function pL(e,t,n,r){const i=r?[r]:e.eventRegistrations_;return function(e,t,n,r){const i=[],s=[];return t.forEach((t=>{var n;"child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&s.push((n=t.childName,{type:"child_moved",snapshotNode:t.snapshotNode,childName:n}))})),wM(e,i,"child_removed",t,r,n),wM(e,i,"child_added",t,r,n),wM(e,i,"child_moved",s,r,n),wM(e,i,"child_changed",t,r,n),wM(e,i,"value",t,r,n),i}(e.eventGenerator_,t,n,i)}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let mL,gL;class yL{constructor(){this.views=new Map}}function vL(e,t,n,r){const i=t.source.queryId;if(null!==i){const s=e.views.get(i);return da(null!=s,"SyncTree gave us an op for an invalid query."),fL(s,t,n,r)}{let i=[];for(const s of e.views.values())i=i.concat(fL(s,t,n,r));return i}}function _L(e,t,n,r,i){const s=t._queryIdentifier,o=e.views.get(s);if(!o){let e=WM(n,i?r:null),s=!1;e?s=!0:r instanceof qP?(e=QM(n,r),s=!1):(e=qP.EMPTY_NODE,s=!1);const o=bM(new vM(e,s,!1),new vM(r,i,!1));return new uL(t,o)}return o}function wL(e,t,n,r,i,s){const o=_L(e,t,r,i,s);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),function(e,t){e.eventRegistrations_.push(t)}(o,n),function(e,t){const n=e.viewCache_.eventCache,r=[];n.getNode().isLeafNode()||n.getNode().forEachChild(DP,((e,t)=>{r.push(QP(e,t))}));return n.isFullyInitialized()&&r.push(WP(n.getNode())),pL(e,r,n.getNode(),t)}(o,n)}function bL(e,t,n,r){const i=t._queryIdentifier,s=[];let o=[];const a=kL(e);if("default"===i)for(const[t,i]of e.views.entries())o=o.concat(dL(i,n,r)),hL(i)&&(e.views.delete(t),i.query._queryParams.loadsAllData()||s.push(i.query));else{const t=e.views.get(i);t&&(o=o.concat(dL(t,n,r)),hL(t)&&(e.views.delete(i),t.query._queryParams.loadsAllData()||s.push(t.query)))}return a&&!kL(e)&&s.push(new(da(mL,"Reference.ts has not been loaded"),mL)(t._repo,t._path)),{removed:s,events:o}}function IL(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function EL(e,t){let n=null;for(const r of e.views.values())n=n||lL(r,t);return n}function TL(e,t){if(t._queryParams.loadsAllData())return CL(e);{const n=t._queryIdentifier;return e.views.get(n)}}function SL(e,t){return null!=TL(e,t)}function kL(e){return null!=CL(e)}function CL(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let xL=1;class AL{constructor(e){this.listenProvider_=e,this.syncPointTree_=new CM(null),this.pendingWriteTree_={visibleWrites:xM.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function NL(e,t,n,r,i){return function(e,t,n,r,i){da(r>e.lastWriteId,"Stacking an older write on top of newer ones"),void 0===i&&(i=!0),e.allWrites.push({path:t,snap:n,writeId:r,visible:i}),i&&(e.visibleWrites=AM(e.visibleWrites,t,n)),e.lastWriteId=r}(e.pendingWriteTree_,t,n,r,i),i?qL(e,new gM({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,n)):[]}function DL(e,t,n,r){!function(e,t,n,r){da(r>e.lastWriteId,"Stacking an older merge on top of newer ones"),e.allWrites.push({path:t,children:n,writeId:r,visible:!0}),e.visibleWrites=NM(e.visibleWrites,t,n),e.lastWriteId=r}(e.pendingWriteTree_,t,n,r);const i=CM.fromObject(n);return qL(e,new yM({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,i))}function RL(e,t,n=!1){const r=function(e,t){for(let n=0;n<e.allWrites.length;n++){const r=e.allWrites[n];if(r.writeId===t)return r}return null}(e.pendingWriteTree_,t);if(VM(e.pendingWriteTree_,t)){let t=new CM(null);return null!=r.snap?t=t.set(KO(),!0):gO(r.children,(e=>{t=t.set(new GO(e),!0)})),qL(e,new pM(r.path,t,n))}return[]}function OL(e,t,n){return qL(e,new gM({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,n))}function PL(e,t,n,r,i=!1){const s=t._path,o=e.syncPointTree_.get(s);let a=[];if(o&&("default"===t._queryIdentifier||SL(o,t))){const c=bL(o,t,n,r);0===o.views.size&&(e.syncPointTree_=e.syncPointTree_.remove(s));const u=c.removed;if(a=c.events,!i){const n=-1!==u.findIndex((e=>e._queryParams.loadsAllData())),i=e.syncPointTree_.findOnPath(s,((e,t)=>kL(t)));if(n&&!i){const t=e.syncPointTree_.subtree(s);if(!t.isEmpty()){const n=function(e){return e.fold(((e,t,n)=>{if(t&&kL(t)){return[CL(t)]}{let e=[];return t&&(e=IL(t)),gO(n,((t,n)=>{e=e.concat(n)})),e}}))}(t);for(let t=0;t<n.length;++t){const r=n[t],i=r.query,s=BL(e,r);e.listenProvider_.startListening(GL(i),zL(e,i),s.hashFn,s.onComplete)}}}if(!i&&u.length>0&&!r)if(n){const n=null;e.listenProvider_.stopListening(GL(t),n)}else u.forEach((t=>{const n=e.queryToTagMap.get($L(t));e.listenProvider_.stopListening(GL(t),n)}))}!function(e,t){for(let n=0;n<t.length;++n){const r=t[n];if(!r._queryParams.loadsAllData()){const t=$L(r),n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t),e.tagToQueryMap.delete(n)}}}(e,u)}return a}function ML(e,t,n,r){const i=WL(e,r);if(null!=i){const r=QL(i),s=r.path,o=r.queryId,a=iP(s,t);return HL(e,s,new gM(fM(o),a,n))}return[]}function LL(e,t,n,r=!1){const i=t._path;let s=null,o=!1;e.syncPointTree_.foreachOnPath(i,((e,t)=>{const n=iP(e,i);s=s||EL(t,n),o=o||kL(t)}));let a,c=e.syncPointTree_.get(i);if(c?(o=o||kL(c),s=s||EL(c,KO())):(c=new yL,e.syncPointTree_=e.syncPointTree_.set(i,c)),null!=s)a=!0;else{a=!1,s=qP.EMPTY_NODE;e.syncPointTree_.subtree(i).foreachChild(((e,t)=>{const n=EL(t,KO());n&&(s=s.updateImmediateChild(e,n))}))}const u=SL(c,t);if(!u&&!t._queryParams.loadsAllData()){const n=$L(t);da(!e.queryToTagMap.has(n),"View does not exist, but we have a tag");const r=xL++;e.queryToTagMap.set(n,r),e.tagToQueryMap.set(r,n)}let l=wL(c,t,n,qM(e.pendingWriteTree_,i),s,a);if(!u&&!o&&!r){const n=TL(c,t);l=l.concat(function(e,t,n){const r=t._path,i=zL(e,t),s=BL(e,n),o=e.listenProvider_.startListening(GL(t),i,s.hashFn,s.onComplete),a=e.syncPointTree_.subtree(r);if(i)da(!kL(a.value),"If we're adding a query, it shouldn't be shadowed");else{const t=a.fold(((e,t,n)=>{if(!rP(e)&&t&&kL(t))return[CL(t).query];{let e=[];return t&&(e=e.concat(IL(t).map((e=>e.query)))),gO(n,((t,n)=>{e=e.concat(n)})),e}}));for(let n=0;n<t.length;++n){const r=t[n];e.listenProvider_.stopListening(GL(r),zL(e,r))}}return o}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e,t,n))}return l}function FL(e,t,n){const r=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(t,((e,n)=>{const r=EL(n,iP(e,t));if(r)return r}));return $M(r,t,i,n,!0)}function jL(e,t){const n=t._path;let r=null;e.syncPointTree_.foreachOnPath(n,((e,t)=>{const i=iP(e,n);r=r||EL(t,i)}));let i=e.syncPointTree_.get(n);i?r=r||EL(i,KO()):(i=new yL,e.syncPointTree_=e.syncPointTree_.set(n,i));const s=null!=r,o=s?new vM(r,!0,!1):null;return function(e){return TM(e.viewCache_)}(_L(i,t,qM(e.pendingWriteTree_,t._path),s?o.getNode():qP.EMPTY_NODE,s))}function qL(e,t){return VL(t,e.syncPointTree_,null,qM(e.pendingWriteTree_,KO()))}function VL(e,t,n,r){if(rP(e.path))return UL(e,t,n,r);{const i=t.get(KO());null==n&&null!=i&&(n=EL(i,KO()));let s=[];const o=YO(e.path),a=e.operationForChild(o),c=t.children.get(o);if(c&&a){const e=n?n.getImmediateChild(o):null,t=JM(r,o);s=s.concat(VL(a,c,e,t))}return i&&(s=s.concat(vL(i,e,r,n))),s}}function UL(e,t,n,r){const i=t.get(KO());null==n&&null!=i&&(n=EL(i,KO()));let s=[];return t.children.inorderTraversal(((t,i)=>{const o=n?n.getImmediateChild(t):null,a=JM(r,t),c=e.operationForChild(t);c&&(s=s.concat(UL(c,i,o,a)))})),i&&(s=s.concat(vL(i,e,r,n))),s}function BL(e,t){const n=t.query,r=zL(e,n);return{hashFn:()=>{const e=function(e){return e.viewCache_.serverCache.getNode()}(t)||qP.EMPTY_NODE;return e.hash()},onComplete:t=>{if("ok"===t)return r?function(e,t,n){const r=WL(e,n);if(r){const n=QL(r),i=n.path,s=n.queryId,o=iP(i,t);return HL(e,i,new mM(fM(s),o))}return[]}(e,n._path,r):function(e,t){return qL(e,new mM({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t))}(e,n._path);{const r=function(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r}(t,n);return PL(e,n,null,r)}}}}function zL(e,t){const n=$L(t);return e.queryToTagMap.get(n)}function $L(e){return e._path.toString()+"$"+e._queryIdentifier}function WL(e,t){return e.tagToQueryMap.get(t)}function QL(e){const t=e.indexOf("$");return da(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new GO(e.substr(0,t))}}function HL(e,t,n){const r=e.syncPointTree_.get(t);da(r,"Missing sync point for query tag that we're tracking");return vL(r,n,qM(e.pendingWriteTree_,t),null)}function GL(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new(da(gL,"Reference.ts has not been loaded"),gL)(e._repo,e._path):e}class KL{constructor(e){this.node_=e}getImmediateChild(e){const t=this.node_.getImmediateChild(e);return new KL(t)}node(){return this.node_}}class YL{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){const t=nP(this.path_,e);return new YL(this.syncTree_,t)}node(){return FL(this.syncTree_,this.path_)}}const JL=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},XL=function(e,t,n){return e&&"object"==typeof e?(da(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?ZL(e[".sv"],t,n):"object"==typeof e[".sv"]?eF(e[".sv"],t):void da(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},ZL=function(e,t,n){if("timestamp"===e)return n.timestamp;da(!1,"Unexpected server value: "+e)},eF=function(e,t,n){e.hasOwnProperty("increment")||da(!1,"Unexpected server value: "+JSON.stringify(e,null,2));const r=e.increment;"number"!=typeof r&&da(!1,"Unexpected increment value: "+r);const i=t.node();if(da(null!=i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return r;const s=i.getValue();return"number"!=typeof s?r:s+r},tF=function(e,t,n,r){return rF(t,new YL(n,e),r)},nF=function(e,t,n){return rF(e,new KL(t),n)};function rF(e,t,n){const r=e.getPriority().val(),i=XL(r,t.getImmediateChild(".priority"),n);let s;if(e.isLeafNode()){const r=e,s=XL(r.getValue(),t,n);return s!==r.getValue()||i!==r.getPriority().val()?new NP(s,BP(i)):e}{const r=e;return s=r,i!==r.getPriority().val()&&(s=s.updatePriority(new NP(i))),r.forEachChild(DP,((e,r)=>{const i=rF(r,t.getImmediateChild(e),n);i!==r&&(s=s.updateImmediateChild(e,i))})),s}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class iF{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function sF(e,t){let n=t instanceof GO?t:new GO(t),r=e,i=YO(n);for(;null!==i;){const e=Ua(r.node.children,i)||{children:{},childCount:0};r=new iF(i,r,e),n=XO(n),i=YO(n)}return r}function oF(e){return e.node.value}function aF(e,t){e.node.value=t,dF(e)}function cF(e){return e.node.childCount>0}function uF(e,t){gO(e.node.children,((n,r)=>{t(new iF(n,e,r))}))}function lF(e,t,n,r){n&&!r&&t(e),uF(e,(e=>{lF(e,t,!0,r)})),n&&r&&t(e)}function hF(e){return new GO(null===e.parent?e.name:hF(e.parent)+"/"+e.name)}function dF(e){null!==e.parent&&function(e,t,n){const r=function(e){return void 0===oF(e)&&!cF(e)}(n),i=Va(e.node.children,t);r&&i?(delete e.node.children[t],e.node.childCount--,dF(e)):r||i||(e.node.children[t]=n.node,e.node.childCount++,dF(e))}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e.parent,e.name,e)}const fF=/[\[\].#$\/\u0000-\u001F\u007F]/,pF=/[\[\].#$\u0000-\u001F\u007F]/,mF=10485760,gF=function(e){return"string"==typeof e&&0!==e.length&&!fF.test(e)},yF=function(e){return"string"==typeof e&&0!==e.length&&!pF.test(e)},vF=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!cO(e)||e&&"object"==typeof e&&Va(e,".sv")},_F=function(e,t,n,r){r&&void 0===t||wF(ec(e,"value"),t,n)},wF=function(e,t,n){const r=n instanceof GO?new cP(n,e):n;if(void 0===t)throw new Error(e+"contains undefined "+lP(r));if("function"==typeof t)throw new Error(e+"contains a function "+lP(r)+" with contents = "+t.toString());if(cO(t))throw new Error(e+"contains "+t.toString()+" "+lP(r));if("string"==typeof t&&t.length>mF/3&&rc(t)>mF)throw new Error(e+"contains a string greater than "+mF+" utf8 bytes "+lP(r)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,i=!1;if(gO(t,((t,s)=>{if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(i=!0,!gF(t)))throw new Error(e+" contains an invalid key ("+t+") "+lP(r)+'.  Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');!function(e,t){e.parts_.length>0&&(e.byteLength_+=1),e.parts_.push(t),e.byteLength_+=rc(t),uP(e)}(r,t),wF(e,s,r),function(e){const t=e.parts_.pop();e.byteLength_-=rc(t),e.parts_.length>0&&(e.byteLength_-=1)}(r)})),n&&i)throw new Error(e+' contains ".value" child '+lP(r)+" in addition to actual children.")}},bF=function(e,t,n,r){if(r&&void 0===t)return;const i=ec(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(i+" must be an object containing the children to replace.");const s=[];gO(t,((e,t)=>{const r=new GO(e);if(wF(i,t,nP(n,r)),".priority"===ZO(r)&&!vF(t))throw new Error(i+"contains an invalid value for '"+r.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(r)})),function(e,t){let n,r;for(n=0;n<t.length;n++){r=t[n];const i=eP(r);for(let t=0;t<i.length;t++)if(".priority"===i[t]&&t===i.length-1);else if(!gF(i[t]))throw new Error(e+"contains an invalid key ("+i[t]+") in path "+r.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}t.sort(sP);let i=null;for(n=0;n<t.length;n++){if(r=t[n],null!==i&&aP(i,r))throw new Error(e+"contains a path "+i.toString()+" that is ancestor of another path "+r.toString());i=r}}(i,s)},IF=function(e,t,n){if(!n||void 0!==t){if(cO(t))throw new Error(ec(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!vF(t))throw new Error(ec(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},EF=function(e,t,n,r){if(!(r&&void 0===n||gF(n)))throw new Error(ec(e,t)+'was an invalid key = "'+n+'".  Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')},TF=function(e,t,n,r){if(!(r&&void 0===n||yF(n)))throw new Error(ec(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},SF=function(e,t,n,r){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),TF(e,t,n,r)},kF=function(e,t){if(".info"===YO(t))throw new Error(e+" failed = Can't modify data under /.info/")},CF=function(e,t){const n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!gF(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),yF(e)}(n))throw new Error(ec(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class xF{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function AF(e,t){let n=null;for(let r=0;r<t.length;r++){const i=t[r],s=i.getPath();null===n||oP(s,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:s}),n.events.push(i)}n&&e.eventLists_.push(n)}function NF(e,t,n){AF(e,n),RF(e,(e=>oP(e,t)))}function DF(e,t,n){AF(e,n),RF(e,(e=>aP(e,t)||aP(t,e)))}function RF(e,t){e.recursionDepth_++;let n=!0;for(let r=0;r<e.eventLists_.length;r++){const i=e.eventLists_[r];if(i){t(i.path)?(OF(e.eventLists_[r]),e.eventLists_[r]=null):n=!1}}n&&(e.eventLists_=[]),e.recursionDepth_--}function OF(e){for(let t=0;t<e.events.length;t++){const n=e.events[t];if(null!==n){e.events[t]=null;const r=n.getEventRunner();eO&&rO("event: "+n.toString()),wO(r)}}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const PF="repo_interrupt",MF=25;class LF{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new xF,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=oM(),this.transactionQueueTree_=new iF,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function FF(e,t,n){if(e.stats_=PO(e.repoInfo_),e.forceRestClient_||("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0)e.server_=new iM(e.repoInfo_,((t,n,r,i)=>{VF(e,t,n,r,i)}),e.authTokenProvider_,e.appCheckProvider_),setTimeout((()=>UF(e,!0)),0);else{if(null!=n){if("object"!=typeof n)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{ja(n)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}e.persistentConnection_=new fP(e.repoInfo_,t,((t,n,r,i)=>{VF(e,t,n,r,i)}),(t=>{UF(e,t)}),(t=>{!function(e,t){gO(t,((t,n)=>{BF(e,t,n)}))}(e,t)}),e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener((t=>{e.server_.refreshAuthToken(t)})),e.appCheckProvider_.addTokenChangeListener((t=>{e.server_.refreshAppCheckToken(t.token)})),e.statsReporter_=function(e,t){const n=e.toString();return OO[n]||(OO[n]=t()),OO[n]}(e.repoInfo_,(()=>new hM(e.stats_,e.server_))),e.infoData_=new sM,e.infoSyncTree_=new AL({startListening:(t,n,r,i)=>{let s=[];const o=e.infoData_.getNode(t._path);return o.isEmpty()||(s=OL(e.infoSyncTree_,t._path,o),setTimeout((()=>{i("ok")}),0)),s},stopListening:()=>{}}),BF(e,"connected",!1),e.serverSyncTree_=new AL({startListening:(t,n,r,i)=>(e.server_.listen(t,r,n,((n,r)=>{const s=i(n,r);DF(e.eventQueue_,t._path,s)})),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function jF(e){const t=e.infoData_.getNode(new GO(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function qF(e){return JL({timestamp:jF(e)})}function VF(e,t,n,r,i){e.dataUpdateCount++;const s=new GO(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let o=[];if(i)if(r){const t=za(n,(e=>BP(e)));o=function(e,t,n,r){const i=WL(e,r);if(i){const r=QL(i),s=r.path,o=r.queryId,a=iP(s,t),c=CM.fromObject(n);return HL(e,s,new yM(fM(o),a,c))}return[]}(e.serverSyncTree_,s,t,i)}else{const t=BP(n);o=ML(e.serverSyncTree_,s,t,i)}else if(r){const t=za(n,(e=>BP(e)));o=function(e,t,n){const r=CM.fromObject(n);return qL(e,new yM({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,r))}(e.serverSyncTree_,s,t)}else{const t=BP(n);o=OL(e.serverSyncTree_,s,t)}let a=s;o.length>0&&(a=ZF(e,s)),DF(e.eventQueue_,a,o)}function UF(e,t){BF(e,"connected",t),!1===t&&function(e){KF(e,"onDisconnectEvents");const t=qF(e),n=oM();uM(e.onDisconnect_,KO(),((r,i)=>{const s=tF(r,i,e.serverSyncTree_,t);aM(n,r,s)}));let r=[];uM(n,KO(),((t,n)=>{r=r.concat(OL(e.serverSyncTree_,t,n));const i=ij(e,t);ZF(e,i)})),e.onDisconnect_=oM(),DF(e.eventQueue_,KO(),r)}(e)}function BF(e,t,n){const r=new GO("/.info/"+t),i=BP(n);e.infoData_.updateSnapshot(r,i);const s=OL(e.infoSyncTree_,r,i);DF(e.eventQueue_,r,s)}function zF(e){return e.nextWriteId_++}function $F(e,t,n,r,i){KF(e,"set",{path:t.toString(),value:n,priority:r});const s=qF(e),o=BP(n,r),a=FL(e.serverSyncTree_,t),c=nF(o,a,s),u=zF(e),l=NL(e.serverSyncTree_,t,c,u,!0);AF(e.eventQueue_,l),e.server_.put(t.toString(),o.val(!0),((n,r)=>{const s="ok"===n;s||aO("set at "+t+" failed: "+n);const o=RL(e.serverSyncTree_,u,!s);DF(e.eventQueue_,t,o),YF(e,i,n,r)}));const h=ij(e,t);ZF(e,h),DF(e.eventQueue_,h,[])}function WF(e,t,n){e.server_.onDisconnectCancel(t.toString(),((r,i)=>{"ok"===r&&cM(e.onDisconnect_,t),YF(e,n,r,i)}))}function QF(e,t,n,r){const i=BP(n);e.server_.onDisconnectPut(t.toString(),i.val(!0),((n,s)=>{"ok"===n&&aM(e.onDisconnect_,t,i),YF(e,r,n,s)}))}function HF(e,t,n){let r;r=".info"===YO(t._path)?PL(e.infoSyncTree_,t,n):PL(e.serverSyncTree_,t,n),NF(e.eventQueue_,t._path,r)}function GF(e){e.persistentConnection_&&e.persistentConnection_.interrupt(PF)}function KF(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),rO(n,...t)}function YF(e,t,n,r){t&&wO((()=>{if("ok"===n)t(null);else{const e=(n||"error").toUpperCase();let i=e;r&&(i+=": "+r);const s=new Error(i);s.code=e,t(s)}}))}function JF(e,t,n){return FL(e.serverSyncTree_,t,n)||qP.EMPTY_NODE}function XF(e,t=e.transactionQueueTree_){if(t||rj(e,t),oF(t)){const n=tj(e,t);da(n.length>0,"Sending zero length transaction queue");n.every((e=>0===e.status))&&function(e,t,n){const r=n.map((e=>e.currentWriteId)),i=JF(e,t,r);let s=i;const o=i.hash();for(let e=0;e<n.length;e++){const r=n[e];da(0===r.status,"tryToSendTransactionQueue_: items in queue should all be run."),r.status=1,r.retryCount++;const i=iP(t,r.path);s=s.updateChild(i,r.currentOutputSnapshotRaw)}const a=s.val(!0),c=t;e.server_.put(c.toString(),a,(r=>{KF(e,"transaction put response",{path:c.toString(),status:r});let i=[];if("ok"===r){const r=[];for(let t=0;t<n.length;t++)n[t].status=2,i=i.concat(RL(e.serverSyncTree_,n[t].currentWriteId)),n[t].onComplete&&r.push((()=>n[t].onComplete(null,!0,n[t].currentOutputSnapshotResolved))),n[t].unwatcher();rj(e,sF(e.transactionQueueTree_,t)),XF(e,e.transactionQueueTree_),DF(e.eventQueue_,t,i);for(let e=0;e<r.length;e++)wO(r[e])}else{if("datastale"===r)for(let e=0;e<n.length;e++)3===n[e].status?n[e].status=4:n[e].status=0;else{aO("transaction at "+c.toString()+" failed: "+r);for(let e=0;e<n.length;e++)n[e].status=4,n[e].abortReason=r}ZF(e,t)}}),o)}(e,hF(t),n)}else cF(t)&&uF(t,(t=>{XF(e,t)}))}function ZF(e,t){const n=ej(e,t),r=hF(n);return function(e,t,n){if(0===t.length)return;const r=[];let i=[];const s=t.filter((e=>0===e.status)),o=s.map((e=>e.currentWriteId));for(let s=0;s<t.length;s++){const c=t[s],u=iP(n,c.path);let l,h=!1;if(da(null!==u,"rerunTransactionsUnderNode_: relativePath should not be null."),4===c.status)h=!0,l=c.abortReason,i=i.concat(RL(e.serverSyncTree_,c.currentWriteId,!0));else if(0===c.status)if(c.retryCount>=MF)h=!0,l="maxretry",i=i.concat(RL(e.serverSyncTree_,c.currentWriteId,!0));else{const n=JF(e,c.path,o);c.currentInputSnapshot=n;const r=t[s].update(n.val());if(void 0!==r){wF("transaction failed: Data returned ",r,c.path);let t=BP(r);"object"==typeof r&&null!=r&&Va(r,".priority")||(t=t.updatePriority(n.getPriority()));const s=c.currentWriteId,a=qF(e),u=nF(t,n,a);c.currentOutputSnapshotRaw=t,c.currentOutputSnapshotResolved=u,c.currentWriteId=zF(e),o.splice(o.indexOf(s),1),i=i.concat(NL(e.serverSyncTree_,c.path,u,c.currentWriteId,c.applyLocally)),i=i.concat(RL(e.serverSyncTree_,s,!0))}else h=!0,l="nodata",i=i.concat(RL(e.serverSyncTree_,c.currentWriteId,!0))}DF(e.eventQueue_,n,i),i=[],h&&(t[s].status=2,a=t[s].unwatcher,setTimeout(a,Math.floor(0)),t[s].onComplete&&("nodata"===l?r.push((()=>t[s].onComplete(null,!1,t[s].currentInputSnapshot))):r.push((()=>t[s].onComplete(new Error(l),!1,null)))))}var a;rj(e,e.transactionQueueTree_);for(let e=0;e<r.length;e++)wO(r[e]);XF(e,e.transactionQueueTree_)}(e,tj(e,n),r),r}function ej(e,t){let n,r=e.transactionQueueTree_;for(n=YO(t);null!==n&&void 0===oF(r);)r=sF(r,n),n=YO(t=XO(t));return r}function tj(e,t){const n=[];return nj(e,t,n),n.sort(((e,t)=>e.order-t.order)),n}function nj(e,t,n){const r=oF(t);if(r)for(let e=0;e<r.length;e++)n.push(r[e]);uF(t,(t=>{nj(e,t,n)}))}function rj(e,t){const n=oF(t);if(n){let e=0;for(let t=0;t<n.length;t++)2!==n[t].status&&(n[e]=n[t],e++);n.length=e,aF(t,n.length>0?n:void 0)}uF(t,(t=>{rj(e,t)}))}function ij(e,t){const n=hF(ej(e,t)),r=sF(e.transactionQueueTree_,t);return function(e,t,n){let r=n?e:e.parent;for(;null!==r;){if(t(r))return!0;r=r.parent}}(r,(t=>{sj(e,t)})),sj(e,r),lF(r,(t=>{sj(e,t)})),n}function sj(e,t){const n=oF(t);if(n){const r=[];let i=[],s=-1;for(let t=0;t<n.length;t++)3===n[t].status||(1===n[t].status?(da(s===t-1,"All SENT items should be at beginning of queue."),s=t,n[t].status=3,n[t].abortReason="set"):(da(0===n[t].status,"Unexpected transaction status in abort"),n[t].unwatcher(),i=i.concat(RL(e.serverSyncTree_,n[t].currentWriteId,!0)),n[t].onComplete&&r.push(n[t].onComplete.bind(null,new Error("set"),!1,null))));-1===s?aF(t,void 0):n.length=s+1,DF(e.eventQueue_,hF(t),i);for(let e=0;e<r.length;e++)wO(r[e])}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const oj=function(e,t){const n=aj(e),r=n.namespace;"firebase.com"===n.domain&&oO(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||oO("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&aO("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");const i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new AO(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new GO(n.pathString)}},aj=function(e){let t="",n="",r="",i="",s="",o=!0,a="https",c=443;if("string"==typeof e){let u=e.indexOf("//");u>=0&&(a=e.substring(0,u-1),e=e.substring(u+2));let l=e.indexOf("/");-1===l&&(l=e.length);let h=e.indexOf("?");-1===h&&(h=e.length),t=e.substring(0,Math.min(l,h)),l<h&&(i=function(e){let t="";const n=e.split("/");for(let e=0;e<n.length;e++)if(n[e].length>0){let r=n[e];try{r=decodeURIComponent(r.replace(/\+/g," "))}catch(e){}t+="/"+r}return t}(e.substring(l,h)));const d=function(e){const t={};"?"===e.charAt(0)&&(e=e.substring(1));for(const n of e.split("&")){if(0===n.length)continue;const r=n.split("=");2===r.length?t[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):aO(`Invalid query segment '${n}' in query '${e}'`)}return t}(e.substring(Math.min(e.length,h)));u=t.indexOf(":"),u>=0?(o="https"===a||"wss"===a,c=parseInt(t.substring(u+1),10)):u=t.length;const f=t.slice(0,u);if("localhost"===f.toLowerCase())n="localhost";else if(f.split(".").length<=2)n=f;else{const e=t.indexOf(".");r=t.substring(0,e).toLowerCase(),n=t.substring(e+1),s=r}"ns"in d&&(s=d.ns)}return{host:t,port:c,domain:n,subdomain:r,secure:o,scheme:a,pathString:i,namespace:s}},cj="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",uj=function(){let e=0;const t=[];return function(n){const r=n===e;let i;e=n;const s=new Array(8);for(i=7;i>=0;i--)s[i]=cj.charAt(n%64),n=Math.floor(n/64);da(0===n,"Cannot push at time == 0");let o=s.join("");if(r){for(i=11;i>=0&&63===t[i];i--)t[i]=0;t[i]++}else for(i=0;i<12;i++)t[i]=Math.floor(64*Math.random());for(i=0;i<12;i++)o+=cj.charAt(t[i]);return da(20===o.length,"nextPushId: Length should be 20."),o}}();
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class lj{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){const e=this.snapshot.ref;return"value"===this.eventType?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+ja(this.snapshot.exportVal())}}class hj{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class dj{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return da(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class fj{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return rP(this._path)?null:ZO(this._path)}get ref(){return new yj(this._repo,this._path)}get _queryIdentifier(){const e=rM(this._queryParams),t=pO(e);return"{}"===t?"default":t}get _queryObject(){return rM(this._queryParams)}isEqual(e){if(!((e=ic(e))instanceof fj))return!1;const t=this._repo===e._repo,n=oP(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier;return t&&n&&r}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}(this._path)}}function pj(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function mj(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===vP){const r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==uO)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==lO)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===DP){if(null!=t&&!vF(t)||null!=n&&!vF(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(da(e.getIndex()instanceof zP||e.getIndex()===$P,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function gj(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class yj extends fj{constructor(e,t){super(e,t,new XP,!1)}get parent(){const e=tP(this._path);return null===e?null:new yj(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}let vj=class e{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(t){const n=new GO(t),r=bj(this.ref,t);return new e(this._node.getChild(n),r,DP)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(t){if(this._node.isLeafNode())return!1;return!!this._node.forEachChild(this._index,((n,r)=>t(new e(r,bj(this.ref,n),DP))))}hasChild(e){const t=new GO(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}};function _j(e,t){return(e=ic(e))._checkNotDeleted("ref"),void 0!==t?bj(e._root,t):e._root}function wj(e,t){(e=ic(e))._checkNotDeleted("refFromURL");const n=oj(t,e._repo.repoInfo_.nodeAdmin);CF("refFromURL",n);const r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||oO("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),_j(e,n.path.toString())}function bj(e,t){return null===YO((e=ic(e))._path)?SF("child","path",t,!1):TF("child","path",t,!1),new yj(e._repo,nP(e._path,t))}function Ij(e,t){e=ic(e),kF("set",e._path),_F("set",t,e._path,!1);const n=new Ta;return $F(e._repo,e._path,t,null,n.wrapCallback((()=>{}))),n.promise}function Ej(e,t){bF("update",t,e._path,!1);const n=new Ta;return function(e,t,n,r){KF(e,"update",{path:t.toString(),value:n});let i=!0;const s=qF(e),o={};if(gO(n,((n,r)=>{i=!1,o[n]=tF(nP(t,n),BP(r),e.serverSyncTree_,s)})),i)rO("update() called with empty data.  Don't do anything."),YF(0,r,"ok",void 0);else{const i=zF(e),s=DL(e.serverSyncTree_,t,o,i);AF(e.eventQueue_,s),e.server_.merge(t.toString(),n,((n,s)=>{const o="ok"===n;o||aO("update at "+t+" failed: "+n);const a=RL(e.serverSyncTree_,i,!o),c=a.length>0?ZF(e,t):t;DF(e.eventQueue_,c,a),YF(0,r,n,s)})),gO(n,(n=>{const r=ij(e,nP(t,n));ZF(e,r)})),DF(e.eventQueue_,t,[])}}(e._repo,e._path,t,n.wrapCallback((()=>{}))),n.promise}function Tj(e){e=ic(e);const t=new dj((()=>{})),n=new Sj(t);return function(e,t,n){const r=jL(e.serverSyncTree_,t);return null!=r?Promise.resolve(r):e.server_.get(t).then((r=>{const i=BP(r).withIndex(t._queryParams.getIndex());let s;if(LL(e.serverSyncTree_,t,n,!0),t._queryParams.loadsAllData())s=OL(e.serverSyncTree_,t._path,i);else{const n=zL(e.serverSyncTree_,t);s=ML(e.serverSyncTree_,t._path,i,n)}return DF(e.eventQueue_,t._path,s),PL(e.serverSyncTree_,t,n,null,!0),i}),(n=>(KF(e,"get for query "+ja(t)+" failed: "+n),Promise.reject(new Error(n)))))}(e._repo,e,n).then((t=>new vj(t,new yj(e._repo,e._path),e._queryParams.getIndex())))}class Sj{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){const n=t._queryParams.getIndex();return new lj("value",this,new vj(e.snapshotNode,new yj(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new hj(this,e,t):null}matches(e){return e instanceof Sj&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class kj{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new hj(this,e,t):null}createEvent(e,t){da(null!=e.childName,"Child events should have a childName.");const n=bj(new yj(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new lj(e.type,this,new vj(e.snapshotNode,n,r),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof kj&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function Cj(e,t,n,r,i){let s;if("object"==typeof r&&(s=void 0,i=r),"function"==typeof r&&(s=r),i&&i.onlyOnce){const t=n,r=(n,r)=>{HF(e._repo,e,a),t(n,r)};r.userCallback=n.userCallback,r.context=n.context,n=r}const o=new dj(n,s||void 0),a="value"===t?new Sj(o):new kj(t,o);return function(e,t,n){let r;r=".info"===YO(t._path)?LL(e.infoSyncTree_,t,n):LL(e.serverSyncTree_,t,n),NF(e.eventQueue_,t._path,r)}(e._repo,e,a),()=>HF(e._repo,e,a)}function xj(e,t,n,r){return Cj(e,"value",t,n,r)}function Aj(e,t,n,r){return Cj(e,"child_added",t,n,r)}function Nj(e,t,n,r){return Cj(e,"child_changed",t,n,r)}function Dj(e,t,n,r){return Cj(e,"child_moved",t,n,r)}function Rj(e,t,n,r){return Cj(e,"child_removed",t,n,r)}function Oj(e,t,n){let r=null;const i=n?new dj(n):null;"value"===t?r=new Sj(i):t&&(r=new kj(t,i)),HF(e._repo,e,r)}class Pj{}class Mj extends Pj{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){_F("endAt",this._value,e._path,!0);const t=eM(e._queryParams,this._value,this._key);if(gj(t),mj(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new fj(e._repo,e._path,t,e._orderByCalled)}}class Lj extends Pj{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){_F("endBefore",this._value,e._path,!1);const t=function(e,t,n){let r;return r=e.index_===vP||n?eM(e,t,n):eM(e,t,uO),r.endBeforeSet_=!0,r}(e._queryParams,this._value,this._key);if(gj(t),mj(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new fj(e._repo,e._path,t,e._orderByCalled)}}class Fj extends Pj{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){_F("startAt",this._value,e._path,!0);const t=ZP(e._queryParams,this._value,this._key);if(gj(t),mj(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new fj(e._repo,e._path,t,e._orderByCalled)}}class jj extends Pj{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){_F("startAfter",this._value,e._path,!1);const t=function(e,t,n){let r;return r=e.index_===vP||n?ZP(e,t,n):ZP(e,t,lO),r.startAfterSet_=!0,r}(e._queryParams,this._value,this._key);if(gj(t),mj(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new fj(e._repo,e._path,t,e._orderByCalled)}}class qj extends Pj{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new fj(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}class Vj extends Pj{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new fj(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}class Uj extends Pj{constructor(e){super(),this._path=e}_apply(e){pj(e,"orderByChild");const t=new GO(this._path);if(rP(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");const n=new zP(t),r=tM(e._queryParams,n);return mj(r),new fj(e._repo,e._path,r,!0)}}class Bj extends Pj{_apply(e){pj(e,"orderByKey");const t=tM(e._queryParams,vP);return mj(t),new fj(e._repo,e._path,t,!0)}}class zj extends Pj{_apply(e){pj(e,"orderByPriority");const t=tM(e._queryParams,DP);return mj(t),new fj(e._repo,e._path,t,!0)}}class $j extends Pj{_apply(e){pj(e,"orderByValue");const t=tM(e._queryParams,$P);return mj(t),new fj(e._repo,e._path,t,!0)}}class Wj extends Pj{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if(_F("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new Mj(this._value,this._key)._apply(new Fj(this._value,this._key)._apply(e))}}function Qj(e,...t){let n=ic(e);for(const e of t)n=e._apply(n);return n}!function(e){da(!mL,"__referenceConstructor has already been defined"),mL=e}(yj),function(e){da(!gL,"__referenceConstructor has already been defined"),gL=e}(yj);
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const Hj="FIREBASE_DATABASE_EMULATOR_HOST",Gj={};let Kj=!1;function Yj(e,t,n,r,i){let s=r||e.options.databaseURL;void 0===s&&(e.options.projectId||oO("Can't determine Firebase Database URL. Be sure to include  a Project ID when calling firebase.initializeApp()."),rO("Using default host for project ",e.options.projectId),s=`${e.options.projectId}-default-rtdb.firebaseio.com`);let o,a,c=oj(s,i),u=c.repoInfo;void 0!==M&&M.env&&(a=M.env[Hj]),a?(o=!0,s=`http://${a}?ns=${u.namespace}`,c=oj(s,i),u=c.repoInfo):o=!c.repoInfo.secure;const l=i&&o?new TO(TO.OWNER):new EO(e.name,e.options,t);CF("Invalid Firebase Database URL",c),rP(c.path)||oO("Database URL must point to the root of a Firebase Database (not including a child path).");const h=function(e,t,n,r){let i=Gj[t.name];i||(i={},Gj[t.name]=i);let s=i[e.toURLString()];s&&oO("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return s=new LF(e,Kj,n,r),i[e.toURLString()]=s,s}(u,e,l,new IO(e.name,n));return new Jj(h,e)}let Jj=class{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(FF(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new yj(this._repo,KO())),this._rootInternal}_delete(){return null!==this._rootInternal&&(!function(e,t){const n=Gj[t];n&&n[e.key]===e||oO(`Database ${t}(${e.repoInfo_}) has already been deleted.`),GF(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&oO("Cannot call "+e+" on a deleted database.")}};function Xj(){UO.IS_TRANSPORT_INITIALIZED&&aO("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function Zj(){Xj(),FO.forceDisallow()}function eq(){Xj(),VO.forceDisallow(),FO.forceAllow()}function tq(e,t,n,r={}){(e=ic(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&oO("Cannot call useEmulator() after instance has already been initialized.");const i=e._repoInternal;let s;if(i.repoInfo_.nodeAdmin)r.mockUserToken&&oO('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),s=new TO(TO.OWNER);else if(r.mockUserToken){const t="string"==typeof r.mockUserToken?r.mockUserToken:Sa(r.mockUserToken,e.app.options.projectId);s=new TO(t)}!function(e,t,n,r){e.repoInfo_=new AO(`${t}:${n}`,!1,e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,!0),r&&(e.authTokenProvider_=r)}(i,t,n,s)}function nq(e){var t;(e=ic(e))._checkNotDeleted("goOnline"),(t=e._repo).persistentConnection_&&t.persistentConnection_.resume(PF)}function rq(e,t){nO(e,t)}
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const iq={".sv":"timestamp"};function sq(e,t,n){var r;if(e=ic(e),kF("Reference.transaction",e._path),".length"===e.key||".keys"===e.key)throw"Reference.transaction failed: "+e.key+" is a read-only object.";const i=null===(r=null==n?void 0:n.applyLocally)||void 0===r||r,s=new Ta,o=xj(e,(()=>{}));return function(e,t,n,r,i,s){KF(e,"transaction on "+t);const o={path:t,update:n,onComplete:r,status:null,order:JR(),applyLocally:s,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},a=JF(e,t,void 0);o.currentInputSnapshot=a;const c=o.update(a.val());if(void 0===c)o.unwatcher(),o.currentOutputSnapshotRaw=null,o.currentOutputSnapshotResolved=null,o.onComplete&&o.onComplete(null,!1,o.currentInputSnapshot);else{wF("transaction failed: Data returned ",c,o.path),o.status=0;const n=sF(e.transactionQueueTree_,t),r=oF(n)||[];let i;r.push(o),aF(n,r),"object"==typeof c&&null!==c&&Va(c,".priority")?(i=Ua(c,".priority"),da(vF(i),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):i=(FL(e.serverSyncTree_,t)||qP.EMPTY_NODE).getPriority().val();const s=qF(e),u=BP(c,i),l=nF(u,a,s);o.currentOutputSnapshotRaw=u,o.currentOutputSnapshotResolved=l,o.currentWriteId=zF(e);const h=NL(e.serverSyncTree_,t,l,o.currentWriteId,o.applyLocally);DF(e.eventQueue_,t,h),XF(e,e.transactionQueueTree_)}}(e._repo,e._path,t,((t,n,r)=>{let i=null;t?s.reject(t):(i=new vj(r,new yj(e._repo,e._path),DP),s.resolve(new class{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}(n,i)))}),o,i),s.promise}fP.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},fP.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},function(e){$R(Hc),zc(new sc("database",((e,{instanceIdentifier:t})=>Yj(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)),"PUBLIC").setMultipleInstances(!0)),Yc(UR,BR,e),Yc(UR,BR,"esm2017")}();const oq=new mc("@firebase/database-compat"),aq=function(e){const t="FIREBASE WARNING: "+e;oq.warn(t)};
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class cq{constructor(e){this._delegate=e}cancel(e){Za("OnDisconnect.cancel",0,1,arguments.length),tc("OnDisconnect.cancel","onComplete",e,!0);const t=this._delegate.cancel();return e&&t.then((()=>e(null)),(t=>e(t))),t}remove(e){Za("OnDisconnect.remove",0,1,arguments.length),tc("OnDisconnect.remove","onComplete",e,!0);const t=this._delegate.remove();return e&&t.then((()=>e(null)),(t=>e(t))),t}set(e,t){Za("OnDisconnect.set",1,2,arguments.length),tc("OnDisconnect.set","onComplete",t,!0);const n=this._delegate.set(e);return t&&n.then((()=>t(null)),(e=>t(e))),n}setWithPriority(e,t,n){Za("OnDisconnect.setWithPriority",2,3,arguments.length),tc("OnDisconnect.setWithPriority","onComplete",n,!0);const r=this._delegate.setWithPriority(e,t);return n&&r.then((()=>n(null)),(e=>n(e))),r}update(e,t){if(Za("OnDisconnect.update",1,2,arguments.length),Array.isArray(e)){const t={};for(let n=0;n<e.length;++n)t[""+n]=e[n];e=t,aq("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}tc("OnDisconnect.update","onComplete",t,!0);const n=this._delegate.update(e);return t&&n.then((()=>t(null)),(e=>t(e))),n}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class uq{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return Za("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class lq{constructor(e,t){this._database=e,this._delegate=t}val(){return Za("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return Za("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return Za("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return Za("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return Za("DataSnapshot.child",0,1,arguments.length),e=String(e),TF("DataSnapshot.child","path",e,!1),new lq(this._database,this._delegate.child(e))}hasChild(e){return Za("DataSnapshot.hasChild",1,1,arguments.length),TF("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return Za("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(e){return Za("DataSnapshot.forEach",1,1,arguments.length),tc("DataSnapshot.forEach","action",e,!1),this._delegate.forEach((t=>e(new lq(this._database,t))))}hasChildren(){return Za("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return Za("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return Za("DataSnapshot.ref",0,0,arguments.length),new dq(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class hq{constructor(e,t){this.database=e,this._delegate=t}on(e,t,n,r){var i;Za("Query.on",2,4,arguments.length),tc("Query.on","callback",t,!1);const s=hq.getCancelAndContextArgs_("Query.on",n,r),o=(e,n)=>{t.call(s.context,new lq(this.database,e),n)};o.userCallback=t,o.context=s.context;const a=null===(i=s.cancel)||void 0===i?void 0:i.bind(s.context);switch(e){case"value":return xj(this._delegate,o,a),t;case"child_added":return Aj(this._delegate,o,a),t;case"child_removed":return Rj(this._delegate,o,a),t;case"child_changed":return Nj(this._delegate,o,a),t;case"child_moved":return Dj(this._delegate,o,a),t;default:throw new Error(ec("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){if(Za("Query.off",0,3,arguments.length),function(e,t,n){if(!n||void 0!==t)switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(ec(e,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}("Query.off",e,!0),tc("Query.off","callback",t,!0),nc("Query.off","context",n,!0),t){const r=()=>{};r.userCallback=t,r.context=n,Oj(this._delegate,e,r)}else Oj(this._delegate,e)}get(){return Tj(this._delegate).then((e=>new lq(this.database,e)))}once(e,t,n,r){Za("Query.once",1,4,arguments.length),tc("Query.once","callback",t,!0);const i=hq.getCancelAndContextArgs_("Query.once",n,r),s=new Ta,o=(e,n)=>{const r=new lq(this.database,e);t&&t.call(i.context,r,n),s.resolve(r)};o.userCallback=t,o.context=i.context;const a=e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)};switch(e){case"value":xj(this._delegate,o,a,{onlyOnce:!0});break;case"child_added":Aj(this._delegate,o,a,{onlyOnce:!0});break;case"child_removed":Rj(this._delegate,o,a,{onlyOnce:!0});break;case"child_changed":Nj(this._delegate,o,a,{onlyOnce:!0});break;case"child_moved":Dj(this._delegate,o,a,{onlyOnce:!0});break;default:throw new Error(ec("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return s.promise}limitToFirst(e){return Za("Query.limitToFirst",1,1,arguments.length),new hq(this.database,Qj(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new qj(e)}(e)))}limitToLast(e){return Za("Query.limitToLast",1,1,arguments.length),new hq(this.database,Qj(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Vj(e)}(e)))}orderByChild(e){return Za("Query.orderByChild",1,1,arguments.length),new hq(this.database,Qj(this._delegate,function(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid.  Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid.  Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid.  Use orderByValue() instead.');return TF("orderByChild","path",e,!1),new Uj(e)}(e)))}orderByKey(){return Za("Query.orderByKey",0,0,arguments.length),new hq(this.database,Qj(this._delegate,new Bj))}orderByPriority(){return Za("Query.orderByPriority",0,0,arguments.length),new hq(this.database,Qj(this._delegate,new zj))}orderByValue(){return Za("Query.orderByValue",0,0,arguments.length),new hq(this.database,Qj(this._delegate,new $j))}startAt(e=null,t){return Za("Query.startAt",0,2,arguments.length),new hq(this.database,Qj(this._delegate,function(e=null,t){return EF("startAt","key",t,!0),new Fj(e,t)}(e,t)))}startAfter(e=null,t){return Za("Query.startAfter",0,2,arguments.length),new hq(this.database,Qj(this._delegate,function(e,t){return EF("startAfter","key",t,!0),new jj(e,t)}(e,t)))}endAt(e=null,t){return Za("Query.endAt",0,2,arguments.length),new hq(this.database,Qj(this._delegate,function(e,t){return EF("endAt","key",t,!0),new Mj(e,t)}(e,t)))}endBefore(e=null,t){return Za("Query.endBefore",0,2,arguments.length),new hq(this.database,Qj(this._delegate,function(e,t){return EF("endBefore","key",t,!0),new Lj(e,t)}(e,t)))}equalTo(e,t){return Za("Query.equalTo",1,2,arguments.length),new hq(this.database,Qj(this._delegate,function(e,t){return EF("equalTo","key",t,!0),new Wj(e,t)}(e,t)))}toString(){return Za("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return Za("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(Za("Query.isEqual",1,1,arguments.length),!(e instanceof hq)){throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}return this._delegate.isEqual(e._delegate)}static getCancelAndContextArgs_(e,t,n){const r={cancel:void 0,context:void 0};if(t&&n)r.cancel=t,tc(e,"cancel",r.cancel,!0),r.context=n,nc(e,"context",r.context,!0);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error(ec(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new dq(this.database,new yj(this._delegate._repo,this._delegate._path))}}class dq extends hq{constructor(e,t){super(e,new fj(t._repo,t._path,new XP,!1)),this.database=e,this._delegate=t}getKey(){return Za("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return Za("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new dq(this.database,bj(this._delegate,e))}getParent(){Za("Reference.parent",0,0,arguments.length);const e=this._delegate.parent;return e?new dq(this.database,e):null}getRoot(){return Za("Reference.root",0,0,arguments.length),new dq(this.database,this._delegate.root)}set(e,t){Za("Reference.set",1,2,arguments.length),tc("Reference.set","onComplete",t,!0);const n=Ij(this._delegate,e);return t&&n.then((()=>t(null)),(e=>t(e))),n}update(e,t){if(Za("Reference.update",1,2,arguments.length),Array.isArray(e)){const t={};for(let n=0;n<e.length;++n)t[""+n]=e[n];e=t,aq("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}kF("Reference.update",this._delegate._path),tc("Reference.update","onComplete",t,!0);const n=Ej(this._delegate,e);return t&&n.then((()=>t(null)),(e=>t(e))),n}setWithPriority(e,t,n){Za("Reference.setWithPriority",2,3,arguments.length),tc("Reference.setWithPriority","onComplete",n,!0);const r=function(e,t,n){if(kF("setWithPriority",e._path),_F("setWithPriority",t,e._path,!1),IF("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new Ta;return $F(e._repo,e._path,t,n,r.wrapCallback((()=>{}))),r.promise}(this._delegate,e,t);return n&&r.then((()=>n(null)),(e=>n(e))),r}remove(e){Za("Reference.remove",0,1,arguments.length),tc("Reference.remove","onComplete",e,!0);const t=function(e){return kF("remove",e._path),Ij(e,null)}(this._delegate);return e&&t.then((()=>e(null)),(t=>e(t))),t}transaction(e,t,n){Za("Reference.transaction",1,3,arguments.length),tc("Reference.transaction","transactionUpdate",e,!1),tc("Reference.transaction","onComplete",t,!0),function(e,t,n,r){if((!r||void 0!==n)&&"boolean"!=typeof n)throw new Error(ec(e,t)+"must be a boolean.")}("Reference.transaction","applyLocally",n,!0);const r=sq(this._delegate,e,{applyLocally:n}).then((e=>new uq(e.committed,new lq(this.database,e.snapshot))));return t&&r.then((e=>t(null,e.committed,e.snapshot)),(e=>t(e,!1,null))),r}setPriority(e,t){Za("Reference.setPriority",1,2,arguments.length),tc("Reference.setPriority","onComplete",t,!0);const n=function(e,t){e=ic(e),kF("setPriority",e._path),IF("setPriority",t,!1);const n=new Ta;return $F(e._repo,nP(e._path,".priority"),t,null,n.wrapCallback((()=>{}))),n.promise}(this._delegate,e);return t&&n.then((()=>t(null)),(e=>t(e))),n}push(e,t){Za("Reference.push",0,2,arguments.length),tc("Reference.push","onComplete",t,!0);const n=function(e,t){e=ic(e),kF("push",e._path),_F("push",t,e._path,!0);const n=jF(e._repo),r=uj(n),i=bj(e,r),s=bj(e,r);let o;return o=null!=t?Ij(s,t).then((()=>s)):Promise.resolve(s),i.then=o.then.bind(o),i.catch=o.then.bind(o,void 0),i}(this._delegate,e),r=n.then((e=>new dq(this.database,e)));t&&r.then((()=>t(null)),(e=>t(e)));const i=new dq(this.database,n);return i.then=r.then.bind(r),i.catch=r.catch.bind(r,void 0),i}onDisconnect(){return kF("Reference.onDisconnect",this._delegate._path),new cq(new class{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new Ta;return WF(this._repo,this._path,e.wrapCallback((()=>{}))),e.promise}remove(){kF("OnDisconnect.remove",this._path);const e=new Ta;return QF(this._repo,this._path,null,e.wrapCallback((()=>{}))),e.promise}set(e){kF("OnDisconnect.set",this._path),_F("OnDisconnect.set",e,this._path,!1);const t=new Ta;return QF(this._repo,this._path,e,t.wrapCallback((()=>{}))),t.promise}setWithPriority(e,t){kF("OnDisconnect.setWithPriority",this._path),_F("OnDisconnect.setWithPriority",e,this._path,!1),IF("OnDisconnect.setWithPriority",t,!1);const n=new Ta;return function(e,t,n,r,i){const s=BP(n,r);e.server_.onDisconnectPut(t.toString(),s.val(!0),((n,r)=>{"ok"===n&&aM(e.onDisconnect_,t,s),YF(0,i,n,r)}))}(this._repo,this._path,e,t,n.wrapCallback((()=>{}))),n.promise}update(e){kF("OnDisconnect.update",this._path),bF("OnDisconnect.update",e,this._path,!1);const t=new Ta;return function(e,t,n,r){if(Ba(n))return rO("onDisconnect().update() called with empty data.  Don't do anything."),void YF(0,r,"ok",void 0);e.server_.onDisconnectMerge(t.toString(),n,((i,s)=>{"ok"===i&&gO(n,((n,r)=>{const i=BP(r);aM(e.onDisconnect_,nP(t,n),i)})),YF(0,r,i,s)}))}(this._repo,this._path,e,t.wrapCallback((()=>{}))),t.promise}}(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class fq{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:Zj,forceLongPolling:eq}}useEmulator(e,t,n={}){tq(this._delegate,e,t,n)}ref(e){if(Za("database.ref",0,1,arguments.length),e instanceof dq){const t=wj(this._delegate,e.toString());return new dq(this,t)}{const t=_j(this._delegate,e);return new dq(this,t)}}refFromURL(e){Za("database.refFromURL",1,1,arguments.length);const t=wj(this._delegate,e);return new dq(this,t)}goOffline(){return Za("database.goOffline",0,0,arguments.length),function(e){(e=ic(e))._checkNotDeleted("goOffline"),GF(e._repo)}(this._delegate)}goOnline(){return Za("database.goOnline",0,0,arguments.length),nq(this._delegate)}}fq.ServerValue={TIMESTAMP:iq,increment:e=>function(e){return{".sv":{increment:e}}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(e)};var pq=Object.freeze({__proto__:null,initStandalone:
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function({app:e,url:t,version:n,customAuthImpl:r,namespace:i,nodeAdmin:s=!1}){$R(n);const o=new ac("auth-internal",new cc("database-standalone"));return o.setComponent(new sc("auth-internal",(()=>r),"PRIVATE")),{instance:new fq(Yj(e,o,void 0,t,s),e),namespace:i}}});
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const mq=fq.ServerValue;!function(e){e.INTERNAL.registerComponent(new sc("database-compat",((e,{instanceIdentifier:t})=>{const n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new fq(r,n)}),"PUBLIC").setServiceProps({Reference:dq,Query:hq,Database:fq,DataSnapshot:lq,enableLogging:rq,INTERNAL:pq,ServerValue:mq}).setMultipleInstances(!0)),e.registerVersion("@firebase/database-compat","0.3.4")}(uh);
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const gq="type.googleapis.com/google.protobuf.Int64Value",yq="type.googleapis.com/google.protobuf.UInt64Value";function vq(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function _q(e){if(null==e)return null;if(e instanceof Number&&(e=e.valueOf()),"number"==typeof e&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map((e=>_q(e)));if("function"==typeof e||"object"==typeof e)return vq(e,(e=>_q(e)));throw new Error("Data cannot be encoded in JSON: "+e)}function wq(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case gq:case yq:{const t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t}default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map((e=>wq(e))):"function"==typeof e||"object"==typeof e?vq(e,(e=>wq(e))):e}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const bq="functions",Iq={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"};
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */class Eq extends Pa{constructor(e,t,n){super(`${bq}/${e}`,t||""),this.details=n}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class Tq{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then((e=>this.auth=e),(()=>{})),this.messaging||t.get().then((e=>this.messaging=e),(()=>{})),this.appCheck||n.get().then((e=>this.appCheck=e),(()=>{}))}async getAuthToken(){if(this.auth)try{const e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return await this.messaging.getToken()}catch(e){return}}async getAppCheckToken(e){if(this.appCheck){const t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return t.error?null:t.token}return null}async getContext(e){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken(e)}}}
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Sq="us-central1";function kq(e,t,n){return r=>function(e,t,n,r){const i=e._url(t);return xq(e,i,n,r)}(e,t,r,n||{})}async function Cq(e,t,n,r){let i;n["Content-Type"]="application/json";try{i=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let s=null;try{s=await i.json()}catch(e){}return{status:i.status,json:s}}async function xq(e,t,n,r){const i={data:n=_q(n)},s={},o=await e.contextProvider.getContext(r.limitedUseAppCheckTokens);o.authToken&&(s.Authorization="Bearer "+o.authToken),o.messagingToken&&(s["Firebase-Instance-ID-Token"]=o.messagingToken),null!==o.appCheckToken&&(s["X-Firebase-AppCheck"]=o.appCheckToken);const a=function(e){let t=null;return{promise:new Promise(((n,r)=>{t=setTimeout((()=>{r(new Eq("deadline-exceeded","deadline-exceeded"))}),e)})),cancel:()=>{t&&clearTimeout(t)}}}(r.timeout||7e4),c=await Promise.race([Cq(t,i,s,e.fetchImpl),a.promise,e.cancelAllRequests]);if(a.cancel(),!c)throw new Eq("cancelled","Firebase Functions instance was deleted.");const u=function(e,t){let n,r=function(e){if(e>=200&&e<300)return"ok";switch(e){case 0:case 500:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}(e),i=r;try{const e=t&&t.error;if(e){const t=e.status;if("string"==typeof t){if(!Iq[t])return new Eq("internal","internal");r=Iq[t],i=t}const s=e.message;"string"==typeof s&&(i=s),n=e.details,void 0!==n&&(n=wq(n))}}catch(e){}return"ok"===r?null:new Eq(r,i,n)}(c.status,c.json);if(u)throw u;if(!c.json)throw new Eq("internal","Response is not valid JSON object.");let l=c.json.data;if(void 0===l&&(l=c.json.result),void 0===l)throw new Eq("internal","Response is missing data field.");return{data:wq(l)}}const Aq="@firebase/functions",Nq="0.10.0";function Dq(e,t,n){!function(e,t,n){e.emulatorOrigin=`http://${t}:${n}`}(ic(e),t,n)}function Rq(e,t,n){return function(e,t,n){return r=>xq(e,t,r,n||{})}(ic(e),t,n)}!function(e,t){zc(new sc(bq,((t,{instanceIdentifier:n})=>{const r=t.getProvider("app").getImmediate(),i=t.getProvider("auth-internal"),s=t.getProvider("messaging-internal"),o=t.getProvider("app-check-internal");return new class{constructor(e,t,n,r,i=Sq,s){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new Tq(t,n,r),this.cancelAllRequests=new Promise((e=>{this.deleteService=()=>Promise.resolve(e())}));try{const e=new URL(i);this.customDomain=e.origin,this.region=Sq}catch(e){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){const t=this.app.options.projectId;return null!==this.emulatorOrigin?`${this.emulatorOrigin}/${t}/${this.region}/${e}`:null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`}}(r,i,s,o,n,e)}),"PUBLIC").setMultipleInstances(!0)),Yc(Aq,Nq,t),Yc(Aq,Nq,"esm2017")}(fetch.bind(self));
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class Oq{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return function(e,t,n){return kq(ic(e),t,n)}(this._delegate,e,t)}httpsCallableFromURL(e,t){return Rq(this._delegate,e,t)}useFunctionsEmulator(e){const t=e.match("[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?");if(null==t)throw new Pa("functions","No origin provided to useFunctionsEmulator()");if(null==t[2])throw new Pa("functions","Port missing in origin provided to useFunctionsEmulator()");return Dq(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return Dq(this._delegate,e,t)}}
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const Pq=(e,{instanceIdentifier:t})=>{const n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("functions").getImmediate({identifier:null!=t?t:"us-central1"});return new Oq(n,r)};
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
!function(){const e={Functions:Oq};uh.INTERNAL.registerComponent(new sc("functions-compat",Pq,"PUBLIC").setServiceProps(e).setMultipleInstances(!0))}(),uh.registerVersion("@firebase/functions-compat","0.3.5");const Mq=uh.initializeApp({apiKey:"AIzaSyA-mOn_mnhY_rY1edIrwkPqbXnD8RO_oUs",authDomain:"storage-38f70.firebaseapp.com",projectId:"storage-38f70",storageBucket:"storage-38f70.appspot.com",messagingSenderId:"485873076970",appId:"1:235233622420:web:7839bd76347760ccd4f781",measurementId:"235233622420"},"aime-feedback-instance");Mq.auth(),Mq.firestore(),Mq.functions();const Lq=Mq.storage(),Fq=(e,n,r=3e3)=>{t.createStandaloneToast().toast({description:n,status:e,position:"bottom",duration:r,isClosable:!0})};var jq,qq;!function(e){e.NEW_FEEDBACK_ITEM="new_feedback_item",e.SUBMITTED_FEEDBACK_ITEM="submitted_feedback_item",e.COMPLETED_FEEDBACK_ITEM="completed_feedback_item",e.REJECTED_FEEDBACK_ITEM="rejected_feedback_item"}(jq||(jq={})),function(e){e.CLIENT_ASSIGNMENTS_PATH="/client-assignments",e.ITEMS_TO_ASSIGN_PATH="/items-to-assign",e.ASSIGNED_TO_AIME_PATH="/assigned-to-aime",e.DASHBOARD_PATH="/dashboard",e.ASSIGNMENTS_PATH="/assignments",e.APP_LINKS_PATH="/app-links",e.COMPLETED_PATH="/completed",e.CLIENT_ACCEPTS_PATH="/client-accepts",e.DEPLOYMENTS_PATH="/deployments"}(qq||(qq={}));const Vq=localStorage.getItem("feedback_p")?JSON.parse(localStorage.getItem("feedback_p")||""):{project_id:244,project_name:"AIME Platform Feedback",project_manager:"Emma and Matt",project_description:"Feedback for the AIME Beta",owner:"matt",org_id:"org_QmYoBxUCo5FB4Yfn",created_at:"2022-08-05T09:52:47.433913+00:00",project_status:"think",updated_at:"2022-08-05T09:52:47.433913+00:00"};var Uq;!function(e){e.ADMIN="admin",e.USER="user",e.AIME_TEAM="aime_team",e.CLIENT_ADMIN="client_admin",e.ANONYMOUS="anonymous"}(Uq||(Uq={}));var Bq=new Map([["aac","audio/aac"],["abw","application/x-abiword"],["arc","application/x-freearc"],["avif","image/avif"],["avi","video/x-msvideo"],["azw","application/vnd.amazon.ebook"],["bin","application/octet-stream"],["bmp","image/bmp"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["cda","application/x-cdf"],["csh","application/x-csh"],["css","text/css"],["csv","text/csv"],["doc","application/msword"],["docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],["eot","application/vnd.ms-fontobject"],["epub","application/epub+zip"],["gz","application/gzip"],["gif","image/gif"],["heic","image/heic"],["heif","image/heif"],["htm","text/html"],["html","text/html"],["ico","image/vnd.microsoft.icon"],["ics","text/calendar"],["jar","application/java-archive"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["js","text/javascript"],["json","application/json"],["jsonld","application/ld+json"],["mid","audio/midi"],["midi","audio/midi"],["mjs","text/javascript"],["mp3","audio/mpeg"],["mp4","video/mp4"],["mpeg","video/mpeg"],["mpkg","application/vnd.apple.installer+xml"],["odp","application/vnd.oasis.opendocument.presentation"],["ods","application/vnd.oasis.opendocument.spreadsheet"],["odt","application/vnd.oasis.opendocument.text"],["oga","audio/ogg"],["ogv","video/ogg"],["ogx","application/ogg"],["opus","audio/opus"],["otf","font/otf"],["png","image/png"],["pdf","application/pdf"],["php","application/x-httpd-php"],["ppt","application/vnd.ms-powerpoint"],["pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],["rar","application/vnd.rar"],["rtf","application/rtf"],["sh","application/x-sh"],["svg","image/svg+xml"],["swf","application/x-shockwave-flash"],["tar","application/x-tar"],["tif","image/tiff"],["tiff","image/tiff"],["ts","video/mp2t"],["ttf","font/ttf"],["txt","text/plain"],["vsd","application/vnd.visio"],["wav","audio/wav"],["weba","audio/webm"],["webm","video/webm"],["webp","image/webp"],["woff","font/woff"],["woff2","font/woff2"],["xhtml","application/xhtml+xml"],["xls","application/vnd.ms-excel"],["xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],["xml","application/xml"],["xul","application/vnd.mozilla.xul+xml"],["zip","application/zip"],["7z","application/x-7z-compressed"],["mkv","video/x-matroska"],["mov","video/quicktime"],["msg","application/vnd.ms-outlook"]]);function zq(e,t){var n=function(e){var t=e.name,n=t&&-1!==t.lastIndexOf(".");if(n&&!e.type){var r=t.split(".").pop().toLowerCase(),i=Bq.get(r);i&&Object.defineProperty(e,"type",{value:i,writable:!1,configurable:!1,enumerable:!0})}return e}(e);if("string"!=typeof n.path){var r=e.webkitRelativePath;Object.defineProperty(n,"path",{value:"string"==typeof t?t:"string"==typeof r&&r.length>0?r:e.name,writable:!1,configurable:!1,enumerable:!0})}return n}var $q=[".DS_Store","Thumbs.db"];function Wq(e){return"object"==typeof e&&null!==e}function Qq(e){return Yq(e.target.files).map((function(e){return zq(e)}))}function Hq(e){return pt(this,void 0,void 0,(function(){return mt(this,(function(t){switch(t.label){case 0:return[4,Promise.all(e.map((function(e){return e.getFile()})))];case 1:return[2,t.sent().map((function(e){return zq(e)}))]}}))}))}function Gq(e,t){return pt(this,void 0,void 0,(function(){var n;return mt(this,(function(r){switch(r.label){case 0:return e.items?(n=Yq(e.items).filter((function(e){return"file"===e.kind})),"drop"!==t?[2,n]:[4,Promise.all(n.map(Jq))]):[3,2];case 1:return[2,Kq(Xq(r.sent()))];case 2:return[2,Kq(Yq(e.files).map((function(e){return zq(e)})))]}}))}))}function Kq(e){return e.filter((function(e){return-1===$q.indexOf(e.name)}))}function Yq(e){if(null===e)return[];for(var t=[],n=0;n<e.length;n++){var r=e[n];t.push(r)}return t}function Jq(e){if("function"!=typeof e.webkitGetAsEntry)return Zq(e);var t=e.webkitGetAsEntry();return t&&t.isDirectory?tV(t):Zq(e)}function Xq(e){return e.reduce((function(e,t){return yt(yt([],gt(e),!1),gt(Array.isArray(t)?Xq(t):[t]),!1)}),[])}function Zq(e){var t=e.getAsFile();if(!t)return Promise.reject("".concat(e," is not a File"));var n=zq(t);return Promise.resolve(n)}function eV(e){return pt(this,void 0,void 0,(function(){return mt(this,(function(t){return[2,e.isDirectory?tV(e):nV(e)]}))}))}function tV(e){var t=e.createReader();return new Promise((function(e,n){var r=[];!function i(){var s=this;t.readEntries((function(t){return pt(s,void 0,void 0,(function(){var s,o,a;return mt(this,(function(c){switch(c.label){case 0:if(t.length)return[3,5];c.label=1;case 1:return c.trys.push([1,3,,4]),[4,Promise.all(r)];case 2:return s=c.sent(),e(s),[3,4];case 3:return o=c.sent(),n(o),[3,4];case 4:return[3,6];case 5:a=Promise.all(t.map(eV)),r.push(a),i(),c.label=6;case 6:return[2]}}))}))}),(function(e){n(e)}))}()}))}function nV(e){return pt(this,void 0,void 0,(function(){return mt(this,(function(t){return[2,new Promise((function(t,n){e.file((function(n){var r=zq(n,e.fullPath);t(r)}),(function(e){n(e)}))}))]}))}))}var rV=function(e,t){if(e&&t){var n=Array.isArray(t)?t:t.split(","),r=e.name||"",i=(e.type||"").toLowerCase(),s=i.replace(/\/.*$/,"");return n.some((function(e){var t=e.trim().toLowerCase();return"."===t.charAt(0)?r.toLowerCase().endsWith(t):t.endsWith("/*")?s===t.replace(/\/.*$/,""):i===t}))}return!0};function iV(e){return function(e){if(Array.isArray(e))return lV(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||uV(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function sV(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function oV(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?sV(Object(n),!0).forEach((function(t){aV(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):sV(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function aV(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function cV(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==n)return;var r,i,s=[],o=!0,a=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(s.push(r.value),!t||s.length!==t);o=!0);}catch(e){a=!0,i=e}finally{try{o||null==n.return||n.return()}finally{if(a)throw i}}return s}(e,t)||uV(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function uV(e,t){if(e){if("string"==typeof e)return lV(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?lV(e,t):void 0}}function lV(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var hV=function(e){e=Array.isArray(e)&&1===e.length?e[0]:e;var t=Array.isArray(e)?"one of ".concat(e.join(", ")):e;return{code:"file-invalid-type",message:"File type must be ".concat(t)}},dV=function(e){return{code:"file-too-large",message:"File is larger than ".concat(e," ").concat(1===e?"byte":"bytes")}},fV=function(e){return{code:"file-too-small",message:"File is smaller than ".concat(e," ").concat(1===e?"byte":"bytes")}},pV={code:"too-many-files",message:"Too many files"};function mV(e,t){var n="application/x-moz-file"===e.type||rV(e,t);return[n,n?null:hV(t)]}function gV(e,t,n){if(yV(e.size))if(yV(t)&&yV(n)){if(e.size>n)return[!1,dV(n)];if(e.size<t)return[!1,fV(t)]}else{if(yV(t)&&e.size<t)return[!1,fV(t)];if(yV(n)&&e.size>n)return[!1,dV(n)]}return[!0,null]}function yV(e){return null!=e}function vV(e){return"function"==typeof e.isPropagationStopped?e.isPropagationStopped():void 0!==e.cancelBubble&&e.cancelBubble}function _V(e){return e.dataTransfer?Array.prototype.some.call(e.dataTransfer.types,(function(e){return"Files"===e||"application/x-moz-file"===e})):!!e.target&&!!e.target.files}function wV(e){e.preventDefault()}function bV(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return t.some((function(t){return!vV(e)&&t&&t.apply(void 0,[e].concat(r)),vV(e)}))}}function IV(e){return"audio/*"===e||"video/*"===e||"image/*"===e||"text/*"===e||/\w+\/[-+.\w]+/g.test(e)}function EV(e){return/^.*\.[\w]+$/.test(e)}var TV=["children"],SV=["open"],kV=["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"],CV=["refKey","onChange","onClick"];function xV(e){return function(e){if(Array.isArray(e))return DV(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||NV(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function AV(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==n)return;var r,i,s=[],o=!0,a=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(s.push(r.value),!t||s.length!==t);o=!0);}catch(e){a=!0,i=e}finally{try{o||null==n.return||n.return()}finally{if(a)throw i}}return s}(e,t)||NV(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function NV(e,t){if(e){if("string"==typeof e)return DV(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?DV(e,t):void 0}}function DV(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function RV(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function OV(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?RV(Object(n),!0).forEach((function(t){PV(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):RV(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function PV(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function MV(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n,r,i={},s=Object.keys(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)>=0||(i[n]=e[n]);return i}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}var LV=n.forwardRef((function(e,t){var r=e.children,i=qV(MV(e,TV)),s=i.open,o=MV(i,SV);return n.useImperativeHandle(t,(function(){return{open:s}}),[s]),n.createElement(n.Fragment,null,r(OV(OV({},o),{},{open:s})))}));LV.displayName="Dropzone";var FV={disabled:!1,getFilesFromEvent:function(e){return pt(this,void 0,void 0,(function(){return mt(this,(function(t){return Wq(e)&&Wq(e.dataTransfer)?[2,Gq(e.dataTransfer,e.type)]:function(e){return Wq(e)&&Wq(e.target)}(e)?[2,Qq(e)]:Array.isArray(e)&&e.every((function(e){return"getFile"in e&&"function"==typeof e.getFile}))?[2,Hq(e)]:[2,[]]}))}))},maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!0,autoFocus:!1};LV.defaultProps=FV,LV.propTypes={children:He.func,accept:He.objectOf(He.arrayOf(He.string)),multiple:He.bool,preventDropOnDocument:He.bool,noClick:He.bool,noKeyboard:He.bool,noDrag:He.bool,noDragEventsBubbling:He.bool,minSize:He.number,maxSize:He.number,maxFiles:He.number,disabled:He.bool,getFilesFromEvent:He.func,onFileDialogCancel:He.func,onFileDialogOpen:He.func,useFsAccessApi:He.bool,autoFocus:He.bool,onDragEnter:He.func,onDragLeave:He.func,onDragOver:He.func,onDrop:He.func,onDropAccepted:He.func,onDropRejected:He.func,onError:He.func,validator:He.func};var jV={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function qV(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=OV(OV({},FV),e),r=t.accept,i=t.disabled,s=t.getFilesFromEvent,o=t.maxSize,a=t.minSize,c=t.multiple,u=t.maxFiles,l=t.onDragEnter,h=t.onDragLeave,d=t.onDragOver,f=t.onDrop,p=t.onDropAccepted,m=t.onDropRejected,g=t.onFileDialogCancel,y=t.onFileDialogOpen,v=t.useFsAccessApi,_=t.autoFocus,w=t.preventDropOnDocument,b=t.noClick,I=t.noKeyboard,E=t.noDrag,T=t.noDragEventsBubbling,S=t.onError,k=t.validator,C=n.useMemo((function(){return function(e){if(yV(e))return Object.entries(e).reduce((function(e,t){var n=cV(t,2),r=n[0],i=n[1];return[].concat(iV(e),[r],iV(i))}),[]).filter((function(e){return IV(e)||EV(e)})).join(",")}(r)}),[r]),x=n.useMemo((function(){return function(e){return yV(e)?[{description:"Files",accept:Object.entries(e).filter((function(e){var t=cV(e,2),n=t[0],r=t[1],i=!0;return IV(n)||(console.warn('Skipped "'.concat(n,'" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.')),i=!1),Array.isArray(r)&&r.every(EV)||(console.warn('Skipped "'.concat(n,'" because an invalid file extension was provided.')),i=!1),i})).reduce((function(e,t){var n=cV(t,2),r=n[0],i=n[1];return oV(oV({},e),{},aV({},r,i))}),{})}]:e}(r)}),[r]),A=n.useMemo((function(){return"function"==typeof y?y:UV}),[y]),N=n.useMemo((function(){return"function"==typeof g?g:UV}),[g]),D=n.useRef(null),R=n.useRef(null),O=AV(n.useReducer(VV,jV),2),P=O[0],M=O[1],L=P.isFocused,F=P.isFileDialogActive,j=n.useRef("undefined"!=typeof window&&window.isSecureContext&&v&&"showOpenFilePicker"in window),q=function(){!j.current&&F&&setTimeout((function(){R.current&&(R.current.files.length||(M({type:"closeDialog"}),N()))}),300)};n.useEffect((function(){return window.addEventListener("focus",q,!1),function(){window.removeEventListener("focus",q,!1)}}),[R,F,N,j]);var V=n.useRef([]),U=function(e){D.current&&D.current.contains(e.target)||(e.preventDefault(),V.current=[])};n.useEffect((function(){return w&&(document.addEventListener("dragover",wV,!1),document.addEventListener("drop",U,!1)),function(){w&&(document.removeEventListener("dragover",wV),document.removeEventListener("drop",U))}}),[D,w]),n.useEffect((function(){return!i&&_&&D.current&&D.current.focus(),function(){}}),[D,_,i]);var B=n.useCallback((function(e){S?S(e):console.error(e)}),[S]),z=n.useCallback((function(e){e.preventDefault(),e.persist(),ne(e),V.current=[].concat(xV(V.current),[e.target]),_V(e)&&Promise.resolve(s(e)).then((function(t){if(!vV(e)||T){var n=t.length,r=n>0&&function(e){var t=e.files,n=e.accept,r=e.minSize,i=e.maxSize,s=e.multiple,o=e.maxFiles,a=e.validator;return!(!s&&t.length>1||s&&o>=1&&t.length>o)&&t.every((function(e){var t=cV(mV(e,n),1)[0],s=cV(gV(e,r,i),1)[0],o=a?a(e):null;return t&&s&&!o}))}({files:t,accept:C,minSize:a,maxSize:o,multiple:c,maxFiles:u,validator:k});M({isDragAccept:r,isDragReject:n>0&&!r,isDragActive:!0,type:"setDraggedFiles"}),l&&l(e)}})).catch((function(e){return B(e)}))}),[s,l,B,T,C,a,o,c,u,k]),$=n.useCallback((function(e){e.preventDefault(),e.persist(),ne(e);var t=_V(e);if(t&&e.dataTransfer)try{e.dataTransfer.dropEffect="copy"}catch(e){}return t&&d&&d(e),!1}),[d,T]),W=n.useCallback((function(e){e.preventDefault(),e.persist(),ne(e);var t=V.current.filter((function(e){return D.current&&D.current.contains(e)})),n=t.indexOf(e.target);-1!==n&&t.splice(n,1),V.current=t,t.length>0||(M({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),_V(e)&&h&&h(e))}),[D,h,T]),Q=n.useCallback((function(e,t){var n=[],r=[];e.forEach((function(e){var t=AV(mV(e,C),2),i=t[0],s=t[1],c=AV(gV(e,a,o),2),u=c[0],l=c[1],h=k?k(e):null;if(i&&u&&!h)n.push(e);else{var d=[s,l];h&&(d=d.concat(h)),r.push({file:e,errors:d.filter((function(e){return e}))})}})),(!c&&n.length>1||c&&u>=1&&n.length>u)&&(n.forEach((function(e){r.push({file:e,errors:[pV]})})),n.splice(0)),M({acceptedFiles:n,fileRejections:r,type:"setFiles"}),f&&f(n,r,t),r.length>0&&m&&m(r,t),n.length>0&&p&&p(n,t)}),[M,c,C,a,o,u,f,p,m,k]),H=n.useCallback((function(e){e.preventDefault(),e.persist(),ne(e),V.current=[],_V(e)&&Promise.resolve(s(e)).then((function(t){vV(e)&&!T||Q(t,e)})).catch((function(e){return B(e)})),M({type:"reset"})}),[s,Q,B,T]),G=n.useCallback((function(){if(j.current){M({type:"openDialog"}),A();var e={multiple:c,types:x};window.showOpenFilePicker(e).then((function(e){return s(e)})).then((function(e){Q(e,null),M({type:"closeDialog"})})).catch((function(e){!function(e){return e instanceof DOMException&&("AbortError"===e.name||e.code===e.ABORT_ERR)}(e)?!function(e){return e instanceof DOMException&&("SecurityError"===e.name||e.code===e.SECURITY_ERR)}(e)?B(e):(j.current=!1,R.current?(R.current.value=null,R.current.click()):B(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no <input> was provided."))):(N(e),M({type:"closeDialog"}))}))}else R.current&&(M({type:"openDialog"}),A(),R.current.value=null,R.current.click())}),[M,A,N,v,Q,B,x,c]),K=n.useCallback((function(e){D.current&&D.current.isEqualNode(e.target)&&(" "!==e.key&&"Enter"!==e.key&&32!==e.keyCode&&13!==e.keyCode||(e.preventDefault(),G()))}),[D,G]),Y=n.useCallback((function(){M({type:"focus"})}),[]),J=n.useCallback((function(){M({type:"blur"})}),[]),X=n.useCallback((function(){b||(!function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.navigator.userAgent;return function(e){return-1!==e.indexOf("MSIE")||-1!==e.indexOf("Trident/")}(e)||function(e){return-1!==e.indexOf("Edge/")}(e)}()?G():setTimeout(G,0))}),[b,G]),Z=function(e){return i?null:e},ee=function(e){return I?null:Z(e)},te=function(e){return E?null:Z(e)},ne=function(e){T&&e.stopPropagation()},re=n.useMemo((function(){return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.refKey,n=void 0===t?"ref":t,r=e.role,s=e.onKeyDown,o=e.onFocus,a=e.onBlur,c=e.onClick,u=e.onDragEnter,l=e.onDragOver,h=e.onDragLeave,d=e.onDrop,f=MV(e,kV);return OV(OV(PV({onKeyDown:ee(bV(s,K)),onFocus:ee(bV(o,Y)),onBlur:ee(bV(a,J)),onClick:Z(bV(c,X)),onDragEnter:te(bV(u,z)),onDragOver:te(bV(l,$)),onDragLeave:te(bV(h,W)),onDrop:te(bV(d,H)),role:"string"==typeof r&&""!==r?r:"presentation"},n,D),i||I?{}:{tabIndex:0}),f)}}),[D,K,Y,J,X,z,$,W,H,I,E,i]),ie=n.useCallback((function(e){e.stopPropagation()}),[]),se=n.useMemo((function(){return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.refKey,n=void 0===t?"ref":t,r=e.onChange,i=e.onClick,s=MV(e,CV);return OV(OV({},PV({accept:C,multiple:c,type:"file",style:{display:"none"},onChange:Z(bV(r,H)),onClick:Z(bV(i,ie)),tabIndex:-1},n,R)),s)}}),[R,r,c,H,i]);return OV(OV({},P),{},{isFocused:L&&!i,getRootProps:re,getInputProps:se,rootRef:D,inputRef:R,open:Z(G)})}function VV(e,t){switch(t.type){case"focus":return OV(OV({},e),{},{isFocused:!0});case"blur":return OV(OV({},e),{},{isFocused:!1});case"openDialog":return OV(OV({},jV),{},{isFileDialogActive:!0});case"closeDialog":return OV(OV({},e),{},{isFileDialogActive:!1});case"setDraggedFiles":return OV(OV({},e),{},{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return OV(OV({},e),{},{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return OV({},jV);default:return e}}function UV(){}let BV;const zV=new Uint8Array(16);function $V(){if(!BV&&(BV="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!BV))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return BV(zV)}const WV=[];for(let e=0;e<256;++e)WV.push((e+256).toString(16).slice(1));var QV={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function HV(e,t,n){if(QV.randomUUID&&!t&&!e)return QV.randomUUID();const r=(e=e||{}).random||(e.rng||$V)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){n=n||0;for(let e=0;e<16;++e)t[n+e]=r[e];return t}return function(e,t=0){return(WV[e[t+0]]+WV[e[t+1]]+WV[e[t+2]]+WV[e[t+3]]+"-"+WV[e[t+4]]+WV[e[t+5]]+"-"+WV[e[t+6]]+WV[e[t+7]]+"-"+WV[e[t+8]]+WV[e[t+9]]+"-"+WV[e[t+10]]+WV[e[t+11]]+WV[e[t+12]]+WV[e[t+13]]+WV[e[t+14]]+WV[e[t+15]]).toLowerCase()}(r)}function GV(){let r=n.useRef(null);const[i,o]=n.useState("#FFFF00"),a=n.useContext($o),c=a?.updateComments??(()=>{}),u=a?.state.comments;return e.jsxs(t.Stack,{spacing:3,w:"100%",children:[e.jsx(t.Box,{h:"2rem",alignItems:"end",display:"flex",w:"100%",children:e.jsx(t.Text,{color:Zo,fontSize:"0.6875rem",fontWeight:"700",children:"Comment"})}),e.jsx(t.Textarea,{ref:r,name:"comment",placeholder:"Enter comment here...",color:Zo,bg:Yo,fontSize:"0.6875rem",fontWeight:"400",_hover:{bg:Yo},_placeholder:{color:Zo},_focusVisible:{outline:"none"},borderColor:Yo}),e.jsxs(t.Flex,{justifyContent:"space-between",alignItems:"center",children:[e.jsx(KV,{currentFill:i,onColorPicked:o}),e.jsx(t.Button,{type:"button",bg:Xo,h:"2.8rem",_hover:{bg:Yo},color:Zo,fontSize:".8rem",fontWeight:"400",onClick:e=>{if(e.preventDefault(),r.current?.value){let e=s.cloneDeep(u);e.push({text:r?.current.value,x:300*Math.random()+140,y:150*Math.random()+100,fill:i}),c(e),r.current.value="";let t=document.getElementsByClassName(`${s.snakeCase("add-comment-btn")}`)[0];t?.click()}},children:"Add Comment"})]})]})}const KV=n=>{const{currentFill:r="#FFFF00",onColorPicked:i}=n;return e.jsx(t.Flex,{gap:2,children:["#FFFF00","#3CC960","#d99634","#2979ff","#bdbdbd","#ce4848"].map(((n,s)=>e.jsx(t.Box,{bg:n,w:r===n?"24px":"18px",h:r===n?"24px":"18px",borderRadius:"50%",border:r===n?"2px solid #000a":"none",transition:"all 0.3s ease",_hover:r===n?{}:{transform:"scale(1.2)"},cursor:"pointer",onClick:()=>i(n)},s)))})};function YV(r){const i=["low","moderate","high"],s=n.useContext($o),o=s?.state.screenshot_images,a=s?.state.comments,c=s?.feedbackItem,u=s?.setFeedbackItem??(()=>{}),l=s?.resetState??(()=>{}),{activeProjectID:h}=n.useContext(Zl),{onClose:d,appName:f}=r,[p,{loading:m}]=qo(Uo,{onCompleted:e=>{Fq("success","Feedback item added"),l(),d()},onError:e=>{console.log("🚀 ~ addFeedbackItem ~ error",e),Fq("error",`This error occurred: ${e.message}`)},refetchQueries:[{query:zo,context:{clientName:"feedback-tool"},variables:{project_id:h},fetchPolicy:"no-cache"}]});return e.jsxs(t.VStack,{spacing:".5rem",bg:Jo,p:"1rem 1.5rem",borderRadius:"1rem",w:"25rem",pt:"9vh",children:[e.jsxs(t.VStack,{spacing:".25rem",w:"100%",justifyContent:"left",children:[e.jsx(t.Box,{h:"2rem",alignItems:"end",display:"flex",w:"100%",children:e.jsx(t.Text,{color:Zo,fontSize:"0.6875rem",fontWeight:"700",mr:"auto",children:"Type"})}),e.jsxs(t.Select,{variant:"filled",bg:Yo,fontSize:"0.6875rem",color:Zo,fontWeight:"400",_hover:{bg:Yo},defaultValue:"null",_focusVisible:{outline:"none"},value:c.type,onChange:e=>u({...c,type:e.target.value}),children:[e.jsx("option",{value:"null",style:{backgroundColor:Yo,color:"white",height:"40px"},children:"Select Type"}),["Bug","Request","Feedback","Wording Change"].map(((t,n)=>e.jsx("option",{style:{backgroundColor:Yo,color:"white",height:"40px"},value:t,id:n,children:t})))]})]}),e.jsxs(t.VStack,{spacing:".25rem",w:"100%",justifyContent:"left",children:[e.jsx(t.Box,{h:"2rem",alignItems:"end",display:"flex",w:"100%",children:e.jsx(t.Text,{color:Zo,fontSize:"0.6875rem",fontWeight:"700",mr:"auto",children:"Priority"})}),e.jsx(t.Tabs,{isFitted:!0,variant:"unstyled",w:"100%",onChange:e=>u({...c,priority:i[e]}),children:e.jsx(t.TabList,{bg:Yo,borderRadius:".35rem",p:".125rem",children:i.map((n=>e.jsx(t.Tab,{fontSize:".75rem",h:"3rem",color:Zo,fontWeight:"700",borderRadius:".25rem",py:".75rem",bg:"transparent",textTransform:"capitalize",_selected:{bg:Xo},_notLast:{mr:".125rem"},children:n},n)))})})]}),e.jsxs(t.VStack,{spacing:".25rem",w:"100%",justifyContent:"left",children:[e.jsx(t.Box,{h:"2rem",alignItems:"end",display:"flex",w:"100%",children:e.jsx(t.Text,{color:Zo,fontSize:"0.6875rem",fontWeight:"700",mr:"auto",children:"Title"})}),e.jsx(t.Input,{type:"text",variant:"filled",bg:Yo,placeholder:"Name the issue",fontSize:"0.6875rem",color:Zo,fontWeight:"400",_hover:{bg:Yo},_placeholder:{color:Zo,textTransform:"capitalize"},_focusVisible:{outline:"none"},value:c.title,onChange:e=>u({...c,title:e.target.value})})]}),e.jsx(t.VStack,{spacing:".25rem",w:"100%",justifyContent:"left",children:e.jsx(GV,{})}),e.jsx(t.Box,{p:"1rem",pl:"0",mr:"auto",children:e.jsx(t.Button,{bg:Xo,h:"2.8rem",w:"4rem",_hover:{bg:Yo},color:Zo,fontSize:".8rem",fontWeight:"400",isLoading:m,onClick:()=>{console.log(c),console.log(o),console.log(a),console.log("activeProjectID",h),p({variables:{type:c?.type,screenshot_images:o,comments:a,project:f,project_id:h,due_date:(new Date).toISOString(),priority:c?.priority,status:"Pending",created_by:"N/A",org_id:"N/A",creator_id:"N/A",title:c?.title}})},children:"Save"})})]})}var JV,XV={exports:{}};function ZV(){if(void 0===JV){var e=new ArrayBuffer(2),t=new Uint8Array(e),n=new Uint16Array(e);if(t[0]=1,t[1]=2,258===n[0])JV="BE";else{if(513!==n[0])throw new Error("unable to figure out endianess");JV="LE"}}return JV}function eU(){return void 0!==h.location?h.location.hostname:""}function tU(){return[]}function nU(){return 0}function rU(){return Number.MAX_VALUE}function iU(){return Number.MAX_VALUE}function sU(){return[]}function oU(){return"Browser"}function aU(){return void 0!==h.navigator?h.navigator.appVersion:""}function cU(){return{}}function uU(){return{}}function lU(){return"javascript"}function hU(){return"browser"}function dU(){return"/tmp"}var fU=dU;function pU(){return"$HOME"}var mU={homedir:pU,EOL:"\n",arch:lU,platform:hU,tmpdir:fU,tmpDir:dU,networkInterfaces:cU,getNetworkInterfaces:uU,release:aU,type:oU,cpus:sU,totalmem:iU,freemem:rU,uptime:nU,loadavg:tU,hostname:eU,endianness:ZV},gU=Ie(Object.freeze({__proto__:null,EOL:"\n",arch:lU,cpus:sU,default:mU,endianness:ZV,freemem:rU,getNetworkInterfaces:uU,homedir:pU,hostname:eU,loadavg:tU,networkInterfaces:cU,platform:hU,release:aU,tmpDir:dU,tmpdir:fU,totalmem:iU,type:oU,uptime:nU})),yU=void 0!==M&&M.pid?M.pid.toString(36):"",vU="";if("function"!=typeof __webpack_require__){var _U="",wU=gU;if(wU.networkInterfaces)var bU=wU.networkInterfaces();if(bU){e:for(let e in bU){const t=bU[e],n=t.length;for(var IU=0;IU<n;IU++)if(void 0!==t[IU]&&t[IU].mac&&"00:00:00:00:00:00"!=t[IU].mac){_U=t[IU].mac;break e}}vU=_U?parseInt(_U.replace(/\:|\D+/gi,"")).toString(36):""}}function EU(){var e=Date.now(),t=EU.last||e;return EU.last=e>t?e:t+1}XV.exports=XV.exports.default=function(e,t){return(e||"")+vU+yU+EU().toString(36)+(t||"")},XV.exports.process=function(e,t){return(e||"")+yU+EU().toString(36)+(t||"")},XV.exports.time=function(e,t){return(e||"")+EU().toString(36)+(t||"")};var TU=be(XV.exports);const SU="https://aime-imageurl.s3.amazonaws.com/avatar.png-1690872724976.png",kU=({src:n})=>e.jsx(t.Box,{p:".09375rem",children:e.jsx(t.Image,{draggable:"false",src:n,alt:"image",minH:"2rem",minW:"2rem"})}),CU=n=>e.jsxs(t.Icon,{width:"1rem",height:"1rem",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...n,children:[e.jsx("path",{d:"M7.00065 8H3.33398",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M1.71625 3.15271C1.59527 2.7882 1.53478 2.60595 1.57881 2.49369C1.61704 2.39619 1.69888 2.32234 1.79977 2.29426C1.91595 2.26194 2.09106 2.34074 2.44129 2.49834L13.5862 7.5135C13.929 7.6678 14.1005 7.74495 14.1535 7.85212C14.1995 7.94524 14.1995 8.05449 14.1535 8.1476C14.1005 8.25477 13.929 8.33192 13.5862 8.48622L2.44517 13.4997C2.09388 13.6577 1.91824 13.7368 1.80195 13.7043C1.70096 13.6761 1.61912 13.6021 1.58101 13.5044C1.53713 13.3919 1.59828 13.2093 1.72057 12.844L3.27718 8.19419C3.29812 8.13164 3.30859 8.10037 3.31277 8.06837C3.31649 8.03997 3.31652 8.01121 3.31288 7.9828C3.30878 7.95079 3.29839 7.91948 3.27761 7.85688L1.71625 3.15271Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]});function xU(r){const{comment:i}=r;const s=n.useContext($o),o=s?.updateComments??(()=>{}),a=s?.state.comments??[];const[u,l]=n.useState(""),h=()=>{if(u&&""!==u){let e=[...a,{id:HV(),text:u,x:300*Math.random()+140,y:150*Math.random()+100,fill:"#FFFF00"}];o(e),l("")}};return e.jsxs(t.VStack,{w:"100%",spacing:4,borderBottom:"1px solid",borderColor:"transparent",p:"0",children:[e.jsxs(t.HStack,{p:"1.5rem 2rem",spacing:"1rem",w:"100%",alignItems:"flex-start",borderBottom:"1px solid",borderColor:Jo,children:[e.jsx(kU,{src:SU}),e.jsxs(t.VStack,{spacing:"1rem",justifyContent:"flex-start",textAlign:"left",w:"100%",children:[e.jsxs(t.Box,{mr:"auto",mt:".5rem",children:[e.jsxs(t.Text,{fontSize:"0.875rem",fontWeight:"600",color:Zo,children:["Aman"," says..."]}),e.jsx(t.Text,{fontSize:"0.875rem",fontWeight:"500",color:Zo,children:i?.text})]}),e.jsx(t.Text,{textAlign:"left",w:"100%",fontSize:"0.75rem",fontWeight:"500",color:Zo,opacity:".8",children:"2 Hour Ago"}),e.jsxs(t.HStack,{w:"100%",spacing:".75rem",children:[e.jsx(th,{}),e.jsx(t.Input,{placeholder:"Reply",variant:"unstyled",color:Zo,borderRadius:"0",value:u,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),h())}}),u&&""!==u&&e.jsx(t.Button,{h:"40px",variant:"link",_hover:{textDecoration:"none",bg:Jo},_active:{color:Zo},bg:Xo,size:"md",color:Zo,onClick:h,p:".75rem",children:e.jsx(t.HStack,{spacing:".75rem",children:e.jsx(CU,{})})}),e.jsx(t.Button,{h:"40px",variant:"link",_hover:{textDecoration:"none",bg:Jo},_active:{color:Zo},bg:"red.800",size:"md",color:Zo,p:".75rem",onClick:()=>{return e=i.id,console.log("ContextComments",a),void o(a.filter((t=>t.id!==e)));var e},children:e.jsx(t.HStack,{spacing:".75rem",children:e.jsx(c.DeleteIcon,{h:"1.15rem",w:"1.25rem",opacity:".5"})})})]})]})]}),undefined]})}function AU(){const r=n.useContext($o),i=r?.updateComments??(()=>{}),s=r?.state.comments,o=n.useRef(null);n.useEffect((()=>{o?.current?.scrollIntoView({behavior:"smooth"})}),[s]);const[a,c]=n.useState(""),u=()=>{if(a&&""!==a){let e=[...s,{id:HV(),text:a,x:300*Math.random()+140,y:150*Math.random()+100,fill:"#FFFF00"}];i(e),c("")}};return e.jsx(t.Box,{zIndex:`calc(${ea} + 1)`,mt:"9vh",w:"30rem",ml:"auto",bg:Yo,border:"1px solid",borderColor:Yo,borderTop:"none",alignItems:"flex-start",children:e.jsxs(t.Tabs,{variant:"unstyled",w:"100%",children:[e.jsx(t.TabList,{border:".0625rem solid",borderLeft:"0",borderRight:"0",borderColor:Yo,p:"0 .5rem",maxH:"2rem",children:["open"].map(((n,r)=>e.jsx(t.Tab,{textTransform:"capitalize",fontSize:"0.6875rem",fontWeight:"700",_selected:{opacity:1},color:Zo,opacity:.3,padding:".88rem 1rem",_focusVisible:{outline:"none"},children:n},r)))}),e.jsx(t.TabPanels,{position:"relative",children:e.jsxs(t.TabPanel,{p:"0",children:[e.jsxs(t.VStack,{overflowY:"auto",minH:"70vh",maxH:"70vh",className:"custom-scrollbar",children:[s.length>0?s.map((t=>e.jsx(xU,{comment:t},TU()))):e.jsx(e.Fragment,{children:e.jsx(t.Box,{w:"25rem",h:"80vh",alignItems:"center",display:"flex",justifyContent:"center",flexDirection:"column",color:"gray.300",children:"No comments yet. Be the first to comment!"})}),e.jsx("div",{ref:o})]}),e.jsx(t.Stack,{bg:Yo,h:"8vh",width:"100%",children:e.jsx(t.HStack,{position:"absolute",p:"2rem",pt:"0",mt:"auto",w:"100%",children:e.jsx(t.HStack,{spacing:"1rem",borderRadius:".25rem",w:"100%",bg:Yo,justifyContent:"space-between",alignContent:"flex-start",children:e.jsxs(t.InputGroup,{variant:"unstyled",maxH:"3rem",pr:"5rem",children:[e.jsx(t.Input,{placeholder:"Add a comment",variant:"unstyled",borderColor:Jo,border:`1px solid ${Jo}`,fontSize:"14",p:"4",color:Zo,_placeholder:{color:Zo,opacity:.4},resize:"none",className:"no-scrollbar",onChange:e=>c(e.target.value),value:a,onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),u())}}),e.jsx(t.InputRightElement,{width:"fit-content",children:e.jsx(t.Button,{variant:"unstyled",ml:"0",w:"3rem",h:"3rem",display:"grid",placeItems:"center",onClick:u,style:{background:ta},children:e.jsx(CU,{color:Yo})})})]})})})})]})})]})})}const NU=["png","jpg","jpeg","svg","gif"];function DU(){const r=n.useContext($o),[i,s]=n.useState(!1),o=r?.state,a=r?.updateScreenshotsObject??(()=>{}),{activeProjectID:c}=n.useContext(Zl),u=n.useCallback((e=>{let t=[];for(let n=0;n<e.length;n++){let r=e[n].name,i=r.lastIndexOf(".")+1,s=r.substr(i,r.length).toLowerCase();NU.includes(s)&&t.push(e[n])}f(t)}),[o]),{getRootProps:l,getInputProps:h,isDragActive:d}=qV({onDrop:u}),f=async e=>{const t=[];for(let n=0;n<e.length;n++){const r=e[n];r.id=`screenshot-image-${HV()}`,t.push(r)}p(t).then((e=>{Fq("info",e)})).catch((e=>{Fq("error",e)}))},p=(e,t=!1)=>new Promise((async(n,r)=>{s(!0);const i=[];for(let n=0;n<e.length;n++){const r=e[n];t?i.push(g(r,n)):i.push(m(r,n))}try{const e=await Promise.all(i);a(e),s(!1),n("Image upload success!")}catch(e){s(!1),console.log("REJECT ",e),r(`Failure to upload image(s): ${e}`)}})),m=(e,t)=>new Promise((async(n,r)=>{const i=await(s=e,new Promise(((e,t)=>{const n=new Image;n.onload=()=>{e({width:n.width/4,height:n.height/4})},n.onerror=t,n.src=URL.createObjectURL(s)})));var s;let o=800*t,a=2*t,u=`/feedback/project_${c}/${(new Date).getTime()}_${e.name}`;$l(Kl(Lq,u),e).then((async e=>{const t=await Gl(e.ref);n({width:i.width,height:i.height,x:o,y:a,url:t,id:`screenshot-image-${HV()}`})})).catch(r)})),g=async(e,t)=>new Promise((async(n,r)=>{const i=await(e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>{t({width:r.width/4,height:r.height/4})},r.onerror=n,r.src=e})))(e);let s=10*t,o=2*t,a=`/feedback/project_${c}/${(new Date).getTime()}`;Wl(Kl(Lq,a),e.split(",")[1],"base64",{contentType:"image/png"}).then((async e=>{const t=await Gl(e.ref);n({width:i.width,height:i.height,x:s,y:o,url:t,id:`screenshot-image-${HV()}`})})).catch(r)}));return e.jsxs(t.Box,{bg:Yo,w:"25rem",h:"80vh",alignItems:"center",display:"flex",justifyContent:"center",flexDirection:"column",_hover:{cursor:"pointer",bg:Jo},color:"gray",mt:"9vh",...l(),children:[e.jsx("input",{disabled:i,type:"file",accept:"image/*",...h()}),i?e.jsxs(t.Stack,{alignItems:"center",justifyContent:"center",spacing:2,children:[e.jsx(t.Spinner,{w:"64px",h:"64px",speed:"2s"}),e.jsx(t.Text,{color:Zo,fontSize:"0.6875rem",fontWeight:"700",children:"Uploading..."})]}):d?e.jsxs(t.Stack,{alignItems:"center",spacing:2,children:[e.jsx(at,{width:"64px",height:"64px"}),e.jsx(t.Text,{color:Zo,fontSize:"0.6875rem",fontWeight:"700",children:"Release to drop image(s)"})]}):e.jsxs(t.Stack,{alignItems:"center",spacing:2,children:[e.jsx(ct,{width:"64px",height:"64px"}),e.jsx(t.Text,{color:Zo,fontSize:"0.6875rem",fontWeight:"700",children:"Drop image(s) here, or click to select"})]})]})}const RU=["png","jpg","jpeg","svg","gif"];function OU(r){const i=n.useContext($o);i?.updateComments;const s=i?.updateScreenshotsObject??(()=>{}),o=i?.state.comments,c=i?.state.screenshot_images,u=i?.toggleState,{onOpen:l,isOpen:h,onClose:d,appName:f,isToUpdate:p=!1,feedback_item:m=null,base64Screenshot:g=null,memberID:y,isAssignment:v=!1}=r,_=v?m?.aime_feedback_tool:m,w={type:_?.type??"bug",comments:o,status:_?.status??"pending",title:_?.title??"",due_date:(new Date).toISOString(),priority:_?.priority??"low",screenshot_images:c},[b,I]=n.useState(w);n.useState("#FFFF00"),n.useRef(null);const[E,T]=n.useState(!1);a.useAuth0();const{activeProjectID:S}=n.useContext(Zl);n.useEffect((()=>{g&&k()}),[g]);qV({onDrop:n.useCallback((e=>{let t=[];for(let n=0;n<e.length;n++){let r=e[n].name,i=r.lastIndexOf(".")+1,s=r.substr(i,r.length).toLowerCase();RU.includes(s)&&t.push(e[n])}M(t)}),[b])});const k=()=>{O([g],!0).then((e=>{Fq("info",e)})).catch((e=>{Fq("error",e)}))},[C,{loading:x}]=qo(Uo,{onCompleted:e=>{Fq("success","Feedback item added"),I(w),d()},onError:e=>{console.log("🚀 ~ addFeedbackItem ~ error",e),Fq("error",`This error occurred: ${e.message}`)},refetchQueries:[{query:zo,context:{clientName:"feedback-tool"},variables:{project_id:S},fetchPolicy:"no-cache"}]}),[A,{loading:N}]=qo(Vo,{context:{clientName:"feedback-tool"},onCompleted:e=>{Fq("success","Feedback item updated"),d()},onError:e=>{console.log(e),Fq("error",`This error occurred: ${e.message}`)},refetchQueries:[{query:zo,context:{clientName:"feedback-tool"},variables:{project_id:S},fetchPolicy:"no-cache"},{query:Bo,variables:{id:_?.id}}]}),D=(e,t)=>new Promise((async(t,n)=>{const r=await P(e);console.log("window.innerWidth / 2 - dimensions.width / 2",window.innerWidth/2-r.width/2);let i=`/feedback/project_${S}/${(new Date).getTime()}_${e.name}`;$l(Kl(Lq,i),e).then((async e=>{const n=await Gl(e.ref);t({width:r.width,height:r.height,x:255,y:255,url:n,id:`screenshot-image-${HV()}`})})).catch(n)})),R=(e,t)=>new Promise(((n,r)=>{let i=800*t,s=2*t,o=`/feedback/project_${S}/${(new Date).getTime()}`;Wl(Kl(Lq,o),e.split(",")[1],"base64",{contentType:"image/png"}).then((async e=>{const t=await Gl(e.ref);n({x:i,y:s,url:t,id:`screenshot-image-${HV()}`})})).catch(r)})),O=(e,t=!1)=>new Promise((async(n,r)=>{T(!0);const i=[];for(let n=0;n<e.length;n++){const r=e[n];t?i.push(R(r,n)):i.push(D(r))}try{const e=await Promise.all(i);s(e),T(!1),n("Image upload success!")}catch(e){T(!1),console.log("REJECT ",e),r(`Failure to upload image(s): ${e}`)}})),P=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>{t({width:r.width/4,height:r.height/4})},r.onerror=n,r.src=URL.createObjectURL(e)})),M=async e=>{const t=[];for(let n=0;n<e.length;n++){const r=e[n];r.id=(new Date).getTime(),t.push(r)}O(t).then((e=>{Fq("info",e)})).catch((e=>{Fq("error",e)}))};return e.jsx(e.Fragment,{children:e.jsxs(t.Modal,{isCentered:!0,isOpen:h,onClose:d,scrollBehavior:"inside",size:"full",children:[e.jsx(t.ModalOverlay,{}),e.jsxs(t.ModalContent,{color:"white",bg:"#242e46",p:0,children:[e.jsx(t.ModalHeader,{children:e.jsx(ih,{appName:f,onClose:d})}),e.jsx(t.ModalBody,{overflow:"hidden",children:e.jsx("form",{id:"comment-form",onSubmit:e=>{e.preventDefault(),p?A({variables:{...b,id:_?.id,project_id:S}}):(console.log("activeProjectID",S),C({variables:{...b,project_id:S,created_by:"N/A",org_id:"N/A",creator_id:"N/A"}}))},children:e.jsxs(t.SimpleGrid,{gap:6,columns:5,position:"relative",children:[e.jsx(t.GridItem,{colSpan:5,children:e.jsx(ua,{screenshotImages:c,comments:aa(o)})}),e.jsxs(t.GridItem,{colSpan:1,position:"absolute",right:0,top:0,children:["settings"===u&&e.jsx(YV,{onClose:d,appName:f}),"chat"===u&&e.jsx(AU,{}),"image"===u&&e.jsx(DU,{})]})]})})})]})]})})}const PU={borderRadius:"50%",boxShadow:"4px 4px 11px #4c4c4c44",display:"grid",placeItems:"center",margin:"8px 0",fontSize:"28px",padding:"12px",cursor:"pointer",position:"relative"};function MU(r){const{currentScreenRef:i,project:s,appName:o}=r,[a,c]=n.useState(!1),[u,l]=n.useState(!1),[h,d]=n.useState(null),{isOpen:f,onOpen:p,onClose:m}=t.useDisclosure();n.useEffect((()=>{const e=e=>{220===e.which&&e.ctrlKey?(e.preventDefault(),l((e=>!e))):"Escape"===e.key&&f&&m()};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}}),[]);const g=(e=!1)=>{p(),e&&(Fq("info","Capturing screenshot...",5e3),async function(e,t={}){return(await we(e,t)).toDataURL()}(i?.current).then((function(e){d(e)})))},y=[{label:"Add Feedback With Screenshot",icon:e.jsx(it,{}),onClick:()=>g(!0)},{label:"Add Blank Feedback",icon:e.jsx(ot,{}),onClick:()=>g(!1)}];return e.jsxs(e.Fragment,{children:[e.jsxs(t.UnorderedList,{display:"flex",flexDirection:"column-reverse",styleType:"none",position:"fixed",bottom:"16px",right:"16px",maxH:a?"max-content":"52px",onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[e.jsx(t.ListItem,{style:PU,bg:"#29334B",color:"white",children:e.jsx(st,{})}),y.map(((n,r)=>e.jsx(t.Tooltip,{label:n.label,placement:"left",children:e.jsx(t.ListItem,{style:PU,bg:"white",transform:a?"translateY(0) scale(1)":"translateY(50px) scale(0)",transition:"transform 300ms, opacity 300ms",onClick:n.onClick,children:n.icon})},r)))]}),f&&e.jsx(OU,{appName:o,onClose:m,onOpen:p,feedback_item:{screenshot_images:[]},base64Screenshot:h,activeProject:s,isOpen:f})]})}var LU=function(e){function t(t){var n=e.call(this)||this;return n.client=t,n}return ht(t,e),t.prototype.request=function(e){var t=this;return new zn((function(n){return t.client.subscribe(dt(dt({},e),{query:r.print(e.query)}),{next:n.next.bind(n),complete:n.complete.bind(n),error:function(e){if(e instanceof Error)return n.error(e);var t=function(e){return Ut(e)&&"code"in e&&"reason"in e}(e);return t||function(e){var t;return Ut(e)&&(null===(t=e.target)||void 0===t?void 0:t.readyState)===WebSocket.CLOSED}(e)?n.error(new Error("Socket closed".concat(t?" with event ".concat(e.code):"").concat(t?" ".concat(e.reason):""))):n.error(new xr({graphQLErrors:Array.isArray(e)?e:[e]}))}})}))},t}(br);function FU(e){return null===e?"null":Array.isArray(e)?"array":typeof e}function jU(e){return"object"===FU(e)}function qU(e,t){return e.length<124?e:t}const VU="graphql-transport-ws";var UU,BU;function zU(e){if(!jU(e))throw new Error(`Message is expected to be an object, but got ${FU(e)}`);if(!e.type)throw new Error("Message is missing the 'type' property");if("string"!=typeof e.type)throw new Error(`Message is expects the 'type' property to be a string, but got ${FU(e.type)}`);switch(e.type){case BU.ConnectionInit:case BU.ConnectionAck:case BU.Ping:case BU.Pong:if(null!=e.payload&&!jU(e.payload))throw new Error(`"${e.type}" message expects the 'payload' property to be an object or nullish or missing, but got "${e.payload}"`);break;case BU.Subscribe:if("string"!=typeof e.id)throw new Error(`"${e.type}" message expects the 'id' property to be a string, but got ${FU(e.id)}`);if(!e.id)throw new Error(`"${e.type}" message requires a non-empty 'id' property`);if(!jU(e.payload))throw new Error(`"${e.type}" message expects the 'payload' property to be an object, but got ${FU(e.payload)}`);if("string"!=typeof e.payload.query)throw new Error(`"${e.type}" message payload expects the 'query' property to be a string, but got ${FU(e.payload.query)}`);if(null!=e.payload.variables&&!jU(e.payload.variables))throw new Error(`"${e.type}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${FU(e.payload.variables)}`);if(null!=e.payload.operationName&&"string"!==FU(e.payload.operationName))throw new Error(`"${e.type}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${FU(e.payload.operationName)}`);if(null!=e.payload.extensions&&!jU(e.payload.extensions))throw new Error(`"${e.type}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${FU(e.payload.extensions)}`);break;case BU.Next:if("string"!=typeof e.id)throw new Error(`"${e.type}" message expects the 'id' property to be a string, but got ${FU(e.id)}`);if(!e.id)throw new Error(`"${e.type}" message requires a non-empty 'id' property`);if(!jU(e.payload))throw new Error(`"${e.type}" message expects the 'payload' property to be an object, but got ${FU(e.payload)}`);break;case BU.Error:if("string"!=typeof e.id)throw new Error(`"${e.type}" message expects the 'id' property to be a string, but got ${FU(e.id)}`);if(!e.id)throw new Error(`"${e.type}" message requires a non-empty 'id' property`);if(t=e.payload,!(Array.isArray(t)&&t.length>0&&t.every((e=>"message"in e))))throw new Error(`"${e.type}" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(e.payload)}`);break;case BU.Complete:if("string"!=typeof e.id)throw new Error(`"${e.type}" message expects the 'id' property to be a string, but got ${FU(e.id)}`);if(!e.id)throw new Error(`"${e.type}" message requires a non-empty 'id' property`);break;default:throw new Error(`Invalid message 'type' property "${e.type}"`)}var t;return e}function $U(e,t){return zU(e),JSON.stringify(e,t)}!function(e){e[e.InternalServerError=4500]="InternalServerError",e[e.InternalClientError=4005]="InternalClientError",e[e.BadRequest=4400]="BadRequest",e[e.BadResponse=4004]="BadResponse",e[e.Unauthorized=4401]="Unauthorized",e[e.Forbidden=4403]="Forbidden",e[e.SubprotocolNotAcceptable=4406]="SubprotocolNotAcceptable",e[e.ConnectionInitialisationTimeout=4408]="ConnectionInitialisationTimeout",e[e.ConnectionAcknowledgementTimeout=4504]="ConnectionAcknowledgementTimeout",e[e.SubscriberAlreadyExists=4409]="SubscriberAlreadyExists",e[e.TooManyInitialisationRequests=4429]="TooManyInitialisationRequests"}(UU||(UU={})),function(e){e.ConnectionInit="connection_init",e.ConnectionAck="connection_ack",e.Ping="ping",e.Pong="pong",e.Subscribe="subscribe",e.Next="next",e.Error="error",e.Complete="complete"}(BU||(BU={}));var WU=function(e){return this instanceof WU?(this.v=e,this):new WU(e)},QU=function(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(e,t||[]),s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(e){i[e]&&(r[e]=function(t){return new Promise((function(n,r){s.push([e,t,n,r])>1||a(e,t)}))})}function a(e,t){try{!function(e){e.value instanceof WU?Promise.resolve(e.value.v).then(c,u):l(s[0][2],e)}(i[e](t))}catch(e){l(s[0][3],e)}}function c(e){a("next",e)}function u(e){a("throw",e)}function l(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}};function HU(e){const{url:t,connectionParams:n,lazy:r=!0,onNonLazyError:i=console.error,lazyCloseTimeout:s=0,keepAlive:o=0,disablePong:a,connectionAckWaitTimeout:c=0,retryAttempts:u=5,retryWait:l=async function(e){let t=1e3;for(let n=0;n<e;n++)t*=2;await new Promise((e=>setTimeout(e,t+Math.floor(2700*Math.random()+300))))},shouldRetry:h=GU,isFatalConnectionProblem:d,on:f,webSocketImpl:p,generateID:m=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},jsonMessageReplacer:g,jsonMessageReviver:y}=e;let v;if(p){if(!function(e){return"function"==typeof e&&"constructor"in e&&"CLOSED"in e&&"CLOSING"in e&&"CONNECTING"in e&&"OPEN"in e}(p))throw new Error("Invalid WebSocket implementation provided");v=p}else"undefined"!=typeof WebSocket?v=WebSocket:"undefined"!=typeof global?v=global.WebSocket||global.MozWebSocket:"undefined"!=typeof window&&(v=window.WebSocket||window.MozWebSocket);if(!v)throw new Error("WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`");const _=v,w=(()=>{const e=(()=>{const e={};return{on:(t,n)=>(e[t]=n,()=>{delete e[t]}),emit(t){var n;"id"in t&&(null===(n=e[t.id])||void 0===n||n.call(e,t))}}})(),t={connecting:(null==f?void 0:f.connecting)?[f.connecting]:[],opened:(null==f?void 0:f.opened)?[f.opened]:[],connected:(null==f?void 0:f.connected)?[f.connected]:[],ping:(null==f?void 0:f.ping)?[f.ping]:[],pong:(null==f?void 0:f.pong)?[f.pong]:[],message:(null==f?void 0:f.message)?[e.emit,f.message]:[e.emit],closed:(null==f?void 0:f.closed)?[f.closed]:[],error:(null==f?void 0:f.error)?[f.error]:[]};return{onMessage:e.on,on(e,n){const r=t[e];return r.push(n),()=>{r.splice(r.indexOf(n),1)}},emit(e,...n){for(const r of[...t[e]])r(...n)}}})();function b(e){const t=[w.on("error",(n=>{t.forEach((e=>e())),e(n)})),w.on("closed",(n=>{t.forEach((e=>e())),e(n)}))]}let I,E,T=0,S=!1,k=0,C=!1;async function x(){clearTimeout(E);const[e,r]=await(null!=I?I:I=new Promise(((e,r)=>(async()=>{if(S){if(await l(k),!T)return I=void 0,r({code:1e3,reason:"All Subscriptions Gone"});k++}w.emit("connecting");const i=new _("function"==typeof t?await t():t,VU);let s,u;function h(){isFinite(o)&&o>0&&(clearTimeout(u),u=setTimeout((()=>{i.readyState===_.OPEN&&(i.send($U({type:BU.Ping})),w.emit("ping",!1,void 0))}),o))}b((e=>{I=void 0,clearTimeout(s),clearTimeout(u),r(e),GU(e)&&4499===e.code&&(i.close(4499,"Terminated"),i.onerror=null,i.onclose=null)})),i.onerror=e=>w.emit("error",e),i.onclose=e=>w.emit("closed",e),i.onopen=async()=>{try{w.emit("opened",i);const e="function"==typeof n?await n():n;if(i.readyState!==_.OPEN)return;i.send($U(e?{type:BU.ConnectionInit,payload:e}:{type:BU.ConnectionInit},g)),isFinite(c)&&c>0&&(s=setTimeout((()=>{i.close(UU.ConnectionAcknowledgementTimeout,"Connection acknowledgement timeout")}),c)),h()}catch(e){w.emit("error",e),i.close(UU.InternalClientError,qU(e instanceof Error?e.message:new Error(e).message,"Internal client error"))}};let d=!1;i.onmessage=({data:t})=>{try{const n=function(e,t){return zU("string"==typeof e?JSON.parse(e,t):e)}(t,y);if(w.emit("message",n),"ping"===n.type||"pong"===n.type)return w.emit(n.type,!0,n.payload),void("pong"===n.type?h():a||(i.send($U(n.payload?{type:BU.Pong,payload:n.payload}:{type:BU.Pong})),w.emit("pong",!1,n.payload)));if(d)return;if(n.type!==BU.ConnectionAck)throw new Error(`First message cannot be of type ${n.type}`);clearTimeout(s),d=!0,w.emit("connected",i,n.payload),S=!1,k=0,e([i,new Promise(((e,t)=>b(t)))])}catch(e){i.onmessage=null,w.emit("error",e),i.close(UU.BadResponse,qU(e instanceof Error?e.message:new Error(e).message,"Bad response"))}}})())));e.readyState===_.CLOSING&&await r;let i=()=>{};const u=new Promise((e=>i=e));return[e,i,Promise.race([u.then((()=>{if(!T){const t=()=>e.close(1e3,"Normal Closure");isFinite(s)&&s>0?E=setTimeout((()=>{e.readyState===_.OPEN&&t()}),s):t()}})),r])]}function A(e){if(GU(e)&&(t=e.code,![1e3,1001,1006,1005,1012,1013,1013].includes(t)&&t>=1e3&&t<=1999||[UU.InternalServerError,UU.InternalClientError,UU.BadRequest,UU.BadResponse,UU.Unauthorized,UU.SubprotocolNotAcceptable,UU.SubscriberAlreadyExists,UU.TooManyInitialisationRequests].includes(e.code)))throw e;var t;if(C)return!1;if(GU(e)&&1e3===e.code)return T>0;if(!u||k>=u)throw e;if(!h(e))throw e;if(null==d?void 0:d(e))throw e;return S=!0}return r||(async()=>{for(T++;;)try{const[,,e]=await x();await e}catch(e){try{if(!A(e))return}catch(e){return null==i?void 0:i(e)}}})(),{on:w.on,subscribe(e,t){const n=m(e);let r=!1,i=!1,s=()=>{T--,r=!0};return(async()=>{for(T++;;)try{const[o,a,c]=await x();if(r)return a();const u=w.onMessage(n,(e=>{switch(e.type){case BU.Next:return void t.next(e.payload);case BU.Error:return i=!0,r=!0,t.error(e.payload),void s();case BU.Complete:return r=!0,void s()}}));return o.send($U({id:n,type:BU.Subscribe,payload:e},g)),s=()=>{r||o.readyState!==_.OPEN||o.send($U({id:n,type:BU.Complete},g)),T--,r=!0,a()},void await c.finally(u)}catch(e){if(!A(e))return}})().then((()=>{i||t.complete()})).catch((e=>{t.error(e)})),()=>{r||s()}},iterate(e){const t=[],n={done:!1,error:null,resolve:()=>{}},r=this.subscribe(e,{next(e){t.push(e),n.resolve()},error(e){n.done=!0,n.error=e,n.resolve()},complete(){n.done=!0,n.resolve()}}),i=function(){return QU(this,arguments,(function*(){for(;;){for(t.length||(yield WU(new Promise((e=>n.resolve=e))));t.length;)yield yield WU(t.shift());if(n.error)throw n.error;if(n.done)return yield WU(void 0)}}))}();return i.throw=async e=>(n.done||(n.done=!0,n.error=e,n.resolve()),{done:!0,value:void 0}),i.return=async()=>(r(),{done:!0,value:void 0}),i},async dispose(){if(C=!0,I){const[e]=await I;e.close(1e3,"Normal Closure")}},terminate(){I&&w.emit("closed",{code:4499,reason:"Terminated",wasClean:!1})}}}function GU(e){return jU(e)&&"code"in e&&"reason"in e}function KU(t){const{getAccessTokenSilently:r,isAuthenticated:i}=a.useAuth0();n.useState(null);const s="admin";n.useEffect((()=>{}),[r,i]);const o=new Vr({uri:"https://feedback-tool.hasura.app/v1/graphql",headers:{"x-hasura-admin-secret":"xdNZ5eroV3ek3q567TILoDrlF0hzhj4jGHC1gC3YzHlqD8dTgWAvViaXUsI5tTvv","x-hasura-role":s}}),c=new LU(HU({url:"wss://feedback-tool.hasura.app/v1/graphql",connectionParams:{lazy:!0,reconnect:!0,headers:{"x-hasura-admin-secret":"xdNZ5eroV3ek3q567TILoDrlF0hzhj4jGHC1gC3YzHlqD8dTgWAvViaXUsI5tTvv","x-hasura-role":s}}})),u=Ir((({query:e})=>{const{kind:t,operation:n}=sn(e);return"OperationDefinition"===t&&"subscription"===n}),c,o),l=new yo({link:u,cache:new Xs({addTypename:!1})});return e.jsx(Mo,{client:l,children:t.children})}const YU=t=>{const n=localStorage.getItem("organization_id"),r={domain:"aime-project.us.auth0.com",clientId:"64N7etrRi8V5K0At30NNmWQFo5Vfzxoy",authorizationParams:{redirect_uri:window.location.origin,audience:"https://aimework-space.hasura.app"},useRefreshTokens:!0,cacheLocation:"localstorage",...n?{organization:n}:null};return e.jsx(a.Auth0Provider,{...r,children:t.children})};var JU;exports.FeedbackComponents=void 0,(JU=exports.FeedbackComponents||(exports.FeedbackComponents={})).FeedbackContainer="FeedbackContainer",JU.FeedbackEditorModal="FeedbackEditorModal",exports.FeedbackContainer=({width:r,height:i,appName:s,aimeProject:o=Vq,children:a})=>{const c=n.useRef();return e.jsx(n.Fragment,{children:e.jsx(Qo,{children:e.jsx(YU,{children:e.jsxs(KU,{children:[e.jsx(t.Stack,{ref:c,spacing:0,p:0,w:r,h:i,children:a}),e.jsx(MU,{currentScreenRef:c,project:o,appName:s})]})})})})},exports.FeedbackEditorModal=OU;
//# sourceMappingURL=index.js.map
