diff --git a/backend/index.js b/backend/index.js index eda6448..53f287f 100644 --- a/backend/index.js +++ b/backend/index.js @@ -17,6 +17,9 @@ const io = new Server(httpServer, { cors: { origin: ["https://light-200.github.io"], }, + // cors: { + // origin: ["http://localhost:8080", "http://127.0.0.1:5500"], // comment in production + // }, }); io.on("connection", (socket) => { diff --git a/docs/bundle.js b/docs/bundle.js index 69d8c28..e378683 100644 --- a/docs/bundle.js +++ b/docs/bundle.js @@ -1,2 +1,2 @@ /*! For license information please see bundle.js.LICENSE.txt */ -(()=>{var t={63:(t,e)=>{function n(t){if(t)return function(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}(t)}e.Q=n,n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,s=this._callbacks["$"+t];if(!s)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var r=0;r{function e(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=e,e.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-n:t+n}return 0|Math.min(t,this.max)},e.prototype.reset=function(){this.attempts=0},e.prototype.setMin=function(t){this.ms=t},e.prototype.setMax=function(t){this.max=t},e.prototype.setJitter=function(t){this.jitter=t}},926:function(t){!function(e){"use strict";var n={escape:function(t){return t.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1")},parseExtension:s,mimeType:function(t){return t=s(t).toLowerCase(),function(){var t="application/font-woff",e="image/jpeg";return{woff:t,woff2:t,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:e,jpeg:e,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml"}}()[t]||""},dataAsUrl:function(t,e){return"data:"+e+";base64,"+t},isDataUrl:function(t){return-1!==t.search(/^(data:)/)},canvasToBlob:function(t){return t.toBlob?new Promise((function(e){t.toBlob(e)})):function(t){return new Promise((function(e){for(var n=y(t.toDataURL().split(",")[1]),s=n.length,r=new Uint8Array(s),i=0;it.toDataURL())).then(n.makeImage):t.cloneNode(!1)})).then((function(r){return function(e,r){return 0===(e=e.childNodes).length?Promise.resolve(r):function(e,n){var r=Promise.resolve();return n.forEach((function(n){r=r.then((function(){return t(n,s,!1,i)})).then((function(t){t&&e.appendChild(t)}))})),r}(r,n.asArray(e)).then((function(){return r}))}(e,r)})).then((function(t){return function(t,e,s){return e instanceof Element?Promise.resolve().then((function(){!function(t,e){t.cssText?(e.cssText=t.cssText,function(t,e){e.font=t.font,e.fontFamily=t.fontFamily,e.fontFeatureSettings=t.fontFeatureSettings,e.fontKerning=t.fontKerning,e.fontSize=t.fontSize,e.fontStretch=t.fontStretch,e.fontStyle=t.fontStyle,e.fontVariant=t.fontVariant,e.fontVariantCaps=t.fontVariantCaps,e.fontVariantEastAsian=t.fontVariantEastAsian,e.fontVariantLigatures=t.fontVariantLigatures,e.fontVariantNumeric=t.fontVariantNumeric,e.fontVariationSettings=t.fontVariationSettings,e.fontWeight=t.fontWeight}(t,e)):function(t,s){n.asArray(t).forEach((function(e){s.setProperty(e,t.getPropertyValue(e),t.getPropertyPriority(e))})),r&&(["inset-block","inset-block-start","inset-block-end"].forEach((t=>e.removeProperty(t))),["left","right","top","bottom"].forEach((t=>{e.getPropertyValue(t)&&e.setProperty(t,"0px")})))}(t,e)}(s?function(t,e){var n,s=document.createElement(t.tagName).style,r=g(t),i=t.style;for(n of r){var o=r.getPropertyValue(n),a=i.getPropertyValue(n);i.setProperty(n,e?"initial":"unset"),r.getPropertyValue(n)!==o?s.setProperty(n,o):s.removeProperty(n),i.setProperty(n,a)}return s}(t,r):g(t),e.style)})).then((function(){[":before",":after"].forEach((function(s){!function(s){var r,i=g(t,s),o=i.getPropertyValue("content");""!==o&&"none"!==o&&(r=n.uid(),(o=e.getAttribute("class"))&&e.setAttribute("class",o+" "+r),(o=document.createElement("style")).appendChild(function(){var t="."+r+":"+s,e=(i.cssText?function(){return i.cssText+" content: "+i.getPropertyValue("content")+";"}:function(){return n.asArray(i).map((function(t){return t+": "+i.getPropertyValue(t)+(i.getPropertyPriority(t)?" !important":"")})).join("; ")+";"})();return document.createTextNode(t+"{"+e+"}")}()),e.appendChild(o))}(s)}))})).then((function(){t instanceof HTMLTextAreaElement&&(e.innerHTML=t.value),t instanceof HTMLInputElement&&e.setAttribute("value",t.value)})).then((function(){e instanceof SVGElement&&(e.setAttribute("xmlns","http://www.w3.org/2000/svg"),e instanceof SVGRectElement&&["width","height"].forEach((function(t){var n=e.getAttribute(t);n&&e.style.setProperty(t,n)})))})).then((function(){return e})):e}(e,t,i)})):Promise.resolve()}(t,e.filter,!0,!e.raster)})).then(b).then(T).then((function(t){e.bgcolor&&(t.style.backgroundColor=e.bgcolor),e.width&&(t.style.width=e.width+"px"),e.height&&(t.style.height=e.height+"px"),e.style&&Object.keys(e.style).forEach((function(n){t.style[n]=e.style[n]}));var n=null;return"function"==typeof e.onclone&&(n=e.onclone(t)),Promise.resolve(n).then((function(){return t}))})).then((function(s){return s=s,r=e.width||n.width(t),i=e.height||n.height(t),Promise.resolve(s).then((function(t){return t.setAttribute("xmlns","http://www.w3.org/1999/xhtml"),(new XMLSerializer).serializeToString(t)})).then(n.escapeXhtml).then((function(t){return''+t+""})).then((function(t){return''+t+""})).then((function(t){return"data:image/svg+xml;charset=utf-8,"+t}));var r,i}))}function w(t,e){return v(t,e).then(n.makeImage).then(n.delay(0)).then((function(s){var r="number"!=typeof e.scale?1:e.scale,i=function(t,s){var r=document.createElement("canvas");return r.width=(e.width||n.width(t))*s,r.height=(e.height||n.height(t))*s,e.bgcolor&&((s=r.getContext("2d")).fillStyle=e.bgcolor,s.fillRect(0,0,r.width,r.height)),r}(t,r),o=i.getContext("2d");return o.mozImageSmoothingEnabled=!1,o.msImageSmoothingEnabled=!1,o.imageSmoothingEnabled=!1,s&&(o.scale(r,r),o.drawImage(s,0,0)),i}))}function b(t){return h.resolveAll().then((function(e){var n=document.createElement("style");return t.appendChild(n),n.appendChild(document.createTextNode(e)),t}))}function T(t){return d.inlineAll(t).then((function(){return t}))}}(this)},162:function(t,e,n){var s;void 0===(s=function(){"use strict";function e(t,e,n){var s=new XMLHttpRequest;s.open("GET",t),s.responseType="blob",s.onload=function(){a(s.response,e,n)},s.onerror=function(){console.error("could not download file")},s.send()}function s(t){var e=new XMLHttpRequest;e.open("HEAD",t,!1);try{e.send()}catch(t){}return 200<=e.status&&299>=e.status}function r(t){try{t.dispatchEvent(new MouseEvent("click"))}catch(n){var e=document.createEvent("MouseEvents");e.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),t.dispatchEvent(e)}}var i="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof n.g&&n.g.global===n.g?n.g:void 0,o=i.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),a=i.saveAs||("object"!=typeof window||window!==i?function(){}:"download"in HTMLAnchorElement.prototype&&!o?function(t,n,o){var a=i.URL||i.webkitURL,c=document.createElement("a");n=n||t.name||"download",c.download=n,c.rel="noopener","string"==typeof t?(c.href=t,c.origin===location.origin?r(c):s(c.href)?e(t,n,o):r(c,c.target="_blank")):(c.href=a.createObjectURL(t),setTimeout((function(){a.revokeObjectURL(c.href)}),4e4),setTimeout((function(){r(c)}),0))}:"msSaveOrOpenBlob"in navigator?function(t,n,i){if(n=n||t.name||"download","string"!=typeof t)navigator.msSaveOrOpenBlob(function(t,e){return void 0===e?e={autoBom:!1}:"object"!=typeof e&&(console.warn("Deprecated: Expected third argument to be a object"),e={autoBom:!e}),e.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(t.type)?new Blob(["\ufeff",t],{type:t.type}):t}(t,i),n);else if(s(t))e(t,n,i);else{var o=document.createElement("a");o.href=t,o.target="_blank",setTimeout((function(){r(o)}))}}:function(t,n,s,r){if((r=r||open("","_blank"))&&(r.document.title=r.document.body.innerText="downloading..."),"string"==typeof t)return e(t,n,s);var a="application/octet-stream"===t.type,c=/constructor/i.test(i.HTMLElement)||i.safari,u=/CriOS\/[\d]+/.test(navigator.userAgent);if((u||a&&c||o)&&"undefined"!=typeof FileReader){var h=new FileReader;h.onloadend=function(){var t=h.result;t=u?t:t.replace(/^data:[^;]*;/,"data:attachment/file;"),r?r.location.href=t:location=t,r=null},h.readAsDataURL(t)}else{var l=i.URL||i.webkitURL,d=l.createObjectURL(t);r?r.location=d:location.href=d,r=null,setTimeout((function(){l.revokeObjectURL(d)}),4e4)}});i.saveAs=a.saveAs=a,t.exports=a}.apply(e,[]))||(t.exports=s)},58:t=>{try{t.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){t.exports=!1}},676:function(t,e){!function(t){"use strict";function e(t){return Array.prototype.slice.call(t)}function n(t){return new Promise((function(e,n){t.onsuccess=function(){e(t.result)},t.onerror=function(){n(t.error)}}))}function s(t,e,s){var r,i=new Promise((function(i,o){n(r=t[e].apply(t,s)).then(i,o)}));return i.request=r,i}function r(t,e,n){var r=s(t,e,n);return r.then((function(t){if(t)return new h(t,r.request)}))}function i(t,e,n){n.forEach((function(n){Object.defineProperty(t.prototype,n,{get:function(){return this[e][n]},set:function(t){this[e][n]=t}})}))}function o(t,e,n,r){r.forEach((function(r){r in n.prototype&&(t.prototype[r]=function(){return s(this[e],r,arguments)})}))}function a(t,e,n,s){s.forEach((function(s){s in n.prototype&&(t.prototype[s]=function(){return this[e][s].apply(this[e],arguments)})}))}function c(t,e,n,s){s.forEach((function(s){s in n.prototype&&(t.prototype[s]=function(){return r(this[e],s,arguments)})}))}function u(t){this._index=t}function h(t,e){this._cursor=t,this._request=e}function l(t){this._store=t}function d(t){this._tx=t,this.complete=new Promise((function(e,n){t.oncomplete=function(){e()},t.onerror=function(){n(t.error)},t.onabort=function(){n(t.error)}}))}function f(t,e,n){this._db=t,this.oldVersion=e,this.transaction=new d(n)}function p(t){this._db=t}i(u,"_index",["name","keyPath","multiEntry","unique"]),o(u,"_index",IDBIndex,["get","getKey","getAll","getAllKeys","count"]),c(u,"_index",IDBIndex,["openCursor","openKeyCursor"]),i(h,"_cursor",["direction","key","primaryKey","value"]),o(h,"_cursor",IDBCursor,["update","delete"]),["advance","continue","continuePrimaryKey"].forEach((function(t){t in IDBCursor.prototype&&(h.prototype[t]=function(){var e=this,s=arguments;return Promise.resolve().then((function(){return e._cursor[t].apply(e._cursor,s),n(e._request).then((function(t){if(t)return new h(t,e._request)}))}))})})),l.prototype.createIndex=function(){return new u(this._store.createIndex.apply(this._store,arguments))},l.prototype.index=function(){return new u(this._store.index.apply(this._store,arguments))},i(l,"_store",["name","keyPath","indexNames","autoIncrement"]),o(l,"_store",IDBObjectStore,["put","add","delete","clear","get","getAll","getKey","getAllKeys","count"]),c(l,"_store",IDBObjectStore,["openCursor","openKeyCursor"]),a(l,"_store",IDBObjectStore,["deleteIndex"]),d.prototype.objectStore=function(){return new l(this._tx.objectStore.apply(this._tx,arguments))},i(d,"_tx",["objectStoreNames","mode"]),a(d,"_tx",IDBTransaction,["abort"]),f.prototype.createObjectStore=function(){return new l(this._db.createObjectStore.apply(this._db,arguments))},i(f,"_db",["name","version","objectStoreNames"]),a(f,"_db",IDBDatabase,["deleteObjectStore","close"]),p.prototype.transaction=function(){return new d(this._db.transaction.apply(this._db,arguments))},i(p,"_db",["name","version","objectStoreNames"]),a(p,"_db",IDBDatabase,["close"]),["openCursor","openKeyCursor"].forEach((function(t){[l,u].forEach((function(n){t in n.prototype&&(n.prototype[t.replace("open","iterate")]=function(){var n=e(arguments),s=n[n.length-1],r=this._store||this._index,i=r[t].apply(r,n.slice(0,-1));i.onsuccess=function(){s(i.result)}})}))})),[u,l].forEach((function(t){t.prototype.getAll||(t.prototype.getAll=function(t,e){var n=this,s=[];return new Promise((function(r){n.iterateCursor(t,(function(t){t?(s.push(t.value),void 0===e||s.length!=e?t.continue():r(s)):r(s)}))}))})})),t.openDb=function(t,e,n){var r=s(indexedDB,"open",[t,e]),i=r.request;return i&&(i.onupgradeneeded=function(t){n&&n(new f(i.result,t.oldVersion,i.transaction))}),r.then((function(t){return new p(t)}))},t.deleteDb=function(t){return s(indexedDB,"deleteDatabase",[t])},Object.defineProperty(t,"__esModule",{value:!0})}(e)},830:(t,e)=>{e.encode=function(t){var e="";for(var n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e},e.decode=function(t){for(var e={},n=t.split("&"),s=0,r=n.length;s{var e=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,n=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var s,r,i=t,o=t.indexOf("["),a=t.indexOf("]");-1!=o&&-1!=a&&(t=t.substring(0,o)+t.substring(o,a).replace(/:/g,";")+t.substring(a,t.length));for(var c,u,h=e.exec(t||""),l={},d=14;d--;)l[n[d]]=h[d]||"";return-1!=o&&-1!=a&&(l.source=i,l.host=l.host.substring(1,l.host.length-1).replace(/;/g,":"),l.authority=l.authority.replace("[","").replace("]","").replace(/;/g,":"),l.ipv6uri=!0),l.pathNames=(s=l.path,r=s.replace(/\/{2,9}/g,"/").split("/"),"/"!=s.substr(0,1)&&0!==s.length||r.splice(0,1),"/"==s.substr(s.length-1,1)&&r.splice(r.length-1,1),r),l.queryKey=(c=l.query,u={},c.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,n){e&&(u[e]=n)})),u),l}},281:t=>{"use strict";var e,n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),s={},r=0,i=0;function o(t){var e="";do{e=n[t%64]+e,t=Math.floor(t/64)}while(t>0);return e}function a(){var t=o(+new Date);return t!==e?(r=0,e=t):t+"."+o(r++)}for(;i<64;i++)s[n[i]]=i;a.encode=o,a.decode=function(t){var e=0;for(i=0;i{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var s in e)n.o(e,s)&&!n.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},(()=>{"use strict";var t={};n.r(t),n.d(t,{Decoder:()=>Tg,Encoder:()=>bg,PacketType:()=>wg,protocol:()=>vg});const e={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(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,s=[];for(let e=0;e>2,h=(3&r)<<4|o>>4;let l=(15&o)<<2|c>>6,d=63&c;a||(d=64,i||(l=64)),s.push(n[u],n[h],n[l],n[d])}return s.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(function(t){const e=[];let n=0;for(let s=0;s>6|192,e[n++]=63&r|128):55296==(64512&r)&&s+1>18|240,e[n++]=r>>12&63|128,e[n++]=r>>6&63|128,e[n++]=63&r|128):(e[n++]=r>>12|224,e[n++]=r>>6&63|128,e[n++]=63&r|128)}return e}(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):function(t){const e=[];let n=0,s=0;for(;n191&&r<224){const i=t[n++];e[s++]=String.fromCharCode((31&r)<<6|63&i)}else if(r>239&&r<365){const i=((7&r)<<18|(63&t[n++])<<12|(63&t[n++])<<6|63&t[n++])-65536;e[s++]=String.fromCharCode(55296+(i>>10)),e[s++]=String.fromCharCode(56320+(1023&i))}else{const i=t[n++],o=t[n++];e[s++]=String.fromCharCode((15&r)<<12|(63&i)<<6|63&o)}}return e.join("")}(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();const n=e?this.charToByteMapWebSafe_:this.charToByteMap_,s=[];for(let e=0;e>4;if(s.push(c),64!==o){const t=i<<4&240|o>>2;if(s.push(t),64!==a){const t=o<<6&192|a;s.push(t)}}}return s},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}};class s{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((t,e)=>{this.resolve=t,this.reject=e}))}wrapCallback(t){return(e,n)=>{e?this.reject(e):this.resolve(n),"function"==typeof t&&(this.promise.catch((()=>{})),1===t.length?t(e):t(e,n))}}}function r(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function i(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(r())}function o(){const t="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof t&&void 0!==t.id}function a(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function c(){const t=r();return t.indexOf("MSIE ")>=0||t.indexOf("Trident/")>=0}class u extends Error{constructor(t,e,n){super(e),this.code=t,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,u.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,h.prototype.create)}}class h{constructor(t,e,n){this.service=t,this.serviceName=e,this.errors=n}create(t,...e){const n=e[0]||{},s=`${this.service}/${t}`,r=this.errors[t],i=r?function(t,e){return t.replace(l,((t,n)=>{const s=e[n];return null!=s?String(s):`<${n}?>`}))}(r,n):"Error",o=`${this.serviceName}: ${i} (${s}).`;return new u(s,o,n)}}const l=/\{\$([^}]+)}/g;function d(t,e){if(t===e)return!0;const n=Object.keys(t),s=Object.keys(e);for(const r of n){if(!s.includes(r))return!1;const n=t[r],i=e[r];if(f(n)&&f(i)){if(!d(n,i))return!1}else if(n!==i)return!1}for(const t of s)if(!n.includes(t))return!1;return!0}function f(t){return null!==t&&"object"==typeof t}function p(t){const e=[];for(const[n,s]of Object.entries(t))Array.isArray(s)?s.forEach((t=>{e.push(encodeURIComponent(n)+"="+encodeURIComponent(t))})):e.push(encodeURIComponent(n)+"="+encodeURIComponent(s));return e.length?"&"+e.join("&"):""}function m(t){const e={};return t.replace(/^\?/,"").split("&").forEach((t=>{if(t){const[n,s]=t.split("=");e[decodeURIComponent(n)]=decodeURIComponent(s)}})),e}function g(t){const e=t.indexOf("?");if(!e)return"";const n=t.indexOf("#",e);return t.substring(e,n>0?n:void 0)}class y{constructor(t,e){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=e,this.task.then((()=>{t(this)})).catch((t=>{this.error(t)}))}next(t){this.forEachObserver((e=>{e.next(t)}))}error(t){this.forEachObserver((e=>{e.error(t)})),this.close(t)}complete(){this.forEachObserver((t=>{t.complete()})),this.close()}subscribe(t,e,n){let s;if(void 0===t&&void 0===e&&void 0===n)throw new Error("Missing Observer.");s=function(t,e){if("object"!=typeof t||null===t)return!1;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return!0;return!1}(t)?t:{next:t,error:e,complete:n},void 0===s.next&&(s.next=v),void 0===s.error&&(s.error=v),void 0===s.complete&&(s.complete=v);const r=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?s.error(this.finalError):s.complete()}catch(t){}})),this.observers.push(s),r}unsubscribeOne(t){void 0!==this.observers&&void 0!==this.observers[t]&&(delete this.observers[t],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(t){if(!this.finalized)for(let e=0;e{if(void 0!==this.observers&&void 0!==this.observers[t])try{e(this.observers[t])}catch(t){"undefined"!=typeof console&&console.error&&console.error(t)}}))}close(t){this.finalized||(this.finalized=!0,void 0!==t&&(this.finalError=t),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function v(){}function w(t,e=1e3,n=2){const s=e*Math.pow(n,t),r=Math.round(.5*s*(Math.random()-.5)*2);return Math.min(144e5,s+r)}function b(t){return t&&t._delegate?t._delegate:t}class T{constructor(t,e,n){this.name=t,this.instanceFactory=e,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(t){return this.instantiationMode=t,this}setMultipleInstances(t){return this.multipleInstances=t,this}setServiceProps(t){return this.serviceProps=t,this}setInstanceCreatedCallback(t){return this.onInstanceCreated=t,this}}const E="[DEFAULT]";class I{constructor(t,e){this.name=t,this.container=e,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(t){const e=this.normalizeInstanceIdentifier(t);if(!this.instancesDeferred.has(e)){const t=new s;if(this.instancesDeferred.set(e,t),this.isInitialized(e)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:e});n&&t.resolve(n)}catch(t){}}return this.instancesDeferred.get(e).promise}getImmediate(t){var e;const n=this.normalizeInstanceIdentifier(null==t?void 0:t.identifier),s=null!==(e=null==t?void 0:t.optional)&&void 0!==e&&e;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(s)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(t){if(s)return null;throw t}}getComponent(){return this.component}setComponent(t){if(t.name!==this.name)throw Error(`Mismatching Component ${t.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=t,this.shouldAutoInitialize()){if(function(t){return"EAGER"===t.instantiationMode}(t))try{this.getOrInitializeService({instanceIdentifier:E})}catch(t){}for(const[t,e]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(t);try{const t=this.getOrInitializeService({instanceIdentifier:n});e.resolve(t)}catch(t){}}}}clearInstance(t="[DEFAULT]"){this.instancesDeferred.delete(t),this.instancesOptions.delete(t),this.instances.delete(t)}async delete(){const t=Array.from(this.instances.values());await Promise.all([...t.filter((t=>"INTERNAL"in t)).map((t=>t.INTERNAL.delete())),...t.filter((t=>"_delete"in t)).map((t=>t._delete()))])}isComponentSet(){return null!=this.component}isInitialized(t="[DEFAULT]"){return this.instances.has(t)}getOptions(t="[DEFAULT]"){return this.instancesOptions.get(t)||{}}initialize(t={}){const{options:e={}}=t,n=this.normalizeInstanceIdentifier(t.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 s=this.getOrInitializeService({instanceIdentifier:n,options:e});for(const[t,e]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(t)&&e.resolve(s);return s}onInit(t,e){var n;const s=this.normalizeInstanceIdentifier(e),r=null!==(n=this.onInitCallbacks.get(s))&&void 0!==n?n:new Set;r.add(t),this.onInitCallbacks.set(s,r);const i=this.instances.get(s);return i&&t(i,s),()=>{r.delete(t)}}invokeOnInitCallbacks(t,e){const n=this.onInitCallbacks.get(e);if(n)for(const s of n)try{s(t,e)}catch(t){}}getOrInitializeService({instanceIdentifier:t,options:e={}}){let n=this.instances.get(t);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(s=t,s===E?void 0:s),options:e}),this.instances.set(t,n),this.instancesOptions.set(t,e),this.invokeOnInitCallbacks(n,t),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,t,n)}catch(t){}var s;return n||null}normalizeInstanceIdentifier(t="[DEFAULT]"){return this.component?this.component.multipleInstances?t:E:t}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class _{constructor(t){this.name=t,this.providers=new Map}addComponent(t){const e=this.getProvider(t.name);if(e.isComponentSet())throw new Error(`Component ${t.name} has already been registered with ${this.name}`);e.setComponent(t)}addOrOverwriteComponent(t){this.getProvider(t.name).isComponentSet()&&this.providers.delete(t.name),this.addComponent(t)}getProvider(t){if(this.providers.has(t))return this.providers.get(t);const e=new I(t,this);return this.providers.set(t,e),e}getProviders(){return Array.from(this.providers.values())}}const S=[];var k,A;(A=k||(k={}))[A.DEBUG=0]="DEBUG",A[A.VERBOSE=1]="VERBOSE",A[A.INFO=2]="INFO",A[A.WARN=3]="WARN",A[A.ERROR=4]="ERROR",A[A.SILENT=5]="SILENT";const C={debug:k.DEBUG,verbose:k.VERBOSE,info:k.INFO,warn:k.WARN,error:k.ERROR,silent:k.SILENT},N=k.INFO,R={[k.DEBUG]:"log",[k.VERBOSE]:"log",[k.INFO]:"info",[k.WARN]:"warn",[k.ERROR]:"error"},L=(t,e,...n)=>{if(e{if(function(t){const e=t.getComponent();return"VERSION"===(null==e?void 0:e.type)}(t)){const e=t.getImmediate();return`${e.library}/${e.version}`}return null})).filter((t=>t)).join(" ")}}const P="@firebase/app",M="0.7.11",x=new D("@firebase/app"),U={[P]:"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"},F=new Map,V=new Map;function j(t,e){try{t.container.addComponent(e)}catch(n){x.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,n)}}function B(t){const e=t.name;if(V.has(e))return x.debug(`There were multiple attempts to register component ${e}.`),!1;V.set(e,t);for(const e of F.values())j(e,t);return!0}function q(t,e){return t.container.getProvider(e)}const H=new h("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","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","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."});class ${constructor(t,e,n){this._isDeleted=!1,this._options=Object.assign({},t),this._config=Object.assign({},e),this._name=e.name,this._automaticDataCollectionEnabled=e.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new T("app",(()=>this),"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(t){this.checkDestroyed(),this._automaticDataCollectionEnabled=t}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(t){this._isDeleted=t}checkDestroyed(){if(this.isDeleted)throw H.create("app-deleted",{appName:this._name})}}const K="9.6.1";function z(t="[DEFAULT]"){const e=F.get(t);if(!e)throw H.create("no-app",{appName:t});return e}function G(t,e,n){var s;let r=null!==(s=U[t])&&void 0!==s?s:t;n&&(r+=`-${n}`);const i=r.match(/\s|\//),o=e.match(/\s|\//);if(i||o){const t=[`Unable to register library "${r}" with version "${e}":`];return i&&t.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&o&&t.push("and"),o&&t.push(`version name "${e}" contains illegal characters (whitespace or "/")`),void x.warn(t.join(" "))}B(new T(`${r}-version`,(()=>({library:r,version:e})),"VERSION"))}B(new T("platform-logger",(t=>new O(t)),"PRIVATE")),G(P,M,""),G(P,M,"esm2017"),G("fire-js",""),G("firebase","9.6.1","app");var W=n(676);const J="@firebase/installations",X="0.5.4",Q="w:0.5.4",Y=new h("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function Z(t){return t instanceof u&&t.code.includes("request-failed")}function tt({projectId:t}){return`https://firebaseinstallations.googleapis.com/v1/projects/${t}/installations`}function et(t){return{token:t.token,requestStatus:2,expiresIn:(e=t.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()};var e}async function nt(t,e){const n=(await e.json()).error;return Y.create("request-failed",{requestName:t,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function st({apiKey:t}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":t})}async function rt(t){const e=await t();return e.status>=500&&e.status<600?t():e}function it(t){return new Promise((e=>{setTimeout(e,t)}))}const ot=/^[cdef][\w-]{21}$/;function at(){try{const t=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(t),t[0]=112+t[0]%16;const e=function(t){return(e=t,btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")).substr(0,22);var e}(t);return ot.test(e)?e:""}catch(t){return""}}function ct(t){return`${t.appName}!${t.appId}`}const ut=new Map;function ht(t,e){const n=ct(t);lt(n,e),function(t,e){const n=(!dt&&"BroadcastChannel"in self&&(dt=new BroadcastChannel("[Firebase] FID Change"),dt.onmessage=t=>{lt(t.data.key,t.data.fid)}),dt);n&&n.postMessage({key:t,fid:e}),0===ut.size&&dt&&(dt.close(),dt=null)}(n,e)}function lt(t,e){const n=ut.get(t);if(n)for(const t of n)t(e)}let dt=null;const ft="firebase-installations-store";let pt=null;function mt(){return pt||(pt=(0,W.openDb)("firebase-installations-database",1,(t=>{0===t.oldVersion&&t.createObjectStore(ft)}))),pt}async function gt(t,e){const n=ct(t),s=(await mt()).transaction(ft,"readwrite"),r=s.objectStore(ft),i=await r.get(n);return await r.put(e,n),await s.complete,i&&i.fid===e.fid||ht(t,e.fid),e}async function yt(t){const e=ct(t),n=(await mt()).transaction(ft,"readwrite");await n.objectStore(ft).delete(e),await n.complete}async function vt(t,e){const n=ct(t),s=(await mt()).transaction(ft,"readwrite"),r=s.objectStore(ft),i=await r.get(n),o=e(i);return void 0===o?await r.delete(n):await r.put(o,n),await s.complete,!o||i&&i.fid===o.fid||ht(t,o.fid),o}async function wt(t){let e;const n=await vt(t,(n=>{const s=function(t){return Et(t||{fid:at(),registrationStatus:0})}(n),r=function(t,e){if(0===e.registrationStatus){if(!navigator.onLine)return{installationEntry:e,registrationPromise:Promise.reject(Y.create("app-offline"))};const n={fid:e.fid,registrationStatus:1,registrationTime:Date.now()},s=async function(t,e){try{const n=await async function(t,{fid:e}){const n=tt(t),s=st(t),r={fid:e,authVersion:"FIS_v2",appId:t.appId,sdkVersion:Q},i={method:"POST",headers:s,body:JSON.stringify(r)},o=await rt((()=>fetch(n,i)));if(o.ok){const t=await o.json();return{fid:t.fid||e,registrationStatus:2,refreshToken:t.refreshToken,authToken:et(t.authToken)}}throw await nt("Create Installation",o)}(t,e);return gt(t,n)}catch(n){throw Z(n)&&409===n.customData.serverCode?await yt(t):await gt(t,{fid:e.fid,registrationStatus:0}),n}}(t,n);return{installationEntry:n,registrationPromise:s}}return 1===e.registrationStatus?{installationEntry:e,registrationPromise:bt(t)}:{installationEntry:e}}(t,s);return e=r.registrationPromise,r.installationEntry}));return""===n.fid?{installationEntry:await e}:{installationEntry:n,registrationPromise:e}}async function bt(t){let e=await Tt(t);for(;1===e.registrationStatus;)await it(100),e=await Tt(t);if(0===e.registrationStatus){const{installationEntry:e,registrationPromise:n}=await wt(t);return n||e}return e}function Tt(t){return vt(t,(t=>{if(!t)throw Y.create("installation-not-found");return Et(t)}))}function Et(t){return 1===(e=t).registrationStatus&&e.registrationTime+1e4fetch(s,a)));if(c.ok)return et(await c.json());throw await nt("Generate Auth Token",c)}async function _t(t,e=!1){let n;const s=await vt(t.appConfig,(s=>{if(!kt(s))throw Y.create("not-registered");const r=s.authToken;if(!e&&(2===(i=r).requestStatus&&!function(t){const e=Date.now();return e{if(!kt(t))throw Y.create("not-registered");return 1===(e=t.authToken).requestStatus&&e.requestTime+1e4{const e=t.getProvider("app").getImmediate(),n=function(t){if(!t||!t.options)throw At("App Configuration");if(!t.name)throw At("App Name");const e=["projectId","apiKey","appId"];for(const n of e)if(!t.options[n])throw At(n);return{appName:t.name,projectId:t.options.projectId,apiKey:t.options.apiKey,appId:t.options.appId}}(e);return{app:e,appConfig:n,platformLoggerProvider:q(e,"platform-logger"),_delete:()=>Promise.resolve()}}),"PUBLIC")),B(new T("installations-internal",(t=>{const e=q(t.getProvider("app").getImmediate(),Ct).getImmediate();return{getId:()=>async function(t){const e=t,{installationEntry:n,registrationPromise:s}=await wt(e.appConfig);return s?s.catch(console.error):_t(e).catch(console.error),n.fid}(e),getToken:t=>async function(t,e=!1){const n=t;return await async function(t){const{registrationPromise:e}=await wt(t);e&&await e}(n.appConfig),(await _t(n,e)).token}(e,t)}}),"PRIVATE")),G(J,X),G(J,X,"esm2017");const Nt="analytics",Rt="https://www.googletagmanager.com/gtag/js",Lt=new D("@firebase/analytics");function Dt(t){return Promise.all(t.map((t=>t.catch((t=>t)))))}const Ot=new h("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.'}),Pt=new class{constructor(t={},e=1e3){this.throttleMetadata=t,this.intervalMillis=e}getThrottleMetadata(t){return this.throttleMetadata[t]}setThrottleMetadata(t,e){this.throttleMetadata[t]=e}deleteThrottleMetadata(t){delete this.throttleMetadata[t]}};function Mt(t){return new Headers({Accept:"application/json","x-goog-api-key":t})}async function xt(t,e=Pt,n){const{appId:s,apiKey:r,measurementId:i}=t.options;if(!s)throw Ot.create("no-app-id");if(!r){if(i)return{measurementId:i,appId:s};throw Ot.create("no-api-key")}const o=e.getThrottleMetadata(s)||{backoffCount:0,throttleEndTimeMillis:Date.now()},a=new Ft;return setTimeout((async()=>{a.abort()}),void 0!==n?n:6e4),Ut({appId:s,apiKey:r,measurementId:i},o,a,e)}async function Ut(t,{throttleEndTimeMillis:e,backoffCount:n},s,r=Pt){const{appId:i,measurementId:o}=t;try{await function(t,e){return new Promise(((n,s)=>{const r=Math.max(e-Date.now(),0),i=setTimeout(n,r);t.addEventListener((()=>{clearTimeout(i),s(Ot.create("fetch-throttle",{throttleEndTimeMillis:e}))}))}))}(s,e)}catch(t){if(o)return Lt.warn(`Timed out fetching this Firebase app's measurement ID from the server. Falling back to the measurement ID ${o} provided in the "measurementId" field in the local Firebase config. [${t.message}]`),{appId:i,measurementId:o};throw t}try{const e=await async function(t){var e;const{appId:n,apiKey:s}=t,r={method:"GET",headers:Mt(s)},i="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig".replace("{app-id}",n),o=await fetch(i,r);if(200!==o.status&&304!==o.status){let t="";try{const n=await o.json();(null===(e=n.error)||void 0===e?void 0:e.message)&&(t=n.error.message)}catch(t){}throw Ot.create("config-fetch-failed",{httpStatus:o.status,responseMessage:t})}return o.json()}(t);return r.deleteThrottleMetadata(i),e}catch(e){if(!function(t){if(!(t instanceof u&&t.customData))return!1;const e=Number(t.customData.httpStatus);return 429===e||500===e||503===e||504===e}(e)){if(r.deleteThrottleMetadata(i),o)return Lt.warn(`Failed to fetch this Firebase app's measurement ID from the server. Falling back to the measurement ID ${o} provided in the "measurementId" field in the local Firebase config. [${e.message}]`),{appId:i,measurementId:o};throw e}const a=503===Number(e.customData.httpStatus)?w(n,r.intervalMillis,30):w(n,r.intervalMillis),c={throttleEndTimeMillis:Date.now()+a,backoffCount:n+1};return r.setThrottleMetadata(i,c),Lt.debug(`Calling attemptFetch again in ${a} millis`),Ut(t,c,s,r)}}class Ft{constructor(){this.listeners=[]}addEventListener(t){this.listeners.push(t)}abort(){this.listeners.forEach((t=>t()))}}async function Vt(t,e,n,s,r,i,o){var a;const c=xt(t);c.then((e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&Lt.warn(`The measurement ID in the local Firebase config (${t.options.measurementId}) does not match the measurement ID fetched from the server (${e.measurementId}). To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.`)})).catch((t=>Lt.error(t))),e.push(c);const u=async function(){if("object"!=typeof indexedDB)return Lt.warn(Ot.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await new Promise(((t,e)=>{try{let n=!0;const s="validate-browser-context-for-indexeddb-analytics-module",r=self.indexedDB.open(s);r.onsuccess=()=>{r.result.close(),n||self.indexedDB.deleteDatabase(s),t(!0)},r.onupgradeneeded=()=>{n=!1},r.onerror=()=>{var t;e((null===(t=r.error)||void 0===t?void 0:t.message)||"")}}catch(t){e(t)}}))}catch(t){return Lt.warn(Ot.create("indexeddb-unavailable",{errorInfo:t}).message),!1}return!0}().then((t=>t?s.getId():void 0)),[h,l]=await Promise.all([c,u]);(function(){const t=window.document.getElementsByTagName("script");for(const e of Object.values(t))if(e.src&&e.src.includes(Rt))return e;return null})()||function(t,e){const n=document.createElement("script");n.src=`${Rt}?l=${t}&id=${e}`,n.async=!0,document.head.appendChild(n)}(i,h.measurementId),r("js",new Date);const d=null!==(a=null==o?void 0:o.config)&&void 0!==a?a:{};return d.origin="firebase",d.update=!0,null!=l&&(d.firebase_id=l),r("config",h.measurementId,d),h.measurementId}class jt{constructor(t){this.app=t}_delete(){return delete Bt[this.app.options.appId],Promise.resolve()}}let Bt={},qt=[];const Ht={};let $t,Kt,zt="dataLayer",Gt=!1;function Wt(t,e,n){!function(){const t=[];if(o()&&t.push("This is a browser extension environment."),"undefined"!=typeof navigator&&navigator.cookieEnabled||t.push("Cookies are not available."),t.length>0){const e=t.map(((t,e)=>`(${e+1}) ${t}`)).join(" "),n=Ot.create("invalid-analytics-context",{errorInfo:e});Lt.warn(n.message)}}();const s=t.options.appId;if(!s)throw Ot.create("no-app-id");if(!t.options.apiKey){if(!t.options.measurementId)throw Ot.create("no-api-key");Lt.warn(`The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest measurement ID for this Firebase app. Falling back to the measurement ID ${t.options.measurementId} provided in the "measurementId" field in the local Firebase config.`)}if(null!=Bt[s])throw Ot.create("already-exists",{id:s});if(!Gt){!function(t){let e=[];Array.isArray(window.dataLayer)?e=window.dataLayer:window.dataLayer=e}();const{wrappedGtag:t,gtagCore:e}=function(t,e,n,s,r){let i=function(...t){window.dataLayer.push(arguments)};return window.gtag&&"function"==typeof window.gtag&&(i=window.gtag),window.gtag=function(t,e,n,s){return async function(r,i,o){try{"event"===r?await async function(t,e,n,s,r){try{let i=[];if(r&&r.send_to){let t=r.send_to;Array.isArray(t)||(t=[t]);const s=await Dt(n);for(const n of t){const t=s.find((t=>t.measurementId===n)),r=t&&e[t.appId];if(!r){i=[];break}i.push(r)}}0===i.length&&(i=Object.values(e)),await Promise.all(i),t("event",s,r||{})}catch(t){Lt.error(t)}}(t,e,n,i,o):"config"===r?await async function(t,e,n,s,r,i){const o=s[r];try{if(o)await e[o];else{const t=(await Dt(n)).find((t=>t.measurementId===r));t&&await e[t.appId]}}catch(t){Lt.error(t)}t("config",r,i)}(t,e,n,s,i,o):t("set",i)}catch(t){Lt.error(t)}}}(i,t,e,n),{gtagCore:i,wrappedGtag:window.gtag}}(Bt,qt,Ht);Kt=t,$t=e,Gt=!0}return Bt[s]=Vt(t,qt,Ht,e,$t,zt,n),new jt(t)}const Jt="@firebase/analytics",Xt="0.7.4";B(new T(Nt,((t,{options:e})=>Wt(t.getProvider("app").getImmediate(),t.getProvider("installations-internal").getImmediate(),e)),"PUBLIC")),B(new T("analytics-internal",(function(t){try{const e=t.getProvider(Nt).getImmediate();return{logEvent:(t,n,s)=>function(t,e,n,s){t=b(t),async function(t,e,n,s,r){if(r&&r.global)t("event",n,s);else{const r=await e;t("event",n,Object.assign(Object.assign({},s),{send_to:r}))}}(Kt,Bt[t.app.options.appId],e,n,s).catch((t=>Lt.error(t)))}(e,t,n,s)}}catch(t){throw Ot.create("interop-component-reg-failed",{reason:t})}}),"PRIVATE")),G(Jt,Xt),G(Jt,Xt,"esm2017");const Qt=function(t,e={}){"object"!=typeof e&&(e={name:e});const n=Object.assign({name:"[DEFAULT]",automaticDataCollectionEnabled:!1},e),s=n.name;if("string"!=typeof s||!s)throw H.create("bad-app-name",{appName:String(s)});const r=F.get(s);if(r){if(d(t,r.options)&&d(n,r.config))return r;throw H.create("duplicate-app",{appName:s})}const i=new _(s);for(const t of V.values())i.addComponent(t);const o=new $(t,n,i);return F.set(s,o),o}({apiKey:"AIzaSyCtAdfUZ8tR-mODZgkDRe6ZACdDdsA36kU",authDomain:"type-master-ecd50.firebaseapp.com",projectId:"type-master-ecd50",storageBucket:"type-master-ecd50.appspot.com",messagingSenderId:"310756367551",appId:"1:310756367551:web:9823810463c7c3e8e63a0a",measurementId:"MISSING_ENV_VAR".FIREBASE_MEADUREMENT_ID});function Yt(t,e){var n={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(n[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(t);rt,"Short delay should be less than long delay!"),this.isMobile=i()||a()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&("http:"===de()||"https:"===de()||o()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function pe(t,e){ce(t.emulator,"Emulator should always be set here");const{url:n}=t.emulator;return e?`${n}${e.startsWith("/")?e.slice(1):e}`:n}class me{static initialize(t,e,n){this.fetchImpl=t,e&&(this.headersImpl=e),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl?this.fetchImpl:"undefined"!=typeof self&&"fetch"in self?self.fetch:void ae("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 ae("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 ae("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const ge={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:"internal-error",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"},ye=new fe(3e4,6e4);function ve(t,e){return t.tenantId&&!e.tenantId?Object.assign(Object.assign({},e),{tenantId:t.tenantId}):e}async function we(t,e,n,s,r={}){return be(t,r,(async()=>{let r={},i={};s&&("GET"===e?i=s:r={body:JSON.stringify(s)});const o=p(Object.assign({key:t.config.apiKey},i)).slice(1),a=await t._getAdditionalHeaders();return a["Content-Type"]="application/json",t.languageCode&&(a["X-Firebase-Locale"]=t.languageCode),me.fetch()(Ee(t,t.config.apiHost,n,o),Object.assign({method:e,headers:a,referrerPolicy:"no-referrer"},r))}))}async function be(t,e,n){t._canInitEmulator=!1;const s=Object.assign(Object.assign({},ge),e);try{const e=new Ie(t),r=await Promise.race([n(),e.promise]);e.clearNetworkTimeout();const i=await r.json();if("needConfirmation"in i)throw _e(t,"account-exists-with-different-credential",i);if(r.ok&&!("errorMessage"in i))return i;{const e=r.ok?i.errorMessage:i.error.message,[n,o]=e.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===n)throw _e(t,"credential-already-in-use",i);if("EMAIL_EXISTS"===n)throw _e(t,"email-already-in-use",i);const a=s[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(o)throw function(t,e,n){const s=Object.assign(Object.assign({},Zt()),{[e]:n});return new h("auth","Firebase",s).create(e,{appName:t.name})}(t,a,o);se(t,a)}}catch(e){if(e instanceof u)throw e;se(t,"network-request-failed")}}async function Te(t,e,n,s,r={}){const i=await we(t,e,n,s,r);return"mfaPendingCredential"in i&&se(t,"multi-factor-auth-required",{_serverResponse:i}),i}function Ee(t,e,n,s){const r=`${e}${n}?${s}`;return t.config.emulator?pe(t.config,r):`${t.config.apiScheme}://${r}`}class Ie{constructor(t){this.auth=t,this.timer=null,this.promise=new Promise(((t,e)=>{this.timer=setTimeout((()=>e(re(this.auth,"timeout"))),ye.get())}))}clearNetworkTimeout(){clearTimeout(this.timer)}}function _e(t,e,n){const s={appName:t.name};n.email&&(s.email=n.email),n.phoneNumber&&(s.phoneNumber=n.phoneNumber);const r=re(t,e,s);return r.customData._tokenResponse=n,r}function Se(t){if(t)try{const e=new Date(Number(t));if(!isNaN(e.getTime()))return e.toUTCString()}catch(t){}}function ke(t){return 1e3*Number(t)}function Ae(t){const[n,s,r]=t.split(".");if(void 0===n||void 0===s||void 0===r)return ne("JWT malformed, contained fewer than 3 sections"),null;try{const t=function(t){try{return e.decodeString(t,!0)}catch(t){console.error("base64Decode failed: ",t)}return null}(s);return t?JSON.parse(t):(ne("Failed to decode base64 JWT payload"),null)}catch(t){return ne("Caught error parsing JWT payload as JSON",t),null}}async function Ce(t,e,n=!1){if(n)return e;try{return await e}catch(e){throw e instanceof u&&function({code:t}){return"auth/user-disabled"===t||"auth/user-token-expired"===t}(e)&&t.auth.currentUser===t&&await t.auth.signOut(),e}}class Ne{constructor(t){this.user=t,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(t){var e;if(t){const t=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),t}{this.errorBackoff=3e4;const t=(null!==(e=this.user.stsTokenManager.expirationTime)&&void 0!==e?e:0)-Date.now()-3e5;return Math.max(0,t)}}schedule(t=!1){if(!this.isRunning)return;const e=this.getInterval(t);this.timerId=setTimeout((async()=>{await this.iteration()}),e)}async iteration(){try{await this.user.getIdToken(!0)}catch(t){return void("auth/network-request-failed"===t.code&&this.schedule(!0))}this.schedule()}}class Re{constructor(t,e){this.createdAt=t,this.lastLoginAt=e,this._initializeTime()}_initializeTime(){this.lastSignInTime=Se(this.lastLoginAt),this.creationTime=Se(this.createdAt)}_copy(t){this.createdAt=t.createdAt,this.lastLoginAt=t.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Le(t){var e;const n=t.auth,s=await t.getIdToken(),r=await Ce(t,async function(t,e){return we(t,"POST","/v1/accounts:lookup",e)}(n,{idToken:s}));oe(null==r?void 0:r.users.length,n,"internal-error");const i=r.users[0];t._notifyReloadListener(i);const o=(null===(e=i.providerUserInfo)||void 0===e?void 0:e.length)?i.providerUserInfo.map((t=>{var{providerId:e}=t,n=Yt(t,["providerId"]);return{providerId:e,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}})):[],a=(c=t.providerData,u=o,[...c.filter((t=>!u.some((e=>e.providerId===t.providerId)))),...u]);var c,u;const h=t.isAnonymous,l=!(t.email&&i.passwordHash||(null==a?void 0:a.length)),d=!!h&&l,f={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:a,metadata:new Re(i.createdAt,i.lastLoginAt),isAnonymous:d};Object.assign(t,f)}class De{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(t){oe(t.idToken,"internal-error"),oe(void 0!==t.idToken,"internal-error"),oe(void 0!==t.refreshToken,"internal-error");const e="expiresIn"in t&&void 0!==t.expiresIn?Number(t.expiresIn):function(t){const e=Ae(t);return oe(e,"internal-error"),oe(void 0!==e.exp,"internal-error"),oe(void 0!==e.iat,"internal-error"),Number(e.exp)-Number(e.iat)}(t.idToken);this.updateTokensAndExpiration(t.idToken,t.refreshToken,e)}async getToken(t,e=!1){return oe(!this.accessToken||this.refreshToken,t,"user-token-expired"),e||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(t,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(t,e){const{accessToken:n,refreshToken:s,expiresIn:r}=await async function(t,e){const n=await be(t,{},(async()=>{const n=p({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:s,apiKey:r}=t.config,i=Ee(t,s,"/v1/token",`key=${r}`),o=await t._getAdditionalHeaders();return o["Content-Type"]="application/x-www-form-urlencoded",me.fetch()(i,{method:"POST",headers:o,body:n})}));return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}(t,e);this.updateTokensAndExpiration(n,s,Number(r))}updateTokensAndExpiration(t,e,n){this.refreshToken=e||null,this.accessToken=t||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(t,e){const{refreshToken:n,accessToken:s,expirationTime:r}=e,i=new De;return n&&(oe("string"==typeof n,"internal-error",{appName:t}),i.refreshToken=n),s&&(oe("string"==typeof s,"internal-error",{appName:t}),i.accessToken=s),r&&(oe("number"==typeof r,"internal-error",{appName:t}),i.expirationTime=r),i}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(t){this.accessToken=t.accessToken,this.refreshToken=t.refreshToken,this.expirationTime=t.expirationTime}_clone(){return Object.assign(new De,this.toJSON())}_performRefresh(){return ae("not implemented")}}function Oe(t,e){oe("string"==typeof t||void 0===t,"internal-error",{appName:e})}class Pe{constructor(t){var{uid:e,auth:n,stsTokenManager:s}=t,r=Yt(t,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.emailVerified=!1,this.isAnonymous=!1,this.tenantId=null,this.providerData=[],this.proactiveRefresh=new Ne(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=n,this.stsTokenManager=s,this.accessToken=s.accessToken,this.displayName=r.displayName||null,this.email=r.email||null,this.emailVerified=r.emailVerified||!1,this.phoneNumber=r.phoneNumber||null,this.photoURL=r.photoURL||null,this.isAnonymous=r.isAnonymous||!1,this.tenantId=r.tenantId||null,this.metadata=new Re(r.createdAt||void 0,r.lastLoginAt||void 0)}async getIdToken(t){const e=await Ce(this,this.stsTokenManager.getToken(this.auth,t));return oe(e,this.auth,"internal-error"),this.accessToken!==e&&(this.accessToken=e,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),e}getIdTokenResult(t){return async function(t,e=!1){const n=b(t),s=await n.getIdToken(e),r=Ae(s);oe(r&&r.exp&&r.auth_time&&r.iat,n.auth,"internal-error");const i="object"==typeof r.firebase?r.firebase:void 0,o=null==i?void 0:i.sign_in_provider;return{claims:r,token:s,authTime:Se(ke(r.auth_time)),issuedAtTime:Se(ke(r.iat)),expirationTime:Se(ke(r.exp)),signInProvider:o||null,signInSecondFactor:(null==i?void 0:i.sign_in_second_factor)||null}}(this,t)}reload(){return async function(t){const e=b(t);await Le(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}(this)}_assign(t){this!==t&&(oe(this.uid===t.uid,this.auth,"internal-error"),this.displayName=t.displayName,this.photoURL=t.photoURL,this.email=t.email,this.emailVerified=t.emailVerified,this.phoneNumber=t.phoneNumber,this.isAnonymous=t.isAnonymous,this.tenantId=t.tenantId,this.providerData=t.providerData.map((t=>Object.assign({},t))),this.metadata._copy(t.metadata),this.stsTokenManager._assign(t.stsTokenManager))}_clone(t){return new Pe(Object.assign(Object.assign({},this),{auth:t,stsTokenManager:this.stsTokenManager._clone()}))}_onReload(t){oe(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=t,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(t){this.reloadListener?this.reloadListener(t):this.reloadUserInfo=t}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(t,e=!1){let n=!1;t.idToken&&t.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(t),n=!0),e&&await Le(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){const t=await this.getIdToken();return await Ce(this,async function(t,e){return we(t,"POST","/v1/accounts:delete",e)}(this.auth,{idToken:t})),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((t=>Object.assign({},t))),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(t,e){var n,s,r,i,o,a,c,u;const h=null!==(n=e.displayName)&&void 0!==n?n:void 0,l=null!==(s=e.email)&&void 0!==s?s:void 0,d=null!==(r=e.phoneNumber)&&void 0!==r?r:void 0,f=null!==(i=e.photoURL)&&void 0!==i?i:void 0,p=null!==(o=e.tenantId)&&void 0!==o?o:void 0,m=null!==(a=e._redirectEventId)&&void 0!==a?a:void 0,g=null!==(c=e.createdAt)&&void 0!==c?c:void 0,y=null!==(u=e.lastLoginAt)&&void 0!==u?u:void 0,{uid:v,emailVerified:w,isAnonymous:b,providerData:T,stsTokenManager:E}=e;oe(v&&E,t,"internal-error");const I=De.fromJSON(this.name,E);oe("string"==typeof v,t,"internal-error"),Oe(h,t.name),Oe(l,t.name),oe("boolean"==typeof w,t,"internal-error"),oe("boolean"==typeof b,t,"internal-error"),Oe(d,t.name),Oe(f,t.name),Oe(p,t.name),Oe(m,t.name),Oe(g,t.name),Oe(y,t.name);const _=new Pe({uid:v,auth:t,email:l,emailVerified:w,displayName:h,isAnonymous:b,photoURL:f,phoneNumber:d,tenantId:p,stsTokenManager:I,createdAt:g,lastLoginAt:y});return T&&Array.isArray(T)&&(_.providerData=T.map((t=>Object.assign({},t)))),m&&(_._redirectEventId=m),_}static async _fromIdTokenResponse(t,e,n=!1){const s=new De;s.updateFromServerResponse(e);const r=new Pe({uid:e.localId,auth:t,stsTokenManager:s,isAnonymous:n});return await Le(r),r}}class Me{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(t,e){this.storage[t]=e}async _get(t){const e=this.storage[t];return void 0===e?null:e}async _remove(t){delete this.storage[t]}_addListener(t,e){}_removeListener(t,e){}}Me.type="NONE";const xe=Me;function Ue(t,e,n){return`firebase:${t}:${e}:${n}`}class Fe{constructor(t,e,n){this.persistence=t,this.auth=e,this.userKey=n;const{config:s,name:r}=this.auth;this.fullUserKey=Ue(this.userKey,s.apiKey,r),this.fullPersistenceKey=Ue("persistence",s.apiKey,r),this.boundEventHandler=e._onStorageEvent.bind(e),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(t){return this.persistence._set(this.fullUserKey,t.toJSON())}async getCurrentUser(){const t=await this.persistence._get(this.fullUserKey);return t?Pe._fromJSON(this.auth,t):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(t){if(this.persistence===t)return;const e=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=t,e?this.setCurrentUser(e):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(t,e,n="authUser"){if(!e.length)return new Fe(he(xe),t,n);const s=(await Promise.all(e.map((async t=>{if(await t._isAvailable())return t})))).filter((t=>t));let r=s[0]||he(xe);const i=Ue(n,t.config.apiKey,t.name);let o=null;for(const n of e)try{const e=await n._get(i);if(e){const s=Pe._fromJSON(t,e);n!==r&&(o=s),r=n;break}}catch(t){}const a=s.filter((t=>t._shouldAllowMigration));return r._shouldAllowMigration&&a.length?(r=a[0],o&&await r._set(i,o.toJSON()),await Promise.all(e.map((async t=>{if(t!==r)try{await t._remove(i)}catch(t){}}))),new Fe(r,t,n)):new Fe(r,t,n)}}function Ve(t){const e=t.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(He(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(je(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(Ke(e))return"Blackberry";if(ze(e))return"Webos";if(Be(e))return"Safari";if((e.includes("chrome/")||qe(e))&&!e.includes("edge/"))return"Chrome";if($e(e))return"Android";{const e=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,n=t.match(e);if(2===(null==n?void 0:n.length))return n[1]}return"Other"}function je(t=r()){return/firefox\//i.test(t)}function Be(t=r()){const e=t.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function qe(t=r()){return/crios\//i.test(t)}function He(t=r()){return/iemobile/i.test(t)}function $e(t=r()){return/android/i.test(t)}function Ke(t=r()){return/blackberry/i.test(t)}function ze(t=r()){return/webos/i.test(t)}function Ge(t=r()){return/iphone|ipad|ipod/i.test(t)}function We(t=r()){return Ge(t)||$e(t)||ze(t)||Ke(t)||/windows phone/i.test(t)||He(t)}function Je(t,e=[]){let n;switch(t){case"Browser":n=Ve(r());break;case"Worker":n=`${Ve(r())}-${t}`;break;default:n=t}return`${n}/JsCore/9.6.1/${e.length?e.join(","):"FirebaseCore-web"}`}class Xe{constructor(t,e){this.app=t,this.config=e,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Ye(this),this.idTokenSubscription=new Ye(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=te,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=t.name,this.clientVersion=e.sdkClientVersion}_initializeWithPersistence(t,e){return e&&(this._popupRedirectResolver=he(e)),this._initializationPromise=this.queue((async()=>{var n,s;if(!this._deleted&&(this.persistenceManager=await Fe.create(this,t),!this._deleted)){if(null===(n=this._popupRedirectResolver)||void 0===n?void 0:n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(t){}await this.initializeCurrentUser(e),this.lastNotifiedUid=(null===(s=this.currentUser)||void 0===s?void 0:s.uid)||null,this._deleted||(this._isInitialized=!0)}})),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const t=await this.assertedPersistence.getCurrentUser();return this.currentUser||t?this.currentUser&&t&&this.currentUser.uid===t.uid?(this._currentUser._assign(t),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(t):void 0}async initializeCurrentUser(t){var e;let n=await this.assertedPersistence.getCurrentUser();if(t&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const s=null===(e=this.redirectUser)||void 0===e?void 0:e._redirectEventId,r=null==n?void 0:n._redirectEventId,i=await this.tryRedirectSignIn(t);s&&s!==r||!(null==i?void 0:i.user)||(n=i.user)}return n?n._redirectEventId?(oe(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===n._redirectEventId?this.directlySetCurrentUser(n):this.reloadAndSetCurrentUserOrClear(n)):this.reloadAndSetCurrentUserOrClear(n):this.directlySetCurrentUser(null)}async tryRedirectSignIn(t){let e=null;try{e=await this._popupRedirectResolver._completeRedirectFn(this,t,!0)}catch(t){await this._setRedirectUser(null)}return e}async reloadAndSetCurrentUserOrClear(t){try{await Le(t)}catch(t){if("auth/network-request-failed"!==t.code)return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(t)}useDeviceLanguage(){this.languageCode=function(){if("undefined"==typeof navigator)return null;const t=navigator;return t.languages&&t.languages[0]||t.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(t){const e=t?b(t):null;return e&&oe(e.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(e&&e._clone(this))}async _updateCurrentUser(t){if(!this._deleted)return t&&oe(this.tenantId===t.tenantId,this,"tenant-id-mismatch"),this.queue((async()=>{await this.directlySetCurrentUser(t),this.notifyAuthListeners()}))}async signOut(){return(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null)}setPersistence(t){return this.queue((async()=>{await this.assertedPersistence.setPersistence(he(t))}))}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(t){this._errorFactory=new h("auth","Firebase",t())}onAuthStateChanged(t,e,n){return this.registerStateListener(this.authStateSubscription,t,e,n)}onIdTokenChanged(t,e,n){return this.registerStateListener(this.idTokenSubscription,t,e,n)}toJSON(){var t;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(t=this._currentUser)||void 0===t?void 0:t.toJSON()}}async _setRedirectUser(t,e){const n=await this.getOrInitRedirectPersistenceManager(e);return null===t?n.removeCurrentUser():n.setCurrentUser(t)}async getOrInitRedirectPersistenceManager(t){if(!this.redirectPersistenceManager){const e=t&&he(t)||this._popupRedirectResolver;oe(e,this,"argument-error"),this.redirectPersistenceManager=await Fe.create(this,[he(e._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(t){var e,n;return this._isInitialized&&await this.queue((async()=>{})),(null===(e=this._currentUser)||void 0===e?void 0:e._redirectEventId)===t?this._currentUser:(null===(n=this.redirectUser)||void 0===n?void 0:n._redirectEventId)===t?this.redirectUser:null}async _persistUserIfCurrent(t){if(t===this.currentUser)return this.queue((async()=>this.directlySetCurrentUser(t)))}_notifyListenersIfCurrent(t){t===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 t,e;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const n=null!==(e=null===(t=this.currentUser)||void 0===t?void 0:t.uid)&&void 0!==e?e:null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(t,e,n,s){if(this._deleted)return()=>{};const r="function"==typeof e?e:e.next.bind(e),i=this._isInitialized?Promise.resolve():this._initializationPromise;return oe(i,this,"internal-error"),i.then((()=>r(this.currentUser))),"function"==typeof e?t.addObserver(e,n,s):t.addObserver(e)}async directlySetCurrentUser(t){this.currentUser&&this.currentUser!==t&&(this._currentUser._stopProactiveRefresh(),t&&this.isProactiveRefreshEnabled&&t._startProactiveRefresh()),this.currentUser=t,t?await this.assertedPersistence.setCurrentUser(t):await this.assertedPersistence.removeCurrentUser()}queue(t){return this.operations=this.operations.then(t,t),this.operations}get assertedPersistence(){return oe(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(t){t&&!this.frameworks.includes(t)&&(this.frameworks.push(t),this.frameworks.sort(),this.clientVersion=Je(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const t={"X-Client-Version":this.clientVersion};return this.app.options.appId&&(t["X-Firebase-gmpid"]=this.app.options.appId),t}}function Qe(t){return b(t)}class Ye{constructor(t){this.auth=t,this.observer=null,this.addObserver=function(t,e){const n=new y(t,void 0);return n.subscribe.bind(n)}((t=>this.observer=t))}get next(){return oe(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}class Ze{constructor(t,e){this.providerId=t,this.signInMethod=e}toJSON(){return ae("not implemented")}_getIdTokenResponse(t){return ae("not implemented")}_linkToIdToken(t,e){return ae("not implemented")}_getReauthenticationResolver(t){return ae("not implemented")}}class tn extends Ze{constructor(t,e,n,s=null){super("password",n),this._email=t,this._password=e,this._tenantId=s}static _fromEmailAndPassword(t,e){return new tn(t,e,"password")}static _fromEmailAndCode(t,e,n=null){return new tn(t,e,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(t){const e="string"==typeof t?JSON.parse(t):t;if((null==e?void 0:e.email)&&(null==e?void 0:e.password)){if("password"===e.signInMethod)return this._fromEmailAndPassword(e.email,e.password);if("emailLink"===e.signInMethod)return this._fromEmailAndCode(e.email,e.password,e.tenantId)}return null}async _getIdTokenResponse(t){switch(this.signInMethod){case"password":return async function(t,e){return Te(t,"POST","/v1/accounts:signInWithPassword",ve(t,e))}(t,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(t,e){return Te(t,"POST","/v1/accounts:signInWithEmailLink",ve(t,e))}(t,{email:this._email,oobCode:this._password});default:se(t,"internal-error")}}async _linkToIdToken(t,e){switch(this.signInMethod){case"password":return async function(t,e){return we(t,"POST","/v1/accounts:update",e)}(t,{idToken:e,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(t,e){return Te(t,"POST","/v1/accounts:signInWithEmailLink",ve(t,e))}(t,{idToken:e,email:this._email,oobCode:this._password});default:se(t,"internal-error")}}_getReauthenticationResolver(t){return this._getIdTokenResponse(t)}}async function en(t,e){return Te(t,"POST","/v1/accounts:signInWithIdp",ve(t,e))}class nn extends Ze{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(t){const e=new nn(t.providerId,t.signInMethod);return t.idToken||t.accessToken?(t.idToken&&(e.idToken=t.idToken),t.accessToken&&(e.accessToken=t.accessToken),t.nonce&&!t.pendingToken&&(e.nonce=t.nonce),t.pendingToken&&(e.pendingToken=t.pendingToken)):t.oauthToken&&t.oauthTokenSecret?(e.accessToken=t.oauthToken,e.secret=t.oauthTokenSecret):se("argument-error"),e}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(t){const e="string"==typeof t?JSON.parse(t):t,{providerId:n,signInMethod:s}=e,r=Yt(e,["providerId","signInMethod"]);if(!n||!s)return null;const i=new nn(n,s);return i.idToken=r.idToken||void 0,i.accessToken=r.accessToken||void 0,i.secret=r.secret,i.nonce=r.nonce,i.pendingToken=r.pendingToken||null,i}_getIdTokenResponse(t){return en(t,this.buildRequest())}_linkToIdToken(t,e){const n=this.buildRequest();return n.idToken=e,en(t,n)}_getReauthenticationResolver(t){const e=this.buildRequest();return e.autoCreate=!1,en(t,e)}buildRequest(){const t={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)t.pendingToken=this.pendingToken;else{const e={};this.idToken&&(e.id_token=this.idToken),this.accessToken&&(e.access_token=this.accessToken),this.secret&&(e.oauth_token_secret=this.secret),e.providerId=this.providerId,this.nonce&&!this.pendingToken&&(e.nonce=this.nonce),t.postBody=p(e)}return t}}const sn={USER_NOT_FOUND:"user-not-found"};class rn extends Ze{constructor(t){super("phone","phone"),this.params=t}static _fromVerification(t,e){return new rn({verificationId:t,verificationCode:e})}static _fromTokenResponse(t,e){return new rn({phoneNumber:t,temporaryProof:e})}_getIdTokenResponse(t){return async function(t,e){return Te(t,"POST","/v1/accounts:signInWithPhoneNumber",ve(t,e))}(t,this._makeVerificationRequest())}_linkToIdToken(t,e){return async function(t,e){const n=await Te(t,"POST","/v1/accounts:signInWithPhoneNumber",ve(t,e));if(n.temporaryProof)throw _e(t,"account-exists-with-different-credential",n);return n}(t,Object.assign({idToken:e},this._makeVerificationRequest()))}_getReauthenticationResolver(t){return async function(t,e){return Te(t,"POST","/v1/accounts:signInWithPhoneNumber",ve(t,Object.assign(Object.assign({},e),{operation:"REAUTH"})),sn)}(t,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:t,phoneNumber:e,verificationId:n,verificationCode:s}=this.params;return t&&e?{temporaryProof:t,phoneNumber:e}:{sessionInfo:n,code:s}}toJSON(){const t={providerId:this.providerId};return this.params.phoneNumber&&(t.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(t.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(t.verificationCode=this.params.verificationCode),this.params.verificationId&&(t.verificationId=this.params.verificationId),t}static fromJSON(t){"string"==typeof t&&(t=JSON.parse(t));const{verificationId:e,verificationCode:n,phoneNumber:s,temporaryProof:r}=t;return n||e||s||r?new rn({verificationId:e,verificationCode:n,phoneNumber:s,temporaryProof:r}):null}}class on{constructor(t){var e,n,s,r,i,o;const a=m(g(t)),c=null!==(e=a.apiKey)&&void 0!==e?e:null,u=null!==(n=a.oobCode)&&void 0!==n?n:null,h=function(t){switch(t){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!==(s=a.mode)&&void 0!==s?s:null);oe(c&&u&&h,"argument-error"),this.apiKey=c,this.operation=h,this.code=u,this.continueUrl=null!==(r=a.continueUrl)&&void 0!==r?r:null,this.languageCode=null!==(i=a.languageCode)&&void 0!==i?i:null,this.tenantId=null!==(o=a.tenantId)&&void 0!==o?o:null}static parseLink(t){const e=function(t){const e=m(g(t)).link,n=e?m(g(e)).deep_link_id:null,s=m(g(t)).deep_link_id;return(s?m(g(s)).link:null)||s||n||e||t}(t);try{return new on(e)}catch(t){return null}}}class an{constructor(){this.providerId=an.PROVIDER_ID}static credential(t,e){return tn._fromEmailAndPassword(t,e)}static credentialWithLink(t,e){const n=on.parseLink(e);return oe(n,"argument-error"),tn._fromEmailAndCode(t,n.code,n.tenantId)}}an.PROVIDER_ID="password",an.EMAIL_PASSWORD_SIGN_IN_METHOD="password",an.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class cn{constructor(t){this.providerId=t,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(t){this.defaultLanguageCode=t}setCustomParameters(t){return this.customParameters=t,this}getCustomParameters(){return this.customParameters}}class un extends cn{constructor(){super(...arguments),this.scopes=[]}addScope(t){return this.scopes.includes(t)||this.scopes.push(t),this}getScopes(){return[...this.scopes]}}class hn extends un{constructor(){super("facebook.com")}static credential(t){return nn._fromParams({providerId:hn.PROVIDER_ID,signInMethod:hn.FACEBOOK_SIGN_IN_METHOD,accessToken:t})}static credentialFromResult(t){return hn.credentialFromTaggedObject(t)}static credentialFromError(t){return hn.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t||!("oauthAccessToken"in t))return null;if(!t.oauthAccessToken)return null;try{return hn.credential(t.oauthAccessToken)}catch(t){return null}}}hn.FACEBOOK_SIGN_IN_METHOD="facebook.com",hn.PROVIDER_ID="facebook.com";class ln extends un{constructor(){super("google.com"),this.addScope("profile")}static credential(t,e){return nn._fromParams({providerId:ln.PROVIDER_ID,signInMethod:ln.GOOGLE_SIGN_IN_METHOD,idToken:t,accessToken:e})}static credentialFromResult(t){return ln.credentialFromTaggedObject(t)}static credentialFromError(t){return ln.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t)return null;const{oauthIdToken:e,oauthAccessToken:n}=t;if(!e&&!n)return null;try{return ln.credential(e,n)}catch(t){return null}}}ln.GOOGLE_SIGN_IN_METHOD="google.com",ln.PROVIDER_ID="google.com";class dn extends un{constructor(){super("github.com")}static credential(t){return nn._fromParams({providerId:dn.PROVIDER_ID,signInMethod:dn.GITHUB_SIGN_IN_METHOD,accessToken:t})}static credentialFromResult(t){return dn.credentialFromTaggedObject(t)}static credentialFromError(t){return dn.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t||!("oauthAccessToken"in t))return null;if(!t.oauthAccessToken)return null;try{return dn.credential(t.oauthAccessToken)}catch(t){return null}}}dn.GITHUB_SIGN_IN_METHOD="github.com",dn.PROVIDER_ID="github.com";class fn extends un{constructor(){super("twitter.com")}static credential(t,e){return nn._fromParams({providerId:fn.PROVIDER_ID,signInMethod:fn.TWITTER_SIGN_IN_METHOD,oauthToken:t,oauthTokenSecret:e})}static credentialFromResult(t){return fn.credentialFromTaggedObject(t)}static credentialFromError(t){return fn.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t)return null;const{oauthAccessToken:e,oauthTokenSecret:n}=t;if(!e||!n)return null;try{return fn.credential(e,n)}catch(t){return null}}}fn.TWITTER_SIGN_IN_METHOD="twitter.com",fn.PROVIDER_ID="twitter.com";class pn{constructor(t){this.user=t.user,this.providerId=t.providerId,this._tokenResponse=t._tokenResponse,this.operationType=t.operationType}static async _fromIdTokenResponse(t,e,n,s=!1){const r=await Pe._fromIdTokenResponse(t,n,s),i=mn(n);return new pn({user:r,providerId:i,_tokenResponse:n,operationType:e})}static async _forOperation(t,e,n){await t._updateTokensIfNecessary(n,!0);const s=mn(n);return new pn({user:t,providerId:s,_tokenResponse:n,operationType:e})}}function mn(t){return t.providerId?t.providerId:"phoneNumber"in t?"phone":null}class gn extends u{constructor(t,e,n,s){var r;super(e.code,e.message),this.operationType=n,this.user=s,Object.setPrototypeOf(this,gn.prototype),this.customData={appName:t.name,tenantId:null!==(r=t.tenantId)&&void 0!==r?r:void 0,_serverResponse:e.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(t,e,n,s){return new gn(t,e,n,s)}}function yn(t,e,n,s){return("reauthenticate"===e?n._getReauthenticationResolver(t):n._getIdTokenResponse(t)).catch((n=>{if("auth/multi-factor-auth-required"===n.code)throw gn._fromErrorAndOperation(t,n,e,s);throw n}))}async function vn(t,e,n=!1){const s="signIn",r=await yn(t,s,e),i=await pn._fromIdTokenResponse(t,s,r);return n||await t._updateCurrentUser(i.user),i}async function wn(t,{displayName:e,photoURL:n}){if(void 0===e&&void 0===n)return;const s=b(t),r={idToken:await s.getIdToken(),displayName:e,photoUrl:n,returnSecureToken:!0},i=await Ce(s,async function(t,e){return we(t,"POST","/v1/accounts:update",e)}(s.auth,r));s.displayName=i.displayName||null,s.photoURL=i.photoUrl||null;const o=s.providerData.find((({providerId:t})=>"password"===t));o&&(o.displayName=s.displayName,o.photoURL=s.photoURL),await s._updateTokensIfNecessary(i)}new WeakMap;const bn="__sak";class Tn{constructor(t,e){this.storageRetriever=t,this.type=e}_isAvailable(){try{return this.storage?(this.storage.setItem(bn,"1"),this.storage.removeItem(bn),Promise.resolve(!0)):Promise.resolve(!1)}catch(t){return Promise.resolve(!1)}}_set(t,e){return this.storage.setItem(t,JSON.stringify(e)),Promise.resolve()}_get(t){const e=this.storage.getItem(t);return Promise.resolve(e?JSON.parse(e):null)}_remove(t){return this.storage.removeItem(t),Promise.resolve()}get storage(){return this.storageRetriever()}}class En extends Tn{constructor(){super((()=>window.localStorage),"LOCAL"),this.boundEventHandler=(t,e)=>this.onStorageEvent(t,e),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=function(){const t=r();return Be(t)||Ge(t)}()&&function(){try{return!(!window||window===window.top)}catch(t){return!1}}(),this.fallbackToPolling=We(),this._shouldAllowMigration=!0}forAllChangedKeys(t){for(const e of Object.keys(this.listeners)){const n=this.storage.getItem(e),s=this.localCache[e];n!==s&&t(e,s,n)}}onStorageEvent(t,e=!1){if(!t.key)return void this.forAllChangedKeys(((t,e,n)=>{this.notifyListeners(t,n)}));const n=t.key;if(e?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const s=this.storage.getItem(n);if(t.newValue!==s)null!==t.newValue?this.storage.setItem(n,t.newValue):this.storage.removeItem(n);else if(this.localCache[n]===t.newValue&&!e)return}const s=()=>{const t=this.storage.getItem(n);(e||this.localCache[n]!==t)&&this.notifyListeners(n,t)},r=this.storage.getItem(n);c()&&10===document.documentMode&&r!==t.newValue&&t.newValue!==t.oldValue?setTimeout(s,10):s()}notifyListeners(t,e){this.localCache[t]=e;const n=this.listeners[t];if(n)for(const t of Array.from(n))t(e?JSON.parse(e):e)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((t,e,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:t,oldValue:e,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(t,e){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[t]||(this.listeners[t]=new Set,this.localCache[t]=this.storage.getItem(t)),this.listeners[t].add(e)}_removeListener(t,e){this.listeners[t]&&(this.listeners[t].delete(e),0===this.listeners[t].size&&delete this.listeners[t]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(t,e){await super._set(t,e),this.localCache[t]=JSON.stringify(e)}async _get(t){const e=await super._get(t);return this.localCache[t]=JSON.stringify(e),e}async _remove(t){await super._remove(t),delete this.localCache[t]}}En.type="LOCAL";const In=En;class _n extends Tn{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(t,e){}_removeListener(t,e){}}_n.type="SESSION";const Sn=_n;class kn{constructor(t){this.eventTarget=t,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(t){const e=this.receivers.find((e=>e.isListeningto(t)));if(e)return e;const n=new kn(t);return this.receivers.push(n),n}isListeningto(t){return this.eventTarget===t}async handleEvent(t){const e=t,{eventId:n,eventType:s,data:r}=e.data,i=this.handlersMap[s];if(!(null==i?void 0:i.size))return;e.ports[0].postMessage({status:"ack",eventId:n,eventType:s});const o=Array.from(i).map((async t=>t(e.origin,r))),a=await function(t){return Promise.all(t.map((async t=>{try{return{fulfilled:!0,value:await t}}catch(t){return{fulfilled:!1,reason:t}}})))}(o);e.ports[0].postMessage({status:"done",eventId:n,eventType:s,response:a})}_subscribe(t,e){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[t]||(this.handlersMap[t]=new Set),this.handlersMap[t].add(e)}_unsubscribe(t,e){this.handlersMap[t]&&e&&this.handlersMap[t].delete(e),e&&0!==this.handlersMap[t].size||delete this.handlersMap[t],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function An(t="",e=10){let n="";for(let t=0;t{const c=An("",20);s.port1.start();const u=setTimeout((()=>{a(new Error("unsupported_event"))}),n);i={messageChannel:s,onMessage(t){const e=t;if(e.data.eventId===c)switch(e.data.status){case"ack":clearTimeout(u),r=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(r),o(e.data.response);break;default:clearTimeout(u),clearTimeout(r),a(new Error("invalid_response"))}}},this.handlers.add(i),s.port1.addEventListener("message",i.onMessage),this.target.postMessage({eventType:t,eventId:c,data:e},[s.port2])})).finally((()=>{i&&this.removeMessageHandler(i)}))}}function Nn(){return window}function Rn(){return void 0!==Nn().WorkerGlobalScope&&"function"==typeof Nn().importScripts}const Ln="firebaseLocalStorageDb",Dn="firebaseLocalStorage",On="fbase_key";class Pn{constructor(t){this.request=t}toPromise(){return new Promise(((t,e)=>{this.request.addEventListener("success",(()=>{t(this.request.result)})),this.request.addEventListener("error",(()=>{e(this.request.error)}))}))}}function Mn(t,e){return t.transaction([Dn],e?"readwrite":"readonly").objectStore(Dn)}function xn(){const t=indexedDB.open(Ln,1);return new Promise(((e,n)=>{t.addEventListener("error",(()=>{n(t.error)})),t.addEventListener("upgradeneeded",(()=>{const e=t.result;try{e.createObjectStore(Dn,{keyPath:On})}catch(t){n(t)}})),t.addEventListener("success",(async()=>{const n=t.result;n.objectStoreNames.contains(Dn)?e(n):(n.close(),await function(){const t=indexedDB.deleteDatabase(Ln);return new Pn(t).toPromise()}(),e(await xn()))}))}))}async function Un(t,e,n){const s=Mn(t,!0).put({[On]:e,value:n});return new Pn(s).toPromise()}function Fn(t,e){const n=Mn(t,!0).delete(e);return new Pn(n).toPromise()}class Vn{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 xn()),this.db}async _withRetries(t){let e=0;for(;;)try{const e=await this._openDb();return await t(e)}catch(t){if(e++>3)throw t;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Rn()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=kn._getInstance(Rn()?self:null),this.receiver._subscribe("keyChanged",(async(t,e)=>({keyProcessed:(await this._poll()).includes(e.key)}))),this.receiver._subscribe("ping",(async(t,e)=>["keyChanged"]))}async initializeSender(){var t,e;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(t){return null}}(),!this.activeServiceWorker)return;this.sender=new Cn(this.activeServiceWorker);const n=await this.sender._send("ping",{},800);n&&(null===(t=n[0])||void 0===t?void 0:t.fulfilled)&&(null===(e=n[0])||void 0===e?void 0:e.value.includes("keyChanged"))&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(t){if(this.sender&&this.activeServiceWorker&&function(){var t;return(null===(t=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===t?void 0:t.controller)||null}()===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:t},this.serviceWorkerReceiverAvailable?800:50)}catch(t){}}async _isAvailable(){try{if(!indexedDB)return!1;const t=await xn();return await Un(t,bn,"1"),await Fn(t,bn),!0}catch(t){}return!1}async _withPendingWrite(t){this.pendingWrites++;try{await t()}finally{this.pendingWrites--}}async _set(t,e){return this._withPendingWrite((async()=>(await this._withRetries((n=>Un(n,t,e))),this.localCache[t]=e,this.notifyServiceWorker(t))))}async _get(t){const e=await this._withRetries((e=>async function(t,e){const n=Mn(t,!1).get(e),s=await new Pn(n).toPromise();return void 0===s?null:s.value}(e,t)));return this.localCache[t]=e,e}async _remove(t){return this._withPendingWrite((async()=>(await this._withRetries((e=>Fn(e,t))),delete this.localCache[t],this.notifyServiceWorker(t))))}async _poll(){const t=await this._withRetries((t=>{const e=Mn(t,!1).getAll();return new Pn(e).toPromise()}));if(!t)return[];if(0!==this.pendingWrites)return[];const e=[],n=new Set;for(const{fbase_key:s,value:r}of t)n.add(s),JSON.stringify(this.localCache[s])!==JSON.stringify(r)&&(this.notifyListeners(s,r),e.push(s));for(const t of Object.keys(this.localCache))this.localCache[t]&&!n.has(t)&&(this.notifyListeners(t,null),e.push(t));return e}notifyListeners(t,e){this.localCache[t]=e;const n=this.listeners[t];if(n)for(const t of Array.from(n))t(e)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((async()=>this._poll()),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(t,e){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[t]||(this.listeners[t]=new Set,this._get(t)),this.listeners[t].add(e)}_removeListener(t,e){this.listeners[t]&&(this.listeners[t].delete(e),0===this.listeners[t].size&&delete this.listeners[t]),0===Object.keys(this.listeners).length&&this.stopPolling()}}Vn.type="LOCAL";const jn=Vn;function Bn(t){return`__${t}${Math.floor(1e6*Math.random())}`}Bn("rcb"),new fe(3e4,6e4);class qn{constructor(t){this.providerId=qn.PROVIDER_ID,this.auth=Qe(t)}verifyPhoneNumber(t,e){return async function(t,e,n){var s;const r=await n.verify();try{let i;if(oe("string"==typeof r,t,"argument-error"),oe("recaptcha"===n.type,t,"argument-error"),i="string"==typeof e?{phoneNumber:e}:e,"session"in i){const e=i.session;if("phoneNumber"in i){oe("enroll"===e.type,t,"internal-error");const n=await function(t,e){return we(t,"POST","/v2/accounts/mfaEnrollment:start",ve(t,e))}(t,{idToken:e.credential,phoneEnrollmentInfo:{phoneNumber:i.phoneNumber,recaptchaToken:r}});return n.phoneSessionInfo.sessionInfo}{oe("signin"===e.type,t,"internal-error");const n=(null===(s=i.multiFactorHint)||void 0===s?void 0:s.uid)||i.multiFactorUid;oe(n,t,"missing-multi-factor-info");const o=await function(t,e){return we(t,"POST","/v2/accounts/mfaSignIn:start",ve(t,e))}(t,{mfaPendingCredential:e.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:r}});return o.phoneResponseInfo.sessionInfo}}{const{sessionInfo:e}=await async function(t,e){return we(t,"POST","/v1/accounts:sendVerificationCode",ve(t,e))}(t,{phoneNumber:i.phoneNumber,recaptchaToken:r});return e}}finally{n._reset()}}(this.auth,t,b(e))}static credential(t,e){return rn._fromVerification(t,e)}static credentialFromResult(t){const e=t;return qn.credentialFromTaggedObject(e)}static credentialFromError(t){return qn.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t)return null;const{phoneNumber:e,temporaryProof:n}=t;return e&&n?rn._fromTokenResponse(e,n):null}}qn.PROVIDER_ID="phone",qn.PHONE_SIGN_IN_METHOD="phone";class Hn extends Ze{constructor(t){super("custom","custom"),this.params=t}_getIdTokenResponse(t){return en(t,this._buildIdpRequest())}_linkToIdToken(t,e){return en(t,this._buildIdpRequest(e))}_getReauthenticationResolver(t){return en(t,this._buildIdpRequest())}_buildIdpRequest(t){const e={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 t&&(e.idToken=t),e}}function $n(t){return vn(t.auth,new Hn(t),t.bypassAuthState)}function Kn(t){const{auth:e,user:n}=t;return oe(n,e,"internal-error"),async function(t,e,n=!1){const{auth:s}=t,r="reauthenticate";try{const i=await Ce(t,yn(s,r,e,t),n);oe(i.idToken,s,"internal-error");const o=Ae(i.idToken);oe(o,s,"internal-error");const{sub:a}=o;return oe(t.uid===a,s,"user-mismatch"),pn._forOperation(t,r,i)}catch(t){throw"auth/user-not-found"===(null==t?void 0:t.code)&&se(s,"user-mismatch"),t}}(n,new Hn(t),t.bypassAuthState)}async function zn(t){const{auth:e,user:n}=t;return oe(n,e,"internal-error"),async function(t,e,n=!1){const s=await Ce(t,e._linkToIdToken(t.auth,await t.getIdToken()),n);return pn._forOperation(t,"link",s)}(n,new Hn(t),t.bypassAuthState)}class Gn{constructor(t,e,n,s,r=!1){this.auth=t,this.resolver=n,this.user=s,this.bypassAuthState=r,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(e)?e:[e]}execute(){return new Promise((async(t,e)=>{this.pendingPromise={resolve:t,reject:e};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(t){this.reject(t)}}))}async onAuthEvent(t){const{urlResponse:e,sessionId:n,postBody:s,tenantId:r,error:i,type:o}=t;if(i)return void this.reject(i);const a={auth:this.auth,requestUri:e,sessionId:n,tenantId:r||void 0,postBody:s||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(t){this.reject(t)}}onError(t){this.reject(t)}getIdpTask(t){switch(t){case"signInViaPopup":case"signInViaRedirect":return $n;case"linkViaPopup":case"linkViaRedirect":return zn;case"reauthViaPopup":case"reauthViaRedirect":return Kn;default:se(this.auth,"internal-error")}}resolve(t){ce(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(t),this.unregisterAndCleanUp()}reject(t){ce(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(t),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const Wn=new fe(2e3,1e4);class Jn extends Gn{constructor(t,e,n,s,r){super(t,e,s,r),this.provider=n,this.authWindow=null,this.pollId=null,Jn.currentPopupAction&&Jn.currentPopupAction.cancel(),Jn.currentPopupAction=this}async executeNotNull(){const t=await this.execute();return oe(t,this.auth,"internal-error"),t}async onExecution(){ce(1===this.filter.length,"Popup operations only handle one event");const t=An();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],t),this.authWindow.associatedEvent=t,this.resolver._originValidation(this.auth).catch((t=>{this.reject(t)})),this.resolver._isIframeWebStorageSupported(this.auth,(t=>{t||this.reject(re(this.auth,"web-storage-unsupported"))})),this.pollUserCancellation()}get eventId(){var t;return(null===(t=this.authWindow)||void 0===t?void 0:t.associatedEvent)||null}cancel(){this.reject(re(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Jn.currentPopupAction=null}pollUserCancellation(){const t=()=>{var e,n;(null===(n=null===(e=this.authWindow)||void 0===e?void 0:e.window)||void 0===n?void 0:n.closed)?this.pollId=window.setTimeout((()=>{this.pollId=null,this.reject(re(this.auth,"popup-closed-by-user"))}),2e3):this.pollId=window.setTimeout(t,Wn.get())};t()}}Jn.currentPopupAction=null;const Xn=new Map;class Qn extends Gn{constructor(t,e,n=!1){super(t,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],e,void 0,n),this.eventId=null}async execute(){let t=Xn.get(this.auth._key());if(!t){try{const e=await async function(t,e){const n=function(t){return Ue("pendingRedirect",t.config.apiKey,t.name)}(e),s=function(t){return he(t._redirectPersistence)}(t);if(!await s._isAvailable())return!1;const r="true"===await s._get(n);return await s._remove(n),r}(this.resolver,this.auth),n=e?await super.execute():null;t=()=>Promise.resolve(n)}catch(e){t=()=>Promise.reject(e)}Xn.set(this.auth._key(),t)}return this.bypassAuthState||Xn.set(this.auth._key(),(()=>Promise.resolve(null))),t()}async onAuthEvent(t){if("signInViaRedirect"===t.type)return super.onAuthEvent(t);if("unknown"!==t.type){if(t.eventId){const e=await this.auth._redirectUserForId(t.eventId);if(e)return this.user=e,super.onAuthEvent(t);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function Yn(t,e,n=!1){const s=Qe(t),r=function(t,e){return e?he(e):(oe(t._popupRedirectResolver,t,"argument-error"),t._popupRedirectResolver)}(s,e),i=new Qn(s,r,n),o=await i.execute();return o&&!n&&(delete o.user._redirectEventId,await s._persistUserIfCurrent(o.user),await s._setRedirectUser(null,e)),o}class Zn{constructor(t){this.auth=t,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(t){this.consumers.add(t),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,t)&&(this.sendToConsumer(this.queuedRedirectEvent,t),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(t){this.consumers.delete(t)}onEvent(t){if(this.hasEventBeenHandled(t))return!1;let e=!1;return this.consumers.forEach((n=>{this.isEventForConsumer(t,n)&&(e=!0,this.sendToConsumer(t,n),this.saveEventToCache(t))})),this.hasHandledPotentialRedirect||!function(t){switch(t.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return es(t);default:return!1}}(t)||(this.hasHandledPotentialRedirect=!0,e||(this.queuedRedirectEvent=t,e=!0)),e}sendToConsumer(t,e){var n;if(t.error&&!es(t)){const s=(null===(n=t.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";e.onError(re(this.auth,s))}else e.onAuthEvent(t)}isEventForConsumer(t,e){const n=null===e.eventId||!!t.eventId&&t.eventId===e.eventId;return e.filter.includes(t.type)&&n}hasEventBeenHandled(t){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(ts(t))}saveEventToCache(t){this.cachedEventUids.add(ts(t)),this.lastProcessedEventTime=Date.now()}}function ts(t){return[t.type,t.eventId,t.sessionId,t.tenantId].filter((t=>t)).join("-")}function es({type:t,error:e}){return"unknown"===t&&"auth/no-auth-event"===(null==e?void 0:e.code)}const ns=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,ss=/^https?/;function rs(t){const e=le(),{protocol:n,hostname:s}=new URL(e);if(t.startsWith("chrome-extension://")){const r=new URL(t);return""===r.hostname&&""===s?"chrome-extension:"===n&&t.replace("chrome-extension://","")===e.replace("chrome-extension://",""):"chrome-extension:"===n&&r.hostname===s}if(!ss.test(n))return!1;if(ns.test(t))return s===t;const r=t.replace(/\./g,"\\.");return new RegExp("^(.+\\."+r+"|"+r+")$","i").test(s)}const is=new fe(3e4,6e4);function os(){const t=Nn().___jsl;if(null==t?void 0:t.H)for(const e of Object.keys(t.H))if(t.H[e].r=t.H[e].r||[],t.H[e].L=t.H[e].L||[],t.H[e].r=[...t.H[e].L],t.CP)for(let e=0;e{var s,r,i,o;function a(){os(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{os(),n(re(t,"network-request-failed"))},timeout:is.get()})}if(null===(r=null===(s=Nn().gapi)||void 0===s?void 0:s.iframes)||void 0===r?void 0:r.Iframe)e(gapi.iframes.getContext());else{if(!(null===(i=Nn().gapi)||void 0===i?void 0:i.load)){const e=Bn("iframefcb");return Nn()[e]=()=>{gapi.load?a():n(re(t,"network-request-failed"))},(o=`https://apis.google.com/js/api.js?onload=${e}`,new Promise(((t,e)=>{const n=document.createElement("script");n.setAttribute("src",o),n.onload=t,n.onerror=t=>{const n=re("internal-error");n.customData=t,e(n)},n.type="text/javascript",n.charset="UTF-8",function(){var t,e;return null!==(e=null===(t=document.getElementsByTagName("head"))||void 0===t?void 0:t[0])&&void 0!==e?e:document}().appendChild(n)}))).catch((t=>n(t)))}a()}})).catch((t=>{throw as=null,t}))}(t),as}const us=new fe(5e3,15e3),hs={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},ls=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function ds(t){const e=t.config;oe(e.authDomain,t,"auth-domain-config-required");const n=e.emulator?pe(e,"emulator/auth/iframe"):`https://${t.config.authDomain}/__/auth/iframe`,s={apiKey:e.apiKey,appName:t.name,v:K},r=ls.get(t.config.apiHost);r&&(s.eid=r);const i=t._getFrameworks();return i.length&&(s.fw=i.join(",")),`${n}?${p(s).slice(1)}`}const fs={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class ps{constructor(t){this.window=t,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(t){}}}function ms(t,e,n,s,r,i){oe(t.config.authDomain,t,"auth-domain-config-required"),oe(t.config.apiKey,t,"invalid-api-key");const o={apiKey:t.config.apiKey,appName:t.name,authType:n,redirectUrl:s,v:K,eventId:r};if(e instanceof cn){e.setDefaultLanguage(t.languageCode),o.providerId=e.providerId||"",function(t){for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}(e.getCustomParameters())||(o.customParameters=JSON.stringify(e.getCustomParameters()));for(const[t,e]of Object.entries(i||{}))o[t]=e}if(e instanceof un){const t=e.getScopes().filter((t=>""!==t));t.length>0&&(o.scopes=t.join(","))}t.tenantId&&(o.tid=t.tenantId);const a=o;for(const t of Object.keys(a))void 0===a[t]&&delete a[t];return`${function({config:t}){return t.emulator?pe(t,"emulator/auth/handler"):`https://${t.authDomain}/__/auth/handler`}(t)}?${p(a).slice(1)}`}const gs="webStorageSupport",ys=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Sn,this._completeRedirectFn=Yn}async _openPopup(t,e,n,s){var i;return ce(null===(i=this.eventManagers[t._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()"),function(t,e,n,s=500,i=600){const o=Math.max((window.screen.availHeight-i)/2,0).toString(),a=Math.max((window.screen.availWidth-s)/2,0).toString();let c="";const u=Object.assign(Object.assign({},fs),{width:s.toString(),height:i.toString(),top:o,left:a}),h=r().toLowerCase();n&&(c=qe(h)?"_blank":n),je(h)&&(e=e||"http://localhost",u.scrollbars="yes");const l=Object.entries(u).reduce(((t,[e,n])=>`${t}${e}=${n},`),"");if(function(t=r()){var e;return Ge(t)&&!!(null===(e=window.navigator)||void 0===e?void 0:e.standalone)}(h)&&"_self"!==c)return function(t,e){const n=document.createElement("a");n.href=t,n.target=e;const s=document.createEvent("MouseEvent");s.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(s)}(e||"",c),new ps(null);const d=window.open(e||"",c,l);oe(d,t,"popup-blocked");try{d.focus()}catch(t){}return new ps(d)}(t,ms(t,e,n,le(),s),An())}async _openRedirect(t,e,n,s){return await this._originValidation(t),r=ms(t,e,n,le(),s),Nn().location.href=r,new Promise((()=>{}));var r}_initialize(t){const e=t._key();if(this.eventManagers[e]){const{manager:t,promise:n}=this.eventManagers[e];return t?Promise.resolve(t):(ce(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(t);return this.eventManagers[e]={promise:n},n.catch((()=>{delete this.eventManagers[e]})),n}async initAndGetManager(t){const e=await async function(t){const e=await cs(t),n=Nn().gapi;return oe(n,t,"internal-error"),e.open({where:document.body,url:ds(t),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:hs,dontclear:!0},(e=>new Promise((async(n,s)=>{await e.restyle({setHideOnLeave:!1});const r=re(t,"network-request-failed"),i=Nn().setTimeout((()=>{s(r)}),us.get());function o(){Nn().clearTimeout(i),n(e)}e.ping(o).then(o,(()=>{s(r)}))}))))}(t),n=new Zn(t);return e.register("authEvent",(e=>(oe(null==e?void 0:e.authEvent,t,"invalid-auth-event"),{status:n.onEvent(e.authEvent)?"ACK":"ERROR"})),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[t._key()]={manager:n},this.iframes[t._key()]=e,n}_isIframeWebStorageSupported(t,e){this.iframes[t._key()].send(gs,{type:gs},(n=>{var s;const r=null===(s=null==n?void 0:n[0])||void 0===s?void 0:s.webStorageSupport;void 0!==r&&e(!!r),se(t,"internal-error")}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(t){const e=t._key();return this.originValidationPromises[e]||(this.originValidationPromises[e]=async function(t){if(t.config.emulator)return;const{authorizedDomains:e}=await async function(t,e={}){return we(t,"GET","/v1/projects",e)}(t);for(const t of e)try{if(rs(t))return}catch(t){}se(t,"unauthorized-domain")}(t)),this.originValidationPromises[e]}get _shouldInitProactively(){return We()||Be()||Ge()}};var vs,ws="@firebase/auth",bs="0.19.4";class Ts{constructor(t){this.auth=t,this.internalListeners=new Map}getUid(){var t;return this.assertAuthConfigured(),(null===(t=this.auth.currentUser)||void 0===t?void 0:t.uid)||null}async getToken(t){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(t)}:null}addAuthTokenListener(t){if(this.assertAuthConfigured(),this.internalListeners.has(t))return;const e=this.auth.onIdTokenChanged((e=>{var n;t((null===(n=e)||void 0===n?void 0:n.stsTokenManager.accessToken)||null)}));this.internalListeners.set(t,e),this.updateProactiveRefresh()}removeAuthTokenListener(t){this.assertAuthConfigured();const e=this.internalListeners.get(t);e&&(this.internalListeners.delete(t),e(),this.updateProactiveRefresh())}assertAuthConfigured(){oe(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function Es(t=z()){const e=q(t,"auth");return e.isInitialized()?e.getImmediate():function(t,e){const n=q(t,"auth");if(n.isInitialized()){const t=n.getImmediate();if(d(n.getOptions(),null!=e?e:{}))return t;se(t,"already-initialized")}return n.initialize({options:e})}(t,{popupRedirectResolver:ys,persistence:[jn,In,Sn]})}vs="Browser",B(new T("auth",((t,{options:e})=>{const n=t.getProvider("app").getImmediate(),{apiKey:s,authDomain:r}=n.options;return(t=>{oe(s&&!s.includes(":"),"invalid-api-key",{appName:t.name}),oe(!(null==r?void 0:r.includes(":")),"argument-error",{appName:t.name});const n={apiKey:s,authDomain:r,clientPlatform:vs,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Je(vs)},i=new Xe(t,n);return function(t,e){const n=(null==e?void 0:e.persistence)||[],s=(Array.isArray(n)?n:[n]).map(he);(null==e?void 0:e.errorMap)&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(s,null==e?void 0:e.popupRedirectResolver)}(i,e),i})(n)}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((t,e,n)=>{t.getProvider("auth-internal").initialize()}))),B(new T("auth-internal",(t=>(t=>new Ts(t))(Qe(t.getProvider("auth").getImmediate()))),"PRIVATE").setInstantiationMode("EXPLICIT")),G(ws,bs,void 0),G(ws,bs,"esm2017");var Is,_s="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self?self:{},Ss={},ks=ks||{},As=_s||self;function Cs(){}function Ns(t){var e=typeof t;return"array"==(e="object"!=e?e:t?Array.isArray(t)?"array":e:"null")||"object"==e&&"number"==typeof t.length}function Rs(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}var Ls="closure_uid_"+(1e9*Math.random()>>>0),Ds=0;function Os(t,e,n){return t.call.apply(t.bind,arguments)}function Ps(t,e,n){if(!t)throw Error();if(2e?1:0}t:{var Js=As.navigator;if(Js){var Xs=Js.userAgent;if(Xs){Ks=Xs;break t}}Ks=""}function Qs(t,e,n){for(const s in t)e.call(n,t[s],s,t)}function Ys(t){const e={};for(const n in t)e[n]=t[n];return e}var Zs="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function tr(t,e){let n,s;for(let e=1;eparseFloat(lr)){nr=String(fr);break t}}nr=lr}var pr,mr={};function gr(){return t=mr,Object.prototype.hasOwnProperty.call(t,9)?t[9]:t[9]=function(){let t=0;const e=zs(String(nr)).split("."),n=zs("9").split("."),s=Math.max(e.length,n.length);for(let o=0;0==t&&o>>0);function jr(t){return"function"==typeof t?t:(t[Vr]||(t[Vr]=function(e){return t.handleEvent(e)}),t[Vr])}function Br(){Fs.call(this),this.i=new kr(this),this.P=this,this.I=null}function qr(t,e){var n,s=t.I;if(s)for(n=[];s;s=s.I)n.push(s);if(t=t.P,s=e.type||e,"string"==typeof e)e=new wr(e,t);else if(e instanceof wr)e.target=e.target||t;else{var r=e;tr(e=new wr(s,t),r)}if(r=!0,n)for(var i=n.length-1;0<=i;i--){var o=e.g=n[i];r=Hr(o,s,!0,e)&&r}if(r=Hr(o=e.g=t,s,!0,e)&&r,r=Hr(o,s,!1,e)&&r,n)for(i=0;inew Wr),(t=>t.reset()));class Wr{constructor(){this.next=this.g=this.h=null}set(t,e){this.h=t,this.g=e,this.next=null}reset(){this.next=this.g=this.h=null}}function Jr(t){As.setTimeout((()=>{throw t}),0)}function Xr(t,e){zr||function(){var t=As.Promise.resolve(void 0);zr=function(){t.then(Zr)}}(),Qr||(zr(),Qr=!0),Yr.add(t,e)}var Qr=!1,Yr=new class{constructor(){this.h=this.g=null}add(t,e){const n=Gr.get();n.set(t,e),this.h?this.h.next=n:this.g=n,this.h=n}};function Zr(){for(var t;t=Kr();){try{t.h.call(t.g)}catch(t){Jr(t)}var e=Gr;e.j(t),100>e.h&&(e.h++,t.next=e.g,e.g=t)}Qr=!1}function ti(t,e){Br.call(this),this.h=t||1,this.g=e||As,this.j=Ms(this.kb,this),this.l=Date.now()}function ei(t){t.da=!1,t.S&&(t.g.clearTimeout(t.S),t.S=null)}function ni(t,e,n){if("function"==typeof t)n&&(t=Ms(t,n));else{if(!t||"function"!=typeof t.handleEvent)throw Error("Invalid listener argument");t=Ms(t.handleEvent,t)}return 2147483647{t.g=null,t.i&&(t.i=!1,si(t))}),t.j);const e=t.h;t.h=null,t.m.apply(null,e)}Us(ti,Br),(Is=ti.prototype).da=!1,Is.S=null,Is.kb=function(){if(this.da){var t=Date.now()-this.l;0s.length)){var r=s[1];if(Array.isArray(r)&&!(1>r.length)){var i=r[0];if("noop"!=i&&"stop"!=i&&"close"!=i)for(var o=1;oe.length?Pi:(e=e.substr(s,n),t.C=s+n,e))}function ji(t){t.Y=Date.now()+t.P,Bi(t,t.P)}function Bi(t,e){if(null!=t.B)throw Error("WatchDog timer not null");t.B=wi(Ms(t.eb,t),e)}function qi(t){t.B&&(As.clearTimeout(t.B),t.B=null)}function Hi(t){0==t.l.G||t.I||fa(t.l,t)}function $i(t){qi(t);var e=t.L;e&&"function"==typeof e.na&&e.na(),t.L=null,ei(t.W),ci(t.V),t.g&&(e=t.g,t.g=null,e.abort(),e.na())}function Ki(t,e){try{var n=t.l;if(0!=n.G&&(n.g==t||_o(n.i,t)))if(n.I=t.N,!t.J&&_o(n.i,t)&&3==n.G){try{var s=n.Ca.g.parse(e)}catch(t){s=null}if(Array.isArray(s)&&3==s.length){var r=s;if(0==r[0]){t:if(!n.u){if(n.g){if(!(n.g.F+3e3r[2]&&n.N&&0==n.A&&!n.v&&(n.v=wi(Ms(n.ab,n),6e3));if(1>=Io(n.i)&&n.ka){try{n.ka()}catch(t){}n.ka=void 0}}else ma(n,11)}else if((t.J||n.g==t)&&da(n),!$s(e))for(r=n.Ca.g.parse(e),e=0;eh)&&(3!=h||ar||this.g&&(this.h.h||this.g.ga()||Xo(this.g)))){this.I||4!=h||7==e||mi(8==e||0>=l?3:2),qi(this);var n=this.g.ba();this.N=n;e:if(Ui(this)){var s=Xo(this.g);t="";var r=s.length,i=4==Jo(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){$i(this),Hi(this);var o="";break e}this.h.i=new As.TextDecoder}for(e=0;ee)throw Error("Bad port number "+e);t.m=e}else t.m=null}function no(t,e,n){e instanceof po?(t.h=e,function(t,e){e&&!t.j&&(mo(t),t.i=null,t.g.forEach((function(t,e){var n=e.toLowerCase();e!=n&&(go(this,e),vo(this,n,t))}),t)),t.j=e}(t.h,t.g)):(n||(e=oo(e,lo)),t.h=new po(e,t.g))}function so(t,e,n){t.h.set(e,n)}function ro(t){return so(t,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),t}function io(t,e){return t?e?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function oo(t,e,n){return"string"==typeof t?(t=encodeURI(t).replace(e,ao),n&&(t=t.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),t):null}function ao(t){return"%"+((t=t.charCodeAt(0))>>4&15).toString(16)+(15&t).toString(16)}Qi.prototype.toString=function(){var t=[],e=this.j;e&&t.push(oo(e,co,!0),":");var n=this.i;return(n||"file"==e)&&(t.push("//"),(e=this.s)&&t.push(oo(e,co,!0),"@"),t.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&t.push(":",String(n))),(n=this.l)&&(this.i&&"/"!=n.charAt(0)&&t.push("/"),t.push(oo(n,"/"==n.charAt(0)?ho:uo,!0))),(n=this.h.toString())&&t.push("?",n),(n=this.o)&&t.push("#",oo(n,fo)),t.join("")};var co=/[#\/\?@]/g,uo=/[#\?:]/g,ho=/[#\?]/g,lo=/[#\?@]/g,fo=/#/g;function po(t,e){this.h=this.g=null,this.i=t||null,this.j=!!e}function mo(t){t.g||(t.g=new Gi,t.h=0,t.i&&function(t,e){if(t){t=t.split("&");for(var n=0;n2*t.i&&Wi(t)))}function yo(t,e){return mo(t),e=wo(t,e),Ji(t.g.h,e)}function vo(t,e,n){go(t,e),0=t.j}function Io(t){return t.h?1:t.g?t.g.size:0}function _o(t,e){return t.h?t.h==e:!!t.g&&t.g.has(e)}function So(t,e){t.g?t.g.add(e):t.h=e}function ko(t,e){t.h&&t.h==e?t.h=null:t.g&&t.g.has(e)&&t.g.delete(e)}function Ao(t){if(null!=t.h)return t.i.concat(t.h.D);if(null!=t.g&&0!==t.g.size){let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}return Hs(t.i)}function Co(){}function No(){this.g=new Co}function Ro(t,e,n){const s=n||"";try{zi(t,(function(t,n){let r=t;Rs(t)&&(r=$r(t)),e.push(s+n+"="+encodeURIComponent(r))}))}catch(t){throw e.push(s+"type="+encodeURIComponent("_badmap")),t}}function Lo(t,e,n,s,r){try{e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null,r(s)}catch(t){}}function Do(t){this.l=t.$b||null,this.j=t.ib||!1}function Oo(t,e){Br.call(this),this.D=t,this.u=e,this.m=void 0,this.readyState=Po,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}bo.prototype.cancel=function(){if(this.i=Ao(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const t of this.g.values())t.cancel();this.g.clear()}},Co.prototype.stringify=function(t){return As.JSON.stringify(t,void 0)},Co.prototype.parse=function(t){return As.JSON.parse(t,void 0)},Us(Do,Ei),Do.prototype.g=function(){return new Oo(this.l,this.j)},Do.prototype.i=function(t){return function(){return t}}({}),Us(Oo,Br);var Po=0;function Mo(t){t.j.read().then(t.Sa.bind(t)).catch(t.ha.bind(t))}function xo(t){t.readyState=4,t.l=null,t.j=null,t.A=null,Uo(t)}function Uo(t){t.onreadystatechange&&t.onreadystatechange.call(t)}(Is=Oo.prototype).open=function(t,e){if(this.readyState!=Po)throw this.abort(),Error("Error reopening a connection");this.C=t,this.B=e,this.readyState=1,Uo(this)},Is.send=function(t){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const e={headers:this.v,method:this.C,credentials:this.m,cache:void 0};t&&(e.body=t),(this.D||As).fetch(new Request(this.B,e)).then(this.Va.bind(this),this.ha.bind(this))},Is.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted."),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,xo(this)),this.readyState=Po},Is.Va=function(t){if(this.g&&(this.l=t,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=t.headers,this.readyState=2,Uo(this)),this.g&&(this.readyState=3,Uo(this),this.g)))if("arraybuffer"===this.responseType)t.arrayBuffer().then(this.Ta.bind(this),this.ha.bind(this));else if(void 0!==As.ReadableStream&&"body"in t){if(this.j=t.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;Mo(this)}else t.text().then(this.Ua.bind(this),this.ha.bind(this))},Is.Sa=function(t){if(this.g){if(this.u&&t.value)this.response.push(t.value);else if(!this.u){var e=t.value?t.value:new Uint8Array(0);(e=this.A.decode(e,{stream:!t.done}))&&(this.response=this.responseText+=e)}t.done?xo(this):Uo(this),3==this.readyState&&Mo(this)}},Is.Ua=function(t){this.g&&(this.response=this.responseText=t,xo(this))},Is.Ta=function(t){this.g&&(this.response=t,xo(this))},Is.ha=function(){this.g&&xo(this)},Is.setRequestHeader=function(t,e){this.v.append(t,e)},Is.getResponseHeader=function(t){return this.h&&this.h.get(t.toLowerCase())||""},Is.getAllResponseHeaders=function(){if(!this.h)return"";const t=[],e=this.h.entries();for(var n=e.next();!n.done;)n=n.value,t.push(n[0]+": "+n[1]),n=e.next();return t.join("\r\n")},Object.defineProperty(Oo.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(t){this.m=t?"include":"same-origin"}});var Fo=As.JSON.parse;function Vo(t){Br.call(this),this.headers=new Gi,this.u=t||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=jo,this.K=this.L=!1}Us(Vo,Br);var jo="",Bo=/^https?$/i,qo=["POST","PUT"];function Ho(t){return"content-type"==t.toLowerCase()}function $o(t,e){t.h=!1,t.g&&(t.l=!0,t.g.abort(),t.l=!1),t.j=e,t.m=5,Ko(t),Go(t)}function Ko(t){t.D||(t.D=!0,qr(t,"complete"),qr(t,"error"))}function zo(t){if(t.h&&void 0!==ks&&(!t.C[1]||4!=Jo(t)||2!=t.ba()))if(t.v&&4==Jo(t))ni(t.Fa,0,t);else if(qr(t,"readystatechange"),4==Jo(t)){t.h=!1;try{const a=t.ba();t:switch(a){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var e=!0;break t;default:e=!1}var n;if(!(n=e)){var s;if(s=0===a){var r=String(t.H).match(Xi)[1]||null;if(!r&&As.self&&As.self.location){var i=As.self.location.protocol;r=i.substr(0,i.length-1)}s=!Bo.test(r?r.toLowerCase():"")}n=s}if(n)qr(t,"complete"),qr(t,"success");else{t.m=6;try{var o=2n)e=Math.max(0,r[o].h-100),i=!1;else try{Ro(a,t,"req"+n+"_")}catch(t){s&&s(a)}}if(i){s=t.join("&");break t}}}return t=t.l.splice(0,n),e.D=t,s}function ca(t){t.g||t.u||(t.Y=1,Xr(t.Ga,t),t.A=0)}function ua(t){return!(t.g||t.u||3<=t.A||(t.Y++,t.u=wi(Ms(t.Ga,t),pa(t,t.A)),t.A++,0))}function ha(t){null!=t.B&&(As.clearTimeout(t.B),t.B=null)}function la(t){t.g=new Ri(t,t.h,"rpc",t.Y),null===t.o&&(t.g.H=t.s),t.g.O=0;var e=Yi(t.oa);so(e,"RID","rpc"),so(e,"SID",t.J),so(e,"CI",t.N?"0":"1"),so(e,"AID",t.U),oa(t,e),so(e,"TYPE","xmlhttp"),t.o&&t.s&&Qo(e,t.o,t.s),t.K&&t.g.setTimeout(t.K);var n=t.g;t=t.la,n.K=1,n.v=ro(Yi(e)),n.s=null,n.U=!0,xi(n,t)}function da(t){null!=t.v&&(As.clearTimeout(t.v),t.v=null)}function fa(t,e){var n=null;if(t.g==e){da(t),ha(t),t.g=null;var s=2}else{if(!_o(t.i,e))return;n=e.D,ko(t.i,e),s=1}if(t.I=e.N,0!=t.G)if(e.i)if(1==s){n=e.s?e.s.length:0,e=Date.now()-e.F;var r=t.C;qr(s=fi(),new vi(s,n,e,r)),ra(t)}else ca(t);else if(3==(r=e.o)||0==r&&0=t.i.j-(t.m?1:0)||(t.m?(t.l=e.D.concat(t.l),0):1==t.G||2==t.G||t.C>=(t.Xa?0:t.Ya)||(t.m=wi(Ms(t.Ha,t,e),pa(t,t.C)),t.C++,0)))}(t,e)||2==s&&ua(t)))switch(n&&0e?null:"string"==typeof t?t.charAt(e):t[e]}(r.T()),n=As.FormData&&t instanceof As.FormData,!(0<=js(qo,e))||s||n||r.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),r.forEach((function(t,e){this.g.setRequestHeader(e,t)}),this),this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{Wo(this),0=this.O)){var t=2*this.O;this.h.info("BP detection timer enabled: "+t),this.B=wi(Ms(this.bb,this),t)}},Is.bb=function(){this.B&&(this.B=null,this.h.info("BP detection timeout reached."),this.h.info("Buffering proxy detected and switch to long-polling!"),this.N=!1,this.L=!0,yi(10),ea(this),la(this))},Is.ab=function(){null!=this.v&&(this.v=null,ea(this),ua(this),yi(19))},Is.jb=function(t){t?(this.h.info("Successfully pinged google.com"),yi(2)):(this.h.info("Failed to ping google.com"),yi(1))},(Is=wa.prototype).xa=function(){},Is.wa=function(){},Is.va=function(){},Is.ua=function(){},Is.Oa=function(){},ba.prototype.g=function(t,e){return new Ta(t,e)},Us(Ta,Br),Ta.prototype.m=function(){this.g.j=this.j,this.A&&(this.g.H=!0);var t=this.g,e=this.l,n=this.h||void 0;t.Wa&&(t.h.info("Origin Trials enabled."),Xr(Ms(t.hb,t,e))),yi(0),t.W=e,t.aa=n||{},t.N=t.X,t.F=ya(t,null,t.W),ra(t)},Ta.prototype.close=function(){ta(this.g)},Ta.prototype.u=function(t){if("string"==typeof t){var e={};e.__data__=t,sa(this.g,e)}else this.v?((e={}).__data__=$r(t),sa(this.g,e)):sa(this.g,t)},Ta.prototype.M=function(){this.g.j=null,delete this.j,ta(this.g),delete this.g,Ta.Z.M.call(this)},Us(Ea,Ai),Us(Ia,Ci),Us(_a,wa),_a.prototype.xa=function(){qr(this.g,"a")},_a.prototype.wa=function(t){qr(this.g,new Ea(t))},_a.prototype.va=function(t){qr(this.g,new Ia(t))},_a.prototype.ua=function(){qr(this.g,"b")},ba.prototype.createWebChannel=ba.prototype.g,Ta.prototype.send=Ta.prototype.u,Ta.prototype.open=Ta.prototype.m,Ta.prototype.close=Ta.prototype.close,bi.NO_ERROR=0,bi.TIMEOUT=8,bi.HTTP_ERROR=6,Ti.COMPLETE="complete",_i.EventType=ki,ki.OPEN="a",ki.CLOSE="b",ki.ERROR="c",ki.MESSAGE="d",Br.prototype.listen=Br.prototype.N,Vo.prototype.listenOnce=Vo.prototype.O,Vo.prototype.getLastError=Vo.prototype.La,Vo.prototype.getLastErrorCode=Vo.prototype.Da,Vo.prototype.getStatus=Vo.prototype.ba,Vo.prototype.getResponseJson=Vo.prototype.Qa,Vo.prototype.getResponseText=Vo.prototype.ga,Vo.prototype.send=Vo.prototype.ea;var Sa=Ss.createWebChannelTransport=function(){return new ba},ka=Ss.getStatEventTarget=function(){return fi()},Aa=Ss.ErrorCode=bi,Ca=Ss.EventType=Ti,Na=Ss.Event=li,Ra=Ss.Stat={rb:0,ub:1,vb:2,Ob:3,Tb:4,Qb:5,Rb:6,Pb:7,Nb:8,Sb:9,PROXY:10,NOPROXY:11,Lb:12,Hb:13,Ib:14,Gb:15,Jb:16,Kb:17,nb:18,mb:19,ob:20},La=Ss.FetchXmlHttpFactory=Do,Da=Ss.WebChannel=_i,Oa=Ss.XhrIo=Vo;const Pa="@firebase/firestore";class Ma{constructor(t){this.uid=t}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(t){return t.uid===this.uid}}Ma.UNAUTHENTICATED=new Ma(null),Ma.GOOGLE_CREDENTIALS=new Ma("google-credentials-uid"),Ma.FIRST_PARTY=new Ma("first-party-uid"),Ma.MOCK_USER=new Ma("mock-user");let xa="9.6.1";const Ua=new D("@firebase/firestore");function Fa(){return Ua.logLevel}function Va(t,...e){if(Ua.logLevel<=k.DEBUG){const n=e.map(qa);Ua.debug(`Firestore (${xa}): ${t}`,...n)}}function ja(t,...e){if(Ua.logLevel<=k.ERROR){const n=e.map(qa);Ua.error(`Firestore (${xa}): ${t}`,...n)}}function Ba(t,...e){if(Ua.logLevel<=k.WARN){const n=e.map(qa);Ua.warn(`Firestore (${xa}): ${t}`,...n)}}function qa(t){if("string"==typeof t)return t;try{return e=t,JSON.stringify(e)}catch(e){return t}var e}function Ha(t="Unexpected state"){const e=`FIRESTORE (${xa}) INTERNAL ASSERTION FAILED: `+t;throw ja(e),new Error(e)}function $a(t,e){t||Ha()}function Ka(t,e){return t}const za={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 Ga extends Error{constructor(t,e){super(e),this.code=t,this.message=e,this.name="FirebaseError",this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class Wa{constructor(){this.promise=new Promise(((t,e)=>{this.resolve=t,this.reject=e}))}}class Ja{constructor(t,e){this.user=e,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${t}`)}}class Xa{getToken(){return Promise.resolve(null)}invalidateToken(){}start(t,e){t.enqueueRetryable((()=>e(Ma.UNAUTHENTICATED)))}shutdown(){}}class Qa{constructor(t){this.t=t,this.currentUser=Ma.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,e){let n=this.i;const s=t=>this.i!==n?(n=this.i,e(t)):Promise.resolve();let r=new Wa;this.o=()=>{this.i++,this.currentUser=this.u(),r.resolve(),r=new Wa,t.enqueueRetryable((()=>s(this.currentUser)))};const i=()=>{const e=r;t.enqueueRetryable((async()=>{await e.promise,await s(this.currentUser)}))},o=t=>{Va("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=t,this.auth.addAuthTokenListener(this.o),i()};this.t.onInit((t=>o(t))),setTimeout((()=>{if(!this.auth){const t=this.t.getImmediate({optional:!0});t?o(t):(Va("FirebaseAuthCredentialsProvider","Auth not yet detected"),r.resolve(),r=new Wa)}}),0),i()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then((e=>this.i!==t?(Va("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?($a("string"==typeof e.accessToken),new Ja(e.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){const t=this.auth&&this.auth.getUid();return $a(null===t||"string"==typeof t),new Ma(t)}}class Ya{constructor(t,e,n){this.type="FirstParty",this.user=Ma.FIRST_PARTY,this.headers=new Map,this.headers.set("X-Goog-AuthUser",e);const s=t.auth.getAuthHeaderValueForFirstParty([]);s&&this.headers.set("Authorization",s),n&&this.headers.set("X-Goog-Iam-Authorization-Token",n)}}class Za{constructor(t,e,n){this.h=t,this.l=e,this.m=n}getToken(){return Promise.resolve(new Ya(this.h,this.l,this.m))}start(t,e){t.enqueueRetryable((()=>e(Ma.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class tc{constructor(t){this.value=t,this.type="AppCheck",this.headers=new Map,t&&t.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class ec{constructor(t){this.g=t,this.forceRefresh=!1,this.appCheck=null}start(t,e){this.o=n=>{t.enqueueRetryable((()=>(t=>(null!=t.error&&Va("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${t.error.message}`),e(t.token)))(n)))};const n=t=>{Va("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=t,this.appCheck.addTokenListener(this.o)};this.g.onInit((t=>n(t))),setTimeout((()=>{if(!this.appCheck){const t=this.g.getImmediate({optional:!0});t?n(t):Va("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const t=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(t).then((t=>t?($a("string"==typeof t.token),new tc(t.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class nc{constructor(t,e){this.previousValue=t,e&&(e.sequenceNumberHandler=t=>this.p(t),this.T=t=>e.writeSequenceNumber(t))}p(t){return this.previousValue=Math.max(t,this.previousValue),this.previousValue}next(){const t=++this.previousValue;return this.T&&this.T(t),t}}function sc(t){const e="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(t);if(e&&"function"==typeof e.getRandomValues)e.getRandomValues(n);else for(let e=0;ee?1:0}function oc(t,e,n){return t.length===e.length&&t.every(((t,s)=>n(t,e[s])))}class ac{constructor(t,e){if(this.seconds=t,this.nanoseconds=e,e<0)throw new Ga(za.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(e>=1e9)throw new Ga(za.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(t<-62135596800)throw new Ga(za.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(t>=253402300800)throw new Ga(za.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}static now(){return ac.fromMillis(Date.now())}static fromDate(t){return ac.fromMillis(t.getTime())}static fromMillis(t){const e=Math.floor(t/1e3),n=Math.floor(1e6*(t-1e3*e));return new ac(e,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(t){return this.seconds===t.seconds?ic(this.nanoseconds,t.nanoseconds):ic(this.seconds,t.seconds)}isEqual(t){return t.seconds===this.seconds&&t.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const t=this.seconds- -62135596800;return String(t).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class cc{constructor(t){this.timestamp=t}static fromTimestamp(t){return new cc(t)}static min(){return new cc(new ac(0,0))}compareTo(t){return this.timestamp._compareTo(t.timestamp)}isEqual(t){return this.timestamp.isEqual(t.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}function uc(t){let e=0;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}function hc(t,e){for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(n,t[n])}function lc(t){for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}class dc{constructor(t,e,n){void 0===e?e=0:e>t.length&&Ha(),void 0===n?n=t.length-e:n>t.length-e&&Ha(),this.segments=t,this.offset=e,this.len=n}get length(){return this.len}isEqual(t){return 0===dc.comparator(this,t)}child(t){const e=this.segments.slice(this.offset,this.limit());return t instanceof dc?t.forEach((t=>{e.push(t)})):e.push(t),this.construct(e)}limit(){return this.offset+this.length}popFirst(t){return t=void 0===t?1:t,this.construct(this.segments,this.offset+t,this.length-t)}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(t){return this.segments[this.offset+t]}isEmpty(){return 0===this.length}isPrefixOf(t){if(t.lengthr)return 1}return t.lengthe.length?1:0}}class fc extends dc{construct(t,e,n){return new fc(t,e,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...t){const e=[];for(const n of t){if(n.indexOf("//")>=0)throw new Ga(za.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);e.push(...n.split("/").filter((t=>t.length>0)))}return new fc(e)}static emptyPath(){return new fc([])}}const pc=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class mc extends dc{construct(t,e,n){return new mc(t,e,n)}static isValidIdentifier(t){return pc.test(t)}canonicalString(){return this.toArray().map((t=>(t=t.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),mc.isValidIdentifier(t)||(t="`"+t+"`"),t))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new mc(["__name__"])}static fromServerFormat(t){const e=[];let n="",s=0;const r=()=>{if(0===n.length)throw new Ga(za.INVALID_ARGUMENT,`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);e.push(n),n=""};let i=!1;for(;st.isEqual(e)))}}class yc{constructor(t){this.binaryString=t}static fromBase64String(t){const e=atob(t);return new yc(e)}static fromUint8Array(t){const e=function(t){let e="";for(let n=0;n=2&&this.path.get(this.path.length-2)===t}isEqual(t){return null!==t&&0===fc.comparator(this.path,t.path)}toString(){return this.path.toString()}static comparator(t,e){return fc.comparator(t.path,e.path)}static isDocumentKey(t){return t.length%2==0}static fromSegments(t){return new Ac(new fc(t.slice()))}}function Cc(t){return"nullValue"in t?0:"booleanValue"in t?1:"integerValue"in t||"doubleValue"in t?2:"timestampValue"in t?3:"stringValue"in t?5:"bytesValue"in t?6:"referenceValue"in t?7:"geoPointValue"in t?8:"arrayValue"in t?9:"mapValue"in t?Ec(t)?4:10:Ha()}function Nc(t,e){const n=Cc(t);if(n!==Cc(e))return!1;switch(n){case 0:return!0;case 1:return t.booleanValue===e.booleanValue;case 4:return _c(t).isEqual(_c(e));case 3:return function(t,e){if("string"==typeof t.timestampValue&&"string"==typeof e.timestampValue&&t.timestampValue.length===e.timestampValue.length)return t.timestampValue===e.timestampValue;const n=wc(t.timestampValue),s=wc(e.timestampValue);return n.seconds===s.seconds&&n.nanos===s.nanos}(t,e);case 5:return t.stringValue===e.stringValue;case 6:return function(t,e){return Tc(t.bytesValue).isEqual(Tc(e.bytesValue))}(t,e);case 7:return t.referenceValue===e.referenceValue;case 8:return function(t,e){return bc(t.geoPointValue.latitude)===bc(e.geoPointValue.latitude)&&bc(t.geoPointValue.longitude)===bc(e.geoPointValue.longitude)}(t,e);case 2:return function(t,e){if("integerValue"in t&&"integerValue"in e)return bc(t.integerValue)===bc(e.integerValue);if("doubleValue"in t&&"doubleValue"in e){const n=bc(t.doubleValue),s=bc(e.doubleValue);return n===s?kc(n)===kc(s):isNaN(n)&&isNaN(s)}return!1}(t,e);case 9:return oc(t.arrayValue.values||[],e.arrayValue.values||[],Nc);case 10:return function(t,e){const n=t.mapValue.fields||{},s=e.mapValue.fields||{};if(uc(n)!==uc(s))return!1;for(const t in n)if(n.hasOwnProperty(t)&&(void 0===s[t]||!Nc(n[t],s[t])))return!1;return!0}(t,e);default:return Ha()}}function Rc(t,e){return void 0!==(t.values||[]).find((t=>Nc(t,e)))}function Lc(t,e){const n=Cc(t),s=Cc(e);if(n!==s)return ic(n,s);switch(n){case 0:return 0;case 1:return ic(t.booleanValue,e.booleanValue);case 2:return function(t,e){const n=bc(t.integerValue||t.doubleValue),s=bc(e.integerValue||e.doubleValue);return ns?1:n===s?0:isNaN(n)?isNaN(s)?0:-1:1}(t,e);case 3:return Dc(t.timestampValue,e.timestampValue);case 4:return Dc(_c(t),_c(e));case 5:return ic(t.stringValue,e.stringValue);case 6:return function(t,e){const n=Tc(t),s=Tc(e);return n.compareTo(s)}(t.bytesValue,e.bytesValue);case 7:return function(t,e){const n=t.split("/"),s=e.split("/");for(let t=0;te.mapValue.fields[t]=jc(n))),e}if(t.arrayValue){const e={arrayValue:{values:[]}};for(let n=0;n<(t.arrayValue.values||[]).length;++n)e.arrayValue.values[n]=jc(t.arrayValue.values[n]);return e}return Object.assign({},t)}class Bc{constructor(t){this.value=t}static empty(){return new Bc({mapValue:{}})}field(t){if(t.isEmpty())return this.value;{let e=this.value;for(let n=0;n{if(!e.isImmediateParentOf(r)){const t=this.getFieldsMap(e);this.applyChanges(t,n,s),n={},s=[],e=r.popLast()}t?n[r.lastSegment()]=jc(t):s.push(r.lastSegment())}));const r=this.getFieldsMap(e);this.applyChanges(r,n,s)}delete(t){const e=this.field(t.popLast());Vc(e)&&e.mapValue.fields&&delete e.mapValue.fields[t.lastSegment()]}isEqual(t){return Nc(this.value,t.value)}getFieldsMap(t){let e=this.value;e.mapValue.fields||(e.mapValue={fields:{}});for(let n=0;nt[e]=n));for(const e of n)delete t[e]}clone(){return new Bc(jc(this.value))}}function qc(t){const e=[];return hc(t.fields,((t,n)=>{const s=new mc([t]);if(Vc(n)){const t=qc(n.mapValue).fields;if(0===t.length)e.push(s);else for(const n of t)e.push(s.child(n))}else e.push(s)})),new gc(e)}class Hc{constructor(t,e,n,s,r){this.key=t,this.documentType=e,this.version=n,this.data=s,this.documentState=r}static newInvalidDocument(t){return new Hc(t,0,cc.min(),Bc.empty(),0)}static newFoundDocument(t,e,n){return new Hc(t,1,e,n,0)}static newNoDocument(t,e){return new Hc(t,2,e,Bc.empty(),0)}static newUnknownDocument(t,e){return new Hc(t,3,e,Bc.empty(),2)}convertToFoundDocument(t,e){return this.version=t,this.documentType=1,this.data=e,this.documentState=0,this}convertToNoDocument(t){return this.version=t,this.documentType=2,this.data=Bc.empty(),this.documentState=0,this}convertToUnknownDocument(t){return this.version=t,this.documentType=3,this.data=Bc.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(t){return t instanceof Hc&&this.key.isEqual(t.key)&&this.version.isEqual(t.version)&&this.documentType===t.documentType&&this.documentState===t.documentState&&this.data.isEqual(t.data)}clone(){return new Hc(this.key,this.documentType,this.version,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class $c{constructor(t,e=null,n=[],s=[],r=null,i=null,o=null){this.path=t,this.collectionGroup=e,this.orderBy=n,this.filters=s,this.limit=r,this.startAt=i,this.endAt=o,this.R=null}}function Kc(t,e=null,n=[],s=[],r=null,i=null,o=null){return new $c(t,e,n,s,r,i,o)}function zc(t){const e=Ka(t);if(null===e.R){let t=e.path.canonicalString();null!==e.collectionGroup&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map((t=>function(t){return t.field.canonicalString()+t.op.toString()+Oc(t.value)}(t))).join(","),t+="|ob:",t+=e.orderBy.map((t=>function(t){return t.field.canonicalString()+t.dir}(t))).join(","),Sc(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=iu(e.startAt)),e.endAt&&(t+="|ub:",t+=iu(e.endAt)),e.R=t}return e.R}function Gc(t,e){if(t.limit!==e.limit)return!1;if(t.orderBy.length!==e.orderBy.length)return!1;for(let n=0;n":return t>0;case">=":return t>=0;default:return Ha()}}V(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}}class Xc extends Jc{constructor(t,e,n){super(t,e,n),this.key=Ac.fromName(n.referenceValue)}matches(t){const e=Ac.comparator(t.key,this.key);return this.v(e)}}class Qc extends Jc{constructor(t,e){super(t,"in",e),this.keys=Zc(0,e)}matches(t){return this.keys.some((e=>e.isEqual(t.key)))}}class Yc extends Jc{constructor(t,e){super(t,"not-in",e),this.keys=Zc(0,e)}matches(t){return!this.keys.some((e=>e.isEqual(t.key)))}}function Zc(t,e){var n;return((null===(n=e.arrayValue)||void 0===n?void 0:n.values)||[]).map((t=>Ac.fromName(t.referenceValue)))}class tu extends Jc{constructor(t,e){super(t,"array-contains",e)}matches(t){const e=t.data.field(this.field);return xc(e)&&Rc(e.arrayValue,this.value)}}class eu extends Jc{constructor(t,e){super(t,"in",e)}matches(t){const e=t.data.field(this.field);return null!==e&&Rc(this.value.arrayValue,e)}}class nu extends Jc{constructor(t,e){super(t,"not-in",e)}matches(t){if(Rc(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const e=t.data.field(this.field);return null!==e&&!Rc(this.value.arrayValue,e)}}class su extends Jc{constructor(t,e){super(t,"array-contains-any",e)}matches(t){const e=t.data.field(this.field);return!(!xc(e)||!e.arrayValue.values)&&e.arrayValue.values.some((t=>Rc(this.value.arrayValue,t)))}}class ru{constructor(t,e){this.position=t,this.before=e}}function iu(t){return`${t.before?"b":"a"}:${t.position.map((t=>Oc(t))).join(",")}`}class ou{constructor(t,e="asc"){this.field=t,this.dir=e}}function au(t,e){return t.dir===e.dir&&t.field.isEqual(e.field)}function cu(t,e,n){let s=0;for(let r=0;r0?t.explicitOrderBy[0].field:null}function mu(t){for(const e of t.filters)if(e.V())return e.field;return null}function gu(t){const e=Ka(t);if(null===e.S){e.S=[];const t=mu(e),n=pu(e);if(null!==t&&null===n)t.isKeyField()||e.S.push(new ou(t)),e.S.push(new ou(mc.keyField(),"asc"));else{let t=!1;for(const n of e.explicitOrderBy)e.S.push(n),n.field.isKeyField()&&(t=!0);if(!t){const t=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";e.S.push(new ou(mc.keyField(),t))}}}return e.S}function yu(t){const e=Ka(t);if(!e.D)if("F"===e.limitType)e.D=Kc(e.path,e.collectionGroup,gu(e),e.filters,e.limit,e.startAt,e.endAt);else{const t=[];for(const n of gu(e)){const e="desc"===n.dir?"asc":"desc";t.push(new ou(n.field,e))}const n=e.endAt?new ru(e.endAt.position,!e.endAt.before):null,s=e.startAt?new ru(e.startAt.position,!e.startAt.before):null;e.D=Kc(e.path,e.collectionGroup,t,e.filters,e.limit,n,s)}return e.D}function vu(t,e,n){return new hu(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),e,n,t.startAt,t.endAt)}function wu(t,e){return Gc(yu(t),yu(e))&&t.limitType===e.limitType}function bu(t){return`${zc(yu(t))}|lt:${t.limitType}`}function Tu(t){return`Query(target=${function(t){let e=t.path.canonicalString();return null!==t.collectionGroup&&(e+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(e+=`, filters: [${t.filters.map((t=>{return`${(e=t).field.canonicalString()} ${e.op} ${Oc(e.value)}`;var e})).join(", ")}]`),Sc(t.limit)||(e+=", limit: "+t.limit),t.orderBy.length>0&&(e+=`, orderBy: [${t.orderBy.map((t=>function(t){return`${t.field.canonicalString()} (${t.dir})`}(t))).join(", ")}]`),t.startAt&&(e+=", startAt: "+iu(t.startAt)),t.endAt&&(e+=", endAt: "+iu(t.endAt)),`Target(${e})`}(yu(t))}; limitType=${t.limitType})`}function Eu(t,e){return e.isFoundDocument()&&function(t,e){const n=e.key.path;return null!==t.collectionGroup?e.key.hasCollectionId(t.collectionGroup)&&t.path.isPrefixOf(n):Ac.isDocumentKey(t.path)?t.path.isEqual(n):t.path.isImmediateParentOf(n)}(t,e)&&function(t,e){for(const n of t.explicitOrderBy)if(!n.field.isKeyField()&&null===e.data.field(n.field))return!1;return!0}(t,e)&&function(t,e){for(const n of t.filters)if(!n.matches(e))return!1;return!0}(t,e)&&function(t,e){return!(t.startAt&&!cu(t.startAt,gu(t),e)||t.endAt&&cu(t.endAt,gu(t),e))}(t,e)}function Iu(t){return(e,n)=>{let s=!1;for(const r of gu(t)){const t=_u(r,e,n);if(0!==t)return t;s=s||r.field.isKeyField()}return 0}}function _u(t,e,n){const s=t.field.isKeyField()?Ac.comparator(e.key,n.key):function(t,e,n){const s=e.data.field(t),r=n.data.field(t);return null!==s&&null!==r?Lc(s,r):Ha()}(t.field,e,n);switch(t.dir){case"asc":return s;case"desc":return-1*s;default:return Ha()}}function Su(t,e){if(t.C){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:kc(e)?"-0":e}}function ku(t){return{integerValue:""+t}}function Au(t,e){return function(t){return"number"==typeof t&&Number.isInteger(t)&&!kc(t)&&t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER}(e)?ku(e):Su(t,e)}class Cu{constructor(){this._=void 0}}function Nu(t,e,n){return t instanceof Du?function(t,e){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:t.seconds,nanos:t.nanoseconds}}}};return e&&(n.fields.__previous_value__=e),{mapValue:n}}(n,e):t instanceof Ou?Pu(t,e):t instanceof Mu?xu(t,e):function(t,e){const n=Lu(t,e),s=Fu(n)+Fu(t.N);return Mc(n)&&Mc(t.N)?ku(s):Su(t.k,s)}(t,e)}function Ru(t,e,n){return t instanceof Ou?Pu(t,e):t instanceof Mu?xu(t,e):n}function Lu(t,e){return t instanceof Uu?Mc(n=e)||function(t){return!!t&&"doubleValue"in t}(n)?e:{integerValue:0}:null;var n}class Du extends Cu{}class Ou extends Cu{constructor(t){super(),this.elements=t}}function Pu(t,e){const n=Vu(e);for(const e of t.elements)n.some((t=>Nc(t,e)))||n.push(e);return{arrayValue:{values:n}}}class Mu extends Cu{constructor(t){super(),this.elements=t}}function xu(t,e){let n=Vu(e);for(const e of t.elements)n=n.filter((t=>!Nc(t,e)));return{arrayValue:{values:n}}}class Uu extends Cu{constructor(t,e){super(),this.k=t,this.N=e}}function Fu(t){return bc(t.integerValue||t.doubleValue)}function Vu(t){return xc(t)&&t.arrayValue.values?t.arrayValue.values.slice():[]}class ju{constructor(t,e){this.version=t,this.transformResults=e}}class Bu{constructor(t,e){this.updateTime=t,this.exists=e}static none(){return new Bu}static exists(t){return new Bu(void 0,t)}static updateTime(t){return new Bu(t)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(t){return this.exists===t.exists&&(this.updateTime?!!t.updateTime&&this.updateTime.isEqual(t.updateTime):!t.updateTime)}}function qu(t,e){return void 0!==t.updateTime?e.isFoundDocument()&&e.version.isEqual(t.updateTime):void 0===t.exists||t.exists===e.isFoundDocument()}class Hu{}function $u(t,e,n){t instanceof Ju?function(t,e,n){const s=t.value.clone(),r=Yu(t.fieldTransforms,e,n.transformResults);s.setAll(r),e.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(t,e,n):t instanceof Xu?function(t,e,n){if(!qu(t.precondition,e))return void e.convertToUnknownDocument(n.version);const s=Yu(t.fieldTransforms,e,n.transformResults),r=e.data;r.setAll(Qu(t)),r.setAll(s),e.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(t,e,n):function(t,e,n){e.convertToNoDocument(n.version).setHasCommittedMutations()}(0,e,n)}function Ku(t,e,n){t instanceof Ju?function(t,e,n){if(!qu(t.precondition,e))return;const s=t.value.clone(),r=Zu(t.fieldTransforms,n,e);s.setAll(r),e.convertToFoundDocument(Wu(e),s).setHasLocalMutations()}(t,e,n):t instanceof Xu?function(t,e,n){if(!qu(t.precondition,e))return;const s=Zu(t.fieldTransforms,n,e),r=e.data;r.setAll(Qu(t)),r.setAll(s),e.convertToFoundDocument(Wu(e),r).setHasLocalMutations()}(t,e,n):function(t,e){qu(t.precondition,e)&&e.convertToNoDocument(cc.min())}(t,e)}function zu(t,e){let n=null;for(const s of t.fieldTransforms){const t=e.data.field(s.field),r=Lu(s.transform,t||null);null!=r&&(null==n&&(n=Bc.empty()),n.set(s.field,r))}return n||null}function Gu(t,e){return t.type===e.type&&!!t.key.isEqual(e.key)&&!!t.precondition.isEqual(e.precondition)&&!!function(t,e){return void 0===t&&void 0===e||!(!t||!e)&&oc(t,e,((t,e)=>function(t,e){return t.field.isEqual(e.field)&&function(t,e){return t instanceof Ou&&e instanceof Ou||t instanceof Mu&&e instanceof Mu?oc(t.elements,e.elements,Nc):t instanceof Uu&&e instanceof Uu?Nc(t.N,e.N):t instanceof Du&&e instanceof Du}(t.transform,e.transform)}(t,e)))}(t.fieldTransforms,e.fieldTransforms)&&(0===t.type?t.value.isEqual(e.value):1!==t.type||t.data.isEqual(e.data)&&t.fieldMask.isEqual(e.fieldMask))}function Wu(t){return t.isFoundDocument()?t.version:cc.min()}class Ju extends Hu{constructor(t,e,n,s=[]){super(),this.key=t,this.value=e,this.precondition=n,this.fieldTransforms=s,this.type=0}}class Xu extends Hu{constructor(t,e,n,s,r=[]){super(),this.key=t,this.data=e,this.fieldMask=n,this.precondition=s,this.fieldTransforms=r,this.type=1}}function Qu(t){const e=new Map;return t.fieldMask.fields.forEach((n=>{if(!n.isEmpty()){const s=t.data.field(n);e.set(n,s)}})),e}function Yu(t,e,n){const s=new Map;$a(t.length===n.length);for(let r=0;r0&&(e=e.right)}return null}indexOf(t){let e=0,n=this.root;for(;!n.isEmpty();){const s=this.comparator(t,n.key);if(0===s)return e+n.left.size;s<0?n=n.left:(e+=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(t){return this.root.inorderTraversal(t)}forEach(t){this.inorderTraversal(((e,n)=>(t(e,n),!1)))}toString(){const t=[];return this.inorderTraversal(((e,n)=>(t.push(`${e}:${n}`),!1))),`{${t.join(", ")}}`}reverseTraversal(t){return this.root.reverseTraversal(t)}getIterator(){return new ah(this.root,null,this.comparator,!1)}getIteratorFrom(t){return new ah(this.root,t,this.comparator,!1)}getReverseIterator(){return new ah(this.root,null,this.comparator,!0)}getReverseIteratorFrom(t){return new ah(this.root,t,this.comparator,!0)}}class ah{constructor(t,e,n,s){this.isReverse=s,this.nodeStack=[];let r=1;for(;!t.isEmpty();)if(r=e?n(t.key,e):1,s&&(r*=-1),r<0)t=this.isReverse?t.left:t.right;else{if(0===r){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}getNext(){let t=this.nodeStack.pop();const e={key:t.key,value:t.value};if(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 t=this.nodeStack[this.nodeStack.length-1];return{key:t.key,value:t.value}}}class ch{constructor(t,e,n,s,r){this.key=t,this.value=e,this.color=null!=n?n:ch.RED,this.left=null!=s?s:ch.EMPTY,this.right=null!=r?r:ch.EMPTY,this.size=this.left.size+1+this.right.size}copy(t,e,n,s,r){return new ch(null!=t?t:this.key,null!=e?e:this.value,null!=n?n:this.color,null!=s?s:this.left,null!=r?r:this.right)}isEmpty(){return!1}inorderTraversal(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)}reverseTraversal(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)}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(t,e,n){let s=this;const r=n(t,s.key);return s=r<0?s.copy(null,null,null,s.left.insert(t,e,n),null):0===r?s.copy(null,e,null,null,null):s.copy(null,null,null,null,s.right.insert(t,e,n)),s.fixUp()}removeMin(){if(this.left.isEmpty())return ch.EMPTY;let t=this;return t.left.isRed()||t.left.left.isRed()||(t=t.moveRedLeft()),t=t.copy(null,null,null,t.left.removeMin(),null),t.fixUp()}remove(t,e){let n,s=this;if(e(t,s.key)<0)s.left.isEmpty()||s.left.isRed()||s.left.left.isRed()||(s=s.moveRedLeft()),s=s.copy(null,null,null,s.left.remove(t,e),null);else{if(s.left.isRed()&&(s=s.rotateRight()),s.right.isEmpty()||s.right.isRed()||s.right.left.isRed()||(s=s.moveRedRight()),0===e(t,s.key)){if(s.right.isEmpty())return ch.EMPTY;n=s.right.min(),s=s.copy(n.key,n.value,null,null,s.right.removeMin())}s=s.copy(null,null,null,null,s.right.remove(t,e))}return s.fixUp()}isRed(){return this.color}fixUp(){let t=this;return t.right.isRed()&&!t.left.isRed()&&(t=t.rotateLeft()),t.left.isRed()&&t.left.left.isRed()&&(t=t.rotateRight()),t.left.isRed()&&t.right.isRed()&&(t=t.colorFlip()),t}moveRedLeft(){let t=this.colorFlip();return t.right.left.isRed()&&(t=t.copy(null,null,null,null,t.right.rotateRight()),t=t.rotateLeft(),t=t.colorFlip()),t}moveRedRight(){let t=this.colorFlip();return t.left.left.isRed()&&(t=t.rotateRight(),t=t.colorFlip()),t}rotateLeft(){const t=this.copy(null,null,ch.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)}rotateRight(){const t=this.copy(null,null,ch.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)}colorFlip(){const t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)}checkMaxDepth(){const t=this.check();return Math.pow(2,t)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw Ha();if(this.right.isRed())throw Ha();const t=this.left.check();if(t!==this.right.check())throw Ha();return t+(this.isRed()?0:1)}}ch.EMPTY=null,ch.RED=!0,ch.BLACK=!1,ch.EMPTY=new class{constructor(){this.size=0}get key(){throw Ha()}get value(){throw Ha()}get color(){throw Ha()}get left(){throw Ha()}get right(){throw Ha()}copy(t,e,n,s,r){return this}insert(t,e,n){return new ch(t,e)}remove(t,e){return this}isEmpty(){return!0}inorderTraversal(t){return!1}reverseTraversal(t){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class uh{constructor(t){this.comparator=t,this.data=new oh(this.comparator)}has(t){return null!==this.data.get(t)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(t){return this.data.indexOf(t)}forEach(t){this.data.inorderTraversal(((e,n)=>(t(e),!1)))}forEachInRange(t,e){const n=this.data.getIteratorFrom(t[0]);for(;n.hasNext();){const s=n.getNext();if(this.comparator(s.key,t[1])>=0)return;e(s.key)}}forEachWhile(t,e){let n;for(n=void 0!==e?this.data.getIteratorFrom(e):this.data.getIterator();n.hasNext();)if(!t(n.getNext().key))return}firstAfterOrEqual(t){const e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null}getIterator(){return new hh(this.data.getIterator())}getIteratorFrom(t){return new hh(this.data.getIteratorFrom(t))}add(t){return this.copy(this.data.remove(t).insert(t,!0))}delete(t){return this.has(t)?this.copy(this.data.remove(t)):this}isEmpty(){return this.data.isEmpty()}unionWith(t){let e=this;return e.size{e=e.add(t)})),e}isEqual(t){if(!(t instanceof uh))return!1;if(this.size!==t.size)return!1;const e=this.data.getIterator(),n=t.data.getIterator();for(;e.hasNext();){const t=e.getNext().key,s=n.getNext().key;if(0!==this.comparator(t,s))return!1}return!0}toArray(){const t=[];return this.forEach((e=>{t.push(e)})),t}toString(){const t=[];return this.forEach((e=>t.push(e))),"SortedSet("+t.toString()+")"}copy(t){const e=new uh(this.comparator);return e.data=t,e}}class hh{constructor(t){this.iter=t}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}const lh=new oh(Ac.comparator);function dh(){return lh}const fh=new oh(Ac.comparator);function ph(){return fh}const mh=new oh(Ac.comparator);const gh=new uh(Ac.comparator);function yh(...t){let e=gh;for(const n of t)e=e.add(n);return e}const vh=new uh(ic);function wh(){return vh}class bh{constructor(t,e,n,s,r){this.snapshotVersion=t,this.targetChanges=e,this.targetMismatches=n,this.documentUpdates=s,this.resolvedLimboDocuments=r}static createSynthesizedRemoteEventForCurrentChange(t,e){const n=new Map;return n.set(t,Th.createSynthesizedTargetChangeForCurrentChange(t,e)),new bh(cc.min(),n,wh(),dh(),yh())}}class Th{constructor(t,e,n,s,r){this.resumeToken=t,this.current=e,this.addedDocuments=n,this.modifiedDocuments=s,this.removedDocuments=r}static createSynthesizedTargetChangeForCurrentChange(t,e){return new Th(yc.EMPTY_BYTE_STRING,e,yh(),yh(),yh())}}class Eh{constructor(t,e,n,s){this.$=t,this.removedTargetIds=e,this.key=n,this.F=s}}class Ih{constructor(t,e){this.targetId=t,this.O=e}}class _h{constructor(t,e,n=yc.EMPTY_BYTE_STRING,s=null){this.state=t,this.targetIds=e,this.resumeToken=n,this.cause=s}}class Sh{constructor(){this.M=0,this.L=Ch(),this.B=yc.EMPTY_BYTE_STRING,this.U=!1,this.q=!0}get current(){return this.U}get resumeToken(){return this.B}get K(){return 0!==this.M}get j(){return this.q}W(t){t.approximateByteSize()>0&&(this.q=!0,this.B=t)}G(){let t=yh(),e=yh(),n=yh();return this.L.forEach(((s,r)=>{switch(r){case 0:t=t.add(s);break;case 2:e=e.add(s);break;case 1:n=n.add(s);break;default:Ha()}})),new Th(this.B,this.U,t,e,n)}H(){this.q=!1,this.L=Ch()}J(t,e){this.q=!0,this.L=this.L.insert(t,e)}Y(t){this.q=!0,this.L=this.L.remove(t)}X(){this.M+=1}Z(){this.M-=1}tt(){this.q=!0,this.U=!0}}class kh{constructor(t){this.et=t,this.nt=new Map,this.st=dh(),this.it=Ah(),this.rt=new uh(ic)}ot(t){for(const e of t.$)t.F&&t.F.isFoundDocument()?this.at(e,t.F):this.ct(e,t.key,t.F);for(const e of t.removedTargetIds)this.ct(e,t.key,t.F)}ut(t){this.forEachTarget(t,(e=>{const n=this.ht(e);switch(t.state){case 0:this.lt(e)&&n.W(t.resumeToken);break;case 1:n.Z(),n.K||n.H(),n.W(t.resumeToken);break;case 2:n.Z(),n.K||this.removeTarget(e);break;case 3:this.lt(e)&&(n.tt(),n.W(t.resumeToken));break;case 4:this.lt(e)&&(this.ft(e),n.W(t.resumeToken));break;default:Ha()}}))}forEachTarget(t,e){t.targetIds.length>0?t.targetIds.forEach(e):this.nt.forEach(((t,n)=>{this.lt(n)&&e(n)}))}dt(t){const e=t.targetId,n=t.O.count,s=this.wt(e);if(s){const t=s.target;if(Wc(t))if(0===n){const n=new Ac(t.path);this.ct(e,n,Hc.newNoDocument(n,cc.min()))}else $a(1===n);else this._t(e)!==n&&(this.ft(e),this.rt=this.rt.add(e))}}gt(t){const e=new Map;this.nt.forEach(((n,s)=>{const r=this.wt(s);if(r){if(n.current&&Wc(r.target)){const e=new Ac(r.target.path);null!==this.st.get(e)||this.yt(s,e)||this.ct(s,e,Hc.newNoDocument(e,t))}n.j&&(e.set(s,n.G()),n.H())}}));let n=yh();this.it.forEach(((t,e)=>{let s=!0;e.forEachWhile((t=>{const e=this.wt(t);return!e||2===e.purpose||(s=!1,!1)})),s&&(n=n.add(t))}));const s=new bh(t,e,this.rt,this.st,n);return this.st=dh(),this.it=Ah(),this.rt=new uh(ic),s}at(t,e){if(!this.lt(t))return;const n=this.yt(t,e.key)?2:0;this.ht(t).J(e.key,n),this.st=this.st.insert(e.key,e),this.it=this.it.insert(e.key,this.Tt(e.key).add(t))}ct(t,e,n){if(!this.lt(t))return;const s=this.ht(t);this.yt(t,e)?s.J(e,1):s.Y(e),this.it=this.it.insert(e,this.Tt(e).delete(t)),n&&(this.st=this.st.insert(e,n))}removeTarget(t){this.nt.delete(t)}_t(t){const e=this.ht(t).G();return this.et.getRemoteKeysForTarget(t).size+e.addedDocuments.size-e.removedDocuments.size}X(t){this.ht(t).X()}ht(t){let e=this.nt.get(t);return e||(e=new Sh,this.nt.set(t,e)),e}Tt(t){let e=this.it.get(t);return e||(e=new uh(ic),this.it=this.it.insert(t,e)),e}lt(t){const e=null!==this.wt(t);return e||Va("WatchChangeAggregator","Detected inactive target",t),e}wt(t){const e=this.nt.get(t);return e&&e.K?null:this.et.Et(t)}ft(t){this.nt.set(t,new Sh),this.et.getRemoteKeysForTarget(t).forEach((e=>{this.ct(t,e,null)}))}yt(t,e){return this.et.getRemoteKeysForTarget(t).has(e)}}function Ah(){return new oh(Ac.comparator)}function Ch(){return new oh(Ac.comparator)}const Nh={asc:"ASCENDING",desc:"DESCENDING"},Rh={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"};class Lh{constructor(t,e){this.databaseId=t,this.C=e}}function Dh(t,e){return t.C?`${new Date(1e3*e.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+e.nanoseconds).slice(-9)}Z`:{seconds:""+e.seconds,nanos:e.nanoseconds}}function Oh(t,e){return t.C?e.toBase64():e.toUint8Array()}function Ph(t,e){return Dh(t,e.toTimestamp())}function Mh(t){return $a(!!t),cc.fromTimestamp(function(t){const e=wc(t);return new ac(e.seconds,e.nanos)}(t))}function xh(t,e){return function(t){return new fc(["projects",t.projectId,"databases",t.database])}(t).child("documents").child(e).canonicalString()}function Uh(t){const e=fc.fromString(t);return $a(sl(e)),e}function Fh(t,e){return xh(t.databaseId,e.path)}function Vh(t,e){const n=Uh(e);if(n.get(1)!==t.databaseId.projectId)throw new Ga(za.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+t.databaseId.projectId);if(n.get(3)!==t.databaseId.database)throw new Ga(za.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+t.databaseId.database);return new Ac(qh(n))}function jh(t,e){return xh(t.databaseId,e)}function Bh(t){return new fc(["projects",t.databaseId.projectId,"databases",t.databaseId.database]).canonicalString()}function qh(t){return $a(t.length>4&&"documents"===t.get(4)),t.popFirst(5)}function Hh(t,e,n){return{name:Fh(t,e),fields:n.value.mapValue.fields}}function $h(t,e){return{documents:[jh(t,e.path)]}}function Kh(t,e){const n={structuredQuery:{}},s=e.path;null!==e.collectionGroup?(n.parent=jh(t,s),n.structuredQuery.from=[{collectionId:e.collectionGroup,allDescendants:!0}]):(n.parent=jh(t,s.popLast()),n.structuredQuery.from=[{collectionId:s.lastSegment()}]);const r=function(t){if(0===t.length)return;const e=t.map((t=>function(t){if("=="===t.op){if(Fc(t.value))return{unaryFilter:{field:Yh(t.field),op:"IS_NAN"}};if(Uc(t.value))return{unaryFilter:{field:Yh(t.field),op:"IS_NULL"}}}else if("!="===t.op){if(Fc(t.value))return{unaryFilter:{field:Yh(t.field),op:"IS_NOT_NAN"}};if(Uc(t.value))return{unaryFilter:{field:Yh(t.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Yh(t.field),op:Qh(t.op),value:t.value}}}(t)));return 1===e.length?e[0]:{compositeFilter:{op:"AND",filters:e}}}(e.filters);r&&(n.structuredQuery.where=r);const i=function(t){if(0!==t.length)return t.map((t=>function(t){return{field:Yh(t.field),direction:Xh(t.dir)}}(t)))}(e.orderBy);i&&(n.structuredQuery.orderBy=i);const o=function(t,e){return t.C||Sc(e)?e:{value:e}}(t,e.limit);return null!==o&&(n.structuredQuery.limit=o),e.startAt&&(n.structuredQuery.startAt=Wh(e.startAt)),e.endAt&&(n.structuredQuery.endAt=Wh(e.endAt)),n}function zh(t){let e=function(t){const e=Uh(t);return 4===e.length?fc.emptyPath():qh(e)}(t.parent);const n=t.structuredQuery,s=n.from?n.from.length:0;let r=null;if(s>0){$a(1===s);const t=n.from[0];t.allDescendants?r=t.collectionId:e=e.child(t.collectionId)}let i=[];n.where&&(i=Gh(n.where));let o=[];n.orderBy&&(o=n.orderBy.map((t=>function(t){return new ou(Zh(t.field),function(t){switch(t){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(t.direction))}(t))));let a=null;n.limit&&(a=function(t){let e;return e="object"==typeof t?t.value:t,Sc(e)?null:e}(n.limit));let c=null;n.startAt&&(c=Jh(n.startAt));let u=null;return n.endAt&&(u=Jh(n.endAt)),function(t,e,n,s,r,i,o,a){return new hu(t,e,n,s,r,i,o,a)}(e,r,o,i,a,"F",c,u)}function Gh(t){return t?void 0!==t.unaryFilter?[el(t)]:void 0!==t.fieldFilter?[tl(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map((t=>Gh(t))).reduce(((t,e)=>t.concat(e))):Ha():[]}function Wh(t){return{before:t.before,values:t.position}}function Jh(t){const e=!!t.before,n=t.values||[];return new ru(n,e)}function Xh(t){return Nh[t]}function Qh(t){return Rh[t]}function Yh(t){return{fieldPath:t.canonicalString()}}function Zh(t){return mc.fromServerFormat(t.fieldPath)}function tl(t){return Jc.create(Zh(t.fieldFilter.field),function(t){switch(t){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 Ha()}}(t.fieldFilter.op),t.fieldFilter.value)}function el(t){switch(t.unaryFilter.op){case"IS_NAN":const e=Zh(t.unaryFilter.field);return Jc.create(e,"==",{doubleValue:NaN});case"IS_NULL":const n=Zh(t.unaryFilter.field);return Jc.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const s=Zh(t.unaryFilter.field);return Jc.create(s,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const r=Zh(t.unaryFilter.field);return Jc.create(r,"!=",{nullValue:"NULL_VALUE"});default:return Ha()}}function nl(t){const e=[];return t.fields.forEach((t=>e.push(t.canonicalString()))),{fieldPaths:e}}function sl(t){return t.length>=4&&"projects"===t.get(0)&&"databases"===t.get(2)}function rl(t){let e="";for(let n=0;n0&&(e=ol(e)),e=il(t.get(n),e);return ol(e)}function il(t,e){let n=e;const s=t.length;for(let e=0;e{this.isDone=!0,this.result=t,this.nextCallback&&this.nextCallback(t)}),(t=>{this.isDone=!0,this.error=t,this.catchCallback&&this.catchCallback(t)}))}catch(t){return this.next(void 0,t)}next(t,e){return this.callbackAttached&&Ha(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(e,this.error):this.wrapSuccess(t,this.result):new bl(((n,s)=>{this.nextCallback=e=>{this.wrapSuccess(t,e).next(n,s)},this.catchCallback=t=>{this.wrapFailure(e,t).next(n,s)}}))}toPromise(){return new Promise(((t,e)=>{this.next(t,e)}))}wrapUserFunction(t){try{const e=t();return e instanceof bl?e:bl.resolve(e)}catch(t){return bl.reject(t)}}wrapSuccess(t,e){return t?this.wrapUserFunction((()=>t(e))):bl.resolve(e)}wrapFailure(t,e){return t?this.wrapUserFunction((()=>t(e))):bl.reject(e)}static resolve(t){return new bl(((e,n)=>{e(t)}))}static reject(t){return new bl(((e,n)=>{n(t)}))}static waitFor(t){return new bl(((e,n)=>{let s=0,r=0,i=!1;t.forEach((t=>{++s,t.next((()=>{++r,i&&r===s&&e()}),(t=>n(t)))})),i=!0,r===s&&e()}))}static or(t){let e=bl.resolve(!1);for(const n of t)e=e.next((t=>t?bl.resolve(t):n()));return e}static forEach(t,e){const n=[];return t.forEach(((t,s)=>{n.push(e.call(this,t,s))})),this.waitFor(n)}}function Tl(t){return"IndexedDbTransactionError"===t.name}class El{constructor(t,e,n,s){this.batchId=t,this.localWriteTime=e,this.baseMutations=n,this.mutations=s}applyToRemoteDocument(t,e){const n=e.mutationResults;for(let e=0;e{const n=t.get(e.key),s=n;this.applyToLocalView(s),n.isValidDocument()||s.convertToNoDocument(cc.min())}))}keys(){return this.mutations.reduce(((t,e)=>t.add(e.key)),yh())}isEqual(t){return this.batchId===t.batchId&&oc(this.mutations,t.mutations,((t,e)=>Gu(t,e)))&&oc(this.baseMutations,t.baseMutations,((t,e)=>Gu(t,e)))}}class Il{constructor(t,e,n,s){this.batch=t,this.commitVersion=e,this.mutationResults=n,this.docVersions=s}static from(t,e,n){$a(t.mutations.length===n.length);let s=mh;const r=t.mutations;for(let t=0;t{for(const[e,s]of n)t(e,s)}))}isEmpty(){return lc(this.inner)}}class Ol{constructor(t,e,n){this.Je=t,this.An=e,this.Jt=n}Rn(t,e){return this.An.getAllMutationBatchesAffectingDocumentKey(t,e).next((n=>this.Pn(t,e,n)))}Pn(t,e,n){return this.Je.getEntry(t,e).next((t=>{for(const e of n)e.applyToLocalView(t);return t}))}bn(t,e){t.forEach(((t,n)=>{for(const t of e)t.applyToLocalView(n)}))}vn(t,e){return this.Je.getEntries(t,e).next((e=>this.Vn(t,e).next((()=>e))))}Vn(t,e){return this.An.getAllMutationBatchesAffectingDocumentKeys(t,e).next((t=>this.bn(e,t)))}getDocumentsMatchingQuery(t,e,n){return function(t){return Ac.isDocumentKey(t.path)&&null===t.collectionGroup&&0===t.filters.length}(e)?this.Sn(t,e.path):function(t){return null!==t.collectionGroup}(e)?this.Dn(t,e,n):this.Cn(t,e,n)}Sn(t,e){return this.Rn(t,new Ac(e)).next((t=>{let e=ph();return t.isFoundDocument()&&(e=e.insert(t.key,t)),e}))}Dn(t,e,n){const s=e.collectionGroup;let r=ph();return this.Jt.getCollectionParents(t,s).next((i=>bl.forEach(i,(i=>{const o=function(t,e){return new hu(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt)}(e,i.child(s));return this.Cn(t,o,n).next((t=>{t.forEach(((t,e)=>{r=r.insert(t,e)}))}))})).next((()=>r))))}Cn(t,e,n){let s,r;return this.Je.getDocumentsMatchingQuery(t,e,n).next((n=>(s=n,this.An.getAllMutationBatchesAffectingQuery(t,e)))).next((e=>(r=e,this.Nn(t,r,s).next((t=>{s=t;for(const t of r)for(const e of t.mutations){const n=e.key;let r=s.get(n);null==r&&(r=Hc.newInvalidDocument(n),s=s.insert(n,r)),Ku(e,r,t.localWriteTime),r.isFoundDocument()||(s=s.remove(n))}}))))).next((()=>(s.forEach(((t,n)=>{Eu(e,n)||(s=s.remove(t))})),s)))}Nn(t,e,n){let s=yh();for(const t of e)for(const e of t.mutations)e instanceof Xu&&null===n.get(e.key)&&(s=s.add(e.key));let r=n;return this.Je.getEntries(t,s).next((t=>(t.forEach(((t,e)=>{e.isFoundDocument()&&(r=r.insert(t,e))})),r)))}}class Pl{constructor(t,e,n,s){this.targetId=t,this.fromCache=e,this.kn=n,this.xn=s}static $n(t,e){let n=yh(),s=yh();for(const t of e.docChanges)switch(t.type){case 0:n=n.add(t.doc.key);break;case 1:s=s.add(t.doc.key)}return new Pl(t,e.fromCache,n,s)}}class Ml{Fn(t){this.On=t}getDocumentsMatchingQuery(t,e,n,s){return function(t){return 0===t.filters.length&&null===t.limit&&null==t.startAt&&null==t.endAt&&(0===t.explicitOrderBy.length||1===t.explicitOrderBy.length&&t.explicitOrderBy[0].field.isKeyField())}(e)||n.isEqual(cc.min())?this.Mn(t,e):this.On.vn(t,s).next((r=>{const i=this.Ln(e,r);return(du(e)||fu(e))&&this.Bn(e.limitType,i,s,n)?this.Mn(t,e):(Fa()<=k.DEBUG&&Va("QueryEngine","Re-using previous result from %s to execute query: %s",n.toString(),Tu(e)),this.On.getDocumentsMatchingQuery(t,e,n).next((t=>(i.forEach((e=>{t=t.insert(e.key,e)})),t))))}))}Ln(t,e){let n=new uh(Iu(t));return e.forEach(((e,s)=>{Eu(t,s)&&(n=n.add(s))})),n}Bn(t,e,n,s){if(n.size!==e.size)return!0;const r="F"===t?e.last():e.first();return!!r&&(r.hasPendingWrites||r.version.compareTo(s)>0)}Mn(t,e){return Fa()<=k.DEBUG&&Va("QueryEngine","Using full collection scan to execute query:",Tu(e)),this.On.getDocumentsMatchingQuery(t,e,cc.min())}}class xl{constructor(t,e,n,s){this.persistence=t,this.Un=e,this.k=s,this.qn=new oh(ic),this.Kn=new Dl((t=>zc(t)),Gc),this.jn=cc.min(),this.An=t.getMutationQueue(n),this.Qn=t.getRemoteDocumentCache(),this.He=t.getTargetCache(),this.Wn=new Ol(this.Qn,this.An,this.persistence.getIndexManager()),this.Ye=t.getBundleCache(),this.Un.Fn(this.Wn)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(e=>t.collect(e,this.qn)))}}async function Ul(t,e){const n=Ka(t);let s=n.An,r=n.Wn;const i=await n.persistence.runTransaction("Handle user change","readonly",(t=>{let i;return n.An.getAllMutationBatches(t).next((o=>(i=o,s=n.persistence.getMutationQueue(e),r=new Ol(n.Qn,s,n.persistence.getIndexManager()),s.getAllMutationBatches(t)))).next((e=>{const n=[],s=[];let o=yh();for(const t of i){n.push(t.batchId);for(const e of t.mutations)o=o.add(e.key)}for(const t of e){s.push(t.batchId);for(const e of t.mutations)o=o.add(e.key)}return r.vn(t,o).next((t=>({Gn:t,removedBatchIds:n,addedBatchIds:s})))}))}));return n.An=s,n.Wn=r,n.Un.Fn(n.Wn),i}function Fl(t){const e=Ka(t);return e.persistence.runTransaction("Get last remote snapshot version","readonly",(t=>e.He.getLastRemoteSnapshotVersion(t)))}function Vl(t,e){const n=Ka(t);return n.persistence.runTransaction("Get next mutation batch","readonly",(t=>(void 0===e&&(e=-1),n.An.getNextMutationBatchAfterBatchId(t,e))))}async function jl(t,e,n){const s=Ka(t),r=s.qn.get(e),i=n?"readwrite":"readwrite-primary";try{n||await s.persistence.runTransaction("Release target",i,(t=>s.persistence.referenceDelegate.removeTarget(t,r)))}catch(t){if(!Tl(t))throw t;Va("LocalStore",`Failed to update sequence numbers for target ${e}: ${t}`)}s.qn=s.qn.remove(e),s.Kn.delete(r.target)}function Bl(t,e,n){const s=Ka(t);let r=cc.min(),i=yh();return s.persistence.runTransaction("Execute query","readonly",(t=>function(t,e,n){const s=Ka(t),r=s.Kn.get(n);return void 0!==r?bl.resolve(s.qn.get(r)):s.He.getTargetData(e,n)}(s,t,yu(e)).next((e=>{if(e)return r=e.lastLimboFreeSnapshotVersion,s.He.getMatchingKeysForTargetId(t,e.targetId).next((t=>{i=t}))})).next((()=>s.Un.getDocumentsMatchingQuery(t,e,n?r:cc.min(),n?i:yh()))).next((t=>({documents:t,zn:i})))))}class ql{constructor(t){this.k=t,this.Xn=new Map,this.Zn=new Map}getBundleMetadata(t,e){return bl.resolve(this.Xn.get(e))}saveBundleMetadata(t,e){var n;return this.Xn.set(e.id,{id:(n=e).id,version:n.version,createTime:Mh(n.createTime)}),bl.resolve()}getNamedQuery(t,e){return bl.resolve(this.Zn.get(e))}saveNamedQuery(t,e){return this.Zn.set(e.name,function(t){return{name:t.name,query:kl(t.bundledQuery),readTime:Mh(t.readTime)}}(e)),bl.resolve()}}class Hl{constructor(){this.ts=new uh($l.es),this.ns=new uh($l.ss)}isEmpty(){return this.ts.isEmpty()}addReference(t,e){const n=new $l(t,e);this.ts=this.ts.add(n),this.ns=this.ns.add(n)}rs(t,e){t.forEach((t=>this.addReference(t,e)))}removeReference(t,e){this.os(new $l(t,e))}cs(t,e){t.forEach((t=>this.removeReference(t,e)))}us(t){const e=new Ac(new fc([])),n=new $l(e,t),s=new $l(e,t+1),r=[];return this.ns.forEachInRange([n,s],(t=>{this.os(t),r.push(t.key)})),r}hs(){this.ts.forEach((t=>this.os(t)))}os(t){this.ts=this.ts.delete(t),this.ns=this.ns.delete(t)}ls(t){const e=new Ac(new fc([])),n=new $l(e,t),s=new $l(e,t+1);let r=yh();return this.ns.forEachInRange([n,s],(t=>{r=r.add(t.key)})),r}containsKey(t){const e=new $l(t,0),n=this.ts.firstAfterOrEqual(e);return null!==n&&t.isEqual(n.key)}}class $l{constructor(t,e){this.key=t,this.fs=e}static es(t,e){return Ac.comparator(t.key,e.key)||ic(t.fs,e.fs)}static ss(t,e){return ic(t.fs,e.fs)||Ac.comparator(t.key,e.key)}}class Kl{constructor(t,e){this.Jt=t,this.referenceDelegate=e,this.An=[],this.ds=1,this.ws=new uh($l.es)}checkEmpty(t){return bl.resolve(0===this.An.length)}addMutationBatch(t,e,n,s){const r=this.ds;this.ds++,this.An.length>0&&this.An[this.An.length-1];const i=new El(r,e,n,s);this.An.push(i);for(const e of s)this.ws=this.ws.add(new $l(e.key,r)),this.Jt.addToCollectionParentIndex(t,e.key.path.popLast());return bl.resolve(i)}lookupMutationBatch(t,e){return bl.resolve(this._s(e))}getNextMutationBatchAfterBatchId(t,e){const n=e+1,s=this.gs(n),r=s<0?0:s;return bl.resolve(this.An.length>r?this.An[r]:null)}getHighestUnacknowledgedBatchId(){return bl.resolve(0===this.An.length?-1:this.ds-1)}getAllMutationBatches(t){return bl.resolve(this.An.slice())}getAllMutationBatchesAffectingDocumentKey(t,e){const n=new $l(e,0),s=new $l(e,Number.POSITIVE_INFINITY),r=[];return this.ws.forEachInRange([n,s],(t=>{const e=this._s(t.fs);r.push(e)})),bl.resolve(r)}getAllMutationBatchesAffectingDocumentKeys(t,e){let n=new uh(ic);return e.forEach((t=>{const e=new $l(t,0),s=new $l(t,Number.POSITIVE_INFINITY);this.ws.forEachInRange([e,s],(t=>{n=n.add(t.fs)}))})),bl.resolve(this.ys(n))}getAllMutationBatchesAffectingQuery(t,e){const n=e.path,s=n.length+1;let r=n;Ac.isDocumentKey(r)||(r=r.child(""));const i=new $l(new Ac(r),0);let o=new uh(ic);return this.ws.forEachWhile((t=>{const e=t.key.path;return!!n.isPrefixOf(e)&&(e.length===s&&(o=o.add(t.fs)),!0)}),i),bl.resolve(this.ys(o))}ys(t){const e=[];return t.forEach((t=>{const n=this._s(t);null!==n&&e.push(n)})),e}removeMutationBatch(t,e){$a(0===this.ps(e.batchId,"removed")),this.An.shift();let n=this.ws;return bl.forEach(e.mutations,(s=>{const r=new $l(s.key,e.batchId);return n=n.delete(r),this.referenceDelegate.markPotentiallyOrphaned(t,s.key)})).next((()=>{this.ws=n}))}ee(t){}containsKey(t,e){const n=new $l(e,0),s=this.ws.firstAfterOrEqual(n);return bl.resolve(e.isEqual(s&&s.key))}performConsistencyCheck(t){return this.An.length,bl.resolve()}ps(t,e){return this.gs(t)}gs(t){return 0===this.An.length?0:t-this.An[0].batchId}_s(t){const e=this.gs(t);return e<0||e>=this.An.length?null:this.An[e]}}class zl{constructor(t,e){this.Jt=t,this.Ts=e,this.docs=new oh(Ac.comparator),this.size=0}addEntry(t,e,n){const s=e.key,r=this.docs.get(s),i=r?r.size:0,o=this.Ts(e);return this.docs=this.docs.insert(s,{document:e.clone(),size:o,readTime:n}),this.size+=o-i,this.Jt.addToCollectionParentIndex(t,s.path.popLast())}removeEntry(t){const e=this.docs.get(t);e&&(this.docs=this.docs.remove(t),this.size-=e.size)}getEntry(t,e){const n=this.docs.get(e);return bl.resolve(n?n.document.clone():Hc.newInvalidDocument(e))}getEntries(t,e){let n=dh();return e.forEach((t=>{const e=this.docs.get(t);n=n.insert(t,e?e.document.clone():Hc.newInvalidDocument(t))})),bl.resolve(n)}getDocumentsMatchingQuery(t,e,n){let s=dh();const r=new Ac(e.path.child("")),i=this.docs.getIteratorFrom(r);for(;i.hasNext();){const{key:t,value:{document:r,readTime:o}}=i.getNext();if(!e.path.isPrefixOf(t.path))break;o.compareTo(n)<=0||Eu(e,r)&&(s=s.insert(r.key,r.clone()))}return bl.resolve(s)}Es(t,e){return bl.forEach(this.docs,(t=>e(t)))}newChangeBuffer(t){return new Gl(this)}getSize(t){return bl.resolve(this.size)}}class Gl extends class{constructor(){this.changes=new Dl((t=>t.toString()),((t,e)=>t.isEqual(e))),this.changesApplied=!1}getReadTime(t){const e=this.changes.get(t);return e?e.readTime:cc.min()}addEntry(t,e){this.assertNotApplied(),this.changes.set(t.key,{document:t,readTime:e})}removeEntry(t,e=null){this.assertNotApplied(),this.changes.set(t,{document:Hc.newInvalidDocument(t),readTime:e})}getEntry(t,e){this.assertNotApplied();const n=this.changes.get(e);return void 0!==n?bl.resolve(n.document):this.getFromCache(t,e)}getEntries(t,e){return this.getAllFromCache(t,e)}apply(t){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(t)}assertNotApplied(){}}{constructor(t){super(),this.De=t}applyChanges(t){const e=[];return this.changes.forEach(((n,s)=>{s.document.isValidDocument()?e.push(this.De.addEntry(t,s.document,this.getReadTime(n))):this.De.removeEntry(n)})),bl.waitFor(e)}getFromCache(t,e){return this.De.getEntry(t,e)}getAllFromCache(t,e){return this.De.getEntries(t,e)}}class Wl{constructor(t){this.persistence=t,this.Is=new Dl((t=>zc(t)),Gc),this.lastRemoteSnapshotVersion=cc.min(),this.highestTargetId=0,this.As=0,this.Rs=new Hl,this.targetCount=0,this.Ps=Rl.ie()}forEachTarget(t,e){return this.Is.forEach(((t,n)=>e(n))),bl.resolve()}getLastRemoteSnapshotVersion(t){return bl.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(t){return bl.resolve(this.As)}allocateTargetId(t){return this.highestTargetId=this.Ps.next(),bl.resolve(this.highestTargetId)}setTargetsMetadata(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.As&&(this.As=e),bl.resolve()}ce(t){this.Is.set(t.target,t);const e=t.targetId;e>this.highestTargetId&&(this.Ps=new Rl(e),this.highestTargetId=e),t.sequenceNumber>this.As&&(this.As=t.sequenceNumber)}addTargetData(t,e){return this.ce(e),this.targetCount+=1,bl.resolve()}updateTargetData(t,e){return this.ce(e),bl.resolve()}removeTargetData(t,e){return this.Is.delete(e.target),this.Rs.us(e.targetId),this.targetCount-=1,bl.resolve()}removeTargets(t,e,n){let s=0;const r=[];return this.Is.forEach(((i,o)=>{o.sequenceNumber<=e&&null===n.get(o.targetId)&&(this.Is.delete(i),r.push(this.removeMatchingKeysForTargetId(t,o.targetId)),s++)})),bl.waitFor(r).next((()=>s))}getTargetCount(t){return bl.resolve(this.targetCount)}getTargetData(t,e){const n=this.Is.get(e)||null;return bl.resolve(n)}addMatchingKeys(t,e,n){return this.Rs.rs(e,n),bl.resolve()}removeMatchingKeys(t,e,n){this.Rs.cs(e,n);const s=this.persistence.referenceDelegate,r=[];return s&&e.forEach((e=>{r.push(s.markPotentiallyOrphaned(t,e))})),bl.waitFor(r)}removeMatchingKeysForTargetId(t,e){return this.Rs.us(e),bl.resolve()}getMatchingKeysForTargetId(t,e){const n=this.Rs.ls(e);return bl.resolve(n)}containsKey(t,e){return bl.resolve(this.Rs.containsKey(e))}}class Jl{constructor(t,e){this.bs={},this.Be=new nc(0),this.Ue=!1,this.Ue=!0,this.referenceDelegate=t(this),this.He=new Wl(this),this.Jt=new Al,this.Je=function(t,e){return new zl(t,e)}(this.Jt,(t=>this.referenceDelegate.vs(t))),this.k=new Sl(e),this.Ye=new ql(this.k)}start(){return Promise.resolve()}shutdown(){return this.Ue=!1,Promise.resolve()}get started(){return this.Ue}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(){return this.Jt}getMutationQueue(t){let e=this.bs[t.toKey()];return e||(e=new Kl(this.Jt,this.referenceDelegate),this.bs[t.toKey()]=e),e}getTargetCache(){return this.He}getRemoteDocumentCache(){return this.Je}getBundleCache(){return this.Ye}runTransaction(t,e,n){Va("MemoryPersistence","Starting transaction:",t);const s=new Xl(this.Be.next());return this.referenceDelegate.Vs(),n(s).next((t=>this.referenceDelegate.Ss(s).next((()=>t)))).toPromise().then((t=>(s.raiseOnCommittedEvent(),t)))}Ds(t,e){return bl.or(Object.values(this.bs).map((n=>()=>n.containsKey(t,e))))}}class Xl extends class{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(t){this.onCommittedListeners.push(t)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((t=>t()))}}{constructor(t){super(),this.currentSequenceNumber=t}}class Ql{constructor(t){this.persistence=t,this.Cs=new Hl,this.Ns=null}static ks(t){return new Ql(t)}get xs(){if(this.Ns)return this.Ns;throw Ha()}addReference(t,e,n){return this.Cs.addReference(n,e),this.xs.delete(n.toString()),bl.resolve()}removeReference(t,e,n){return this.Cs.removeReference(n,e),this.xs.add(n.toString()),bl.resolve()}markPotentiallyOrphaned(t,e){return this.xs.add(e.toString()),bl.resolve()}removeTarget(t,e){this.Cs.us(e.targetId).forEach((t=>this.xs.add(t.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(t,e.targetId).next((t=>{t.forEach((t=>this.xs.add(t.toString())))})).next((()=>n.removeTargetData(t,e)))}Vs(){this.Ns=new Set}Ss(t){const e=this.persistence.getRemoteDocumentCache().newChangeBuffer();return bl.forEach(this.xs,(n=>{const s=Ac.fromPath(n);return this.$s(t,s).next((t=>{t||e.removeEntry(s)}))})).next((()=>(this.Ns=null,e.apply(t))))}updateLimboDocument(t,e){return this.$s(t,e).next((t=>{t?this.xs.delete(e.toString()):this.xs.add(e.toString())}))}vs(t){return 0}$s(t,e){return bl.or([()=>bl.resolve(this.Cs.containsKey(e)),()=>this.persistence.getTargetCache().containsKey(t,e),()=>this.persistence.Ds(t,e)])}}class Yl{constructor(){this.activeTargetIds=wh()}Ms(t){this.activeTargetIds=this.activeTargetIds.add(t)}Ls(t){this.activeTargetIds=this.activeTargetIds.delete(t)}Os(){const t={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(t)}}class Zl{constructor(){this.pi=new Yl,this.Ti={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(t){}updateMutationState(t,e,n){}addLocalQueryTarget(t){return this.pi.Ms(t),this.Ti[t]||"not-current"}updateQueryState(t,e,n){this.Ti[t]=e}removeLocalQueryTarget(t){this.pi.Ls(t)}isLocalQueryTarget(t){return this.pi.activeTargetIds.has(t)}clearQueryState(t){delete this.Ti[t]}getAllActiveQueryTargets(){return this.pi.activeTargetIds}isActiveQueryTarget(t){return this.pi.activeTargetIds.has(t)}start(){return this.pi=new Yl,Promise.resolve()}handleUserChange(t,e,n){}setOnlineState(t){}shutdown(){}writeSequenceNumber(t){}notifyBundleLoaded(){}}class td{Ei(t){}shutdown(){}}class ed{constructor(){this.Ii=()=>this.Ai(),this.Ri=()=>this.Pi(),this.bi=[],this.vi()}Ei(t){this.bi.push(t)}shutdown(){window.removeEventListener("online",this.Ii),window.removeEventListener("offline",this.Ri)}vi(){window.addEventListener("online",this.Ii),window.addEventListener("offline",this.Ri)}Ai(){Va("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const t of this.bi)t(0)}Pi(){Va("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const t of this.bi)t(1)}static bt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const nd={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class sd{constructor(t){this.Vi=t.Vi,this.Si=t.Si}Di(t){this.Ci=t}Ni(t){this.ki=t}onMessage(t){this.xi=t}close(){this.Si()}send(t){this.Vi(t)}$i(){this.Ci()}Fi(t){this.ki(t)}Oi(t){this.xi(t)}}class rd extends class{constructor(t){this.databaseInfo=t,this.databaseId=t.databaseId;const e=t.ssl?"https":"http";this.Mi=e+"://"+t.host,this.Li="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}Bi(t,e,n,s,r){const i=this.Ui(t,e);Va("RestConnection","Sending: ",i,n);const o={};return this.qi(o,s,r),this.Ki(t,i,o,n).then((t=>(Va("RestConnection","Received: ",t),t)),(e=>{throw Ba("RestConnection",`${t} failed with error: `,e,"url: ",i,"request:",n),e}))}ji(t,e,n,s,r){return this.Bi(t,e,n,s,r)}qi(t,e,n){t["X-Goog-Api-Client"]="gl-js/ fire/"+xa,t["Content-Type"]="text/plain",this.databaseInfo.appId&&(t["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach(((e,n)=>t[n]=e)),n&&n.headers.forEach(((e,n)=>t[n]=e))}Ui(t,e){const n=nd[t];return`${this.Mi}/v1/${e}:${n}`}}{constructor(t){super(t),this.forceLongPolling=t.forceLongPolling,this.autoDetectLongPolling=t.autoDetectLongPolling,this.useFetchStreams=t.useFetchStreams}Ki(t,e,n,s){return new Promise(((r,i)=>{const o=new Oa;o.listenOnce(Ca.COMPLETE,(()=>{try{switch(o.getLastErrorCode()){case Aa.NO_ERROR:const e=o.getResponseJson();Va("Connection","XHR received:",JSON.stringify(e)),r(e);break;case Aa.TIMEOUT:Va("Connection",'RPC "'+t+'" timed out'),i(new Ga(za.DEADLINE_EXCEEDED,"Request time out"));break;case Aa.HTTP_ERROR:const n=o.getStatus();if(Va("Connection",'RPC "'+t+'" failed with status:',n,"response text:",o.getResponseText()),n>0){const t=o.getResponseJson().error;if(t&&t.status&&t.message){const e=function(t){const e=t.toLowerCase().replace(/_/g,"-");return Object.values(za).indexOf(e)>=0?e:za.UNKNOWN}(t.status);i(new Ga(e,t.message))}else i(new Ga(za.UNKNOWN,"Server responded with status "+o.getStatus()))}else i(new Ga(za.UNAVAILABLE,"Connection failed."));break;default:Ha()}}finally{Va("Connection",'RPC "'+t+'" completed.')}}));const a=JSON.stringify(s);o.send(e,"POST",a,n,15)}))}Qi(t,e,n){const s=[this.Mi,"/","google.firestore.v1.Firestore","/",t,"/channel"],u=Sa(),h=ka(),l={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(l.xmlHttpFactory=new La({})),this.qi(l.initMessageHeaders,e,n),i()||a()||r().indexOf("Electron/")>=0||c()||r().indexOf("MSAppHost/")>=0||o()||(l.httpHeadersOverwriteParam="$httpHeaders");const d=s.join("");Va("Connection","Creating WebChannel: "+d,l);const f=u.createWebChannel(d,l);let p=!1,m=!1;const g=new sd({Vi:t=>{m?Va("Connection","Not sending because WebChannel is closed:",t):(p||(Va("Connection","Opening WebChannel transport."),f.open(),p=!0),Va("Connection","WebChannel sending:",t),f.send(t))},Si:()=>f.close()}),y=(t,e,n)=>{t.listen(e,(t=>{try{n(t)}catch(t){setTimeout((()=>{throw t}),0)}}))};return y(f,Da.EventType.OPEN,(()=>{m||Va("Connection","WebChannel transport opened.")})),y(f,Da.EventType.CLOSE,(()=>{m||(m=!0,Va("Connection","WebChannel transport closed"),g.Fi())})),y(f,Da.EventType.ERROR,(t=>{m||(m=!0,Ba("Connection","WebChannel transport errored:",t),g.Fi(new Ga(za.UNAVAILABLE,"The operation could not be completed")))})),y(f,Da.EventType.MESSAGE,(t=>{var e;if(!m){const n=t.data[0];$a(!!n);const s=n,r=s.error||(null===(e=s[0])||void 0===e?void 0:e.error);if(r){Va("Connection","WebChannel received error:",r);const t=r.status;let e=function(t){const e=sh[t];if(void 0!==e)return ih(e)}(t),n=r.message;void 0===e&&(e=za.INTERNAL,n="Unknown error status: "+t+" with message "+r.message),m=!0,g.Fi(new Ga(e,n)),f.close()}else Va("Connection","WebChannel received:",n),g.Oi(n)}})),y(h,Na.STAT_EVENT,(t=>{t.stat===Ra.PROXY?Va("Connection","Detected buffering proxy"):t.stat===Ra.NOPROXY&&Va("Connection","Detected no buffering proxy")})),setTimeout((()=>{g.$i()}),0),g}}function id(){return"undefined"!=typeof document?document:null}function od(t){return new Lh(t,!0)}class ad{constructor(t,e,n=1e3,s=1.5,r=6e4){this.Oe=t,this.timerId=e,this.Wi=n,this.Gi=s,this.zi=r,this.Hi=0,this.Ji=null,this.Yi=Date.now(),this.reset()}reset(){this.Hi=0}Xi(){this.Hi=this.zi}Zi(t){this.cancel();const e=Math.floor(this.Hi+this.tr()),n=Math.max(0,Date.now()-this.Yi),s=Math.max(0,e-n);s>0&&Va("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.Hi} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`),this.Ji=this.Oe.enqueueAfterDelay(this.timerId,s,(()=>(this.Yi=Date.now(),t()))),this.Hi*=this.Gi,this.Hithis.zi&&(this.Hi=this.zi)}er(){null!==this.Ji&&(this.Ji.skipDelay(),this.Ji=null)}cancel(){null!==this.Ji&&(this.Ji.cancel(),this.Ji=null)}tr(){return(Math.random()-.5)*this.Hi}}class cd{constructor(t,e,n,s,r,i,o,a){this.Oe=t,this.nr=n,this.sr=s,this.ir=r,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.rr=0,this.ar=null,this.cr=null,this.stream=null,this.ur=new ad(t,e)}hr(){return 1===this.state||5===this.state||this.lr()}lr(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.dr()}async stop(){this.hr()&&await this.close(0)}wr(){this.state=0,this.ur.reset()}_r(){this.lr()&&null===this.ar&&(this.ar=this.Oe.enqueueAfterDelay(this.nr,6e4,(()=>this.mr())))}gr(t){this.yr(),this.stream.send(t)}async mr(){if(this.lr())return this.close(0)}yr(){this.ar&&(this.ar.cancel(),this.ar=null)}pr(){this.cr&&(this.cr.cancel(),this.cr=null)}async close(t,e){this.yr(),this.pr(),this.ur.cancel(),this.rr++,4!==t?this.ur.reset():e&&e.code===za.RESOURCE_EXHAUSTED?(ja(e.toString()),ja("Using maximum backoff delay to prevent overloading the backend."),this.ur.Xi()):e&&e.code===za.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Tr(),this.stream.close(),this.stream=null),this.state=t,await this.listener.Ni(e)}Tr(){}auth(){this.state=1;const t=this.Er(this.rr),e=this.rr;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([t,n])=>{this.rr===e&&this.Ir(t,n)}),(e=>{t((()=>{const t=new Ga(za.UNKNOWN,"Fetching auth token failed: "+e.message);return this.Ar(t)}))}))}Ir(t,e){const n=this.Er(this.rr);this.stream=this.Rr(t,e),this.stream.Di((()=>{n((()=>(this.state=2,this.cr=this.Oe.enqueueAfterDelay(this.sr,1e4,(()=>(this.lr()&&(this.state=3),Promise.resolve()))),this.listener.Di())))})),this.stream.Ni((t=>{n((()=>this.Ar(t)))})),this.stream.onMessage((t=>{n((()=>this.onMessage(t)))}))}dr(){this.state=5,this.ur.Zi((async()=>{this.state=0,this.start()}))}Ar(t){return Va("PersistentStream",`close with error: ${t}`),this.stream=null,this.close(4,t)}Er(t){return e=>{this.Oe.enqueueAndForget((()=>this.rr===t?e():(Va("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class ud extends cd{constructor(t,e,n,s,r,i){super(t,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",e,n,s,i),this.k=r}Rr(t,e){return this.ir.Qi("Listen",t,e)}onMessage(t){this.ur.reset();const e=function(t,e){let n;if("targetChange"in e){e.targetChange;const s=function(t){return"NO_CHANGE"===t?0:"ADD"===t?1:"REMOVE"===t?2:"CURRENT"===t?3:"RESET"===t?4:Ha()}(e.targetChange.targetChangeType||"NO_CHANGE"),r=e.targetChange.targetIds||[],i=function(t,e){return t.C?($a(void 0===e||"string"==typeof e),yc.fromBase64String(e||"")):($a(void 0===e||e instanceof Uint8Array),yc.fromUint8Array(e||new Uint8Array))}(t,e.targetChange.resumeToken),o=e.targetChange.cause,a=o&&function(t){const e=void 0===t.code?za.UNKNOWN:ih(t.code);return new Ga(e,t.message||"")}(o);n=new _h(s,r,i,a||null)}else if("documentChange"in e){e.documentChange;const s=e.documentChange;s.document,s.document.name,s.document.updateTime;const r=Vh(t,s.document.name),i=Mh(s.document.updateTime),o=new Bc({mapValue:{fields:s.document.fields}}),a=Hc.newFoundDocument(r,i,o),c=s.targetIds||[],u=s.removedTargetIds||[];n=new Eh(c,u,a.key,a)}else if("documentDelete"in e){e.documentDelete;const s=e.documentDelete;s.document;const r=Vh(t,s.document),i=s.readTime?Mh(s.readTime):cc.min(),o=Hc.newNoDocument(r,i),a=s.removedTargetIds||[];n=new Eh([],a,o.key,o)}else if("documentRemove"in e){e.documentRemove;const s=e.documentRemove;s.document;const r=Vh(t,s.document),i=s.removedTargetIds||[];n=new Eh([],i,r,null)}else{if(!("filter"in e))return Ha();{e.filter;const t=e.filter;t.targetId;const s=t.count||0,r=new nh(s),i=t.targetId;n=new Ih(i,r)}}return n}(this.k,t),n=function(t){if(!("targetChange"in t))return cc.min();const e=t.targetChange;return e.targetIds&&e.targetIds.length?cc.min():e.readTime?Mh(e.readTime):cc.min()}(t);return this.listener.Pr(e,n)}br(t){const e={};e.database=Bh(this.k),e.addTarget=function(t,e){let n;const s=e.target;return n=Wc(s)?{documents:$h(t,s)}:{query:Kh(t,s)},n.targetId=e.targetId,e.resumeToken.approximateByteSize()>0?n.resumeToken=Oh(t,e.resumeToken):e.snapshotVersion.compareTo(cc.min())>0&&(n.readTime=Dh(t,e.snapshotVersion.toTimestamp())),n}(this.k,t);const n=function(t,e){const n=function(t,e){switch(e){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return Ha()}}(0,e.purpose);return null==n?null:{"goog-listen-tags":n}}(this.k,t);n&&(e.labels=n),this.gr(e)}vr(t){const e={};e.database=Bh(this.k),e.removeTarget=t,this.gr(e)}}class hd extends cd{constructor(t,e,n,s,r,i){super(t,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",e,n,s,i),this.k=r,this.Vr=!1}get Sr(){return this.Vr}start(){this.Vr=!1,this.lastStreamToken=void 0,super.start()}Tr(){this.Vr&&this.Dr([])}Rr(t,e){return this.ir.Qi("Write",t,e)}onMessage(t){if($a(!!t.streamToken),this.lastStreamToken=t.streamToken,this.Vr){this.ur.reset();const e=function(t,e){return t&&t.length>0?($a(void 0!==e),t.map((t=>function(t,e){let n=t.updateTime?Mh(t.updateTime):Mh(e);return n.isEqual(cc.min())&&(n=Mh(e)),new ju(n,t.transformResults||[])}(t,e)))):[]}(t.writeResults,t.commitTime),n=Mh(t.commitTime);return this.listener.Cr(n,e)}return $a(!t.writeResults||0===t.writeResults.length),this.Vr=!0,this.listener.Nr()}kr(){const t={};t.database=Bh(this.k),this.gr(t)}Dr(t){const e={streamToken:this.lastStreamToken,writes:t.map((t=>function(t,e){let n;if(e instanceof Ju)n={update:Hh(t,e.key,e.value)};else if(e instanceof th)n={delete:Fh(t,e.key)};else if(e instanceof Xu)n={update:Hh(t,e.key,e.data),updateMask:nl(e.fieldMask)};else{if(!(e instanceof eh))return Ha();n={verify:Fh(t,e.key)}}return e.fieldTransforms.length>0&&(n.updateTransforms=e.fieldTransforms.map((t=>function(t,e){const n=e.transform;if(n instanceof Du)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof Ou)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof Mu)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof Uu)return{fieldPath:e.field.canonicalString(),increment:n.N};throw Ha()}(0,t)))),e.precondition.isNone||(n.currentDocument=function(t,e){return void 0!==e.updateTime?{updateTime:Ph(t,e.updateTime)}:void 0!==e.exists?{exists:e.exists}:Ha()}(t,e.precondition)),n}(this.k,t)))};this.gr(e)}}class ld extends class{}{constructor(t,e,n,s){super(),this.authCredentials=t,this.appCheckCredentials=e,this.ir=n,this.k=s,this.$r=!1}Fr(){if(this.$r)throw new Ga(za.FAILED_PRECONDITION,"The client has already been terminated.")}Bi(t,e,n){return this.Fr(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([s,r])=>this.ir.Bi(t,e,n,s,r))).catch((t=>{throw"FirebaseError"===t.name?(t.code===za.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),t):new Ga(za.UNKNOWN,t.toString())}))}ji(t,e,n){return this.Fr(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([s,r])=>this.ir.ji(t,e,n,s,r))).catch((t=>{throw"FirebaseError"===t.name?(t.code===za.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),t):new Ga(za.UNKNOWN,t.toString())}))}terminate(){this.$r=!0}}class dd{constructor(t,e){this.asyncQueue=t,this.onlineStateHandler=e,this.state="Unknown",this.Or=0,this.Mr=null,this.Lr=!0}Br(){0===this.Or&&(this.Ur("Unknown"),this.Mr=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.Mr=null,this.qr("Backend didn't respond within 10 seconds."),this.Ur("Offline"),Promise.resolve()))))}Kr(t){"Online"===this.state?this.Ur("Unknown"):(this.Or++,this.Or>=1&&(this.jr(),this.qr(`Connection failed 1 times. Most recent error: ${t.toString()}`),this.Ur("Offline")))}set(t){this.jr(),this.Or=0,"Online"===t&&(this.Lr=!1),this.Ur(t)}Ur(t){t!==this.state&&(this.state=t,this.onlineStateHandler(t))}qr(t){const e=`Could not reach Cloud Firestore backend. ${t}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.Lr?(ja(e),this.Lr=!1):Va("OnlineStateTracker",e)}jr(){null!==this.Mr&&(this.Mr.cancel(),this.Mr=null)}}class fd{constructor(t,e,n,s,r){this.localStore=t,this.datastore=e,this.asyncQueue=n,this.remoteSyncer={},this.Qr=[],this.Wr=new Map,this.Gr=new Set,this.zr=[],this.Hr=r,this.Hr.Ei((t=>{n.enqueueAndForget((async()=>{Ed(this)&&(Va("RemoteStore","Restarting streams for network reachability change."),await async function(t){const e=Ka(t);e.Gr.add(4),await md(e),e.Jr.set("Unknown"),e.Gr.delete(4),await pd(e)}(this))}))})),this.Jr=new dd(n,s)}}async function pd(t){if(Ed(t))for(const e of t.zr)await e(!0)}async function md(t){for(const e of t.zr)await e(!1)}function gd(t,e){const n=Ka(t);n.Wr.has(e.targetId)||(n.Wr.set(e.targetId,e),Td(n)?bd(n):Fd(n).lr()&&vd(n,e))}function yd(t,e){const n=Ka(t),s=Fd(n);n.Wr.delete(e),s.lr()&&wd(n,e),0===n.Wr.size&&(s.lr()?s._r():Ed(n)&&n.Jr.set("Unknown"))}function vd(t,e){t.Yr.X(e.targetId),Fd(t).br(e)}function wd(t,e){t.Yr.X(e),Fd(t).vr(e)}function bd(t){t.Yr=new kh({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),Et:e=>t.Wr.get(e)||null}),Fd(t).start(),t.Jr.Br()}function Td(t){return Ed(t)&&!Fd(t).hr()&&t.Wr.size>0}function Ed(t){return 0===Ka(t).Gr.size}function Id(t){t.Yr=void 0}async function _d(t){t.Wr.forEach(((e,n)=>{vd(t,e)}))}async function Sd(t,e){Id(t),Td(t)?(t.Jr.Kr(e),bd(t)):t.Jr.set("Unknown")}async function kd(t,e,n){if(t.Jr.set("Online"),e instanceof _h&&2===e.state&&e.cause)try{await async function(t,e){const n=e.cause;for(const s of e.targetIds)t.Wr.has(s)&&(await t.remoteSyncer.rejectListen(s,n),t.Wr.delete(s),t.Yr.removeTarget(s))}(t,e)}catch(n){Va("RemoteStore","Failed to remove targets %s: %s ",e.targetIds.join(","),n),await Ad(t,n)}else if(e instanceof Eh?t.Yr.ot(e):e instanceof Ih?t.Yr.dt(e):t.Yr.ut(e),!n.isEqual(cc.min()))try{const e=await Fl(t.localStore);n.compareTo(e)>=0&&await function(t,e){const n=t.Yr.gt(e);return n.targetChanges.forEach(((n,s)=>{if(n.resumeToken.approximateByteSize()>0){const r=t.Wr.get(s);r&&t.Wr.set(s,r.withResumeToken(n.resumeToken,e))}})),n.targetMismatches.forEach((e=>{const n=t.Wr.get(e);if(!n)return;t.Wr.set(e,n.withResumeToken(yc.EMPTY_BYTE_STRING,n.snapshotVersion)),wd(t,e);const s=new _l(n.target,e,1,n.sequenceNumber);vd(t,s)})),t.remoteSyncer.applyRemoteEvent(n)}(t,n)}catch(e){Va("RemoteStore","Failed to raise snapshot:",e),await Ad(t,e)}}async function Ad(t,e,n){if(!Tl(e))throw e;t.Gr.add(1),await md(t),t.Jr.set("Offline"),n||(n=()=>Fl(t.localStore)),t.asyncQueue.enqueueRetryable((async()=>{Va("RemoteStore","Retrying IndexedDB access"),await n(),t.Gr.delete(1),await pd(t)}))}function Cd(t,e){return e().catch((n=>Ad(t,n,e)))}async function Nd(t){const e=Ka(t),n=Vd(e);let s=e.Qr.length>0?e.Qr[e.Qr.length-1].batchId:-1;for(;Rd(e);)try{const t=await Vl(e.localStore,s);if(null===t){0===e.Qr.length&&n._r();break}s=t.batchId,Ld(e,t)}catch(t){await Ad(e,t)}Dd(e)&&Od(e)}function Rd(t){return Ed(t)&&t.Qr.length<10}function Ld(t,e){t.Qr.push(e);const n=Vd(t);n.lr()&&n.Sr&&n.Dr(e.mutations)}function Dd(t){return Ed(t)&&!Vd(t).hr()&&t.Qr.length>0}function Od(t){Vd(t).start()}async function Pd(t){Vd(t).kr()}async function Md(t){const e=Vd(t);for(const n of t.Qr)e.Dr(n.mutations)}async function xd(t,e,n){const s=t.Qr.shift(),r=Il.from(s,e,n);await Cd(t,(()=>t.remoteSyncer.applySuccessfulWrite(r))),await Nd(t)}async function Ud(t,e){e&&Vd(t).Sr&&await async function(t,e){if(function(t){switch(t){default:return Ha();case za.CANCELLED:case za.UNKNOWN:case za.DEADLINE_EXCEEDED:case za.RESOURCE_EXHAUSTED:case za.INTERNAL:case za.UNAVAILABLE:case za.UNAUTHENTICATED:return!1;case za.INVALID_ARGUMENT:case za.NOT_FOUND:case za.ALREADY_EXISTS:case za.PERMISSION_DENIED:case za.FAILED_PRECONDITION:case za.ABORTED:case za.OUT_OF_RANGE:case za.UNIMPLEMENTED:case za.DATA_LOSS:return!0}}(n=e.code)&&n!==za.ABORTED){const n=t.Qr.shift();Vd(t).wr(),await Cd(t,(()=>t.remoteSyncer.rejectFailedWrite(n.batchId,e))),await Nd(t)}var n}(t,e),Dd(t)&&Od(t)}function Fd(t){return t.Xr||(t.Xr=function(t,e,n){const s=Ka(t);return s.Fr(),new ud(e,s.ir,s.authCredentials,s.appCheckCredentials,s.k,n)}(t.datastore,t.asyncQueue,{Di:_d.bind(null,t),Ni:Sd.bind(null,t),Pr:kd.bind(null,t)}),t.zr.push((async e=>{e?(t.Xr.wr(),Td(t)?bd(t):t.Jr.set("Unknown")):(await t.Xr.stop(),Id(t))}))),t.Xr}function Vd(t){return t.Zr||(t.Zr=function(t,e,n){const s=Ka(t);return s.Fr(),new hd(e,s.ir,s.authCredentials,s.appCheckCredentials,s.k,n)}(t.datastore,t.asyncQueue,{Di:Pd.bind(null,t),Ni:Ud.bind(null,t),Nr:Md.bind(null,t),Cr:xd.bind(null,t)}),t.zr.push((async e=>{e?(t.Zr.wr(),await Nd(t)):(await t.Zr.stop(),t.Qr.length>0&&(Va("RemoteStore",`Stopping write stream with ${t.Qr.length} pending writes`),t.Qr=[]))}))),t.Zr}class jd{constructor(t,e,n,s,r){this.asyncQueue=t,this.timerId=e,this.targetTimeMs=n,this.op=s,this.removalCallback=r,this.deferred=new Wa,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((t=>{}))}static createAndSchedule(t,e,n,s,r){const i=Date.now()+n,o=new jd(t,e,i,s,r);return o.start(n),o}start(t){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),t)}skipDelay(){return this.handleDelayElapsed()}cancel(t){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new Ga(za.CANCELLED,"Operation cancelled"+(t?": "+t:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then((t=>this.deferred.resolve(t)))):Promise.resolve()))}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function Bd(t,e){if(ja("AsyncQueue",`${e}: ${t}`),Tl(t))return new Ga(za.UNAVAILABLE,`${e}: ${t}`);throw t}class qd{constructor(t){this.comparator=t?(e,n)=>t(e,n)||Ac.comparator(e.key,n.key):(t,e)=>Ac.comparator(t.key,e.key),this.keyedMap=ph(),this.sortedSet=new oh(this.comparator)}static emptySet(t){return new qd(t.comparator)}has(t){return null!=this.keyedMap.get(t)}get(t){return this.keyedMap.get(t)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(t){const e=this.keyedMap.get(t);return e?this.sortedSet.indexOf(e):-1}get size(){return this.sortedSet.size}forEach(t){this.sortedSet.inorderTraversal(((e,n)=>(t(e),!1)))}add(t){const e=this.delete(t.key);return e.copy(e.keyedMap.insert(t.key,t),e.sortedSet.insert(t,null))}delete(t){const e=this.get(t);return e?this.copy(this.keyedMap.remove(t),this.sortedSet.remove(e)):this}isEqual(t){if(!(t instanceof qd))return!1;if(this.size!==t.size)return!1;const e=this.sortedSet.getIterator(),n=t.sortedSet.getIterator();for(;e.hasNext();){const t=e.getNext().key,s=n.getNext().key;if(!t.isEqual(s))return!1}return!0}toString(){const t=[];return this.forEach((e=>{t.push(e.toString())})),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(t,e){const n=new qd;return n.comparator=this.comparator,n.keyedMap=t,n.sortedSet=e,n}}class Hd{constructor(){this.eo=new oh(Ac.comparator)}track(t){const e=t.doc.key,n=this.eo.get(e);n?0!==t.type&&3===n.type?this.eo=this.eo.insert(e,t):3===t.type&&1!==n.type?this.eo=this.eo.insert(e,{type:n.type,doc:t.doc}):2===t.type&&2===n.type?this.eo=this.eo.insert(e,{type:2,doc:t.doc}):2===t.type&&0===n.type?this.eo=this.eo.insert(e,{type:0,doc:t.doc}):1===t.type&&0===n.type?this.eo=this.eo.remove(e):1===t.type&&2===n.type?this.eo=this.eo.insert(e,{type:1,doc:n.doc}):0===t.type&&1===n.type?this.eo=this.eo.insert(e,{type:2,doc:t.doc}):Ha():this.eo=this.eo.insert(e,t)}no(){const t=[];return this.eo.inorderTraversal(((e,n)=>{t.push(n)})),t}}class $d{constructor(t,e,n,s,r,i,o,a){this.query=t,this.docs=e,this.oldDocs=n,this.docChanges=s,this.mutatedKeys=r,this.fromCache=i,this.syncStateChanged=o,this.excludesMetadataChanges=a}static fromInitialDocuments(t,e,n,s){const r=[];return e.forEach((t=>{r.push({type:0,doc:t})})),new $d(t,e,qd.emptySet(e),r,n,s,!0,!1)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(t){if(!(this.fromCache===t.fromCache&&this.syncStateChanged===t.syncStateChanged&&this.mutatedKeys.isEqual(t.mutatedKeys)&&wu(this.query,t.query)&&this.docs.isEqual(t.docs)&&this.oldDocs.isEqual(t.oldDocs)))return!1;const e=this.docChanges,n=t.docChanges;if(e.length!==n.length)return!1;for(let t=0;tbu(t)),wu),this.onlineState="Unknown",this.io=new Set}}async function Gd(t,e){const n=Ka(t),s=e.query;let r=!1,i=n.queries.get(s);if(i||(r=!0,i=new Kd),r)try{i.so=await n.onListen(s)}catch(t){const n=Bd(t,`Initialization of query '${Tu(e.query)}' failed`);return void e.onError(n)}n.queries.set(s,i),i.listeners.push(e),e.ro(n.onlineState),i.so&&e.oo(i.so)&&Qd(n)}async function Wd(t,e){const n=Ka(t),s=e.query;let r=!1;const i=n.queries.get(s);if(i){const t=i.listeners.indexOf(e);t>=0&&(i.listeners.splice(t,1),r=0===i.listeners.length)}if(r)return n.queries.delete(s),n.onUnlisten(s)}function Jd(t,e){const n=Ka(t);let s=!1;for(const t of e){const e=t.query,r=n.queries.get(e);if(r){for(const e of r.listeners)e.oo(t)&&(s=!0);r.so=t}}s&&Qd(n)}function Xd(t,e,n){const s=Ka(t),r=s.queries.get(e);if(r)for(const t of r.listeners)t.onError(n);s.queries.delete(e)}function Qd(t){t.io.forEach((t=>{t.next()}))}class Yd{constructor(t,e,n){this.query=t,this.ao=e,this.co=!1,this.uo=null,this.onlineState="Unknown",this.options=n||{}}oo(t){if(!this.options.includeMetadataChanges){const e=[];for(const n of t.docChanges)3!==n.type&&e.push(n);t=new $d(t.query,t.docs,t.oldDocs,e,t.mutatedKeys,t.fromCache,t.syncStateChanged,!0)}let e=!1;return this.co?this.ho(t)&&(this.ao.next(t),e=!0):this.lo(t,this.onlineState)&&(this.fo(t),e=!0),this.uo=t,e}onError(t){this.ao.error(t)}ro(t){this.onlineState=t;let e=!1;return this.uo&&!this.co&&this.lo(this.uo,t)&&(this.fo(this.uo),e=!0),e}lo(t,e){if(!t.fromCache)return!0;const n="Offline"!==e;return!(this.options.wo&&n||t.docs.isEmpty()&&"Offline"!==e)}ho(t){if(t.docChanges.length>0)return!0;const e=this.uo&&this.uo.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&!0===this.options.includeMetadataChanges}fo(t){t=$d.fromInitialDocuments(t.query,t.docs,t.mutatedKeys,t.fromCache),this.co=!0,this.ao.next(t)}}class Zd{constructor(t){this.key=t}}class tf{constructor(t){this.key=t}}class ef{constructor(t,e){this.query=t,this.To=e,this.Eo=null,this.current=!1,this.Io=yh(),this.mutatedKeys=yh(),this.Ao=Iu(t),this.Ro=new qd(this.Ao)}get Po(){return this.To}bo(t,e){const n=e?e.vo:new Hd,s=e?e.Ro:this.Ro;let r=e?e.mutatedKeys:this.mutatedKeys,i=s,o=!1;const a=du(this.query)&&s.size===this.query.limit?s.last():null,c=fu(this.query)&&s.size===this.query.limit?s.first():null;if(t.inorderTraversal(((t,e)=>{const u=s.get(t),h=Eu(this.query,e)?e:null,l=!!u&&this.mutatedKeys.has(u.key),d=!!h&&(h.hasLocalMutations||this.mutatedKeys.has(h.key)&&h.hasCommittedMutations);let f=!1;u&&h?u.data.isEqual(h.data)?l!==d&&(n.track({type:3,doc:h}),f=!0):this.Vo(u,h)||(n.track({type:2,doc:h}),f=!0,(a&&this.Ao(h,a)>0||c&&this.Ao(h,c)<0)&&(o=!0)):!u&&h?(n.track({type:0,doc:h}),f=!0):u&&!h&&(n.track({type:1,doc:u}),f=!0,(a||c)&&(o=!0)),f&&(h?(i=i.add(h),r=d?r.add(t):r.delete(t)):(i=i.delete(t),r=r.delete(t)))})),du(this.query)||fu(this.query))for(;i.size>this.query.limit;){const t=du(this.query)?i.last():i.first();i=i.delete(t.key),r=r.delete(t.key),n.track({type:1,doc:t})}return{Ro:i,vo:n,Bn:o,mutatedKeys:r}}Vo(t,e){return t.hasLocalMutations&&e.hasCommittedMutations&&!e.hasLocalMutations}applyChanges(t,e,n){const s=this.Ro;this.Ro=t.Ro,this.mutatedKeys=t.mutatedKeys;const r=t.vo.no();r.sort(((t,e)=>function(t,e){const n=t=>{switch(t){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Ha()}};return n(t)-n(e)}(t.type,e.type)||this.Ao(t.doc,e.doc))),this.So(n);const i=e?this.Do():[],o=0===this.Io.size&&this.current?1:0,a=o!==this.Eo;return this.Eo=o,0!==r.length||a?{snapshot:new $d(this.query,t.Ro,s,r,t.mutatedKeys,0===o,a,!1),Co:i}:{Co:i}}ro(t){return this.current&&"Offline"===t?(this.current=!1,this.applyChanges({Ro:this.Ro,vo:new Hd,mutatedKeys:this.mutatedKeys,Bn:!1},!1)):{Co:[]}}No(t){return!this.To.has(t)&&!!this.Ro.has(t)&&!this.Ro.get(t).hasLocalMutations}So(t){t&&(t.addedDocuments.forEach((t=>this.To=this.To.add(t))),t.modifiedDocuments.forEach((t=>{})),t.removedDocuments.forEach((t=>this.To=this.To.delete(t))),this.current=t.current)}Do(){if(!this.current)return[];const t=this.Io;this.Io=yh(),this.Ro.forEach((t=>{this.No(t.key)&&(this.Io=this.Io.add(t.key))}));const e=[];return t.forEach((t=>{this.Io.has(t)||e.push(new tf(t))})),this.Io.forEach((n=>{t.has(n)||e.push(new Zd(n))})),e}ko(t){this.To=t.zn,this.Io=yh();const e=this.bo(t.documents);return this.applyChanges(e,!0)}xo(){return $d.fromInitialDocuments(this.query,this.Ro,this.mutatedKeys,0===this.Eo)}}class nf{constructor(t,e,n){this.query=t,this.targetId=e,this.view=n}}class sf{constructor(t){this.key=t,this.$o=!1}}class rf{constructor(t,e,n,s,r,i){this.localStore=t,this.remoteStore=e,this.eventManager=n,this.sharedClientState=s,this.currentUser=r,this.maxConcurrentLimboResolutions=i,this.Fo={},this.Oo=new Dl((t=>bu(t)),wu),this.Mo=new Map,this.Lo=new Set,this.Bo=new oh(Ac.comparator),this.Uo=new Map,this.qo=new Hl,this.Ko={},this.jo=new Map,this.Qo=Rl.re(),this.onlineState="Unknown",this.Wo=void 0}get isPrimaryClient(){return!0===this.Wo}}async function of(t,e){const n=function(t){const e=Ka(t);return e.remoteStore.remoteSyncer.applyRemoteEvent=cf.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=Ef.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=hf.bind(null,e),e.Fo.Pr=Jd.bind(null,e.eventManager),e.Fo.zo=Xd.bind(null,e.eventManager),e}(t);let s,r;const i=n.Oo.get(e);if(i)s=i.targetId,n.sharedClientState.addLocalQueryTarget(s),r=i.view.xo();else{const t=await function(t,e){const n=Ka(t);return n.persistence.runTransaction("Allocate target","readwrite",(t=>{let s;return n.He.getTargetData(t,e).next((r=>r?(s=r,bl.resolve(s)):n.He.allocateTargetId(t).next((r=>(s=new _l(e,r,0,t.currentSequenceNumber),n.He.addTargetData(t,s).next((()=>s)))))))})).then((t=>{const s=n.qn.get(t.targetId);return(null===s||t.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(n.qn=n.qn.insert(t.targetId,t),n.Kn.set(e,t.targetId)),t}))}(n.localStore,yu(e)),i=n.sharedClientState.addLocalQueryTarget(t.targetId);s=t.targetId,r=await async function(t,e,n,s){t.Go=(e,n,s)=>async function(t,e,n,s){let r=e.view.bo(n);r.Bn&&(r=await Bl(t.localStore,e.query,!1).then((({documents:t})=>e.view.bo(t,r))));const i=s&&s.targetChanges.get(e.targetId),o=e.view.applyChanges(r,t.isPrimaryClient,i);return yf(t,e.targetId,o.Co),o.snapshot}(t,e,n,s);const r=await Bl(t.localStore,e,!0),i=new ef(e,r.zn),o=i.bo(r.documents),a=Th.createSynthesizedTargetChangeForCurrentChange(n,s&&"Offline"!==t.onlineState),c=i.applyChanges(o,t.isPrimaryClient,a);yf(t,n,c.Co);const u=new nf(e,n,i);return t.Oo.set(e,u),t.Mo.has(n)?t.Mo.get(n).push(e):t.Mo.set(n,[e]),c.snapshot}(n,e,s,"current"===i),n.isPrimaryClient&&gd(n.remoteStore,t)}return r}async function af(t,e){const n=Ka(t),s=n.Oo.get(e),r=n.Mo.get(s.targetId);if(r.length>1)return n.Mo.set(s.targetId,r.filter((t=>!wu(t,e)))),void n.Oo.delete(e);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(s.targetId),n.sharedClientState.isActiveQueryTarget(s.targetId)||await jl(n.localStore,s.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(s.targetId),yd(n.remoteStore,s.targetId),mf(n,s.targetId)})).catch(Ll)):(mf(n,s.targetId),await jl(n.localStore,s.targetId,!0))}async function cf(t,e){const n=Ka(t);try{const t=await function(t,e){const n=Ka(t),s=e.snapshotVersion;let r=n.qn;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(t=>{const i=n.Qn.newChangeBuffer({trackRemovals:!0});r=n.qn;const o=[];e.targetChanges.forEach(((e,i)=>{const a=r.get(i);if(!a)return;o.push(n.He.removeMatchingKeys(t,e.removedDocuments,i).next((()=>n.He.addMatchingKeys(t,e.addedDocuments,i))));const c=e.resumeToken;if(c.approximateByteSize()>0){const u=a.withResumeToken(c,s).withSequenceNumber(t.currentSequenceNumber);r=r.insert(i,u),function(t,e,n){return $a(e.resumeToken.approximateByteSize()>0),0===t.resumeToken.approximateByteSize()||e.snapshotVersion.toMicroseconds()-t.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(a,u,e)&&o.push(n.He.updateTargetData(t,u))}}));let a=dh();if(e.documentUpdates.forEach(((s,r)=>{e.resolvedLimboDocuments.has(s)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(t,s))})),o.push(function(t,e,n,s,r){let i=yh();return n.forEach((t=>i=i.add(t))),e.getEntries(t,i).next((t=>{let i=dh();return n.forEach(((n,o)=>{const a=t.get(n),c=(null==r?void 0:r.get(n))||s;o.isNoDocument()&&o.version.isEqual(cc.min())?(e.removeEntry(n,c),i=i.insert(n,o)):!a.isValidDocument()||o.version.compareTo(a.version)>0||0===o.version.compareTo(a.version)&&a.hasPendingWrites?(e.addEntry(o,c),i=i.insert(n,o)):Va("LocalStore","Ignoring outdated watch update for ",n,". Current version:",a.version," Watch version:",o.version)})),i}))}(t,i,e.documentUpdates,s,void 0).next((t=>{a=t}))),!s.isEqual(cc.min())){const e=n.He.getLastRemoteSnapshotVersion(t).next((e=>n.He.setTargetsMetadata(t,t.currentSequenceNumber,s)));o.push(e)}return bl.waitFor(o).next((()=>i.apply(t))).next((()=>n.Wn.Vn(t,a))).next((()=>a))})).then((t=>(n.qn=r,t)))}(n.localStore,e);e.targetChanges.forEach(((t,e)=>{const s=n.Uo.get(e);s&&($a(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1),t.addedDocuments.size>0?s.$o=!0:t.modifiedDocuments.size>0?$a(s.$o):t.removedDocuments.size>0&&($a(s.$o),s.$o=!1))})),await bf(n,t,e)}catch(t){await Ll(t)}}function uf(t,e,n){const s=Ka(t);if(s.isPrimaryClient&&0===n||!s.isPrimaryClient&&1===n){const t=[];s.Oo.forEach(((n,s)=>{const r=s.view.ro(e);r.snapshot&&t.push(r.snapshot)})),function(t,e){const n=Ka(t);n.onlineState=e;let s=!1;n.queries.forEach(((t,n)=>{for(const t of n.listeners)t.ro(e)&&(s=!0)})),s&&Qd(n)}(s.eventManager,e),t.length&&s.Fo.Pr(t),s.onlineState=e,s.isPrimaryClient&&s.sharedClientState.setOnlineState(e)}}async function hf(t,e,n){const s=Ka(t);s.sharedClientState.updateQueryState(e,"rejected",n);const r=s.Uo.get(e),i=r&&r.key;if(i){let t=new oh(Ac.comparator);t=t.insert(i,Hc.newNoDocument(i,cc.min()));const n=yh().add(i),r=new bh(cc.min(),new Map,new uh(ic),t,n);await cf(s,r),s.Bo=s.Bo.remove(i),s.Uo.delete(e),wf(s)}else await jl(s.localStore,e,!1).then((()=>mf(s,e,n))).catch(Ll)}async function lf(t,e){const n=Ka(t),s=e.batch.batchId;try{const t=await function(t,e){const n=Ka(t);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",(t=>{const s=e.batch.keys(),r=n.Qn.newChangeBuffer({trackRemovals:!0});return function(t,e,n,s){const r=n.batch,i=r.keys();let o=bl.resolve();return i.forEach((t=>{o=o.next((()=>s.getEntry(e,t))).next((e=>{const i=n.docVersions.get(t);$a(null!==i),e.version.compareTo(i)<0&&(r.applyToRemoteDocument(e,n),e.isValidDocument()&&s.addEntry(e,n.commitVersion))}))})),o.next((()=>t.An.removeMutationBatch(e,r)))}(n,t,e,r).next((()=>r.apply(t))).next((()=>n.An.performConsistencyCheck(t))).next((()=>n.Wn.vn(t,s)))}))}(n.localStore,e);pf(n,s,null),ff(n,s),n.sharedClientState.updateMutationState(s,"acknowledged"),await bf(n,t)}catch(t){await Ll(t)}}async function df(t,e,n){const s=Ka(t);try{const t=await function(t,e){const n=Ka(t);return n.persistence.runTransaction("Reject batch","readwrite-primary",(t=>{let s;return n.An.lookupMutationBatch(t,e).next((e=>($a(null!==e),s=e.keys(),n.An.removeMutationBatch(t,e)))).next((()=>n.An.performConsistencyCheck(t))).next((()=>n.Wn.vn(t,s)))}))}(s.localStore,e);pf(s,e,n),ff(s,e),s.sharedClientState.updateMutationState(e,"rejected",n),await bf(s,t)}catch(n){await Ll(n)}}function ff(t,e){(t.jo.get(e)||[]).forEach((t=>{t.resolve()})),t.jo.delete(e)}function pf(t,e,n){const s=Ka(t);let r=s.Ko[s.currentUser.toKey()];if(r){const t=r.get(e);t&&(n?t.reject(n):t.resolve(),r=r.remove(e)),s.Ko[s.currentUser.toKey()]=r}}function mf(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const s of t.Mo.get(e))t.Oo.delete(s),n&&t.Fo.zo(s,n);t.Mo.delete(e),t.isPrimaryClient&&t.qo.us(e).forEach((e=>{t.qo.containsKey(e)||gf(t,e)}))}function gf(t,e){t.Lo.delete(e.path.canonicalString());const n=t.Bo.get(e);null!==n&&(yd(t.remoteStore,n),t.Bo=t.Bo.remove(e),t.Uo.delete(n),wf(t))}function yf(t,e,n){for(const s of n)s instanceof Zd?(t.qo.addReference(s.key,e),vf(t,s)):s instanceof tf?(Va("SyncEngine","Document no longer in limbo: "+s.key),t.qo.removeReference(s.key,e),t.qo.containsKey(s.key)||gf(t,s.key)):Ha()}function vf(t,e){const n=e.key,s=n.path.canonicalString();t.Bo.get(n)||t.Lo.has(s)||(Va("SyncEngine","New document in limbo: "+n),t.Lo.add(s),wf(t))}function wf(t){for(;t.Lo.size>0&&t.Bo.size{o.push(s.Go(a,e,n).then((t=>{if(t){s.isPrimaryClient&&s.sharedClientState.updateQueryState(a.targetId,t.fromCache?"not-current":"current"),r.push(t);const e=Pl.$n(a.targetId,t);i.push(e)}})))})),await Promise.all(o),s.Fo.Pr(r),await async function(t,e){const n=Ka(t);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(t=>bl.forEach(e,(e=>bl.forEach(e.kn,(s=>n.persistence.referenceDelegate.addReference(t,e.targetId,s))).next((()=>bl.forEach(e.xn,(s=>n.persistence.referenceDelegate.removeReference(t,e.targetId,s)))))))))}catch(t){if(!Tl(t))throw t;Va("LocalStore","Failed to update sequence numbers: "+t)}for(const t of e){const e=t.targetId;if(!t.fromCache){const t=n.qn.get(e),s=t.snapshotVersion,r=t.withLastLimboFreeSnapshotVersion(s);n.qn=n.qn.insert(e,r)}}}(s.localStore,i))}async function Tf(t,e){const n=Ka(t);if(!n.currentUser.isEqual(e)){Va("SyncEngine","User change. New user:",e.toKey());const t=await Ul(n.localStore,e);n.currentUser=e,function(t,e){t.jo.forEach((t=>{t.forEach((t=>{t.reject(new Ga(za.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))}))})),t.jo.clear()}(n),n.sharedClientState.handleUserChange(e,t.removedBatchIds,t.addedBatchIds),await bf(n,t.Gn)}}function Ef(t,e){const n=Ka(t),s=n.Uo.get(e);if(s&&s.$o)return yh().add(s.key);{let t=yh();const s=n.Mo.get(e);if(!s)return t;for(const e of s){const s=n.Oo.get(e);t=t.unionWith(s.view.Po)}return t}}function If(t){const e=Ka(t);return e.remoteStore.remoteSyncer.applySuccessfulWrite=lf.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=df.bind(null,e),e}class _f{constructor(){this.synchronizeTabs=!1}async initialize(t){this.k=od(t.databaseInfo.databaseId),this.sharedClientState=this.Jo(t),this.persistence=this.Yo(t),await this.persistence.start(),this.gcScheduler=this.Xo(t),this.localStore=this.Zo(t)}Xo(t){return null}Zo(t){return function(t,e,n,s){return new xl(t,e,n,s)}(this.persistence,new Ml,t.initialUser,this.k)}Yo(t){return new Jl(Ql.ks,this.k)}Jo(t){return new Zl}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class Sf{async initialize(t,e){this.localStore||(this.localStore=t.localStore,this.sharedClientState=t.sharedClientState,this.datastore=this.createDatastore(e),this.remoteStore=this.createRemoteStore(e),this.eventManager=this.createEventManager(e),this.syncEngine=this.createSyncEngine(e,!t.synchronizeTabs),this.sharedClientState.onlineStateHandler=t=>uf(this.syncEngine,t,1),this.remoteStore.remoteSyncer.handleCredentialChange=Tf.bind(null,this.syncEngine),await async function(t,e){const n=Ka(t);e?(n.Gr.delete(2),await pd(n)):e||(n.Gr.add(2),await md(n),n.Jr.set("Unknown"))}(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(t){return new zd}createDatastore(t){const e=od(t.databaseInfo.databaseId),n=(s=t.databaseInfo,new rd(s));var s;return function(t,e,n,s){return new ld(t,e,n,s)}(t.authCredentials,t.appCheckCredentials,n,e)}createRemoteStore(t){return e=this.localStore,n=this.datastore,s=t.asyncQueue,r=t=>uf(this.syncEngine,t,0),i=ed.bt()?new ed:new td,new fd(e,n,s,r,i);var e,n,s,r,i}createSyncEngine(t,e){return function(t,e,n,s,r,i,o){const a=new rf(t,e,n,s,r,i);return o&&(a.Wo=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,t.initialUser,t.maxConcurrentLimboResolutions,e)}terminate(){return async function(t){const e=Ka(t);Va("RemoteStore","RemoteStore shutting down."),e.Gr.add(5),await md(e),e.Hr.shutdown(),e.Jr.set("Unknown")}(this.remoteStore)}}class kf{constructor(t){this.observer=t,this.muted=!1}next(t){this.observer.next&&this.ea(this.observer.next,t)}error(t){this.observer.error?this.ea(this.observer.error,t):console.error("Uncaught Error in snapshot listener:",t)}na(){this.muted=!0}ea(t,e){this.muted||setTimeout((()=>{this.muted||t(e)}),0)}}class Af{constructor(t,e,n,s){this.authCredentials=t,this.appCheckCredentials=e,this.asyncQueue=n,this.databaseInfo=s,this.user=Ma.UNAUTHENTICATED,this.clientId=rc.A(),this.authCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,(async t=>{Va("FirestoreClient","Received user=",t.uid),await this.authCredentialListener(t),this.user=t})),this.appCheckCredentials.start(n,(()=>Promise.resolve()))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(t){this.authCredentialListener=t}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new Ga(za.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const t=new Wa;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),t.resolve()}catch(e){const n=Bd(e,"Failed to shutdown persistence");t.reject(n)}})),t.promise}}async function Cf(t,e){t.asyncQueue.verifyOperationInProgress();const n=await async function(t){return t.offlineComponents||(Va("FirestoreClient","Using default OfflineComponentProvider"),await async function(t,e){t.asyncQueue.verifyOperationInProgress(),Va("FirestoreClient","Initializing OfflineComponentProvider");const n=await t.getConfiguration();await e.initialize(n);let s=n.initialUser;t.setCredentialChangeListener((async t=>{s.isEqual(t)||(await Ul(e.localStore,t),s=t)})),e.persistence.setDatabaseDeletedListener((()=>t.terminate())),t.offlineComponents=e}(t,new _f)),t.offlineComponents}(t);Va("FirestoreClient","Initializing OnlineComponentProvider");const s=await t.getConfiguration();await e.initialize(n,s),t.setCredentialChangeListener((t=>async function(t,e){const n=Ka(t);n.asyncQueue.verifyOperationInProgress(),Va("RemoteStore","RemoteStore received new credentials");const s=Ed(n);n.Gr.add(3),await md(n),s&&n.Jr.set("Unknown"),await n.remoteSyncer.handleCredentialChange(e),n.Gr.delete(3),await pd(n)}(e.remoteStore,t))),t.onlineComponents=e}async function Nf(t){return t.onlineComponents||(Va("FirestoreClient","Using default OnlineComponentProvider"),await Cf(t,new Sf)),t.onlineComponents}async function Rf(t){const e=await Nf(t),n=e.eventManager;return n.onListen=of.bind(null,e.syncEngine),n.onUnlisten=af.bind(null,e.syncEngine),n}class Lf{constructor(t,e,n,s,r,i,o,a){this.databaseId=t,this.appId=e,this.persistenceKey=n,this.host=s,this.ssl=r,this.forceLongPolling=i,this.autoDetectLongPolling=o,this.useFetchStreams=a}}class Df{constructor(t,e){this.projectId=t,this.database=e||"(default)"}get isDefaultDatabase(){return"(default)"===this.database}isEqual(t){return t instanceof Df&&t.projectId===this.projectId&&t.database===this.database}}const Of=new Map;function Pf(t,e,n){if(!n)throw new Ga(za.INVALID_ARGUMENT,`Function ${t}() cannot be called with an empty ${e}.`)}function Mf(t){if(!Ac.isDocumentKey(t))throw new Ga(za.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`)}function xf(t){if(Ac.isDocumentKey(t))throw new Ga(za.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`)}function Uf(t){if(void 0===t)return"undefined";if(null===t)return"null";if("string"==typeof t)return t.length>20&&(t=`${t.substring(0,20)}...`),JSON.stringify(t);if("number"==typeof t||"boolean"==typeof t)return""+t;if("object"==typeof t){if(t instanceof Array)return"an array";{const e=function(t){return t.constructor?t.constructor.name:null}(t);return e?`a custom ${e} object`:"an object"}}return"function"==typeof t?"a function":Ha()}function Ff(t,e){if("_delegate"in t&&(t=t._delegate),!(t instanceof e)){if(e.name===t.constructor.name)throw new Ga(za.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=Uf(t);throw new Ga(za.INVALID_ARGUMENT,`Expected type '${e.name}', but it was: ${n}`)}}return t}class Vf{constructor(t){var e;if(void 0===t.host){if(void 0!==t.ssl)throw new Ga(za.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=t.host,this.ssl=null===(e=t.ssl)||void 0===e||e;if(this.credentials=t.credentials,this.ignoreUndefinedProperties=!!t.ignoreUndefinedProperties,void 0===t.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==t.cacheSizeBytes&&t.cacheSizeBytes<1048576)throw new Ga(za.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=t.cacheSizeBytes}this.experimentalForceLongPolling=!!t.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!t.experimentalAutoDetectLongPolling,this.useFetchStreams=!!t.useFetchStreams,function(t,e,n,s){if(!0===e&&!0===s)throw new Ga(za.INVALID_ARGUMENT,"experimentalForceLongPolling and experimentalAutoDetectLongPolling cannot be used together.")}(0,t.experimentalForceLongPolling,0,t.experimentalAutoDetectLongPolling)}isEqual(t){return this.host===t.host&&this.ssl===t.ssl&&this.credentials===t.credentials&&this.cacheSizeBytes===t.cacheSizeBytes&&this.experimentalForceLongPolling===t.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===t.experimentalAutoDetectLongPolling&&this.ignoreUndefinedProperties===t.ignoreUndefinedProperties&&this.useFetchStreams===t.useFetchStreams}}class jf{constructor(t,e,n){this._authCredentials=e,this._appCheckCredentials=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Vf({}),this._settingsFrozen=!1,t instanceof Df?this._databaseId=t:(this._app=t,this._databaseId=function(t){if(!Object.prototype.hasOwnProperty.apply(t.options,["projectId"]))throw new Ga(za.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Df(t.options.projectId)}(t))}get app(){if(!this._app)throw new Ga(za.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(t){if(this._settingsFrozen)throw new Ga(za.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 Vf(t),void 0!==t.credentials&&(this._authCredentials=function(t){if(!t)return new Xa;switch(t.type){case"gapi":const e=t.client;return $a(!("object"!=typeof e||null===e||!e.auth||!e.auth.getAuthHeaderValueForFirstParty)),new Za(e,t.sessionIndex||"0",t.iamToken||null);case"provider":return t.client;default:throw new Ga(za.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(t.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(t){const e=Of.get(t);e&&(Va("ComponentProvider","Removing Datastore"),Of.delete(t),e.terminate())}(this),Promise.resolve()}}class Bf{constructor(t,e,n){this.converter=e,this._key=n,this.type="document",this.firestore=t}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Hf(this.firestore,this.converter,this._key.path.popLast())}withConverter(t){return new Bf(this.firestore,t,this._key)}}class qf{constructor(t,e,n){this.converter=e,this._query=n,this.type="query",this.firestore=t}withConverter(t){return new qf(this.firestore,t,this._query)}}class Hf extends qf{constructor(t,e,n){super(t,e,lu(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const t=this._path.popLast();return t.isEmpty()?null:new Bf(this.firestore,null,new Ac(t))}withConverter(t){return new Hf(this.firestore,t,this._path)}}function $f(t,e,...n){if(t=b(t),1===arguments.length&&(e=rc.A()),Pf("doc","path",e),t instanceof jf){const s=fc.fromString(e,...n);return Mf(s),new Bf(t,null,new Ac(s))}{if(!(t instanceof Bf||t instanceof Hf))throw new Ga(za.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const s=t._path.child(fc.fromString(e,...n));return Mf(s),new Bf(t.firestore,t instanceof Hf?t.converter:null,new Ac(s))}}class Kf{constructor(){this.ma=Promise.resolve(),this.ga=[],this.ya=!1,this.pa=[],this.Ta=null,this.Ea=!1,this.Ia=!1,this.Aa=[],this.ur=new ad(this,"async_queue_retry"),this.Ra=()=>{const t=id();t&&Va("AsyncQueue","Visibility state changed to "+t.visibilityState),this.ur.er()};const t=id();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.Ra)}get isShuttingDown(){return this.ya}enqueueAndForget(t){this.enqueue(t)}enqueueAndForgetEvenWhileRestricted(t){this.Pa(),this.ba(t)}enterRestrictedMode(t){if(!this.ya){this.ya=!0,this.Ia=t||!1;const e=id();e&&"function"==typeof e.removeEventListener&&e.removeEventListener("visibilitychange",this.Ra)}}enqueue(t){if(this.Pa(),this.ya)return new Promise((()=>{}));const e=new Wa;return this.ba((()=>this.ya&&this.Ia?Promise.resolve():(t().then(e.resolve,e.reject),e.promise))).then((()=>e.promise))}enqueueRetryable(t){this.enqueueAndForget((()=>(this.ga.push(t),this.va())))}async va(){if(0!==this.ga.length){try{await this.ga[0](),this.ga.shift(),this.ur.reset()}catch(t){if(!Tl(t))throw t;Va("AsyncQueue","Operation failed with retryable error: "+t)}this.ga.length>0&&this.ur.Zi((()=>this.va()))}}ba(t){const e=this.ma.then((()=>(this.Ea=!0,t().catch((t=>{this.Ta=t,this.Ea=!1;const e=function(t){let e=t.message||"";return t.stack&&(e=t.stack.includes(t.message)?t.stack:t.message+"\n"+t.stack),e}(t);throw ja("INTERNAL UNHANDLED ERROR: ",e),t})).then((t=>(this.Ea=!1,t))))));return this.ma=e,e}enqueueAfterDelay(t,e,n){this.Pa(),this.Aa.indexOf(t)>-1&&(e=0);const s=jd.createAndSchedule(this,t,e,n,(t=>this.Va(t)));return this.pa.push(s),s}Pa(){this.Ta&&Ha()}verifyOperationInProgress(){}async Sa(){let t;do{t=this.ma,await t}while(t!==this.ma)}Da(t){for(const e of this.pa)if(e.timerId===t)return!0;return!1}Ca(t){return this.Sa().then((()=>{this.pa.sort(((t,e)=>t.targetTimeMs-e.targetTimeMs));for(const e of this.pa)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Sa()}))}Na(t){this.Aa.push(t)}Va(t){const e=this.pa.indexOf(t);this.pa.splice(e,1)}}function zf(t){return function(t,e){if("object"!=typeof t||null===t)return!1;const n=t;for(const t of["next","error","complete"])if(t in n&&"function"==typeof n[t])return!0;return!1}(t)}class Gf extends jf{constructor(t,e,n){super(t,e,n),this.type="firestore",this._queue=new Kf,this._persistenceKey="name"in t?t.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||Jf(this),this._firestoreClient.terminate()}}function Wf(t){return t._firestoreClient||Jf(t),t._firestoreClient.verifyNotTerminated(),t._firestoreClient}function Jf(t){var e;const n=t._freezeSettings(),s=function(t,e,n,s){return new Lf(t,e,n,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,s.useFetchStreams)}(t._databaseId,(null===(e=t._app)||void 0===e?void 0:e.options.appId)||"",t._persistenceKey,n);t._firestoreClient=new Af(t._authCredentials,t._appCheckCredentials,t._queue,s)}class Xf{constructor(...t){for(let e=0;e90)throw new Ga(za.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new Ga(za.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this._long=e}get latitude(){return this._lat}get longitude(){return this._long}isEqual(t){return this._lat===t._lat&&this._long===t._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(t){return ic(this._lat,t._lat)||ic(this._long,t._long)}}const tp=/^__.*__$/;class ep{constructor(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}toMutation(t,e){return null!==this.fieldMask?new Xu(t,this.data,this.fieldMask,e,this.fieldTransforms):new Ju(t,this.data,e,this.fieldTransforms)}}function np(t){switch(t){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw Ha()}}class sp{constructor(t,e,n,s,r,i){this.settings=t,this.databaseId=e,this.k=n,this.ignoreUndefinedProperties=s,void 0===r&&this.ka(),this.fieldTransforms=r||[],this.fieldMask=i||[]}get path(){return this.settings.path}get xa(){return this.settings.xa}$a(t){return new sp(Object.assign(Object.assign({},this.settings),t),this.databaseId,this.k,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Fa(t){var e;const n=null===(e=this.path)||void 0===e?void 0:e.child(t),s=this.$a({path:n,Oa:!1});return s.Ma(t),s}La(t){var e;const n=null===(e=this.path)||void 0===e?void 0:e.child(t),s=this.$a({path:n,Oa:!1});return s.ka(),s}Ba(t){return this.$a({path:void 0,Oa:!0})}Ua(t){return pp(t,this.settings.methodName,this.settings.qa||!1,this.path,this.settings.Ka)}contains(t){return void 0!==this.fieldMask.find((e=>t.isPrefixOf(e)))||void 0!==this.fieldTransforms.find((e=>t.isPrefixOf(e.field)))}ka(){if(this.path)for(let t=0;tc.covers(t.field)))}else c=null,u=o.fieldTransforms;return new ep(new Bc(a),c,u)}function ap(t,e){if(up(t=b(t)))return hp("Unsupported field value:",e,t),cp(t,e);if(t instanceof Yf)return function(t,e){if(!np(e.xa))throw e.Ua(`${t._methodName}() can only be used with update() and set()`);if(!e.path)throw e.Ua(`${t._methodName}() is not currently supported inside arrays`);const n=t._toFieldTransform(e);n&&e.fieldTransforms.push(n)}(t,e),null;if(void 0===t&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),t instanceof Array){if(e.settings.Oa&&4!==e.xa)throw e.Ua("Nested arrays are not supported");return function(t,e){const n=[];let s=0;for(const r of t){let t=ap(r,e.Ba(s));null==t&&(t={nullValue:"NULL_VALUE"}),n.push(t),s++}return{arrayValue:{values:n}}}(t,e)}return function(t,e){if(null===(t=b(t)))return{nullValue:"NULL_VALUE"};if("number"==typeof t)return Au(e.k,t);if("boolean"==typeof t)return{booleanValue:t};if("string"==typeof t)return{stringValue:t};if(t instanceof Date){const n=ac.fromDate(t);return{timestampValue:Dh(e.k,n)}}if(t instanceof ac){const n=new ac(t.seconds,1e3*Math.floor(t.nanoseconds/1e3));return{timestampValue:Dh(e.k,n)}}if(t instanceof Zf)return{geoPointValue:{latitude:t.latitude,longitude:t.longitude}};if(t instanceof Qf)return{bytesValue:Oh(e.k,t._byteString)};if(t instanceof Bf){const n=e.databaseId,s=t.firestore._databaseId;if(!s.isEqual(n))throw e.Ua(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:xh(t.firestore._databaseId||e.databaseId,t._key.path)}}throw e.Ua(`Unsupported field value: ${Uf(t)}`)}(t,e)}function cp(t,e){const n={};return lc(t)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):hc(t,((t,s)=>{const r=ap(s,e.Fa(t));null!=r&&(n[t]=r)})),{mapValue:{fields:n}}}function up(t){return!("object"!=typeof t||null===t||t instanceof Array||t instanceof Date||t instanceof ac||t instanceof Zf||t instanceof Qf||t instanceof Bf||t instanceof Yf)}function hp(t,e,n){if(!up(n)||!function(t){return"object"==typeof t&&null!==t&&(Object.getPrototypeOf(t)===Object.prototype||null===Object.getPrototypeOf(t))}(n)){const s=Uf(n);throw"an object"===s?e.Ua(t+" a custom object"):e.Ua(t+" "+s)}}function lp(t,e,n){if((e=b(e))instanceof Xf)return e._internalPath;if("string"==typeof e)return fp(t,e);throw pp("Field path arguments must be of type string or FieldPath.",t,!1,void 0,n)}const dp=new RegExp("[~\\*/\\[\\]]");function fp(t,e,n){if(e.search(dp)>=0)throw pp(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,n);try{return new Xf(...e.split("."))._internalPath}catch(s){throw pp(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,n)}}function pp(t,e,n,s,r){const i=s&&!s.isEmpty(),o=void 0!==r;let a=`Function ${e}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(i||o)&&(c+=" (found",i&&(c+=` in field ${s}`),o&&(c+=` in document ${r}`),c+=")"),new Ga(za.INVALID_ARGUMENT,a+t+c)}function mp(t,e){return t.some((t=>t.isEqual(e)))}class gp{constructor(t,e,n,s,r){this._firestore=t,this._userDataWriter=e,this._key=n,this._document=s,this._converter=r}get id(){return this._key.path.lastSegment()}get ref(){return new Bf(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const t=new yp(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(t)}return this._userDataWriter.convertValue(this._document.data.value)}}get(t){if(this._document){const e=this._document.data.field(vp("DocumentSnapshot.get",t));if(null!==e)return this._userDataWriter.convertValue(e)}}}class yp extends gp{data(){return super.data()}}function vp(t,e){return"string"==typeof e?fp(t,e):e instanceof Xf?e._internalPath:e._delegate._internalPath}class wp{constructor(t,e){this.hasPendingWrites=t,this.fromCache=e}isEqual(t){return this.hasPendingWrites===t.hasPendingWrites&&this.fromCache===t.fromCache}}class bp extends gp{constructor(t,e,n,s,r,i){super(t,e,n,s,i),this._firestore=t,this._firestoreImpl=t,this.metadata=r}exists(){return super.exists()}data(t={}){if(this._document){if(this._converter){const e=new Tp(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(e,t)}return this._userDataWriter.convertValue(this._document.data.value,t.serverTimestamps)}}get(t,e={}){if(this._document){const n=this._document.data.field(vp("DocumentSnapshot.get",t));if(null!==n)return this._userDataWriter.convertValue(n,e.serverTimestamps)}}}class Tp extends bp{data(t={}){return super.data(t)}}class Ep{constructor(t,e,n,s){this._firestore=t,this._userDataWriter=e,this._snapshot=s,this.metadata=new wp(s.hasPendingWrites,s.fromCache),this.query=n}get docs(){const t=[];return this.forEach((e=>t.push(e))),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,e){this._snapshot.docs.forEach((n=>{t.call(e,new Tp(this._firestore,this._userDataWriter,n.key,n,new wp(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(t={}){const e=!!t.includeMetadataChanges;if(e&&this._snapshot.excludesMetadataChanges)throw new Ga(za.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=function(t,e){if(t._snapshot.oldDocs.isEmpty()){let e=0;return t._snapshot.docChanges.map((n=>({type:"added",doc:new Tp(t._firestore,t._userDataWriter,n.doc.key,n.doc,new wp(t._snapshot.mutatedKeys.has(n.doc.key),t._snapshot.fromCache),t.query.converter),oldIndex:-1,newIndex:e++})))}{let n=t._snapshot.oldDocs;return t._snapshot.docChanges.filter((t=>e||3!==t.type)).map((e=>{const s=new Tp(t._firestore,t._userDataWriter,e.doc.key,e.doc,new wp(t._snapshot.mutatedKeys.has(e.doc.key),t._snapshot.fromCache),t.query.converter);let r=-1,i=-1;return 0!==e.type&&(r=n.indexOf(e.doc.key),n=n.delete(e.doc.key)),1!==e.type&&(n=n.add(e.doc),i=n.indexOf(e.doc.key)),{type:Ip(e.type),doc:s,oldIndex:r,newIndex:i}}))}}(this,e),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges}}function Ip(t){switch(t){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Ha()}}class _p{}class Sp extends _p{constructor(t,e){super(),this.Ga=t,this.Ja=e,this.type="orderBy"}_apply(t){const e=function(t,e,n){if(null!==t.startAt)throw new Ga(za.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==t.endAt)throw new Ga(za.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");const s=new ou(e,n);return function(t,e){if(null===pu(t)){const n=mu(t);null!==n&&function(t,e,n){if(!n.isEqual(e))throw new Ga(za.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}(0,n,e.field)}}(t,s),s}(t._query,this.Ga,this.Ja);return new qf(t.firestore,t.converter,function(t,e){const n=t.explicitOrderBy.concat([e]);return new hu(t.path,t.collectionGroup,n,t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt)}(t._query,e))}}class kp extends _p{constructor(t,e,n){super(),this.type=t,this.Ya=e,this.Xa=n}_apply(t){return new qf(t.firestore,t.converter,vu(t._query,this.Ya,this.Xa))}}class Ap extends class{convertValue(t,e="none"){switch(Cc(t)){case 0:return null;case 1:return t.booleanValue;case 2:return bc(t.integerValue||t.doubleValue);case 3:return this.convertTimestamp(t.timestampValue);case 4:return this.convertServerTimestamp(t,e);case 5:return t.stringValue;case 6:return this.convertBytes(Tc(t.bytesValue));case 7:return this.convertReference(t.referenceValue);case 8:return this.convertGeoPoint(t.geoPointValue);case 9:return this.convertArray(t.arrayValue,e);case 10:return this.convertObject(t.mapValue,e);default:throw Ha()}}convertObject(t,e){const n={};return hc(t.fields,((t,s)=>{n[t]=this.convertValue(s,e)})),n}convertGeoPoint(t){return new Zf(bc(t.latitude),bc(t.longitude))}convertArray(t,e){return(t.values||[]).map((t=>this.convertValue(t,e)))}convertServerTimestamp(t,e){switch(e){case"previous":const n=Ic(t);return null==n?null:this.convertValue(n,e);case"estimate":return this.convertTimestamp(_c(t));default:return null}}convertTimestamp(t){const e=wc(t);return new ac(e.seconds,e.nanos)}convertDocumentKey(t,e){const n=fc.fromString(t);$a(sl(n));const s=new Df(n.get(1),n.get(3)),r=new Ac(n.popFirst(5));return s.isEqual(e)||ja(`Document ${r} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`),r}}{constructor(t){super(),this.firestore=t}convertBytes(t){return new Qf(t)}convertReference(t){const e=this.convertDocumentKey(t,this.firestore._databaseId);return new Bf(this.firestore,null,e)}}function Cp(t,e){return function(t,e){const n=new Wa;return t.asyncQueue.enqueueAndForget((async()=>async function(t,e,n){const s=If(t);try{const t=await function(t,e){const n=Ka(t),s=ac.now(),r=e.reduce(((t,e)=>t.add(e.key)),yh());let i;return n.persistence.runTransaction("Locally write mutations","readwrite",(t=>n.Wn.vn(t,r).next((r=>{i=r;const o=[];for(const t of e){const e=zu(t,i.get(t.key));null!=e&&o.push(new Xu(t.key,e,qc(e.value.mapValue),Bu.exists(!0)))}return n.An.addMutationBatch(t,s,o,e)})))).then((t=>(t.applyToLocalDocumentSet(i),{batchId:t.batchId,changes:i})))}(s.localStore,e);s.sharedClientState.addPendingMutation(t.batchId),function(t,e,n){let s=t.Ko[t.currentUser.toKey()];s||(s=new oh(ic)),s=s.insert(e,n),t.Ko[t.currentUser.toKey()]=s}(s,t.batchId,n),await bf(s,t.changes),await Nd(s.remoteStore)}catch(t){const e=Bd(t,"Failed to persist write");n.reject(e)}}(await function(t){return Nf(t).then((t=>t.syncEngine))}(t),e,n))),n.promise}(Wf(t),e)}function Np(t,e,n){const s=n.docs.get(e._key),r=new Ap(t);return new bp(t,r,e._key,s,new wp(n.hasPendingWrites,n.fromCache),e.converter)}!function(t,e=!0){xa="9.6.1",B(new T("firestore",((t,{options:n})=>{const s=t.getProvider("app").getImmediate(),r=new Gf(s,new Qa(t.getProvider("auth-internal")),new ec(t.getProvider("app-check-internal")));return n=Object.assign({useFetchStreams:e},n),r._setSettings(n),r}),"PUBLIC")),G(Pa,"3.4.1",t),G(Pa,"3.4.1","esm2017")}();const Rp=document.querySelector("body"),Lp=document.querySelector(".saveStats"),Dp=document.querySelector(".profile>.routs>.signUp"),Op=document.querySelector(".windowTop>.options>.signupBtn"),Pp=document.querySelector(".profileBtn"),Mp=document.querySelector(".profile"),xp=document.querySelectorAll(".options>.close"),Up=document.querySelectorAll(".windowTop>.move"),Fp=document.querySelector(".settingsBtn"),Vp=document.querySelector(".settings"),jp=document.querySelector(".themeSelector"),Bp=document.querySelector(".profile>.routs"),qp=document.querySelector(".text"),Hp=document.querySelector(".stats"),$p=document.querySelector(".containerStats>.speed"),Kp=document.querySelector(".loginBtn"),zp=document.querySelector(".profile>.routs>.signIn"),Gp=document.querySelector(".updateBtn"),Wp=document.querySelector(".profile>.routs>.update"),Jp=document.querySelector(".logoutBtn"),Xp=document.querySelector(".info"),Qp=document.querySelector(".loader"),Yp=(document.querySelector(".options"),document.querySelector(".leaderBoard")),Zp=document.querySelector(".leaderBoard>.content"),tm=document.querySelector(".leaderBoardBtn"),em=document.querySelector(".container>.info"),nm=document.querySelector(".username"),sm=document.querySelector(".textOptions"),rm=document.querySelector(".nextBtn"),im=document.querySelector(".infoPopup"),om=document.querySelector(".mpBtn"),am=document.querySelector(".mpContainer"),cm=document.querySelector(".joinRoom"),um=document.querySelector(".createRoom"),hm=document.querySelector(".playArea"),lm=document.querySelector(".roomHeader"),dm=document.querySelector(".copyRoomId"),fm=document.querySelector("span.roomId");function pm(t,e){if(e){let n=`${t}${e.userName}${e.speed}`,s=document.createElement("li");s.innerHTML=n,s.classList.add("leaderBoardListItem"),Zp.appendChild(s)}}const mm=function(t=z()){return q(t,"firestore").getImmediate()}(Qt),gm=async()=>{let t=Es(),e=t.currentUser&&t.currentUser.uid;if(e){const t=$f(mm,`scores/${e}`);let n=t&&await function(t){t=Ff(t,Bf);const e=Ff(t.firestore,Gf);return function(t,e,n={}){const s=new Wa;return t.asyncQueue.enqueueAndForget((async()=>function(t,e,n,s,r){const i=new kf({next:i=>{e.enqueueAndForget((()=>Wd(t,o)));const a=i.docs.has(n);!a&&i.fromCache?r.reject(new Ga(za.UNAVAILABLE,"Failed to get document because the client is offline.")):a&&i.fromCache&&s&&"server"===s.source?r.reject(new Ga(za.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.)')):r.resolve(i)},error:t=>r.reject(t)}),o=new Yd(lu(n.path),i,{includeMetadataChanges:!0,wo:!0});return Gd(t,o)}(await Rf(t),t.asyncQueue,e,n,s))),s.promise}(Wf(e),t._key).then((n=>Np(e,t,n)))}(t);return n.exists()?n.data():null}return null},ym=t=>{(function(t,e,n){t=Ff(t,Bf);const s=Ff(t.firestore,Gf),r=function(t,e,n){let s;return s=t?n&&(n.merge||n.mergeFields)?t.toFirestore(e,n):t.toFirestore(e):e,s}(t.converter,e,n);return Cp(s,[op(ip(s),"setDoc",t._key,r,null!==t.converter,n).toMutation(t._key,Bu.none())])})($f(mm,`scores/${t.uId}`),t,{merge:!0}).then(console.log("added successfully")).catch((t=>console.error("I got an error",t)))};let vm;const wm="user.data";async function bm(){return navigator.onLine?await gm():JSON.parse(localStorage.getItem(wm))}function Tm(){return JSON.parse(localStorage.getItem(wm))}function Em(t){return localStorage.setItem(wm,JSON.stringify(t)),t}function Im(t){return localStorage.setItem(wm,JSON.stringify(t)),ym(t),t}var _m=n(187),Sm=n(58);const km="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Am(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||Sm))return new XMLHttpRequest}catch(t){}if(!e)try{return new(km[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}function Cm(t,...e){return e.reduce(((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e)),{})}const Nm=setTimeout,Rm=clearTimeout;function Lm(t,e){e.useNativeTimers?(t.setTimeoutFn=Nm.bind(km),t.clearTimeoutFn=Rm.bind(km)):(t.setTimeoutFn=setTimeout.bind(km),t.clearTimeoutFn=clearTimeout.bind(km))}var Dm=n(63);const Om=Object.create(null);Om.open="0",Om.close="1",Om.ping="2",Om.pong="3",Om.message="4",Om.upgrade="5",Om.noop="6";const Pm=Object.create(null);Object.keys(Om).forEach((t=>{Pm[Om[t]]=t}));const Mm={type:"error",data:"parser error"},xm="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Um="function"==typeof ArrayBuffer,Fm=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+t)},n.readAsDataURL(t)},Vm=({type:t,data:e},n,s)=>{return xm&&e instanceof Blob?n?s(e):Fm(e,s):Um&&(e instanceof ArrayBuffer||(r=e,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer))?n?s(e):Fm(new Blob([e]),s):s(Om[t]+(e||""));var r};for(var jm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Bm="undefined"==typeof Uint8Array?[]:new Uint8Array(256),qm=0;qm{if(Hm){const n=function(t){var e,n,s,r,i,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);var u=new ArrayBuffer(o),h=new Uint8Array(u);for(e=0;e>4,h[c++]=(15&s)<<4|r>>2,h[c++]=(3&r)<<6|63&i;return u}(t);return Km(n,e)}return{base64:!0,data:t}},Km=(t,e)=>"blob"===e&&t instanceof ArrayBuffer?new Blob([t]):t,zm=(t,e)=>{if("string"!=typeof t)return{type:"message",data:Km(t,e)};const n=t.charAt(0);return"b"===n?{type:"message",data:$m(t.substring(1),e)}:Pm[n]?t.length>1?{type:Pm[n],data:t.substring(1)}:{type:Pm[n]}:Mm},Gm=String.fromCharCode(30);class Wm extends Dm.Q{constructor(t){super(),this.writable=!1,Lm(this,t),this.opts=t,this.query=t.query,this.readyState="",this.socket=t.socket}onError(t,e){const n=new Error(t);return n.type="TransportError",n.description=e,super.emit("error",n),this}open(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emit("open")}onData(t){const e=zm(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emit("packet",t)}onClose(){this.readyState="closed",super.emit("close")}}var Jm=n(281),Xm=n(830);class Qm extends Wm{constructor(){super(...arguments),this.polling=!1}get name(){return"polling"}doOpen(){this.poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.polling||!this.writable){let t=0;this.polling&&(t++,this.once("pollComplete",(function(){--t||e()}))),this.writable||(t++,this.once("drain",(function(){--t||e()})))}else e()}poll(){this.polling=!0,this.doPoll(),this.emit("poll")}onData(t){((t,e)=>{const n=t.split(Gm),s=[];for(let t=0;t{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose(),!1;this.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const n=t.length,s=new Array(n);let r=0;t.forEach(((t,i)=>{Vm(t,!1,(t=>{s[i]=t,++r===n&&e(s.join(Gm))}))}))})(t,(t=>{this.doWrite(t,(()=>{this.writable=!0,this.emit("drain")}))}))}uri(){let t=this.query||{};const e=this.opts.secure?"https":"http";let n="";!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Jm()),this.supportsBinary||t.sid||(t.b64=1),this.opts.port&&("https"===e&&443!==Number(this.opts.port)||"http"===e&&80!==Number(this.opts.port))&&(n=":"+this.opts.port);const s=Xm.encode(t);return e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+n+this.opts.path+(s.length?"?"+s:"")}}function Ym(){}const Zm=null!=new Am({xdomain:!1}).responseType;class tg extends Dm.Q{constructor(t,e){super(),Lm(this,e),this.opts=e,this.method=e.method||"GET",this.uri=t,this.async=!1!==e.async,this.data=void 0!==e.data?e.data:null,this.create()}create(){const t=Cm(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd,t.xscheme=!!this.opts.xs;const e=this.xhr=new Am(t);try{e.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0);for(let t in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(t)&&e.setRequestHeader(t,this.opts.extraHeaders[t])}}catch(t){}if("POST"===this.method)try{e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(e.timeout=this.opts.requestTimeout),e.onreadystatechange=()=>{4===e.readyState&&(200===e.status||1223===e.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof e.status?e.status:0)}),0))},e.send(this.data)}catch(t){return void this.setTimeoutFn((()=>{this.onError(t)}),0)}"undefined"!=typeof document&&(this.index=tg.requestsCount++,tg.requests[this.index]=this)}onSuccess(){this.emit("success"),this.cleanup()}onData(t){this.emit("data",t),this.onSuccess()}onError(t){this.emit("error",t),this.cleanup(!0)}cleanup(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Ym,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete tg.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;null!==t&&this.onData(t)}abort(){this.cleanup()}}function eg(){for(let t in tg.requests)tg.requests.hasOwnProperty(t)&&tg.requests[t].abort()}tg.requestsCount=0,tg.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",eg):"function"==typeof addEventListener&&addEventListener("onpagehide"in km?"pagehide":"unload",eg,!1));const ng="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),sg=km.WebSocket||km.MozWebSocket,rg="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class ig extends Wm{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),e=this.opts.protocols,n=rg?{}:Cm(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=rg?new sg(t,e,n):e?new sg(t,e):new sg(t)}catch(t){return this.emit("error",t)}this.ws.binaryType=this.socket.binaryType||"arraybuffer",this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=this.onClose.bind(this),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e{try{this.ws.send(t)}catch(t){}s&&ng((()=>{this.writable=!0,this.emit("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let t=this.query||{};const e=this.opts.secure?"wss":"ws";let n="";this.opts.port&&("wss"===e&&443!==Number(this.opts.port)||"ws"===e&&80!==Number(this.opts.port))&&(n=":"+this.opts.port),this.opts.timestampRequests&&(t[this.opts.timestampParam]=Jm()),this.supportsBinary||(t.b64=1);const s=Xm.encode(t);return e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+n+this.opts.path+(s.length?"?"+s:"")}check(){return!(!sg||"__initialize"in sg&&this.name===ig.prototype.name)}}const og={websocket:ig,polling:class extends Qm{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port,this.xs=t.secure!==e}const e=t&&t.forceBase64;this.supportsBinary=Zm&&!e}request(t={}){return Object.assign(t,{xd:this.xd,xs:this.xs},this.opts),new tg(this.uri(),t)}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(t=>{this.onError("xhr post error",t)}))}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t=>{this.onError("xhr poll error",t)})),this.pollXhr=t}}};class ag extends Dm.Q{constructor(t,e={}){super(),t&&"object"==typeof t&&(e=t,t=null),t?(t=_m(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=_m(e.host).host),Lm(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=e.transports||["polling","websocket"],this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},e),this.opts.path=this.opts.path.replace(/\/$/,"")+"/","string"==typeof this.opts.query&&(this.opts.query=Xm.decode(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&addEventListener("beforeunload",(()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())}),!1),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close")},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const e=function(t){const e={};for(let n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}(this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts.transportOptions[t],this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new og[t](n)}open(){let t;if(this.opts.rememberUpgrade&&ag.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(()=>{this.onClose("transport close")}))}probe(t){let e=this.createTransport(t),n=!1;ag.priorWebsocketSuccess=!1;const s=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",(t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;ag.priorWebsocketSuccess="websocket"===e.name,this.transport.pause((()=>{n||"closed"!==this.readyState&&(u(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())}))}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}})))};function r(){n||(n=!0,u(),e.close(),e=null)}const i=t=>{const n=new Error("probe error: "+t);n.transport=e.name,r(),this.emitReserved("upgradeError",n)};function o(){i("transport closed")}function a(){i("socket closed")}function c(t){e&&t.name!==e.name&&r()}const u=()=>{e.removeListener("open",s),e.removeListener("error",i),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",s),e.once("error",i),e.once("close",o),this.once("close",a),this.once("upgrading",c),e.open()}onOpen(){if(this.readyState="open",ag.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade&&this.transport.pause){let t=0;const e=this.upgrades.length;for(;t{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emitReserved("flush"))}write(t,e,n){return this.sendPacket("message",t,e,n),this}send(t,e,n){return this.sendPacket("message",t,e,n),this}sendPacket(t,e,n,s){if("function"==typeof e&&(s=e,e=void 0),"function"==typeof n&&(s=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const r={type:t,data:e,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),s&&this.once("flush",s),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?n():t()})):this.upgrading?n():t()),this}onError(t){ag.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&removeEventListener("offline",this.offlineEventListener,!1),this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const e=[];let n=0;const s=t.length;for(;n"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||hg&&t instanceof Blob||lg&&t instanceof File}function fg(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e0;case wg.ACK:case wg.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&this.reconstructor.finishedReconstruction()}}class Eg{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=gg(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function Ig(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const _g=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Sg extends Dm.Q{constructor(t,e,n){super(),this.connected=!1,this.disconnected=!0,this.receiveBuffer=[],this.sendBuffer=[],this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this.io._autoConnect&&this.open()}subEvents(){if(this.subs)return;const t=this.io;this.subs=[Ig(t,"open",this.onopen.bind(this)),Ig(t,"packet",this.onpacket.bind(this)),Ig(t,"error",this.onerror.bind(this)),Ig(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){if(_g.hasOwnProperty(t))throw new Error('"'+t+'" is a reserved event name');e.unshift(t);const n={type:wg.EVENT,data:e,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,s=e.pop();this._registerAckCallback(t,s),n.id=t}const s=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!s||!this.connected)||(this.connected?this.packet(n):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(t,e){const n=this.flags.timeout;if(void 0===n)return void(this.acks[t]=e);const s=this.io.setTimeoutFn((()=>{delete this.acks[t];for(let e=0;e{this.io.clearTimeoutFn(s),e.apply(this,[null,...t])}}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth((t=>{this.packet({type:wg.CONNECT,data:t})})):this.packet({type:wg.CONNECT,data:this.auth})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t){this.connected=!1,this.disconnected=!0,delete this.id,this.emitReserved("disconnect",t)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case wg.CONNECT:if(t.data&&t.data.sid){const e=t.data.sid;this.onconnect(e)}else this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case wg.EVENT:case wg.BINARY_EVENT:this.onevent(t);break;case wg.ACK:case wg.BINARY_ACK:this.onack(t);break;case wg.DISCONNECT:this.ondisconnect();break;case wg.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t)}ack(t){const e=this;let n=!1;return function(...s){n||(n=!0,e.packet({type:wg.ACK,id:t,data:s}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(e.apply(this,t.data),delete this.acks[t.id])}onconnect(t){this.id=t,this.connected=!0,this.disconnected=!1,this.emitBuffered(),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach((t=>this.emitEvent(t))),this.receiveBuffer=[],this.sendBuffer.forEach((t=>this.packet(t))),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((t=>t())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:wg.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n{n.cleanup(),n._readyState="closed",this.emitReserved("error",e),t?t(e):n.maybeReconnectOnOpen()}));if(!1!==this._timeout){const t=this._timeout;0===t&&s();const n=this.setTimeoutFn((()=>{s(),e.close(),e.emit("error",new Error("timeout"))}),t);this.opts.autoUnref&&n.unref(),this.subs.push((function(){clearTimeout(n)}))}return this.subs.push(s),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Ig(t,"ping",this.onping.bind(this)),Ig(t,"data",this.ondata.bind(this)),Ig(t,"error",this.onerror.bind(this)),Ig(t,"close",this.onclose.bind(this)),Ig(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){this.decoder.add(t)}ondecoded(t){this.emitReserved("packet",t)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n||(n=new Sg(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;nt())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn((()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open((e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()})))}),e);this.opts.autoUnref&&n.unref(),this.subs.push((function(){clearTimeout(n)}))}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Cg={};function Ng(t,e){"object"==typeof t&&(e=t,t=void 0);const n=function(t,e="",n){let s=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),s=_m(t)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+e,s.href=s.protocol+"://"+r+(n&&n.port===s.port?"":":"+s.port),s}(t,(e=e||{}).path||"/socket.io"),s=n.source,r=n.id,i=n.path,o=Cg[r]&&i in Cg[r].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new Ag(s,e):(Cg[r]||(Cg[r]=new Ag(s,e)),a=Cg[r]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}function Rg(t,e){im.classList.toggle("hide"),im.classList.remove("fadeOut"),im.innerHTML=t,setTimeout((()=>{im.classList.add("fadeOut"),setTimeout((()=>{im.classList.add("hide")}),200)}),e),document.addEventListener("click",(()=>{im.classList.contains("hide")||(im.classList.add("fadeOut"),setTimeout((()=>{im.classList.add("hide")}),200))}))}Object.assign(Ng,{Manager:Ag,Socket:Sg,io:Ng,connect:Ng});let Lg=!1,Dg=!0,Og="dark";var Pg=!1,Mg=!1;const xg=Ng("https://type-master-multiplayer.herokuapp.com/");let Ug;xg.on("connect",(()=>{console.log("connection established")})),xg.on("disconnect",(()=>{console.log("you are disconnected")})),xg.on("roomId",(t=>{cm.classList.add("hide"),lm.classList.remove("hide"),lm.children[1].innerText=t,Pg=!0,qp.innerText="...",!Mg&&(am.classList.add("scale0"),am.classList.add("fadeOut"),setTimeout((()=>{am.classList.add("hide")}),500))})),xg.on("unknownCode",(()=>{Rg("not a valid room 😞",1e3)})),xg.on("tooManyPlayers",(()=>{Rg("room is full 😞",1e3)})),xg.on("playerList",(t=>{let e=t.findIndex((t=>t.id==xg.id));-1!==e&&(Ug=t[e]),function(t){!function(){for(;hm.firstChild;)hm.firstChild.remove()}(),t&&(t.forEach((t=>{let e=`
${t.name}
\n
${t.speed}
`,n=document.createElement("span");n.innerHTML=e,n.children[0].firstChild.style.left=t.progress+"%",n.children[0].firstChild.style.transform="translateX(-"+t.progress+"%)",n.classList.add("player"),hm.appendChild(n)})),hm.classList.remove("hide"))}(t)})),xg.on("newText",(t=>{!async function(t){Bg=qp.innerText=t,ey(),Qg(qp),jg(Bg)}(t)})),xg.on("textTimer",(()=>{let t=5,e=setInterval((()=>{Rg(`text in ${t--} seconds`,500)}),1e3);setTimeout((()=>{Mg&&Hg(),clearInterval(e)}),5e3)}));const Fg=xg;var Vg;const jg=t=>{let e,n,s=!0,r=t,i=0,o=0,a=document.querySelectorAll(".text>span");a[i].classList.add("blink"),document.addEventListener("keypress",(c=>{if(c.key===r[0]){if(s&&(e=(new Date).getTime(),s=!1),r=r.substr(1),a[i].classList.add("correctWord"),a[i].classList.remove("blink"),i{let n=t/(e.toPrecision(2)/60);Vg=Math.floor(n.toPrecision(3)),$p.innerText=Vg;let s=await bm();s&&Vg>s.topSpeed?(s={...s,topSpeed:Vg},console.log("setUserData called"),Im(s)):s&&Em({...s,lastSpeed:Vg}),Pg||Mg||(em.classList.toggle("hide"),em.classList.toggle("fadeOut"),setTimeout((()=>{$g(),em.classList.toggle("fadeOut"),setTimeout((()=>{em.classList.toggle("hide")}),500)}),500))})(Jg,(n-e)/1e3)),i++}else null!=a[i]&&a[i].classList.add("wrongWord")}))};var Bg;let qg=0;async function Hg(){Mg&&Fg.emit("getText",fm.innerText)}const $g=async()=>{await bm()||(qg++,5!=qg&&15!=qg||Rg("Login to save data 🙂",1e4));let t=await fetch("https://api.quotable.io/random").then((t=>t.json())).then((t=>t.content)).catch((t=>{console.error(t.message),qp.innerText="check your network connection"})),e=Tm();e.punctuationMode||(t=t.replace(/[^ \w]/g,"")),e.smallCaseMode&&(t=t.toLowerCase()),Bg=qp.innerText=t,ey(),Qg(qp),jg(Bg)};function Kg(t){t?(Jp.classList.remove("hide"),Gp.classList.remove("hide"),Op.classList.add("hide"),Kp.classList.add("hide")):(Jp.classList.add("hide"),Gp.classList.add("hide"),Op.classList.remove("hide"),Kp.classList.remove("hide"))}Kg();const zg=(t,e)=>{Bp.childNodes.forEach((n=>{n.classList&&(n==t?(n.classList.remove("hide"),n.classList.contains("stats")&&e?Lp.classList.remove("hide"):Lp.classList.add("hide")):!n.classList.contains("hide")&&n.classList.add("hide"))}))};n(162);var Gg=n(926),Wg=n.n(Gg);var Jg;const Xg=document.querySelector(".words"),Qg=t=>{let e=[];for(let t=0;t${Bg[t]}`);let n=e.join("");t.innerHTML=n};Pp.addEventListener("click",(async()=>{if(Mp.classList.contains("hide")){Mp.classList.toggle("hide");let t=await bm();Kg(t),!t||0===Object.entries(t).length&&t.constructor===Object?zg(Xp):(Zg(t),Gp.classList.remove("hide"),Op.classList.add("hide"))}else Mp.classList.add("hide")})),xp.forEach((t=>{t.addEventListener("click",(t=>{let e=t.target.parentElement.parentElement.parentElement;zg(Qp),e.classList.toggle("hide")}))})),Up.forEach((t=>{t.addEventListener("drag",(t=>{t.target.parentElement.parentElement.style.filter="brightness(.7)"}))})),Up.forEach((t=>{t.addEventListener("dragend",(t=>{let e=t.target.parentElement.parentElement;e.style.filter="brightness(1)",Yg(t,e)}))}));const Yg=(t,e)=>{e.style.left=t.pageX-20+"px",e.style.top=t.pageY-20+"px"},Zg=async t=>(!t||0===Object.entries(t).length&&t.constructor===Object?zg(Xp):(Hp.lastElementChild.lastElementChild.childNodes.forEach((e=>{e.classList&&(e.classList.contains("name")?(t.userName.length>10?e.style.fontSize=20:t.userName.length>20&&(e.style.fontSize=15),e.innerHTML=t.userName):e.classList.contains("speed")&&(t.userName.length>10&&(e.style.fontSize=30),e.innerHTML=t.topSpeed))})),zg(Hp,t)),t);Fp.addEventListener("click",(()=>{Vp.classList.toggle("hide")})),jp.addEventListener("change",(async t=>{let e=await bm();if(t.target.options.light.selected){if(Rp.classList.contains("light"))return;Rp.classList.remove("dark"),Rp.classList.add("light"),e?Im({...e,theme:"light"}):(e=Tm(),Em({...e,theme:"light"}))}else if(t.target.options.dark.selected){if(Rp.classList.contains("dark"))return;Rp.classList.remove("light"),Rp.classList.add("dark"),e?Im({...e,theme:"dark"}):(e=Tm(),Em({...e,theme:"dark"}))}})),Lp.addEventListener("click",(()=>{Wg().toBlob(Hp).then((async t=>{let e=await bm(),n=e.userName+e.topSpeed;window.saveAs(t,n)}))})),Dp.addEventListener("submit",(t=>{t.preventDefault(),ry({email:t.target.email.value,username:t.target.username.value,password:t.target.password.value}),zg(Qp)})),zp.addEventListener("submit",(t=>{t.preventDefault(),sy({email:t.target.email.value,password:t.target.password.value}),zg(Qp)})),Op.addEventListener("click",(()=>{zg(Dp)})),Kp.addEventListener("click",(()=>{zg(zp)})),Jp.addEventListener("click",(()=>{iy()})),Gp.addEventListener("click",(()=>{zg(Wp)})),Wp.addEventListener("submit",(t=>{t.preventDefault();let e=t.target.username.value;e&&" "!=e[0]&&e.length>0?oy(e):console.log("enter username",e)})),tm.addEventListener("click",(()=>{Zp.parentElement.classList.contains("hide")?(Zp.parentElement.classList.toggle("hide"),setTimeout((()=>{Zp.parentElement.classList.toggle("fadeOut")}),200)):(Zp.parentElement.classList.toggle("fadeOut"),setTimeout((()=>{Zp.parentElement.classList.toggle("hide")}),500))})),Yp.addEventListener("click",(t=>{t.target.classList.contains("leaderBoard")&&(Yp.classList.toggle("fadeOut"),setTimeout((()=>{Yp.classList.toggle("hide")}),200))})),sm.addEventListener("click",(async t=>{let e=await bm();t.target.classList.contains("smallCase")?(t.target.classList.contains("active")?(Lg=!1,t.target.classList.remove("active")):(Lg=!0,t.target.classList.add("active")),e?Im({...e,smallCaseMode:Lg}):(e=Tm(),Em({...e,smallCaseMode:Lg}))):t.target.classList.contains("punctuation")&&(t.target.classList.contains("active")?(Dg=!1,t.target.classList.remove("active")):(Dg=!0,t.target.classList.add("active")),e?Im({...e,punctuationMode:Dg}):(e=Tm(),Em({...e,punctuationMode:Dg})))})),rm.addEventListener("click",(()=>{Pg?Hg():$g()}));let ty=!0;document.addEventListener("keypress",(t=>{t.getModifierState("CapsLock")&&ty&&Rg("CapsLock",2e3),ty=!1})),om.addEventListener("click",(t=>{am.classList.contains("hide")?(am.classList.remove("hide"),am.classList.remove("scale0"),am.classList.remove("fadeOut")):(am.classList.add("scale0"),am.classList.add("fadeOut"),setTimeout((()=>{am.classList.add("hide")}),500))})),um.addEventListener("click",(t=>{!async function(){let t=await bm();Fg.emit("createRoom",t?t.userName:null,Fg.id),Mg=!0}()})),cm.addEventListener("submit",(t=>{t.preventDefault(),t.target.roomId.value&&" "!=t.target.roomId.value&&async function(t){let e=await bm();Fg.emit("joinRoom",e?e.userName:null,t)}(t.target.roomId.value)})),dm.addEventListener("click",(()=>{navigator.clipboard.writeText(fm.innerHTML).then((()=>{dm.innerText="✅",dm.classList.add("active")}))}));const ey=(t=0)=>{let e,n=/ /g,s=[];for(;e=n.exec(Bg);)s.push(e.index);Jg=s.length+1,Xg.innerText=`${Jg}/${t}`},ny=Es(Qt),sy=async({email:t,password:e})=>{try{await function(t,e,n){return async function(t,e){return vn(Qe(t),e)}(b(t),an.credential(e,n))}(ny,t,e)}catch(t){alert(t.code)}},ry=async({email:t,password:e,username:n})=>{try{const s=await async function(t,e,n){const s=Qe(t),r=await async function(t,e){return Te(t,"POST","/v1/accounts:signUp",ve(t,e))}(s,{returnSecureToken:!0,email:e,password:n}),i=await pn._fromIdTokenResponse(s,"signIn",r);return await s._updateCurrentUser(i.user),i}(ny,t,e);await wn(s.user,{displayName:n||s.email.split("@")[0]}).then((()=>{console.log("updated the name"),Im({uId:s.user.uid,userName:s.user.displayName,topSpeed:0,theme:Og,punctuationMode:Dg,smallCaseMode:Lg,lastSpeed:0})}))}catch(t){alert(t.code)}},iy=()=>{try{!function(t){b(t).signOut()}(ny),console.log("user logged out")}catch(t){alert(t.code)}},oy=async t=>{try{let e=ny.currentUser;zg(Qp),await wn(e,{displayName:t}).then((()=>{console.log("updated the name"),function(t){ym(t);let e=getUserTheme();localStorage.setItem(wm,JSON.stringify({...e,userName:t.username}))}({uId:e.uid,userName:e.displayName}),bm().then((t=>{Zg(t)}))}))}catch(t){alert("check your network")}};window.onload=()=>{if(Tm()){let t=Tm().theme;"dark"!=t&&(Rp.classList.remove("dark"),Rp.classList.add(t)),jp.options[t].selected=!0,Tm().punctuationMode?sm.children[0].classList.add("active"):sm.children[0].classList.remove("active"),Tm().smallCaseMode?sm.children[1].classList.add("active"):sm.children[1].classList.remove("active"),function(t){t&&($p.innerText=t)}(Tm().lastSpeed)}else Em({punctuationMode:Dg,smallCaseMode:Lg,theme:Og})},$g(),function(t,e,n,s){b(t).onAuthStateChanged((async t=>{t?(Kg(t=await bm()),Zg(t),nm.innerText=t.userName):(Kg(t),Zg(t),nm.innerText=" ")}),void 0,void 0)}(ny),function(){const t=function(t,e,...n){if(t=b(t),Pf("collection","path",e),t instanceof jf){const s=fc.fromString(e,...n);return xf(s),new Hf(t,null,s)}{if(!(t instanceof Bf||t instanceof Hf))throw new Ga(za.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const s=t._path.child(fc.fromString(e,...n));return xf(s),new Hf(t.firestore,null,s)}}(mm,"scores"),e=function(t,...e){for(const n of e)t=n._apply(t);return t}(t,function(t,e="asc"){const n=e,s=vp("orderBy","topSpeed");return new Sp(s,n)}(0,"desc"),(function(t,e){if(e<=0)throw new Ga(za.INVALID_ARGUMENT,`Function ${t}() requires a positive number, but it was: ${e}.`)}("limit",10),new kp("limit",10,"F")));vm=function(t,...e){var n,s,r;t=b(t);let i={includeMetadataChanges:!1},o=0;"object"!=typeof e[o]||zf(e[o])||(i=e[o],o++);const a={includeMetadataChanges:i.includeMetadataChanges};if(zf(e[o])){const t=e[o];e[o]=null===(n=t.next)||void 0===n?void 0:n.bind(t),e[o+1]=null===(s=t.error)||void 0===s?void 0:s.bind(t),e[o+2]=null===(r=t.complete)||void 0===r?void 0:r.bind(t)}let c,u,h;if(t instanceof Bf)u=Ff(t.firestore,Gf),h=lu(t._key.path),c={next:n=>{e[o]&&e[o](Np(u,t,n))},error:e[o+1],complete:e[o+2]};else{const n=Ff(t,qf);u=Ff(n.firestore,Gf),h=n._query;const s=new Ap(u);c={next:t=>{e[o]&&e[o](new Ep(u,s,n,t))},error:e[o+1],complete:e[o+2]},function(t){if(fu(t)&&0===t.explicitOrderBy.length)throw new Ga(za.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}(t._query)}return function(t,e,n,s){const r=new kf(s),i=new Yd(e,r,n);return t.asyncQueue.enqueueAndForget((async()=>Gd(await Rf(t),i))),()=>{r.na(),t.asyncQueue.enqueueAndForget((async()=>Wd(await Rf(t),i)))}}(Wf(u),h,a,c)}(e,t,(t=>{if(t){const e=[];!function(){for(;Zp.firstChild;)Zp.firstChild.remove()}(),function(){let t=document.createElement("li");t.classList.add("leaderBoardHeader"),t.innerText="leaderboard";let e=document.createElement("li");e.classList.add("leaderBoardInfo"),e.innerHTML='RankUsernameTop Speed',Zp.appendChild(t),Zp.appendChild(e)}(),t.forEach((t=>{let n=t.data();n.topSpeed>0&&e.push({userName:n.userName,speed:n.topSpeed})}));for(let t=0;t{var t={63:(t,e)=>{function n(t){if(t)return function(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}(t)}e.Q=n,n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,s=this._callbacks["$"+t];if(!s)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var r=0;r{function e(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=e,e.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-n:t+n}return 0|Math.min(t,this.max)},e.prototype.reset=function(){this.attempts=0},e.prototype.setMin=function(t){this.ms=t},e.prototype.setMax=function(t){this.max=t},e.prototype.setJitter=function(t){this.jitter=t}},926:function(t){!function(e){"use strict";var n={escape:function(t){return t.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1")},parseExtension:s,mimeType:function(t){return t=s(t).toLowerCase(),function(){var t="application/font-woff",e="image/jpeg";return{woff:t,woff2:t,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:e,jpeg:e,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml"}}()[t]||""},dataAsUrl:function(t,e){return"data:"+e+";base64,"+t},isDataUrl:function(t){return-1!==t.search(/^(data:)/)},canvasToBlob:function(t){return t.toBlob?new Promise((function(e){t.toBlob(e)})):function(t){return new Promise((function(e){for(var n=y(t.toDataURL().split(",")[1]),s=n.length,r=new Uint8Array(s),i=0;it.toDataURL())).then(n.makeImage):t.cloneNode(!1)})).then((function(r){return function(e,r){return 0===(e=e.childNodes).length?Promise.resolve(r):function(e,n){var r=Promise.resolve();return n.forEach((function(n){r=r.then((function(){return t(n,s,!1,i)})).then((function(t){t&&e.appendChild(t)}))})),r}(r,n.asArray(e)).then((function(){return r}))}(e,r)})).then((function(t){return function(t,e,s){return e instanceof Element?Promise.resolve().then((function(){!function(t,e){t.cssText?(e.cssText=t.cssText,function(t,e){e.font=t.font,e.fontFamily=t.fontFamily,e.fontFeatureSettings=t.fontFeatureSettings,e.fontKerning=t.fontKerning,e.fontSize=t.fontSize,e.fontStretch=t.fontStretch,e.fontStyle=t.fontStyle,e.fontVariant=t.fontVariant,e.fontVariantCaps=t.fontVariantCaps,e.fontVariantEastAsian=t.fontVariantEastAsian,e.fontVariantLigatures=t.fontVariantLigatures,e.fontVariantNumeric=t.fontVariantNumeric,e.fontVariationSettings=t.fontVariationSettings,e.fontWeight=t.fontWeight}(t,e)):function(t,s){n.asArray(t).forEach((function(e){s.setProperty(e,t.getPropertyValue(e),t.getPropertyPriority(e))})),r&&(["inset-block","inset-block-start","inset-block-end"].forEach((t=>e.removeProperty(t))),["left","right","top","bottom"].forEach((t=>{e.getPropertyValue(t)&&e.setProperty(t,"0px")})))}(t,e)}(s?function(t,e){var n,s=document.createElement(t.tagName).style,r=g(t),i=t.style;for(n of r){var o=r.getPropertyValue(n),a=i.getPropertyValue(n);i.setProperty(n,e?"initial":"unset"),r.getPropertyValue(n)!==o?s.setProperty(n,o):s.removeProperty(n),i.setProperty(n,a)}return s}(t,r):g(t),e.style)})).then((function(){[":before",":after"].forEach((function(s){!function(s){var r,i=g(t,s),o=i.getPropertyValue("content");""!==o&&"none"!==o&&(r=n.uid(),(o=e.getAttribute("class"))&&e.setAttribute("class",o+" "+r),(o=document.createElement("style")).appendChild(function(){var t="."+r+":"+s,e=(i.cssText?function(){return i.cssText+" content: "+i.getPropertyValue("content")+";"}:function(){return n.asArray(i).map((function(t){return t+": "+i.getPropertyValue(t)+(i.getPropertyPriority(t)?" !important":"")})).join("; ")+";"})();return document.createTextNode(t+"{"+e+"}")}()),e.appendChild(o))}(s)}))})).then((function(){t instanceof HTMLTextAreaElement&&(e.innerHTML=t.value),t instanceof HTMLInputElement&&e.setAttribute("value",t.value)})).then((function(){e instanceof SVGElement&&(e.setAttribute("xmlns","http://www.w3.org/2000/svg"),e instanceof SVGRectElement&&["width","height"].forEach((function(t){var n=e.getAttribute(t);n&&e.style.setProperty(t,n)})))})).then((function(){return e})):e}(e,t,i)})):Promise.resolve()}(t,e.filter,!0,!e.raster)})).then(b).then(T).then((function(t){e.bgcolor&&(t.style.backgroundColor=e.bgcolor),e.width&&(t.style.width=e.width+"px"),e.height&&(t.style.height=e.height+"px"),e.style&&Object.keys(e.style).forEach((function(n){t.style[n]=e.style[n]}));var n=null;return"function"==typeof e.onclone&&(n=e.onclone(t)),Promise.resolve(n).then((function(){return t}))})).then((function(s){return s=s,r=e.width||n.width(t),i=e.height||n.height(t),Promise.resolve(s).then((function(t){return t.setAttribute("xmlns","http://www.w3.org/1999/xhtml"),(new XMLSerializer).serializeToString(t)})).then(n.escapeXhtml).then((function(t){return''+t+""})).then((function(t){return''+t+""})).then((function(t){return"data:image/svg+xml;charset=utf-8,"+t}));var r,i}))}function w(t,e){return v(t,e).then(n.makeImage).then(n.delay(0)).then((function(s){var r="number"!=typeof e.scale?1:e.scale,i=function(t,s){var r=document.createElement("canvas");return r.width=(e.width||n.width(t))*s,r.height=(e.height||n.height(t))*s,e.bgcolor&&((s=r.getContext("2d")).fillStyle=e.bgcolor,s.fillRect(0,0,r.width,r.height)),r}(t,r),o=i.getContext("2d");return o.mozImageSmoothingEnabled=!1,o.msImageSmoothingEnabled=!1,o.imageSmoothingEnabled=!1,s&&(o.scale(r,r),o.drawImage(s,0,0)),i}))}function b(t){return h.resolveAll().then((function(e){var n=document.createElement("style");return t.appendChild(n),n.appendChild(document.createTextNode(e)),t}))}function T(t){return d.inlineAll(t).then((function(){return t}))}}(this)},162:function(t,e,n){var s;void 0===(s=function(){"use strict";function e(t,e,n){var s=new XMLHttpRequest;s.open("GET",t),s.responseType="blob",s.onload=function(){a(s.response,e,n)},s.onerror=function(){console.error("could not download file")},s.send()}function s(t){var e=new XMLHttpRequest;e.open("HEAD",t,!1);try{e.send()}catch(t){}return 200<=e.status&&299>=e.status}function r(t){try{t.dispatchEvent(new MouseEvent("click"))}catch(n){var e=document.createEvent("MouseEvents");e.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),t.dispatchEvent(e)}}var i="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof n.g&&n.g.global===n.g?n.g:void 0,o=i.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),a=i.saveAs||("object"!=typeof window||window!==i?function(){}:"download"in HTMLAnchorElement.prototype&&!o?function(t,n,o){var a=i.URL||i.webkitURL,c=document.createElement("a");n=n||t.name||"download",c.download=n,c.rel="noopener","string"==typeof t?(c.href=t,c.origin===location.origin?r(c):s(c.href)?e(t,n,o):r(c,c.target="_blank")):(c.href=a.createObjectURL(t),setTimeout((function(){a.revokeObjectURL(c.href)}),4e4),setTimeout((function(){r(c)}),0))}:"msSaveOrOpenBlob"in navigator?function(t,n,i){if(n=n||t.name||"download","string"!=typeof t)navigator.msSaveOrOpenBlob(function(t,e){return void 0===e?e={autoBom:!1}:"object"!=typeof e&&(console.warn("Deprecated: Expected third argument to be a object"),e={autoBom:!e}),e.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(t.type)?new Blob(["\ufeff",t],{type:t.type}):t}(t,i),n);else if(s(t))e(t,n,i);else{var o=document.createElement("a");o.href=t,o.target="_blank",setTimeout((function(){r(o)}))}}:function(t,n,s,r){if((r=r||open("","_blank"))&&(r.document.title=r.document.body.innerText="downloading..."),"string"==typeof t)return e(t,n,s);var a="application/octet-stream"===t.type,c=/constructor/i.test(i.HTMLElement)||i.safari,u=/CriOS\/[\d]+/.test(navigator.userAgent);if((u||a&&c||o)&&"undefined"!=typeof FileReader){var h=new FileReader;h.onloadend=function(){var t=h.result;t=u?t:t.replace(/^data:[^;]*;/,"data:attachment/file;"),r?r.location.href=t:location=t,r=null},h.readAsDataURL(t)}else{var l=i.URL||i.webkitURL,d=l.createObjectURL(t);r?r.location=d:location.href=d,r=null,setTimeout((function(){l.revokeObjectURL(d)}),4e4)}});i.saveAs=a.saveAs=a,t.exports=a}.apply(e,[]))||(t.exports=s)},58:t=>{try{t.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){t.exports=!1}},676:function(t,e){!function(t){"use strict";function e(t){return Array.prototype.slice.call(t)}function n(t){return new Promise((function(e,n){t.onsuccess=function(){e(t.result)},t.onerror=function(){n(t.error)}}))}function s(t,e,s){var r,i=new Promise((function(i,o){n(r=t[e].apply(t,s)).then(i,o)}));return i.request=r,i}function r(t,e,n){var r=s(t,e,n);return r.then((function(t){if(t)return new h(t,r.request)}))}function i(t,e,n){n.forEach((function(n){Object.defineProperty(t.prototype,n,{get:function(){return this[e][n]},set:function(t){this[e][n]=t}})}))}function o(t,e,n,r){r.forEach((function(r){r in n.prototype&&(t.prototype[r]=function(){return s(this[e],r,arguments)})}))}function a(t,e,n,s){s.forEach((function(s){s in n.prototype&&(t.prototype[s]=function(){return this[e][s].apply(this[e],arguments)})}))}function c(t,e,n,s){s.forEach((function(s){s in n.prototype&&(t.prototype[s]=function(){return r(this[e],s,arguments)})}))}function u(t){this._index=t}function h(t,e){this._cursor=t,this._request=e}function l(t){this._store=t}function d(t){this._tx=t,this.complete=new Promise((function(e,n){t.oncomplete=function(){e()},t.onerror=function(){n(t.error)},t.onabort=function(){n(t.error)}}))}function f(t,e,n){this._db=t,this.oldVersion=e,this.transaction=new d(n)}function p(t){this._db=t}i(u,"_index",["name","keyPath","multiEntry","unique"]),o(u,"_index",IDBIndex,["get","getKey","getAll","getAllKeys","count"]),c(u,"_index",IDBIndex,["openCursor","openKeyCursor"]),i(h,"_cursor",["direction","key","primaryKey","value"]),o(h,"_cursor",IDBCursor,["update","delete"]),["advance","continue","continuePrimaryKey"].forEach((function(t){t in IDBCursor.prototype&&(h.prototype[t]=function(){var e=this,s=arguments;return Promise.resolve().then((function(){return e._cursor[t].apply(e._cursor,s),n(e._request).then((function(t){if(t)return new h(t,e._request)}))}))})})),l.prototype.createIndex=function(){return new u(this._store.createIndex.apply(this._store,arguments))},l.prototype.index=function(){return new u(this._store.index.apply(this._store,arguments))},i(l,"_store",["name","keyPath","indexNames","autoIncrement"]),o(l,"_store",IDBObjectStore,["put","add","delete","clear","get","getAll","getKey","getAllKeys","count"]),c(l,"_store",IDBObjectStore,["openCursor","openKeyCursor"]),a(l,"_store",IDBObjectStore,["deleteIndex"]),d.prototype.objectStore=function(){return new l(this._tx.objectStore.apply(this._tx,arguments))},i(d,"_tx",["objectStoreNames","mode"]),a(d,"_tx",IDBTransaction,["abort"]),f.prototype.createObjectStore=function(){return new l(this._db.createObjectStore.apply(this._db,arguments))},i(f,"_db",["name","version","objectStoreNames"]),a(f,"_db",IDBDatabase,["deleteObjectStore","close"]),p.prototype.transaction=function(){return new d(this._db.transaction.apply(this._db,arguments))},i(p,"_db",["name","version","objectStoreNames"]),a(p,"_db",IDBDatabase,["close"]),["openCursor","openKeyCursor"].forEach((function(t){[l,u].forEach((function(n){t in n.prototype&&(n.prototype[t.replace("open","iterate")]=function(){var n=e(arguments),s=n[n.length-1],r=this._store||this._index,i=r[t].apply(r,n.slice(0,-1));i.onsuccess=function(){s(i.result)}})}))})),[u,l].forEach((function(t){t.prototype.getAll||(t.prototype.getAll=function(t,e){var n=this,s=[];return new Promise((function(r){n.iterateCursor(t,(function(t){t?(s.push(t.value),void 0===e||s.length!=e?t.continue():r(s)):r(s)}))}))})})),t.openDb=function(t,e,n){var r=s(indexedDB,"open",[t,e]),i=r.request;return i&&(i.onupgradeneeded=function(t){n&&n(new f(i.result,t.oldVersion,i.transaction))}),r.then((function(t){return new p(t)}))},t.deleteDb=function(t){return s(indexedDB,"deleteDatabase",[t])},Object.defineProperty(t,"__esModule",{value:!0})}(e)},830:(t,e)=>{e.encode=function(t){var e="";for(var n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e},e.decode=function(t){for(var e={},n=t.split("&"),s=0,r=n.length;s{var e=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,n=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var s,r,i=t,o=t.indexOf("["),a=t.indexOf("]");-1!=o&&-1!=a&&(t=t.substring(0,o)+t.substring(o,a).replace(/:/g,";")+t.substring(a,t.length));for(var c,u,h=e.exec(t||""),l={},d=14;d--;)l[n[d]]=h[d]||"";return-1!=o&&-1!=a&&(l.source=i,l.host=l.host.substring(1,l.host.length-1).replace(/;/g,":"),l.authority=l.authority.replace("[","").replace("]","").replace(/;/g,":"),l.ipv6uri=!0),l.pathNames=(s=l.path,r=s.replace(/\/{2,9}/g,"/").split("/"),"/"!=s.substr(0,1)&&0!==s.length||r.splice(0,1),"/"==s.substr(s.length-1,1)&&r.splice(r.length-1,1),r),l.queryKey=(c=l.query,u={},c.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,n){e&&(u[e]=n)})),u),l}},281:t=>{"use strict";var e,n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),s={},r=0,i=0;function o(t){var e="";do{e=n[t%64]+e,t=Math.floor(t/64)}while(t>0);return e}function a(){var t=o(+new Date);return t!==e?(r=0,e=t):t+"."+o(r++)}for(;i<64;i++)s[n[i]]=i;a.encode=o,a.decode=function(t){var e=0;for(i=0;i{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var s in e)n.o(e,s)&&!n.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},(()=>{"use strict";var t={};n.r(t),n.d(t,{Decoder:()=>Tg,Encoder:()=>bg,PacketType:()=>wg,protocol:()=>vg});const e={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(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,s=[];for(let e=0;e>2,h=(3&r)<<4|o>>4;let l=(15&o)<<2|c>>6,d=63&c;a||(d=64,i||(l=64)),s.push(n[u],n[h],n[l],n[d])}return s.join("")},encodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(function(t){const e=[];let n=0;for(let s=0;s>6|192,e[n++]=63&r|128):55296==(64512&r)&&s+1>18|240,e[n++]=r>>12&63|128,e[n++]=r>>6&63|128,e[n++]=63&r|128):(e[n++]=r>>12|224,e[n++]=r>>6&63|128,e[n++]=63&r|128)}return e}(t),e)},decodeString(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):function(t){const e=[];let n=0,s=0;for(;n191&&r<224){const i=t[n++];e[s++]=String.fromCharCode((31&r)<<6|63&i)}else if(r>239&&r<365){const i=((7&r)<<18|(63&t[n++])<<12|(63&t[n++])<<6|63&t[n++])-65536;e[s++]=String.fromCharCode(55296+(i>>10)),e[s++]=String.fromCharCode(56320+(1023&i))}else{const i=t[n++],o=t[n++];e[s++]=String.fromCharCode((15&r)<<12|(63&i)<<6|63&o)}}return e.join("")}(this.decodeStringToByteArray(t,e))},decodeStringToByteArray(t,e){this.init_();const n=e?this.charToByteMapWebSafe_:this.charToByteMap_,s=[];for(let e=0;e>4;if(s.push(c),64!==o){const t=i<<4&240|o>>2;if(s.push(t),64!==a){const t=o<<6&192|a;s.push(t)}}}return s},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}};class s{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((t,e)=>{this.resolve=t,this.reject=e}))}wrapCallback(t){return(e,n)=>{e?this.reject(e):this.resolve(n),"function"==typeof t&&(this.promise.catch((()=>{})),1===t.length?t(e):t(e,n))}}}function r(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function i(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(r())}function o(){const t="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof t&&void 0!==t.id}function a(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function c(){const t=r();return t.indexOf("MSIE ")>=0||t.indexOf("Trident/")>=0}class u extends Error{constructor(t,e,n){super(e),this.code=t,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,u.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,h.prototype.create)}}class h{constructor(t,e,n){this.service=t,this.serviceName=e,this.errors=n}create(t,...e){const n=e[0]||{},s=`${this.service}/${t}`,r=this.errors[t],i=r?function(t,e){return t.replace(l,((t,n)=>{const s=e[n];return null!=s?String(s):`<${n}?>`}))}(r,n):"Error",o=`${this.serviceName}: ${i} (${s}).`;return new u(s,o,n)}}const l=/\{\$([^}]+)}/g;function d(t,e){if(t===e)return!0;const n=Object.keys(t),s=Object.keys(e);for(const r of n){if(!s.includes(r))return!1;const n=t[r],i=e[r];if(f(n)&&f(i)){if(!d(n,i))return!1}else if(n!==i)return!1}for(const t of s)if(!n.includes(t))return!1;return!0}function f(t){return null!==t&&"object"==typeof t}function p(t){const e=[];for(const[n,s]of Object.entries(t))Array.isArray(s)?s.forEach((t=>{e.push(encodeURIComponent(n)+"="+encodeURIComponent(t))})):e.push(encodeURIComponent(n)+"="+encodeURIComponent(s));return e.length?"&"+e.join("&"):""}function m(t){const e={};return t.replace(/^\?/,"").split("&").forEach((t=>{if(t){const[n,s]=t.split("=");e[decodeURIComponent(n)]=decodeURIComponent(s)}})),e}function g(t){const e=t.indexOf("?");if(!e)return"";const n=t.indexOf("#",e);return t.substring(e,n>0?n:void 0)}class y{constructor(t,e){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=e,this.task.then((()=>{t(this)})).catch((t=>{this.error(t)}))}next(t){this.forEachObserver((e=>{e.next(t)}))}error(t){this.forEachObserver((e=>{e.error(t)})),this.close(t)}complete(){this.forEachObserver((t=>{t.complete()})),this.close()}subscribe(t,e,n){let s;if(void 0===t&&void 0===e&&void 0===n)throw new Error("Missing Observer.");s=function(t,e){if("object"!=typeof t||null===t)return!1;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return!0;return!1}(t)?t:{next:t,error:e,complete:n},void 0===s.next&&(s.next=v),void 0===s.error&&(s.error=v),void 0===s.complete&&(s.complete=v);const r=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?s.error(this.finalError):s.complete()}catch(t){}})),this.observers.push(s),r}unsubscribeOne(t){void 0!==this.observers&&void 0!==this.observers[t]&&(delete this.observers[t],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(t){if(!this.finalized)for(let e=0;e{if(void 0!==this.observers&&void 0!==this.observers[t])try{e(this.observers[t])}catch(t){"undefined"!=typeof console&&console.error&&console.error(t)}}))}close(t){this.finalized||(this.finalized=!0,void 0!==t&&(this.finalError=t),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function v(){}function w(t,e=1e3,n=2){const s=e*Math.pow(n,t),r=Math.round(.5*s*(Math.random()-.5)*2);return Math.min(144e5,s+r)}function b(t){return t&&t._delegate?t._delegate:t}class T{constructor(t,e,n){this.name=t,this.instanceFactory=e,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(t){return this.instantiationMode=t,this}setMultipleInstances(t){return this.multipleInstances=t,this}setServiceProps(t){return this.serviceProps=t,this}setInstanceCreatedCallback(t){return this.onInstanceCreated=t,this}}const E="[DEFAULT]";class I{constructor(t,e){this.name=t,this.container=e,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(t){const e=this.normalizeInstanceIdentifier(t);if(!this.instancesDeferred.has(e)){const t=new s;if(this.instancesDeferred.set(e,t),this.isInitialized(e)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:e});n&&t.resolve(n)}catch(t){}}return this.instancesDeferred.get(e).promise}getImmediate(t){var e;const n=this.normalizeInstanceIdentifier(null==t?void 0:t.identifier),s=null!==(e=null==t?void 0:t.optional)&&void 0!==e&&e;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(s)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(t){if(s)return null;throw t}}getComponent(){return this.component}setComponent(t){if(t.name!==this.name)throw Error(`Mismatching Component ${t.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=t,this.shouldAutoInitialize()){if(function(t){return"EAGER"===t.instantiationMode}(t))try{this.getOrInitializeService({instanceIdentifier:E})}catch(t){}for(const[t,e]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(t);try{const t=this.getOrInitializeService({instanceIdentifier:n});e.resolve(t)}catch(t){}}}}clearInstance(t="[DEFAULT]"){this.instancesDeferred.delete(t),this.instancesOptions.delete(t),this.instances.delete(t)}async delete(){const t=Array.from(this.instances.values());await Promise.all([...t.filter((t=>"INTERNAL"in t)).map((t=>t.INTERNAL.delete())),...t.filter((t=>"_delete"in t)).map((t=>t._delete()))])}isComponentSet(){return null!=this.component}isInitialized(t="[DEFAULT]"){return this.instances.has(t)}getOptions(t="[DEFAULT]"){return this.instancesOptions.get(t)||{}}initialize(t={}){const{options:e={}}=t,n=this.normalizeInstanceIdentifier(t.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 s=this.getOrInitializeService({instanceIdentifier:n,options:e});for(const[t,e]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(t)&&e.resolve(s);return s}onInit(t,e){var n;const s=this.normalizeInstanceIdentifier(e),r=null!==(n=this.onInitCallbacks.get(s))&&void 0!==n?n:new Set;r.add(t),this.onInitCallbacks.set(s,r);const i=this.instances.get(s);return i&&t(i,s),()=>{r.delete(t)}}invokeOnInitCallbacks(t,e){const n=this.onInitCallbacks.get(e);if(n)for(const s of n)try{s(t,e)}catch(t){}}getOrInitializeService({instanceIdentifier:t,options:e={}}){let n=this.instances.get(t);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(s=t,s===E?void 0:s),options:e}),this.instances.set(t,n),this.instancesOptions.set(t,e),this.invokeOnInitCallbacks(n,t),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,t,n)}catch(t){}var s;return n||null}normalizeInstanceIdentifier(t="[DEFAULT]"){return this.component?this.component.multipleInstances?t:E:t}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class _{constructor(t){this.name=t,this.providers=new Map}addComponent(t){const e=this.getProvider(t.name);if(e.isComponentSet())throw new Error(`Component ${t.name} has already been registered with ${this.name}`);e.setComponent(t)}addOrOverwriteComponent(t){this.getProvider(t.name).isComponentSet()&&this.providers.delete(t.name),this.addComponent(t)}getProvider(t){if(this.providers.has(t))return this.providers.get(t);const e=new I(t,this);return this.providers.set(t,e),e}getProviders(){return Array.from(this.providers.values())}}const S=[];var k,A;(A=k||(k={}))[A.DEBUG=0]="DEBUG",A[A.VERBOSE=1]="VERBOSE",A[A.INFO=2]="INFO",A[A.WARN=3]="WARN",A[A.ERROR=4]="ERROR",A[A.SILENT=5]="SILENT";const C={debug:k.DEBUG,verbose:k.VERBOSE,info:k.INFO,warn:k.WARN,error:k.ERROR,silent:k.SILENT},N=k.INFO,R={[k.DEBUG]:"log",[k.VERBOSE]:"log",[k.INFO]:"info",[k.WARN]:"warn",[k.ERROR]:"error"},L=(t,e,...n)=>{if(e{if(function(t){const e=t.getComponent();return"VERSION"===(null==e?void 0:e.type)}(t)){const e=t.getImmediate();return`${e.library}/${e.version}`}return null})).filter((t=>t)).join(" ")}}const P="@firebase/app",M="0.7.11",x=new D("@firebase/app"),U={[P]:"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"},F=new Map,V=new Map;function j(t,e){try{t.container.addComponent(e)}catch(n){x.debug(`Component ${e.name} failed to register with FirebaseApp ${t.name}`,n)}}function B(t){const e=t.name;if(V.has(e))return x.debug(`There were multiple attempts to register component ${e}.`),!1;V.set(e,t);for(const e of F.values())j(e,t);return!0}function q(t,e){return t.container.getProvider(e)}const H=new h("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","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","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."});class ${constructor(t,e,n){this._isDeleted=!1,this._options=Object.assign({},t),this._config=Object.assign({},e),this._name=e.name,this._automaticDataCollectionEnabled=e.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new T("app",(()=>this),"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(t){this.checkDestroyed(),this._automaticDataCollectionEnabled=t}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(t){this._isDeleted=t}checkDestroyed(){if(this.isDeleted)throw H.create("app-deleted",{appName:this._name})}}const K="9.6.1";function z(t="[DEFAULT]"){const e=F.get(t);if(!e)throw H.create("no-app",{appName:t});return e}function G(t,e,n){var s;let r=null!==(s=U[t])&&void 0!==s?s:t;n&&(r+=`-${n}`);const i=r.match(/\s|\//),o=e.match(/\s|\//);if(i||o){const t=[`Unable to register library "${r}" with version "${e}":`];return i&&t.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&o&&t.push("and"),o&&t.push(`version name "${e}" contains illegal characters (whitespace or "/")`),void x.warn(t.join(" "))}B(new T(`${r}-version`,(()=>({library:r,version:e})),"VERSION"))}B(new T("platform-logger",(t=>new O(t)),"PRIVATE")),G(P,M,""),G(P,M,"esm2017"),G("fire-js",""),G("firebase","9.6.1","app");var W=n(676);const J="@firebase/installations",X="0.5.4",Q="w:0.5.4",Y=new h("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function Z(t){return t instanceof u&&t.code.includes("request-failed")}function tt({projectId:t}){return`https://firebaseinstallations.googleapis.com/v1/projects/${t}/installations`}function et(t){return{token:t.token,requestStatus:2,expiresIn:(e=t.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()};var e}async function nt(t,e){const n=(await e.json()).error;return Y.create("request-failed",{requestName:t,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function st({apiKey:t}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":t})}async function rt(t){const e=await t();return e.status>=500&&e.status<600?t():e}function it(t){return new Promise((e=>{setTimeout(e,t)}))}const ot=/^[cdef][\w-]{21}$/;function at(){try{const t=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(t),t[0]=112+t[0]%16;const e=function(t){return(e=t,btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")).substr(0,22);var e}(t);return ot.test(e)?e:""}catch(t){return""}}function ct(t){return`${t.appName}!${t.appId}`}const ut=new Map;function ht(t,e){const n=ct(t);lt(n,e),function(t,e){const n=(!dt&&"BroadcastChannel"in self&&(dt=new BroadcastChannel("[Firebase] FID Change"),dt.onmessage=t=>{lt(t.data.key,t.data.fid)}),dt);n&&n.postMessage({key:t,fid:e}),0===ut.size&&dt&&(dt.close(),dt=null)}(n,e)}function lt(t,e){const n=ut.get(t);if(n)for(const t of n)t(e)}let dt=null;const ft="firebase-installations-store";let pt=null;function mt(){return pt||(pt=(0,W.openDb)("firebase-installations-database",1,(t=>{0===t.oldVersion&&t.createObjectStore(ft)}))),pt}async function gt(t,e){const n=ct(t),s=(await mt()).transaction(ft,"readwrite"),r=s.objectStore(ft),i=await r.get(n);return await r.put(e,n),await s.complete,i&&i.fid===e.fid||ht(t,e.fid),e}async function yt(t){const e=ct(t),n=(await mt()).transaction(ft,"readwrite");await n.objectStore(ft).delete(e),await n.complete}async function vt(t,e){const n=ct(t),s=(await mt()).transaction(ft,"readwrite"),r=s.objectStore(ft),i=await r.get(n),o=e(i);return void 0===o?await r.delete(n):await r.put(o,n),await s.complete,!o||i&&i.fid===o.fid||ht(t,o.fid),o}async function wt(t){let e;const n=await vt(t,(n=>{const s=function(t){return Et(t||{fid:at(),registrationStatus:0})}(n),r=function(t,e){if(0===e.registrationStatus){if(!navigator.onLine)return{installationEntry:e,registrationPromise:Promise.reject(Y.create("app-offline"))};const n={fid:e.fid,registrationStatus:1,registrationTime:Date.now()},s=async function(t,e){try{const n=await async function(t,{fid:e}){const n=tt(t),s=st(t),r={fid:e,authVersion:"FIS_v2",appId:t.appId,sdkVersion:Q},i={method:"POST",headers:s,body:JSON.stringify(r)},o=await rt((()=>fetch(n,i)));if(o.ok){const t=await o.json();return{fid:t.fid||e,registrationStatus:2,refreshToken:t.refreshToken,authToken:et(t.authToken)}}throw await nt("Create Installation",o)}(t,e);return gt(t,n)}catch(n){throw Z(n)&&409===n.customData.serverCode?await yt(t):await gt(t,{fid:e.fid,registrationStatus:0}),n}}(t,n);return{installationEntry:n,registrationPromise:s}}return 1===e.registrationStatus?{installationEntry:e,registrationPromise:bt(t)}:{installationEntry:e}}(t,s);return e=r.registrationPromise,r.installationEntry}));return""===n.fid?{installationEntry:await e}:{installationEntry:n,registrationPromise:e}}async function bt(t){let e=await Tt(t);for(;1===e.registrationStatus;)await it(100),e=await Tt(t);if(0===e.registrationStatus){const{installationEntry:e,registrationPromise:n}=await wt(t);return n||e}return e}function Tt(t){return vt(t,(t=>{if(!t)throw Y.create("installation-not-found");return Et(t)}))}function Et(t){return 1===(e=t).registrationStatus&&e.registrationTime+1e4fetch(s,a)));if(c.ok)return et(await c.json());throw await nt("Generate Auth Token",c)}async function _t(t,e=!1){let n;const s=await vt(t.appConfig,(s=>{if(!kt(s))throw Y.create("not-registered");const r=s.authToken;if(!e&&(2===(i=r).requestStatus&&!function(t){const e=Date.now();return e{if(!kt(t))throw Y.create("not-registered");return 1===(e=t.authToken).requestStatus&&e.requestTime+1e4{const e=t.getProvider("app").getImmediate(),n=function(t){if(!t||!t.options)throw At("App Configuration");if(!t.name)throw At("App Name");const e=["projectId","apiKey","appId"];for(const n of e)if(!t.options[n])throw At(n);return{appName:t.name,projectId:t.options.projectId,apiKey:t.options.apiKey,appId:t.options.appId}}(e);return{app:e,appConfig:n,platformLoggerProvider:q(e,"platform-logger"),_delete:()=>Promise.resolve()}}),"PUBLIC")),B(new T("installations-internal",(t=>{const e=q(t.getProvider("app").getImmediate(),Ct).getImmediate();return{getId:()=>async function(t){const e=t,{installationEntry:n,registrationPromise:s}=await wt(e.appConfig);return s?s.catch(console.error):_t(e).catch(console.error),n.fid}(e),getToken:t=>async function(t,e=!1){const n=t;return await async function(t){const{registrationPromise:e}=await wt(t);e&&await e}(n.appConfig),(await _t(n,e)).token}(e,t)}}),"PRIVATE")),G(J,X),G(J,X,"esm2017");const Nt="analytics",Rt="https://www.googletagmanager.com/gtag/js",Lt=new D("@firebase/analytics");function Dt(t){return Promise.all(t.map((t=>t.catch((t=>t)))))}const Ot=new h("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.'}),Pt=new class{constructor(t={},e=1e3){this.throttleMetadata=t,this.intervalMillis=e}getThrottleMetadata(t){return this.throttleMetadata[t]}setThrottleMetadata(t,e){this.throttleMetadata[t]=e}deleteThrottleMetadata(t){delete this.throttleMetadata[t]}};function Mt(t){return new Headers({Accept:"application/json","x-goog-api-key":t})}async function xt(t,e=Pt,n){const{appId:s,apiKey:r,measurementId:i}=t.options;if(!s)throw Ot.create("no-app-id");if(!r){if(i)return{measurementId:i,appId:s};throw Ot.create("no-api-key")}const o=e.getThrottleMetadata(s)||{backoffCount:0,throttleEndTimeMillis:Date.now()},a=new Ft;return setTimeout((async()=>{a.abort()}),void 0!==n?n:6e4),Ut({appId:s,apiKey:r,measurementId:i},o,a,e)}async function Ut(t,{throttleEndTimeMillis:e,backoffCount:n},s,r=Pt){const{appId:i,measurementId:o}=t;try{await function(t,e){return new Promise(((n,s)=>{const r=Math.max(e-Date.now(),0),i=setTimeout(n,r);t.addEventListener((()=>{clearTimeout(i),s(Ot.create("fetch-throttle",{throttleEndTimeMillis:e}))}))}))}(s,e)}catch(t){if(o)return Lt.warn(`Timed out fetching this Firebase app's measurement ID from the server. Falling back to the measurement ID ${o} provided in the "measurementId" field in the local Firebase config. [${t.message}]`),{appId:i,measurementId:o};throw t}try{const e=await async function(t){var e;const{appId:n,apiKey:s}=t,r={method:"GET",headers:Mt(s)},i="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig".replace("{app-id}",n),o=await fetch(i,r);if(200!==o.status&&304!==o.status){let t="";try{const n=await o.json();(null===(e=n.error)||void 0===e?void 0:e.message)&&(t=n.error.message)}catch(t){}throw Ot.create("config-fetch-failed",{httpStatus:o.status,responseMessage:t})}return o.json()}(t);return r.deleteThrottleMetadata(i),e}catch(e){if(!function(t){if(!(t instanceof u&&t.customData))return!1;const e=Number(t.customData.httpStatus);return 429===e||500===e||503===e||504===e}(e)){if(r.deleteThrottleMetadata(i),o)return Lt.warn(`Failed to fetch this Firebase app's measurement ID from the server. Falling back to the measurement ID ${o} provided in the "measurementId" field in the local Firebase config. [${e.message}]`),{appId:i,measurementId:o};throw e}const a=503===Number(e.customData.httpStatus)?w(n,r.intervalMillis,30):w(n,r.intervalMillis),c={throttleEndTimeMillis:Date.now()+a,backoffCount:n+1};return r.setThrottleMetadata(i,c),Lt.debug(`Calling attemptFetch again in ${a} millis`),Ut(t,c,s,r)}}class Ft{constructor(){this.listeners=[]}addEventListener(t){this.listeners.push(t)}abort(){this.listeners.forEach((t=>t()))}}async function Vt(t,e,n,s,r,i,o){var a;const c=xt(t);c.then((e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&Lt.warn(`The measurement ID in the local Firebase config (${t.options.measurementId}) does not match the measurement ID fetched from the server (${e.measurementId}). To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.`)})).catch((t=>Lt.error(t))),e.push(c);const u=async function(){if("object"!=typeof indexedDB)return Lt.warn(Ot.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await new Promise(((t,e)=>{try{let n=!0;const s="validate-browser-context-for-indexeddb-analytics-module",r=self.indexedDB.open(s);r.onsuccess=()=>{r.result.close(),n||self.indexedDB.deleteDatabase(s),t(!0)},r.onupgradeneeded=()=>{n=!1},r.onerror=()=>{var t;e((null===(t=r.error)||void 0===t?void 0:t.message)||"")}}catch(t){e(t)}}))}catch(t){return Lt.warn(Ot.create("indexeddb-unavailable",{errorInfo:t}).message),!1}return!0}().then((t=>t?s.getId():void 0)),[h,l]=await Promise.all([c,u]);(function(){const t=window.document.getElementsByTagName("script");for(const e of Object.values(t))if(e.src&&e.src.includes(Rt))return e;return null})()||function(t,e){const n=document.createElement("script");n.src=`${Rt}?l=${t}&id=${e}`,n.async=!0,document.head.appendChild(n)}(i,h.measurementId),r("js",new Date);const d=null!==(a=null==o?void 0:o.config)&&void 0!==a?a:{};return d.origin="firebase",d.update=!0,null!=l&&(d.firebase_id=l),r("config",h.measurementId,d),h.measurementId}class jt{constructor(t){this.app=t}_delete(){return delete Bt[this.app.options.appId],Promise.resolve()}}let Bt={},qt=[];const Ht={};let $t,Kt,zt="dataLayer",Gt=!1;function Wt(t,e,n){!function(){const t=[];if(o()&&t.push("This is a browser extension environment."),"undefined"!=typeof navigator&&navigator.cookieEnabled||t.push("Cookies are not available."),t.length>0){const e=t.map(((t,e)=>`(${e+1}) ${t}`)).join(" "),n=Ot.create("invalid-analytics-context",{errorInfo:e});Lt.warn(n.message)}}();const s=t.options.appId;if(!s)throw Ot.create("no-app-id");if(!t.options.apiKey){if(!t.options.measurementId)throw Ot.create("no-api-key");Lt.warn(`The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest measurement ID for this Firebase app. Falling back to the measurement ID ${t.options.measurementId} provided in the "measurementId" field in the local Firebase config.`)}if(null!=Bt[s])throw Ot.create("already-exists",{id:s});if(!Gt){!function(t){let e=[];Array.isArray(window.dataLayer)?e=window.dataLayer:window.dataLayer=e}();const{wrappedGtag:t,gtagCore:e}=function(t,e,n,s,r){let i=function(...t){window.dataLayer.push(arguments)};return window.gtag&&"function"==typeof window.gtag&&(i=window.gtag),window.gtag=function(t,e,n,s){return async function(r,i,o){try{"event"===r?await async function(t,e,n,s,r){try{let i=[];if(r&&r.send_to){let t=r.send_to;Array.isArray(t)||(t=[t]);const s=await Dt(n);for(const n of t){const t=s.find((t=>t.measurementId===n)),r=t&&e[t.appId];if(!r){i=[];break}i.push(r)}}0===i.length&&(i=Object.values(e)),await Promise.all(i),t("event",s,r||{})}catch(t){Lt.error(t)}}(t,e,n,i,o):"config"===r?await async function(t,e,n,s,r,i){const o=s[r];try{if(o)await e[o];else{const t=(await Dt(n)).find((t=>t.measurementId===r));t&&await e[t.appId]}}catch(t){Lt.error(t)}t("config",r,i)}(t,e,n,s,i,o):t("set",i)}catch(t){Lt.error(t)}}}(i,t,e,n),{gtagCore:i,wrappedGtag:window.gtag}}(Bt,qt,Ht);Kt=t,$t=e,Gt=!0}return Bt[s]=Vt(t,qt,Ht,e,$t,zt,n),new jt(t)}const Jt="@firebase/analytics",Xt="0.7.4";B(new T(Nt,((t,{options:e})=>Wt(t.getProvider("app").getImmediate(),t.getProvider("installations-internal").getImmediate(),e)),"PUBLIC")),B(new T("analytics-internal",(function(t){try{const e=t.getProvider(Nt).getImmediate();return{logEvent:(t,n,s)=>function(t,e,n,s){t=b(t),async function(t,e,n,s,r){if(r&&r.global)t("event",n,s);else{const r=await e;t("event",n,Object.assign(Object.assign({},s),{send_to:r}))}}(Kt,Bt[t.app.options.appId],e,n,s).catch((t=>Lt.error(t)))}(e,t,n,s)}}catch(t){throw Ot.create("interop-component-reg-failed",{reason:t})}}),"PRIVATE")),G(Jt,Xt),G(Jt,Xt,"esm2017");const Qt=function(t,e={}){"object"!=typeof e&&(e={name:e});const n=Object.assign({name:"[DEFAULT]",automaticDataCollectionEnabled:!1},e),s=n.name;if("string"!=typeof s||!s)throw H.create("bad-app-name",{appName:String(s)});const r=F.get(s);if(r){if(d(t,r.options)&&d(n,r.config))return r;throw H.create("duplicate-app",{appName:s})}const i=new _(s);for(const t of V.values())i.addComponent(t);const o=new $(t,n,i);return F.set(s,o),o}({apiKey:"AIzaSyCtAdfUZ8tR-mODZgkDRe6ZACdDdsA36kU",authDomain:"type-master-ecd50.firebaseapp.com",projectId:"type-master-ecd50",storageBucket:"type-master-ecd50.appspot.com",messagingSenderId:"310756367551",appId:"1:310756367551:web:9823810463c7c3e8e63a0a",measurementId:"MISSING_ENV_VAR".FIREBASE_MEADUREMENT_ID});function Yt(t,e){var n={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(n[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(t);rt,"Short delay should be less than long delay!"),this.isMobile=i()||a()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&("http:"===de()||"https:"===de()||o()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function pe(t,e){ce(t.emulator,"Emulator should always be set here");const{url:n}=t.emulator;return e?`${n}${e.startsWith("/")?e.slice(1):e}`:n}class me{static initialize(t,e,n){this.fetchImpl=t,e&&(this.headersImpl=e),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl?this.fetchImpl:"undefined"!=typeof self&&"fetch"in self?self.fetch:void ae("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 ae("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 ae("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const ge={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:"internal-error",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"},ye=new fe(3e4,6e4);function ve(t,e){return t.tenantId&&!e.tenantId?Object.assign(Object.assign({},e),{tenantId:t.tenantId}):e}async function we(t,e,n,s,r={}){return be(t,r,(async()=>{let r={},i={};s&&("GET"===e?i=s:r={body:JSON.stringify(s)});const o=p(Object.assign({key:t.config.apiKey},i)).slice(1),a=await t._getAdditionalHeaders();return a["Content-Type"]="application/json",t.languageCode&&(a["X-Firebase-Locale"]=t.languageCode),me.fetch()(Ee(t,t.config.apiHost,n,o),Object.assign({method:e,headers:a,referrerPolicy:"no-referrer"},r))}))}async function be(t,e,n){t._canInitEmulator=!1;const s=Object.assign(Object.assign({},ge),e);try{const e=new Ie(t),r=await Promise.race([n(),e.promise]);e.clearNetworkTimeout();const i=await r.json();if("needConfirmation"in i)throw _e(t,"account-exists-with-different-credential",i);if(r.ok&&!("errorMessage"in i))return i;{const e=r.ok?i.errorMessage:i.error.message,[n,o]=e.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===n)throw _e(t,"credential-already-in-use",i);if("EMAIL_EXISTS"===n)throw _e(t,"email-already-in-use",i);const a=s[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(o)throw function(t,e,n){const s=Object.assign(Object.assign({},Zt()),{[e]:n});return new h("auth","Firebase",s).create(e,{appName:t.name})}(t,a,o);se(t,a)}}catch(e){if(e instanceof u)throw e;se(t,"network-request-failed")}}async function Te(t,e,n,s,r={}){const i=await we(t,e,n,s,r);return"mfaPendingCredential"in i&&se(t,"multi-factor-auth-required",{_serverResponse:i}),i}function Ee(t,e,n,s){const r=`${e}${n}?${s}`;return t.config.emulator?pe(t.config,r):`${t.config.apiScheme}://${r}`}class Ie{constructor(t){this.auth=t,this.timer=null,this.promise=new Promise(((t,e)=>{this.timer=setTimeout((()=>e(re(this.auth,"timeout"))),ye.get())}))}clearNetworkTimeout(){clearTimeout(this.timer)}}function _e(t,e,n){const s={appName:t.name};n.email&&(s.email=n.email),n.phoneNumber&&(s.phoneNumber=n.phoneNumber);const r=re(t,e,s);return r.customData._tokenResponse=n,r}function Se(t){if(t)try{const e=new Date(Number(t));if(!isNaN(e.getTime()))return e.toUTCString()}catch(t){}}function ke(t){return 1e3*Number(t)}function Ae(t){const[n,s,r]=t.split(".");if(void 0===n||void 0===s||void 0===r)return ne("JWT malformed, contained fewer than 3 sections"),null;try{const t=function(t){try{return e.decodeString(t,!0)}catch(t){console.error("base64Decode failed: ",t)}return null}(s);return t?JSON.parse(t):(ne("Failed to decode base64 JWT payload"),null)}catch(t){return ne("Caught error parsing JWT payload as JSON",t),null}}async function Ce(t,e,n=!1){if(n)return e;try{return await e}catch(e){throw e instanceof u&&function({code:t}){return"auth/user-disabled"===t||"auth/user-token-expired"===t}(e)&&t.auth.currentUser===t&&await t.auth.signOut(),e}}class Ne{constructor(t){this.user=t,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(t){var e;if(t){const t=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),t}{this.errorBackoff=3e4;const t=(null!==(e=this.user.stsTokenManager.expirationTime)&&void 0!==e?e:0)-Date.now()-3e5;return Math.max(0,t)}}schedule(t=!1){if(!this.isRunning)return;const e=this.getInterval(t);this.timerId=setTimeout((async()=>{await this.iteration()}),e)}async iteration(){try{await this.user.getIdToken(!0)}catch(t){return void("auth/network-request-failed"===t.code&&this.schedule(!0))}this.schedule()}}class Re{constructor(t,e){this.createdAt=t,this.lastLoginAt=e,this._initializeTime()}_initializeTime(){this.lastSignInTime=Se(this.lastLoginAt),this.creationTime=Se(this.createdAt)}_copy(t){this.createdAt=t.createdAt,this.lastLoginAt=t.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Le(t){var e;const n=t.auth,s=await t.getIdToken(),r=await Ce(t,async function(t,e){return we(t,"POST","/v1/accounts:lookup",e)}(n,{idToken:s}));oe(null==r?void 0:r.users.length,n,"internal-error");const i=r.users[0];t._notifyReloadListener(i);const o=(null===(e=i.providerUserInfo)||void 0===e?void 0:e.length)?i.providerUserInfo.map((t=>{var{providerId:e}=t,n=Yt(t,["providerId"]);return{providerId:e,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}})):[],a=(c=t.providerData,u=o,[...c.filter((t=>!u.some((e=>e.providerId===t.providerId)))),...u]);var c,u;const h=t.isAnonymous,l=!(t.email&&i.passwordHash||(null==a?void 0:a.length)),d=!!h&&l,f={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:a,metadata:new Re(i.createdAt,i.lastLoginAt),isAnonymous:d};Object.assign(t,f)}class De{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(t){oe(t.idToken,"internal-error"),oe(void 0!==t.idToken,"internal-error"),oe(void 0!==t.refreshToken,"internal-error");const e="expiresIn"in t&&void 0!==t.expiresIn?Number(t.expiresIn):function(t){const e=Ae(t);return oe(e,"internal-error"),oe(void 0!==e.exp,"internal-error"),oe(void 0!==e.iat,"internal-error"),Number(e.exp)-Number(e.iat)}(t.idToken);this.updateTokensAndExpiration(t.idToken,t.refreshToken,e)}async getToken(t,e=!1){return oe(!this.accessToken||this.refreshToken,t,"user-token-expired"),e||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(t,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(t,e){const{accessToken:n,refreshToken:s,expiresIn:r}=await async function(t,e){const n=await be(t,{},(async()=>{const n=p({grant_type:"refresh_token",refresh_token:e}).slice(1),{tokenApiHost:s,apiKey:r}=t.config,i=Ee(t,s,"/v1/token",`key=${r}`),o=await t._getAdditionalHeaders();return o["Content-Type"]="application/x-www-form-urlencoded",me.fetch()(i,{method:"POST",headers:o,body:n})}));return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}(t,e);this.updateTokensAndExpiration(n,s,Number(r))}updateTokensAndExpiration(t,e,n){this.refreshToken=e||null,this.accessToken=t||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(t,e){const{refreshToken:n,accessToken:s,expirationTime:r}=e,i=new De;return n&&(oe("string"==typeof n,"internal-error",{appName:t}),i.refreshToken=n),s&&(oe("string"==typeof s,"internal-error",{appName:t}),i.accessToken=s),r&&(oe("number"==typeof r,"internal-error",{appName:t}),i.expirationTime=r),i}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(t){this.accessToken=t.accessToken,this.refreshToken=t.refreshToken,this.expirationTime=t.expirationTime}_clone(){return Object.assign(new De,this.toJSON())}_performRefresh(){return ae("not implemented")}}function Oe(t,e){oe("string"==typeof t||void 0===t,"internal-error",{appName:e})}class Pe{constructor(t){var{uid:e,auth:n,stsTokenManager:s}=t,r=Yt(t,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.emailVerified=!1,this.isAnonymous=!1,this.tenantId=null,this.providerData=[],this.proactiveRefresh=new Ne(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=n,this.stsTokenManager=s,this.accessToken=s.accessToken,this.displayName=r.displayName||null,this.email=r.email||null,this.emailVerified=r.emailVerified||!1,this.phoneNumber=r.phoneNumber||null,this.photoURL=r.photoURL||null,this.isAnonymous=r.isAnonymous||!1,this.tenantId=r.tenantId||null,this.metadata=new Re(r.createdAt||void 0,r.lastLoginAt||void 0)}async getIdToken(t){const e=await Ce(this,this.stsTokenManager.getToken(this.auth,t));return oe(e,this.auth,"internal-error"),this.accessToken!==e&&(this.accessToken=e,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),e}getIdTokenResult(t){return async function(t,e=!1){const n=b(t),s=await n.getIdToken(e),r=Ae(s);oe(r&&r.exp&&r.auth_time&&r.iat,n.auth,"internal-error");const i="object"==typeof r.firebase?r.firebase:void 0,o=null==i?void 0:i.sign_in_provider;return{claims:r,token:s,authTime:Se(ke(r.auth_time)),issuedAtTime:Se(ke(r.iat)),expirationTime:Se(ke(r.exp)),signInProvider:o||null,signInSecondFactor:(null==i?void 0:i.sign_in_second_factor)||null}}(this,t)}reload(){return async function(t){const e=b(t);await Le(e),await e.auth._persistUserIfCurrent(e),e.auth._notifyListenersIfCurrent(e)}(this)}_assign(t){this!==t&&(oe(this.uid===t.uid,this.auth,"internal-error"),this.displayName=t.displayName,this.photoURL=t.photoURL,this.email=t.email,this.emailVerified=t.emailVerified,this.phoneNumber=t.phoneNumber,this.isAnonymous=t.isAnonymous,this.tenantId=t.tenantId,this.providerData=t.providerData.map((t=>Object.assign({},t))),this.metadata._copy(t.metadata),this.stsTokenManager._assign(t.stsTokenManager))}_clone(t){return new Pe(Object.assign(Object.assign({},this),{auth:t,stsTokenManager:this.stsTokenManager._clone()}))}_onReload(t){oe(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=t,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(t){this.reloadListener?this.reloadListener(t):this.reloadUserInfo=t}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(t,e=!1){let n=!1;t.idToken&&t.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(t),n=!0),e&&await Le(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){const t=await this.getIdToken();return await Ce(this,async function(t,e){return we(t,"POST","/v1/accounts:delete",e)}(this.auth,{idToken:t})),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((t=>Object.assign({},t))),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(t,e){var n,s,r,i,o,a,c,u;const h=null!==(n=e.displayName)&&void 0!==n?n:void 0,l=null!==(s=e.email)&&void 0!==s?s:void 0,d=null!==(r=e.phoneNumber)&&void 0!==r?r:void 0,f=null!==(i=e.photoURL)&&void 0!==i?i:void 0,p=null!==(o=e.tenantId)&&void 0!==o?o:void 0,m=null!==(a=e._redirectEventId)&&void 0!==a?a:void 0,g=null!==(c=e.createdAt)&&void 0!==c?c:void 0,y=null!==(u=e.lastLoginAt)&&void 0!==u?u:void 0,{uid:v,emailVerified:w,isAnonymous:b,providerData:T,stsTokenManager:E}=e;oe(v&&E,t,"internal-error");const I=De.fromJSON(this.name,E);oe("string"==typeof v,t,"internal-error"),Oe(h,t.name),Oe(l,t.name),oe("boolean"==typeof w,t,"internal-error"),oe("boolean"==typeof b,t,"internal-error"),Oe(d,t.name),Oe(f,t.name),Oe(p,t.name),Oe(m,t.name),Oe(g,t.name),Oe(y,t.name);const _=new Pe({uid:v,auth:t,email:l,emailVerified:w,displayName:h,isAnonymous:b,photoURL:f,phoneNumber:d,tenantId:p,stsTokenManager:I,createdAt:g,lastLoginAt:y});return T&&Array.isArray(T)&&(_.providerData=T.map((t=>Object.assign({},t)))),m&&(_._redirectEventId=m),_}static async _fromIdTokenResponse(t,e,n=!1){const s=new De;s.updateFromServerResponse(e);const r=new Pe({uid:e.localId,auth:t,stsTokenManager:s,isAnonymous:n});return await Le(r),r}}class Me{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(t,e){this.storage[t]=e}async _get(t){const e=this.storage[t];return void 0===e?null:e}async _remove(t){delete this.storage[t]}_addListener(t,e){}_removeListener(t,e){}}Me.type="NONE";const xe=Me;function Ue(t,e,n){return`firebase:${t}:${e}:${n}`}class Fe{constructor(t,e,n){this.persistence=t,this.auth=e,this.userKey=n;const{config:s,name:r}=this.auth;this.fullUserKey=Ue(this.userKey,s.apiKey,r),this.fullPersistenceKey=Ue("persistence",s.apiKey,r),this.boundEventHandler=e._onStorageEvent.bind(e),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(t){return this.persistence._set(this.fullUserKey,t.toJSON())}async getCurrentUser(){const t=await this.persistence._get(this.fullUserKey);return t?Pe._fromJSON(this.auth,t):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(t){if(this.persistence===t)return;const e=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=t,e?this.setCurrentUser(e):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(t,e,n="authUser"){if(!e.length)return new Fe(he(xe),t,n);const s=(await Promise.all(e.map((async t=>{if(await t._isAvailable())return t})))).filter((t=>t));let r=s[0]||he(xe);const i=Ue(n,t.config.apiKey,t.name);let o=null;for(const n of e)try{const e=await n._get(i);if(e){const s=Pe._fromJSON(t,e);n!==r&&(o=s),r=n;break}}catch(t){}const a=s.filter((t=>t._shouldAllowMigration));return r._shouldAllowMigration&&a.length?(r=a[0],o&&await r._set(i,o.toJSON()),await Promise.all(e.map((async t=>{if(t!==r)try{await t._remove(i)}catch(t){}}))),new Fe(r,t,n)):new Fe(r,t,n)}}function Ve(t){const e=t.toLowerCase();if(e.includes("opera/")||e.includes("opr/")||e.includes("opios/"))return"Opera";if(He(e))return"IEMobile";if(e.includes("msie")||e.includes("trident/"))return"IE";if(e.includes("edge/"))return"Edge";if(je(e))return"Firefox";if(e.includes("silk/"))return"Silk";if(Ke(e))return"Blackberry";if(ze(e))return"Webos";if(Be(e))return"Safari";if((e.includes("chrome/")||qe(e))&&!e.includes("edge/"))return"Chrome";if($e(e))return"Android";{const e=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,n=t.match(e);if(2===(null==n?void 0:n.length))return n[1]}return"Other"}function je(t=r()){return/firefox\//i.test(t)}function Be(t=r()){const e=t.toLowerCase();return e.includes("safari/")&&!e.includes("chrome/")&&!e.includes("crios/")&&!e.includes("android")}function qe(t=r()){return/crios\//i.test(t)}function He(t=r()){return/iemobile/i.test(t)}function $e(t=r()){return/android/i.test(t)}function Ke(t=r()){return/blackberry/i.test(t)}function ze(t=r()){return/webos/i.test(t)}function Ge(t=r()){return/iphone|ipad|ipod/i.test(t)}function We(t=r()){return Ge(t)||$e(t)||ze(t)||Ke(t)||/windows phone/i.test(t)||He(t)}function Je(t,e=[]){let n;switch(t){case"Browser":n=Ve(r());break;case"Worker":n=`${Ve(r())}-${t}`;break;default:n=t}return`${n}/JsCore/9.6.1/${e.length?e.join(","):"FirebaseCore-web"}`}class Xe{constructor(t,e){this.app=t,this.config=e,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Ye(this),this.idTokenSubscription=new Ye(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=te,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=t.name,this.clientVersion=e.sdkClientVersion}_initializeWithPersistence(t,e){return e&&(this._popupRedirectResolver=he(e)),this._initializationPromise=this.queue((async()=>{var n,s;if(!this._deleted&&(this.persistenceManager=await Fe.create(this,t),!this._deleted)){if(null===(n=this._popupRedirectResolver)||void 0===n?void 0:n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(t){}await this.initializeCurrentUser(e),this.lastNotifiedUid=(null===(s=this.currentUser)||void 0===s?void 0:s.uid)||null,this._deleted||(this._isInitialized=!0)}})),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const t=await this.assertedPersistence.getCurrentUser();return this.currentUser||t?this.currentUser&&t&&this.currentUser.uid===t.uid?(this._currentUser._assign(t),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(t):void 0}async initializeCurrentUser(t){var e;let n=await this.assertedPersistence.getCurrentUser();if(t&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const s=null===(e=this.redirectUser)||void 0===e?void 0:e._redirectEventId,r=null==n?void 0:n._redirectEventId,i=await this.tryRedirectSignIn(t);s&&s!==r||!(null==i?void 0:i.user)||(n=i.user)}return n?n._redirectEventId?(oe(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===n._redirectEventId?this.directlySetCurrentUser(n):this.reloadAndSetCurrentUserOrClear(n)):this.reloadAndSetCurrentUserOrClear(n):this.directlySetCurrentUser(null)}async tryRedirectSignIn(t){let e=null;try{e=await this._popupRedirectResolver._completeRedirectFn(this,t,!0)}catch(t){await this._setRedirectUser(null)}return e}async reloadAndSetCurrentUserOrClear(t){try{await Le(t)}catch(t){if("auth/network-request-failed"!==t.code)return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(t)}useDeviceLanguage(){this.languageCode=function(){if("undefined"==typeof navigator)return null;const t=navigator;return t.languages&&t.languages[0]||t.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(t){const e=t?b(t):null;return e&&oe(e.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(e&&e._clone(this))}async _updateCurrentUser(t){if(!this._deleted)return t&&oe(this.tenantId===t.tenantId,this,"tenant-id-mismatch"),this.queue((async()=>{await this.directlySetCurrentUser(t),this.notifyAuthListeners()}))}async signOut(){return(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null)}setPersistence(t){return this.queue((async()=>{await this.assertedPersistence.setPersistence(he(t))}))}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(t){this._errorFactory=new h("auth","Firebase",t())}onAuthStateChanged(t,e,n){return this.registerStateListener(this.authStateSubscription,t,e,n)}onIdTokenChanged(t,e,n){return this.registerStateListener(this.idTokenSubscription,t,e,n)}toJSON(){var t;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(t=this._currentUser)||void 0===t?void 0:t.toJSON()}}async _setRedirectUser(t,e){const n=await this.getOrInitRedirectPersistenceManager(e);return null===t?n.removeCurrentUser():n.setCurrentUser(t)}async getOrInitRedirectPersistenceManager(t){if(!this.redirectPersistenceManager){const e=t&&he(t)||this._popupRedirectResolver;oe(e,this,"argument-error"),this.redirectPersistenceManager=await Fe.create(this,[he(e._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(t){var e,n;return this._isInitialized&&await this.queue((async()=>{})),(null===(e=this._currentUser)||void 0===e?void 0:e._redirectEventId)===t?this._currentUser:(null===(n=this.redirectUser)||void 0===n?void 0:n._redirectEventId)===t?this.redirectUser:null}async _persistUserIfCurrent(t){if(t===this.currentUser)return this.queue((async()=>this.directlySetCurrentUser(t)))}_notifyListenersIfCurrent(t){t===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 t,e;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const n=null!==(e=null===(t=this.currentUser)||void 0===t?void 0:t.uid)&&void 0!==e?e:null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(t,e,n,s){if(this._deleted)return()=>{};const r="function"==typeof e?e:e.next.bind(e),i=this._isInitialized?Promise.resolve():this._initializationPromise;return oe(i,this,"internal-error"),i.then((()=>r(this.currentUser))),"function"==typeof e?t.addObserver(e,n,s):t.addObserver(e)}async directlySetCurrentUser(t){this.currentUser&&this.currentUser!==t&&(this._currentUser._stopProactiveRefresh(),t&&this.isProactiveRefreshEnabled&&t._startProactiveRefresh()),this.currentUser=t,t?await this.assertedPersistence.setCurrentUser(t):await this.assertedPersistence.removeCurrentUser()}queue(t){return this.operations=this.operations.then(t,t),this.operations}get assertedPersistence(){return oe(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(t){t&&!this.frameworks.includes(t)&&(this.frameworks.push(t),this.frameworks.sort(),this.clientVersion=Je(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const t={"X-Client-Version":this.clientVersion};return this.app.options.appId&&(t["X-Firebase-gmpid"]=this.app.options.appId),t}}function Qe(t){return b(t)}class Ye{constructor(t){this.auth=t,this.observer=null,this.addObserver=function(t,e){const n=new y(t,void 0);return n.subscribe.bind(n)}((t=>this.observer=t))}get next(){return oe(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}class Ze{constructor(t,e){this.providerId=t,this.signInMethod=e}toJSON(){return ae("not implemented")}_getIdTokenResponse(t){return ae("not implemented")}_linkToIdToken(t,e){return ae("not implemented")}_getReauthenticationResolver(t){return ae("not implemented")}}class tn extends Ze{constructor(t,e,n,s=null){super("password",n),this._email=t,this._password=e,this._tenantId=s}static _fromEmailAndPassword(t,e){return new tn(t,e,"password")}static _fromEmailAndCode(t,e,n=null){return new tn(t,e,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(t){const e="string"==typeof t?JSON.parse(t):t;if((null==e?void 0:e.email)&&(null==e?void 0:e.password)){if("password"===e.signInMethod)return this._fromEmailAndPassword(e.email,e.password);if("emailLink"===e.signInMethod)return this._fromEmailAndCode(e.email,e.password,e.tenantId)}return null}async _getIdTokenResponse(t){switch(this.signInMethod){case"password":return async function(t,e){return Te(t,"POST","/v1/accounts:signInWithPassword",ve(t,e))}(t,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(t,e){return Te(t,"POST","/v1/accounts:signInWithEmailLink",ve(t,e))}(t,{email:this._email,oobCode:this._password});default:se(t,"internal-error")}}async _linkToIdToken(t,e){switch(this.signInMethod){case"password":return async function(t,e){return we(t,"POST","/v1/accounts:update",e)}(t,{idToken:e,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(t,e){return Te(t,"POST","/v1/accounts:signInWithEmailLink",ve(t,e))}(t,{idToken:e,email:this._email,oobCode:this._password});default:se(t,"internal-error")}}_getReauthenticationResolver(t){return this._getIdTokenResponse(t)}}async function en(t,e){return Te(t,"POST","/v1/accounts:signInWithIdp",ve(t,e))}class nn extends Ze{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(t){const e=new nn(t.providerId,t.signInMethod);return t.idToken||t.accessToken?(t.idToken&&(e.idToken=t.idToken),t.accessToken&&(e.accessToken=t.accessToken),t.nonce&&!t.pendingToken&&(e.nonce=t.nonce),t.pendingToken&&(e.pendingToken=t.pendingToken)):t.oauthToken&&t.oauthTokenSecret?(e.accessToken=t.oauthToken,e.secret=t.oauthTokenSecret):se("argument-error"),e}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(t){const e="string"==typeof t?JSON.parse(t):t,{providerId:n,signInMethod:s}=e,r=Yt(e,["providerId","signInMethod"]);if(!n||!s)return null;const i=new nn(n,s);return i.idToken=r.idToken||void 0,i.accessToken=r.accessToken||void 0,i.secret=r.secret,i.nonce=r.nonce,i.pendingToken=r.pendingToken||null,i}_getIdTokenResponse(t){return en(t,this.buildRequest())}_linkToIdToken(t,e){const n=this.buildRequest();return n.idToken=e,en(t,n)}_getReauthenticationResolver(t){const e=this.buildRequest();return e.autoCreate=!1,en(t,e)}buildRequest(){const t={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)t.pendingToken=this.pendingToken;else{const e={};this.idToken&&(e.id_token=this.idToken),this.accessToken&&(e.access_token=this.accessToken),this.secret&&(e.oauth_token_secret=this.secret),e.providerId=this.providerId,this.nonce&&!this.pendingToken&&(e.nonce=this.nonce),t.postBody=p(e)}return t}}const sn={USER_NOT_FOUND:"user-not-found"};class rn extends Ze{constructor(t){super("phone","phone"),this.params=t}static _fromVerification(t,e){return new rn({verificationId:t,verificationCode:e})}static _fromTokenResponse(t,e){return new rn({phoneNumber:t,temporaryProof:e})}_getIdTokenResponse(t){return async function(t,e){return Te(t,"POST","/v1/accounts:signInWithPhoneNumber",ve(t,e))}(t,this._makeVerificationRequest())}_linkToIdToken(t,e){return async function(t,e){const n=await Te(t,"POST","/v1/accounts:signInWithPhoneNumber",ve(t,e));if(n.temporaryProof)throw _e(t,"account-exists-with-different-credential",n);return n}(t,Object.assign({idToken:e},this._makeVerificationRequest()))}_getReauthenticationResolver(t){return async function(t,e){return Te(t,"POST","/v1/accounts:signInWithPhoneNumber",ve(t,Object.assign(Object.assign({},e),{operation:"REAUTH"})),sn)}(t,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:t,phoneNumber:e,verificationId:n,verificationCode:s}=this.params;return t&&e?{temporaryProof:t,phoneNumber:e}:{sessionInfo:n,code:s}}toJSON(){const t={providerId:this.providerId};return this.params.phoneNumber&&(t.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(t.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(t.verificationCode=this.params.verificationCode),this.params.verificationId&&(t.verificationId=this.params.verificationId),t}static fromJSON(t){"string"==typeof t&&(t=JSON.parse(t));const{verificationId:e,verificationCode:n,phoneNumber:s,temporaryProof:r}=t;return n||e||s||r?new rn({verificationId:e,verificationCode:n,phoneNumber:s,temporaryProof:r}):null}}class on{constructor(t){var e,n,s,r,i,o;const a=m(g(t)),c=null!==(e=a.apiKey)&&void 0!==e?e:null,u=null!==(n=a.oobCode)&&void 0!==n?n:null,h=function(t){switch(t){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!==(s=a.mode)&&void 0!==s?s:null);oe(c&&u&&h,"argument-error"),this.apiKey=c,this.operation=h,this.code=u,this.continueUrl=null!==(r=a.continueUrl)&&void 0!==r?r:null,this.languageCode=null!==(i=a.languageCode)&&void 0!==i?i:null,this.tenantId=null!==(o=a.tenantId)&&void 0!==o?o:null}static parseLink(t){const e=function(t){const e=m(g(t)).link,n=e?m(g(e)).deep_link_id:null,s=m(g(t)).deep_link_id;return(s?m(g(s)).link:null)||s||n||e||t}(t);try{return new on(e)}catch(t){return null}}}class an{constructor(){this.providerId=an.PROVIDER_ID}static credential(t,e){return tn._fromEmailAndPassword(t,e)}static credentialWithLink(t,e){const n=on.parseLink(e);return oe(n,"argument-error"),tn._fromEmailAndCode(t,n.code,n.tenantId)}}an.PROVIDER_ID="password",an.EMAIL_PASSWORD_SIGN_IN_METHOD="password",an.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class cn{constructor(t){this.providerId=t,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(t){this.defaultLanguageCode=t}setCustomParameters(t){return this.customParameters=t,this}getCustomParameters(){return this.customParameters}}class un extends cn{constructor(){super(...arguments),this.scopes=[]}addScope(t){return this.scopes.includes(t)||this.scopes.push(t),this}getScopes(){return[...this.scopes]}}class hn extends un{constructor(){super("facebook.com")}static credential(t){return nn._fromParams({providerId:hn.PROVIDER_ID,signInMethod:hn.FACEBOOK_SIGN_IN_METHOD,accessToken:t})}static credentialFromResult(t){return hn.credentialFromTaggedObject(t)}static credentialFromError(t){return hn.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t||!("oauthAccessToken"in t))return null;if(!t.oauthAccessToken)return null;try{return hn.credential(t.oauthAccessToken)}catch(t){return null}}}hn.FACEBOOK_SIGN_IN_METHOD="facebook.com",hn.PROVIDER_ID="facebook.com";class ln extends un{constructor(){super("google.com"),this.addScope("profile")}static credential(t,e){return nn._fromParams({providerId:ln.PROVIDER_ID,signInMethod:ln.GOOGLE_SIGN_IN_METHOD,idToken:t,accessToken:e})}static credentialFromResult(t){return ln.credentialFromTaggedObject(t)}static credentialFromError(t){return ln.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t)return null;const{oauthIdToken:e,oauthAccessToken:n}=t;if(!e&&!n)return null;try{return ln.credential(e,n)}catch(t){return null}}}ln.GOOGLE_SIGN_IN_METHOD="google.com",ln.PROVIDER_ID="google.com";class dn extends un{constructor(){super("github.com")}static credential(t){return nn._fromParams({providerId:dn.PROVIDER_ID,signInMethod:dn.GITHUB_SIGN_IN_METHOD,accessToken:t})}static credentialFromResult(t){return dn.credentialFromTaggedObject(t)}static credentialFromError(t){return dn.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t||!("oauthAccessToken"in t))return null;if(!t.oauthAccessToken)return null;try{return dn.credential(t.oauthAccessToken)}catch(t){return null}}}dn.GITHUB_SIGN_IN_METHOD="github.com",dn.PROVIDER_ID="github.com";class fn extends un{constructor(){super("twitter.com")}static credential(t,e){return nn._fromParams({providerId:fn.PROVIDER_ID,signInMethod:fn.TWITTER_SIGN_IN_METHOD,oauthToken:t,oauthTokenSecret:e})}static credentialFromResult(t){return fn.credentialFromTaggedObject(t)}static credentialFromError(t){return fn.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t)return null;const{oauthAccessToken:e,oauthTokenSecret:n}=t;if(!e||!n)return null;try{return fn.credential(e,n)}catch(t){return null}}}fn.TWITTER_SIGN_IN_METHOD="twitter.com",fn.PROVIDER_ID="twitter.com";class pn{constructor(t){this.user=t.user,this.providerId=t.providerId,this._tokenResponse=t._tokenResponse,this.operationType=t.operationType}static async _fromIdTokenResponse(t,e,n,s=!1){const r=await Pe._fromIdTokenResponse(t,n,s),i=mn(n);return new pn({user:r,providerId:i,_tokenResponse:n,operationType:e})}static async _forOperation(t,e,n){await t._updateTokensIfNecessary(n,!0);const s=mn(n);return new pn({user:t,providerId:s,_tokenResponse:n,operationType:e})}}function mn(t){return t.providerId?t.providerId:"phoneNumber"in t?"phone":null}class gn extends u{constructor(t,e,n,s){var r;super(e.code,e.message),this.operationType=n,this.user=s,Object.setPrototypeOf(this,gn.prototype),this.customData={appName:t.name,tenantId:null!==(r=t.tenantId)&&void 0!==r?r:void 0,_serverResponse:e.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(t,e,n,s){return new gn(t,e,n,s)}}function yn(t,e,n,s){return("reauthenticate"===e?n._getReauthenticationResolver(t):n._getIdTokenResponse(t)).catch((n=>{if("auth/multi-factor-auth-required"===n.code)throw gn._fromErrorAndOperation(t,n,e,s);throw n}))}async function vn(t,e,n=!1){const s="signIn",r=await yn(t,s,e),i=await pn._fromIdTokenResponse(t,s,r);return n||await t._updateCurrentUser(i.user),i}async function wn(t,{displayName:e,photoURL:n}){if(void 0===e&&void 0===n)return;const s=b(t),r={idToken:await s.getIdToken(),displayName:e,photoUrl:n,returnSecureToken:!0},i=await Ce(s,async function(t,e){return we(t,"POST","/v1/accounts:update",e)}(s.auth,r));s.displayName=i.displayName||null,s.photoURL=i.photoUrl||null;const o=s.providerData.find((({providerId:t})=>"password"===t));o&&(o.displayName=s.displayName,o.photoURL=s.photoURL),await s._updateTokensIfNecessary(i)}new WeakMap;const bn="__sak";class Tn{constructor(t,e){this.storageRetriever=t,this.type=e}_isAvailable(){try{return this.storage?(this.storage.setItem(bn,"1"),this.storage.removeItem(bn),Promise.resolve(!0)):Promise.resolve(!1)}catch(t){return Promise.resolve(!1)}}_set(t,e){return this.storage.setItem(t,JSON.stringify(e)),Promise.resolve()}_get(t){const e=this.storage.getItem(t);return Promise.resolve(e?JSON.parse(e):null)}_remove(t){return this.storage.removeItem(t),Promise.resolve()}get storage(){return this.storageRetriever()}}class En extends Tn{constructor(){super((()=>window.localStorage),"LOCAL"),this.boundEventHandler=(t,e)=>this.onStorageEvent(t,e),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=function(){const t=r();return Be(t)||Ge(t)}()&&function(){try{return!(!window||window===window.top)}catch(t){return!1}}(),this.fallbackToPolling=We(),this._shouldAllowMigration=!0}forAllChangedKeys(t){for(const e of Object.keys(this.listeners)){const n=this.storage.getItem(e),s=this.localCache[e];n!==s&&t(e,s,n)}}onStorageEvent(t,e=!1){if(!t.key)return void this.forAllChangedKeys(((t,e,n)=>{this.notifyListeners(t,n)}));const n=t.key;if(e?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const s=this.storage.getItem(n);if(t.newValue!==s)null!==t.newValue?this.storage.setItem(n,t.newValue):this.storage.removeItem(n);else if(this.localCache[n]===t.newValue&&!e)return}const s=()=>{const t=this.storage.getItem(n);(e||this.localCache[n]!==t)&&this.notifyListeners(n,t)},r=this.storage.getItem(n);c()&&10===document.documentMode&&r!==t.newValue&&t.newValue!==t.oldValue?setTimeout(s,10):s()}notifyListeners(t,e){this.localCache[t]=e;const n=this.listeners[t];if(n)for(const t of Array.from(n))t(e?JSON.parse(e):e)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((t,e,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:t,oldValue:e,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(t,e){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[t]||(this.listeners[t]=new Set,this.localCache[t]=this.storage.getItem(t)),this.listeners[t].add(e)}_removeListener(t,e){this.listeners[t]&&(this.listeners[t].delete(e),0===this.listeners[t].size&&delete this.listeners[t]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(t,e){await super._set(t,e),this.localCache[t]=JSON.stringify(e)}async _get(t){const e=await super._get(t);return this.localCache[t]=JSON.stringify(e),e}async _remove(t){await super._remove(t),delete this.localCache[t]}}En.type="LOCAL";const In=En;class _n extends Tn{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(t,e){}_removeListener(t,e){}}_n.type="SESSION";const Sn=_n;class kn{constructor(t){this.eventTarget=t,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(t){const e=this.receivers.find((e=>e.isListeningto(t)));if(e)return e;const n=new kn(t);return this.receivers.push(n),n}isListeningto(t){return this.eventTarget===t}async handleEvent(t){const e=t,{eventId:n,eventType:s,data:r}=e.data,i=this.handlersMap[s];if(!(null==i?void 0:i.size))return;e.ports[0].postMessage({status:"ack",eventId:n,eventType:s});const o=Array.from(i).map((async t=>t(e.origin,r))),a=await function(t){return Promise.all(t.map((async t=>{try{return{fulfilled:!0,value:await t}}catch(t){return{fulfilled:!1,reason:t}}})))}(o);e.ports[0].postMessage({status:"done",eventId:n,eventType:s,response:a})}_subscribe(t,e){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[t]||(this.handlersMap[t]=new Set),this.handlersMap[t].add(e)}_unsubscribe(t,e){this.handlersMap[t]&&e&&this.handlersMap[t].delete(e),e&&0!==this.handlersMap[t].size||delete this.handlersMap[t],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function An(t="",e=10){let n="";for(let t=0;t{const c=An("",20);s.port1.start();const u=setTimeout((()=>{a(new Error("unsupported_event"))}),n);i={messageChannel:s,onMessage(t){const e=t;if(e.data.eventId===c)switch(e.data.status){case"ack":clearTimeout(u),r=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(r),o(e.data.response);break;default:clearTimeout(u),clearTimeout(r),a(new Error("invalid_response"))}}},this.handlers.add(i),s.port1.addEventListener("message",i.onMessage),this.target.postMessage({eventType:t,eventId:c,data:e},[s.port2])})).finally((()=>{i&&this.removeMessageHandler(i)}))}}function Nn(){return window}function Rn(){return void 0!==Nn().WorkerGlobalScope&&"function"==typeof Nn().importScripts}const Ln="firebaseLocalStorageDb",Dn="firebaseLocalStorage",On="fbase_key";class Pn{constructor(t){this.request=t}toPromise(){return new Promise(((t,e)=>{this.request.addEventListener("success",(()=>{t(this.request.result)})),this.request.addEventListener("error",(()=>{e(this.request.error)}))}))}}function Mn(t,e){return t.transaction([Dn],e?"readwrite":"readonly").objectStore(Dn)}function xn(){const t=indexedDB.open(Ln,1);return new Promise(((e,n)=>{t.addEventListener("error",(()=>{n(t.error)})),t.addEventListener("upgradeneeded",(()=>{const e=t.result;try{e.createObjectStore(Dn,{keyPath:On})}catch(t){n(t)}})),t.addEventListener("success",(async()=>{const n=t.result;n.objectStoreNames.contains(Dn)?e(n):(n.close(),await function(){const t=indexedDB.deleteDatabase(Ln);return new Pn(t).toPromise()}(),e(await xn()))}))}))}async function Un(t,e,n){const s=Mn(t,!0).put({[On]:e,value:n});return new Pn(s).toPromise()}function Fn(t,e){const n=Mn(t,!0).delete(e);return new Pn(n).toPromise()}class Vn{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 xn()),this.db}async _withRetries(t){let e=0;for(;;)try{const e=await this._openDb();return await t(e)}catch(t){if(e++>3)throw t;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Rn()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=kn._getInstance(Rn()?self:null),this.receiver._subscribe("keyChanged",(async(t,e)=>({keyProcessed:(await this._poll()).includes(e.key)}))),this.receiver._subscribe("ping",(async(t,e)=>["keyChanged"]))}async initializeSender(){var t,e;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(t){return null}}(),!this.activeServiceWorker)return;this.sender=new Cn(this.activeServiceWorker);const n=await this.sender._send("ping",{},800);n&&(null===(t=n[0])||void 0===t?void 0:t.fulfilled)&&(null===(e=n[0])||void 0===e?void 0:e.value.includes("keyChanged"))&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(t){if(this.sender&&this.activeServiceWorker&&function(){var t;return(null===(t=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===t?void 0:t.controller)||null}()===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:t},this.serviceWorkerReceiverAvailable?800:50)}catch(t){}}async _isAvailable(){try{if(!indexedDB)return!1;const t=await xn();return await Un(t,bn,"1"),await Fn(t,bn),!0}catch(t){}return!1}async _withPendingWrite(t){this.pendingWrites++;try{await t()}finally{this.pendingWrites--}}async _set(t,e){return this._withPendingWrite((async()=>(await this._withRetries((n=>Un(n,t,e))),this.localCache[t]=e,this.notifyServiceWorker(t))))}async _get(t){const e=await this._withRetries((e=>async function(t,e){const n=Mn(t,!1).get(e),s=await new Pn(n).toPromise();return void 0===s?null:s.value}(e,t)));return this.localCache[t]=e,e}async _remove(t){return this._withPendingWrite((async()=>(await this._withRetries((e=>Fn(e,t))),delete this.localCache[t],this.notifyServiceWorker(t))))}async _poll(){const t=await this._withRetries((t=>{const e=Mn(t,!1).getAll();return new Pn(e).toPromise()}));if(!t)return[];if(0!==this.pendingWrites)return[];const e=[],n=new Set;for(const{fbase_key:s,value:r}of t)n.add(s),JSON.stringify(this.localCache[s])!==JSON.stringify(r)&&(this.notifyListeners(s,r),e.push(s));for(const t of Object.keys(this.localCache))this.localCache[t]&&!n.has(t)&&(this.notifyListeners(t,null),e.push(t));return e}notifyListeners(t,e){this.localCache[t]=e;const n=this.listeners[t];if(n)for(const t of Array.from(n))t(e)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((async()=>this._poll()),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(t,e){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[t]||(this.listeners[t]=new Set,this._get(t)),this.listeners[t].add(e)}_removeListener(t,e){this.listeners[t]&&(this.listeners[t].delete(e),0===this.listeners[t].size&&delete this.listeners[t]),0===Object.keys(this.listeners).length&&this.stopPolling()}}Vn.type="LOCAL";const jn=Vn;function Bn(t){return`__${t}${Math.floor(1e6*Math.random())}`}Bn("rcb"),new fe(3e4,6e4);class qn{constructor(t){this.providerId=qn.PROVIDER_ID,this.auth=Qe(t)}verifyPhoneNumber(t,e){return async function(t,e,n){var s;const r=await n.verify();try{let i;if(oe("string"==typeof r,t,"argument-error"),oe("recaptcha"===n.type,t,"argument-error"),i="string"==typeof e?{phoneNumber:e}:e,"session"in i){const e=i.session;if("phoneNumber"in i){oe("enroll"===e.type,t,"internal-error");const n=await function(t,e){return we(t,"POST","/v2/accounts/mfaEnrollment:start",ve(t,e))}(t,{idToken:e.credential,phoneEnrollmentInfo:{phoneNumber:i.phoneNumber,recaptchaToken:r}});return n.phoneSessionInfo.sessionInfo}{oe("signin"===e.type,t,"internal-error");const n=(null===(s=i.multiFactorHint)||void 0===s?void 0:s.uid)||i.multiFactorUid;oe(n,t,"missing-multi-factor-info");const o=await function(t,e){return we(t,"POST","/v2/accounts/mfaSignIn:start",ve(t,e))}(t,{mfaPendingCredential:e.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:r}});return o.phoneResponseInfo.sessionInfo}}{const{sessionInfo:e}=await async function(t,e){return we(t,"POST","/v1/accounts:sendVerificationCode",ve(t,e))}(t,{phoneNumber:i.phoneNumber,recaptchaToken:r});return e}}finally{n._reset()}}(this.auth,t,b(e))}static credential(t,e){return rn._fromVerification(t,e)}static credentialFromResult(t){const e=t;return qn.credentialFromTaggedObject(e)}static credentialFromError(t){return qn.credentialFromTaggedObject(t.customData||{})}static credentialFromTaggedObject({_tokenResponse:t}){if(!t)return null;const{phoneNumber:e,temporaryProof:n}=t;return e&&n?rn._fromTokenResponse(e,n):null}}qn.PROVIDER_ID="phone",qn.PHONE_SIGN_IN_METHOD="phone";class Hn extends Ze{constructor(t){super("custom","custom"),this.params=t}_getIdTokenResponse(t){return en(t,this._buildIdpRequest())}_linkToIdToken(t,e){return en(t,this._buildIdpRequest(e))}_getReauthenticationResolver(t){return en(t,this._buildIdpRequest())}_buildIdpRequest(t){const e={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 t&&(e.idToken=t),e}}function $n(t){return vn(t.auth,new Hn(t),t.bypassAuthState)}function Kn(t){const{auth:e,user:n}=t;return oe(n,e,"internal-error"),async function(t,e,n=!1){const{auth:s}=t,r="reauthenticate";try{const i=await Ce(t,yn(s,r,e,t),n);oe(i.idToken,s,"internal-error");const o=Ae(i.idToken);oe(o,s,"internal-error");const{sub:a}=o;return oe(t.uid===a,s,"user-mismatch"),pn._forOperation(t,r,i)}catch(t){throw"auth/user-not-found"===(null==t?void 0:t.code)&&se(s,"user-mismatch"),t}}(n,new Hn(t),t.bypassAuthState)}async function zn(t){const{auth:e,user:n}=t;return oe(n,e,"internal-error"),async function(t,e,n=!1){const s=await Ce(t,e._linkToIdToken(t.auth,await t.getIdToken()),n);return pn._forOperation(t,"link",s)}(n,new Hn(t),t.bypassAuthState)}class Gn{constructor(t,e,n,s,r=!1){this.auth=t,this.resolver=n,this.user=s,this.bypassAuthState=r,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(e)?e:[e]}execute(){return new Promise((async(t,e)=>{this.pendingPromise={resolve:t,reject:e};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(t){this.reject(t)}}))}async onAuthEvent(t){const{urlResponse:e,sessionId:n,postBody:s,tenantId:r,error:i,type:o}=t;if(i)return void this.reject(i);const a={auth:this.auth,requestUri:e,sessionId:n,tenantId:r||void 0,postBody:s||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(t){this.reject(t)}}onError(t){this.reject(t)}getIdpTask(t){switch(t){case"signInViaPopup":case"signInViaRedirect":return $n;case"linkViaPopup":case"linkViaRedirect":return zn;case"reauthViaPopup":case"reauthViaRedirect":return Kn;default:se(this.auth,"internal-error")}}resolve(t){ce(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(t),this.unregisterAndCleanUp()}reject(t){ce(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(t),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const Wn=new fe(2e3,1e4);class Jn extends Gn{constructor(t,e,n,s,r){super(t,e,s,r),this.provider=n,this.authWindow=null,this.pollId=null,Jn.currentPopupAction&&Jn.currentPopupAction.cancel(),Jn.currentPopupAction=this}async executeNotNull(){const t=await this.execute();return oe(t,this.auth,"internal-error"),t}async onExecution(){ce(1===this.filter.length,"Popup operations only handle one event");const t=An();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],t),this.authWindow.associatedEvent=t,this.resolver._originValidation(this.auth).catch((t=>{this.reject(t)})),this.resolver._isIframeWebStorageSupported(this.auth,(t=>{t||this.reject(re(this.auth,"web-storage-unsupported"))})),this.pollUserCancellation()}get eventId(){var t;return(null===(t=this.authWindow)||void 0===t?void 0:t.associatedEvent)||null}cancel(){this.reject(re(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Jn.currentPopupAction=null}pollUserCancellation(){const t=()=>{var e,n;(null===(n=null===(e=this.authWindow)||void 0===e?void 0:e.window)||void 0===n?void 0:n.closed)?this.pollId=window.setTimeout((()=>{this.pollId=null,this.reject(re(this.auth,"popup-closed-by-user"))}),2e3):this.pollId=window.setTimeout(t,Wn.get())};t()}}Jn.currentPopupAction=null;const Xn=new Map;class Qn extends Gn{constructor(t,e,n=!1){super(t,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],e,void 0,n),this.eventId=null}async execute(){let t=Xn.get(this.auth._key());if(!t){try{const e=await async function(t,e){const n=function(t){return Ue("pendingRedirect",t.config.apiKey,t.name)}(e),s=function(t){return he(t._redirectPersistence)}(t);if(!await s._isAvailable())return!1;const r="true"===await s._get(n);return await s._remove(n),r}(this.resolver,this.auth),n=e?await super.execute():null;t=()=>Promise.resolve(n)}catch(e){t=()=>Promise.reject(e)}Xn.set(this.auth._key(),t)}return this.bypassAuthState||Xn.set(this.auth._key(),(()=>Promise.resolve(null))),t()}async onAuthEvent(t){if("signInViaRedirect"===t.type)return super.onAuthEvent(t);if("unknown"!==t.type){if(t.eventId){const e=await this.auth._redirectUserForId(t.eventId);if(e)return this.user=e,super.onAuthEvent(t);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function Yn(t,e,n=!1){const s=Qe(t),r=function(t,e){return e?he(e):(oe(t._popupRedirectResolver,t,"argument-error"),t._popupRedirectResolver)}(s,e),i=new Qn(s,r,n),o=await i.execute();return o&&!n&&(delete o.user._redirectEventId,await s._persistUserIfCurrent(o.user),await s._setRedirectUser(null,e)),o}class Zn{constructor(t){this.auth=t,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(t){this.consumers.add(t),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,t)&&(this.sendToConsumer(this.queuedRedirectEvent,t),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(t){this.consumers.delete(t)}onEvent(t){if(this.hasEventBeenHandled(t))return!1;let e=!1;return this.consumers.forEach((n=>{this.isEventForConsumer(t,n)&&(e=!0,this.sendToConsumer(t,n),this.saveEventToCache(t))})),this.hasHandledPotentialRedirect||!function(t){switch(t.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return es(t);default:return!1}}(t)||(this.hasHandledPotentialRedirect=!0,e||(this.queuedRedirectEvent=t,e=!0)),e}sendToConsumer(t,e){var n;if(t.error&&!es(t)){const s=(null===(n=t.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";e.onError(re(this.auth,s))}else e.onAuthEvent(t)}isEventForConsumer(t,e){const n=null===e.eventId||!!t.eventId&&t.eventId===e.eventId;return e.filter.includes(t.type)&&n}hasEventBeenHandled(t){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(ts(t))}saveEventToCache(t){this.cachedEventUids.add(ts(t)),this.lastProcessedEventTime=Date.now()}}function ts(t){return[t.type,t.eventId,t.sessionId,t.tenantId].filter((t=>t)).join("-")}function es({type:t,error:e}){return"unknown"===t&&"auth/no-auth-event"===(null==e?void 0:e.code)}const ns=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,ss=/^https?/;function rs(t){const e=le(),{protocol:n,hostname:s}=new URL(e);if(t.startsWith("chrome-extension://")){const r=new URL(t);return""===r.hostname&&""===s?"chrome-extension:"===n&&t.replace("chrome-extension://","")===e.replace("chrome-extension://",""):"chrome-extension:"===n&&r.hostname===s}if(!ss.test(n))return!1;if(ns.test(t))return s===t;const r=t.replace(/\./g,"\\.");return new RegExp("^(.+\\."+r+"|"+r+")$","i").test(s)}const is=new fe(3e4,6e4);function os(){const t=Nn().___jsl;if(null==t?void 0:t.H)for(const e of Object.keys(t.H))if(t.H[e].r=t.H[e].r||[],t.H[e].L=t.H[e].L||[],t.H[e].r=[...t.H[e].L],t.CP)for(let e=0;e{var s,r,i,o;function a(){os(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{os(),n(re(t,"network-request-failed"))},timeout:is.get()})}if(null===(r=null===(s=Nn().gapi)||void 0===s?void 0:s.iframes)||void 0===r?void 0:r.Iframe)e(gapi.iframes.getContext());else{if(!(null===(i=Nn().gapi)||void 0===i?void 0:i.load)){const e=Bn("iframefcb");return Nn()[e]=()=>{gapi.load?a():n(re(t,"network-request-failed"))},(o=`https://apis.google.com/js/api.js?onload=${e}`,new Promise(((t,e)=>{const n=document.createElement("script");n.setAttribute("src",o),n.onload=t,n.onerror=t=>{const n=re("internal-error");n.customData=t,e(n)},n.type="text/javascript",n.charset="UTF-8",function(){var t,e;return null!==(e=null===(t=document.getElementsByTagName("head"))||void 0===t?void 0:t[0])&&void 0!==e?e:document}().appendChild(n)}))).catch((t=>n(t)))}a()}})).catch((t=>{throw as=null,t}))}(t),as}const us=new fe(5e3,15e3),hs={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},ls=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function ds(t){const e=t.config;oe(e.authDomain,t,"auth-domain-config-required");const n=e.emulator?pe(e,"emulator/auth/iframe"):`https://${t.config.authDomain}/__/auth/iframe`,s={apiKey:e.apiKey,appName:t.name,v:K},r=ls.get(t.config.apiHost);r&&(s.eid=r);const i=t._getFrameworks();return i.length&&(s.fw=i.join(",")),`${n}?${p(s).slice(1)}`}const fs={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class ps{constructor(t){this.window=t,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(t){}}}function ms(t,e,n,s,r,i){oe(t.config.authDomain,t,"auth-domain-config-required"),oe(t.config.apiKey,t,"invalid-api-key");const o={apiKey:t.config.apiKey,appName:t.name,authType:n,redirectUrl:s,v:K,eventId:r};if(e instanceof cn){e.setDefaultLanguage(t.languageCode),o.providerId=e.providerId||"",function(t){for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}(e.getCustomParameters())||(o.customParameters=JSON.stringify(e.getCustomParameters()));for(const[t,e]of Object.entries(i||{}))o[t]=e}if(e instanceof un){const t=e.getScopes().filter((t=>""!==t));t.length>0&&(o.scopes=t.join(","))}t.tenantId&&(o.tid=t.tenantId);const a=o;for(const t of Object.keys(a))void 0===a[t]&&delete a[t];return`${function({config:t}){return t.emulator?pe(t,"emulator/auth/handler"):`https://${t.authDomain}/__/auth/handler`}(t)}?${p(a).slice(1)}`}const gs="webStorageSupport",ys=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Sn,this._completeRedirectFn=Yn}async _openPopup(t,e,n,s){var i;return ce(null===(i=this.eventManagers[t._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()"),function(t,e,n,s=500,i=600){const o=Math.max((window.screen.availHeight-i)/2,0).toString(),a=Math.max((window.screen.availWidth-s)/2,0).toString();let c="";const u=Object.assign(Object.assign({},fs),{width:s.toString(),height:i.toString(),top:o,left:a}),h=r().toLowerCase();n&&(c=qe(h)?"_blank":n),je(h)&&(e=e||"http://localhost",u.scrollbars="yes");const l=Object.entries(u).reduce(((t,[e,n])=>`${t}${e}=${n},`),"");if(function(t=r()){var e;return Ge(t)&&!!(null===(e=window.navigator)||void 0===e?void 0:e.standalone)}(h)&&"_self"!==c)return function(t,e){const n=document.createElement("a");n.href=t,n.target=e;const s=document.createEvent("MouseEvent");s.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(s)}(e||"",c),new ps(null);const d=window.open(e||"",c,l);oe(d,t,"popup-blocked");try{d.focus()}catch(t){}return new ps(d)}(t,ms(t,e,n,le(),s),An())}async _openRedirect(t,e,n,s){return await this._originValidation(t),r=ms(t,e,n,le(),s),Nn().location.href=r,new Promise((()=>{}));var r}_initialize(t){const e=t._key();if(this.eventManagers[e]){const{manager:t,promise:n}=this.eventManagers[e];return t?Promise.resolve(t):(ce(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(t);return this.eventManagers[e]={promise:n},n.catch((()=>{delete this.eventManagers[e]})),n}async initAndGetManager(t){const e=await async function(t){const e=await cs(t),n=Nn().gapi;return oe(n,t,"internal-error"),e.open({where:document.body,url:ds(t),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:hs,dontclear:!0},(e=>new Promise((async(n,s)=>{await e.restyle({setHideOnLeave:!1});const r=re(t,"network-request-failed"),i=Nn().setTimeout((()=>{s(r)}),us.get());function o(){Nn().clearTimeout(i),n(e)}e.ping(o).then(o,(()=>{s(r)}))}))))}(t),n=new Zn(t);return e.register("authEvent",(e=>(oe(null==e?void 0:e.authEvent,t,"invalid-auth-event"),{status:n.onEvent(e.authEvent)?"ACK":"ERROR"})),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[t._key()]={manager:n},this.iframes[t._key()]=e,n}_isIframeWebStorageSupported(t,e){this.iframes[t._key()].send(gs,{type:gs},(n=>{var s;const r=null===(s=null==n?void 0:n[0])||void 0===s?void 0:s.webStorageSupport;void 0!==r&&e(!!r),se(t,"internal-error")}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(t){const e=t._key();return this.originValidationPromises[e]||(this.originValidationPromises[e]=async function(t){if(t.config.emulator)return;const{authorizedDomains:e}=await async function(t,e={}){return we(t,"GET","/v1/projects",e)}(t);for(const t of e)try{if(rs(t))return}catch(t){}se(t,"unauthorized-domain")}(t)),this.originValidationPromises[e]}get _shouldInitProactively(){return We()||Be()||Ge()}};var vs,ws="@firebase/auth",bs="0.19.4";class Ts{constructor(t){this.auth=t,this.internalListeners=new Map}getUid(){var t;return this.assertAuthConfigured(),(null===(t=this.auth.currentUser)||void 0===t?void 0:t.uid)||null}async getToken(t){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(t)}:null}addAuthTokenListener(t){if(this.assertAuthConfigured(),this.internalListeners.has(t))return;const e=this.auth.onIdTokenChanged((e=>{var n;t((null===(n=e)||void 0===n?void 0:n.stsTokenManager.accessToken)||null)}));this.internalListeners.set(t,e),this.updateProactiveRefresh()}removeAuthTokenListener(t){this.assertAuthConfigured();const e=this.internalListeners.get(t);e&&(this.internalListeners.delete(t),e(),this.updateProactiveRefresh())}assertAuthConfigured(){oe(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function Es(t=z()){const e=q(t,"auth");return e.isInitialized()?e.getImmediate():function(t,e){const n=q(t,"auth");if(n.isInitialized()){const t=n.getImmediate();if(d(n.getOptions(),null!=e?e:{}))return t;se(t,"already-initialized")}return n.initialize({options:e})}(t,{popupRedirectResolver:ys,persistence:[jn,In,Sn]})}vs="Browser",B(new T("auth",((t,{options:e})=>{const n=t.getProvider("app").getImmediate(),{apiKey:s,authDomain:r}=n.options;return(t=>{oe(s&&!s.includes(":"),"invalid-api-key",{appName:t.name}),oe(!(null==r?void 0:r.includes(":")),"argument-error",{appName:t.name});const n={apiKey:s,authDomain:r,clientPlatform:vs,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Je(vs)},i=new Xe(t,n);return function(t,e){const n=(null==e?void 0:e.persistence)||[],s=(Array.isArray(n)?n:[n]).map(he);(null==e?void 0:e.errorMap)&&t._updateErrorMap(e.errorMap),t._initializeWithPersistence(s,null==e?void 0:e.popupRedirectResolver)}(i,e),i})(n)}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((t,e,n)=>{t.getProvider("auth-internal").initialize()}))),B(new T("auth-internal",(t=>(t=>new Ts(t))(Qe(t.getProvider("auth").getImmediate()))),"PRIVATE").setInstantiationMode("EXPLICIT")),G(ws,bs,void 0),G(ws,bs,"esm2017");var Is,_s="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self?self:{},Ss={},ks=ks||{},As=_s||self;function Cs(){}function Ns(t){var e=typeof t;return"array"==(e="object"!=e?e:t?Array.isArray(t)?"array":e:"null")||"object"==e&&"number"==typeof t.length}function Rs(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}var Ls="closure_uid_"+(1e9*Math.random()>>>0),Ds=0;function Os(t,e,n){return t.call.apply(t.bind,arguments)}function Ps(t,e,n){if(!t)throw Error();if(2e?1:0}t:{var Js=As.navigator;if(Js){var Xs=Js.userAgent;if(Xs){Ks=Xs;break t}}Ks=""}function Qs(t,e,n){for(const s in t)e.call(n,t[s],s,t)}function Ys(t){const e={};for(const n in t)e[n]=t[n];return e}var Zs="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function tr(t,e){let n,s;for(let e=1;eparseFloat(lr)){nr=String(fr);break t}}nr=lr}var pr,mr={};function gr(){return t=mr,Object.prototype.hasOwnProperty.call(t,9)?t[9]:t[9]=function(){let t=0;const e=zs(String(nr)).split("."),n=zs("9").split("."),s=Math.max(e.length,n.length);for(let o=0;0==t&&o>>0);function jr(t){return"function"==typeof t?t:(t[Vr]||(t[Vr]=function(e){return t.handleEvent(e)}),t[Vr])}function Br(){Fs.call(this),this.i=new kr(this),this.P=this,this.I=null}function qr(t,e){var n,s=t.I;if(s)for(n=[];s;s=s.I)n.push(s);if(t=t.P,s=e.type||e,"string"==typeof e)e=new wr(e,t);else if(e instanceof wr)e.target=e.target||t;else{var r=e;tr(e=new wr(s,t),r)}if(r=!0,n)for(var i=n.length-1;0<=i;i--){var o=e.g=n[i];r=Hr(o,s,!0,e)&&r}if(r=Hr(o=e.g=t,s,!0,e)&&r,r=Hr(o,s,!1,e)&&r,n)for(i=0;inew Wr),(t=>t.reset()));class Wr{constructor(){this.next=this.g=this.h=null}set(t,e){this.h=t,this.g=e,this.next=null}reset(){this.next=this.g=this.h=null}}function Jr(t){As.setTimeout((()=>{throw t}),0)}function Xr(t,e){zr||function(){var t=As.Promise.resolve(void 0);zr=function(){t.then(Zr)}}(),Qr||(zr(),Qr=!0),Yr.add(t,e)}var Qr=!1,Yr=new class{constructor(){this.h=this.g=null}add(t,e){const n=Gr.get();n.set(t,e),this.h?this.h.next=n:this.g=n,this.h=n}};function Zr(){for(var t;t=Kr();){try{t.h.call(t.g)}catch(t){Jr(t)}var e=Gr;e.j(t),100>e.h&&(e.h++,t.next=e.g,e.g=t)}Qr=!1}function ti(t,e){Br.call(this),this.h=t||1,this.g=e||As,this.j=Ms(this.kb,this),this.l=Date.now()}function ei(t){t.da=!1,t.S&&(t.g.clearTimeout(t.S),t.S=null)}function ni(t,e,n){if("function"==typeof t)n&&(t=Ms(t,n));else{if(!t||"function"!=typeof t.handleEvent)throw Error("Invalid listener argument");t=Ms(t.handleEvent,t)}return 2147483647{t.g=null,t.i&&(t.i=!1,si(t))}),t.j);const e=t.h;t.h=null,t.m.apply(null,e)}Us(ti,Br),(Is=ti.prototype).da=!1,Is.S=null,Is.kb=function(){if(this.da){var t=Date.now()-this.l;0s.length)){var r=s[1];if(Array.isArray(r)&&!(1>r.length)){var i=r[0];if("noop"!=i&&"stop"!=i&&"close"!=i)for(var o=1;oe.length?Pi:(e=e.substr(s,n),t.C=s+n,e))}function ji(t){t.Y=Date.now()+t.P,Bi(t,t.P)}function Bi(t,e){if(null!=t.B)throw Error("WatchDog timer not null");t.B=wi(Ms(t.eb,t),e)}function qi(t){t.B&&(As.clearTimeout(t.B),t.B=null)}function Hi(t){0==t.l.G||t.I||fa(t.l,t)}function $i(t){qi(t);var e=t.L;e&&"function"==typeof e.na&&e.na(),t.L=null,ei(t.W),ci(t.V),t.g&&(e=t.g,t.g=null,e.abort(),e.na())}function Ki(t,e){try{var n=t.l;if(0!=n.G&&(n.g==t||_o(n.i,t)))if(n.I=t.N,!t.J&&_o(n.i,t)&&3==n.G){try{var s=n.Ca.g.parse(e)}catch(t){s=null}if(Array.isArray(s)&&3==s.length){var r=s;if(0==r[0]){t:if(!n.u){if(n.g){if(!(n.g.F+3e3r[2]&&n.N&&0==n.A&&!n.v&&(n.v=wi(Ms(n.ab,n),6e3));if(1>=Io(n.i)&&n.ka){try{n.ka()}catch(t){}n.ka=void 0}}else ma(n,11)}else if((t.J||n.g==t)&&da(n),!$s(e))for(r=n.Ca.g.parse(e),e=0;eh)&&(3!=h||ar||this.g&&(this.h.h||this.g.ga()||Xo(this.g)))){this.I||4!=h||7==e||mi(8==e||0>=l?3:2),qi(this);var n=this.g.ba();this.N=n;e:if(Ui(this)){var s=Xo(this.g);t="";var r=s.length,i=4==Jo(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){$i(this),Hi(this);var o="";break e}this.h.i=new As.TextDecoder}for(e=0;ee)throw Error("Bad port number "+e);t.m=e}else t.m=null}function no(t,e,n){e instanceof po?(t.h=e,function(t,e){e&&!t.j&&(mo(t),t.i=null,t.g.forEach((function(t,e){var n=e.toLowerCase();e!=n&&(go(this,e),vo(this,n,t))}),t)),t.j=e}(t.h,t.g)):(n||(e=oo(e,lo)),t.h=new po(e,t.g))}function so(t,e,n){t.h.set(e,n)}function ro(t){return so(t,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),t}function io(t,e){return t?e?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function oo(t,e,n){return"string"==typeof t?(t=encodeURI(t).replace(e,ao),n&&(t=t.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),t):null}function ao(t){return"%"+((t=t.charCodeAt(0))>>4&15).toString(16)+(15&t).toString(16)}Qi.prototype.toString=function(){var t=[],e=this.j;e&&t.push(oo(e,co,!0),":");var n=this.i;return(n||"file"==e)&&(t.push("//"),(e=this.s)&&t.push(oo(e,co,!0),"@"),t.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&t.push(":",String(n))),(n=this.l)&&(this.i&&"/"!=n.charAt(0)&&t.push("/"),t.push(oo(n,"/"==n.charAt(0)?ho:uo,!0))),(n=this.h.toString())&&t.push("?",n),(n=this.o)&&t.push("#",oo(n,fo)),t.join("")};var co=/[#\/\?@]/g,uo=/[#\?:]/g,ho=/[#\?]/g,lo=/[#\?@]/g,fo=/#/g;function po(t,e){this.h=this.g=null,this.i=t||null,this.j=!!e}function mo(t){t.g||(t.g=new Gi,t.h=0,t.i&&function(t,e){if(t){t=t.split("&");for(var n=0;n2*t.i&&Wi(t)))}function yo(t,e){return mo(t),e=wo(t,e),Ji(t.g.h,e)}function vo(t,e,n){go(t,e),0=t.j}function Io(t){return t.h?1:t.g?t.g.size:0}function _o(t,e){return t.h?t.h==e:!!t.g&&t.g.has(e)}function So(t,e){t.g?t.g.add(e):t.h=e}function ko(t,e){t.h&&t.h==e?t.h=null:t.g&&t.g.has(e)&&t.g.delete(e)}function Ao(t){if(null!=t.h)return t.i.concat(t.h.D);if(null!=t.g&&0!==t.g.size){let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}return Hs(t.i)}function Co(){}function No(){this.g=new Co}function Ro(t,e,n){const s=n||"";try{zi(t,(function(t,n){let r=t;Rs(t)&&(r=$r(t)),e.push(s+n+"="+encodeURIComponent(r))}))}catch(t){throw e.push(s+"type="+encodeURIComponent("_badmap")),t}}function Lo(t,e,n,s,r){try{e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null,r(s)}catch(t){}}function Do(t){this.l=t.$b||null,this.j=t.ib||!1}function Oo(t,e){Br.call(this),this.D=t,this.u=e,this.m=void 0,this.readyState=Po,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}bo.prototype.cancel=function(){if(this.i=Ao(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const t of this.g.values())t.cancel();this.g.clear()}},Co.prototype.stringify=function(t){return As.JSON.stringify(t,void 0)},Co.prototype.parse=function(t){return As.JSON.parse(t,void 0)},Us(Do,Ei),Do.prototype.g=function(){return new Oo(this.l,this.j)},Do.prototype.i=function(t){return function(){return t}}({}),Us(Oo,Br);var Po=0;function Mo(t){t.j.read().then(t.Sa.bind(t)).catch(t.ha.bind(t))}function xo(t){t.readyState=4,t.l=null,t.j=null,t.A=null,Uo(t)}function Uo(t){t.onreadystatechange&&t.onreadystatechange.call(t)}(Is=Oo.prototype).open=function(t,e){if(this.readyState!=Po)throw this.abort(),Error("Error reopening a connection");this.C=t,this.B=e,this.readyState=1,Uo(this)},Is.send=function(t){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const e={headers:this.v,method:this.C,credentials:this.m,cache:void 0};t&&(e.body=t),(this.D||As).fetch(new Request(this.B,e)).then(this.Va.bind(this),this.ha.bind(this))},Is.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted."),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,xo(this)),this.readyState=Po},Is.Va=function(t){if(this.g&&(this.l=t,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=t.headers,this.readyState=2,Uo(this)),this.g&&(this.readyState=3,Uo(this),this.g)))if("arraybuffer"===this.responseType)t.arrayBuffer().then(this.Ta.bind(this),this.ha.bind(this));else if(void 0!==As.ReadableStream&&"body"in t){if(this.j=t.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;Mo(this)}else t.text().then(this.Ua.bind(this),this.ha.bind(this))},Is.Sa=function(t){if(this.g){if(this.u&&t.value)this.response.push(t.value);else if(!this.u){var e=t.value?t.value:new Uint8Array(0);(e=this.A.decode(e,{stream:!t.done}))&&(this.response=this.responseText+=e)}t.done?xo(this):Uo(this),3==this.readyState&&Mo(this)}},Is.Ua=function(t){this.g&&(this.response=this.responseText=t,xo(this))},Is.Ta=function(t){this.g&&(this.response=t,xo(this))},Is.ha=function(){this.g&&xo(this)},Is.setRequestHeader=function(t,e){this.v.append(t,e)},Is.getResponseHeader=function(t){return this.h&&this.h.get(t.toLowerCase())||""},Is.getAllResponseHeaders=function(){if(!this.h)return"";const t=[],e=this.h.entries();for(var n=e.next();!n.done;)n=n.value,t.push(n[0]+": "+n[1]),n=e.next();return t.join("\r\n")},Object.defineProperty(Oo.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(t){this.m=t?"include":"same-origin"}});var Fo=As.JSON.parse;function Vo(t){Br.call(this),this.headers=new Gi,this.u=t||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=jo,this.K=this.L=!1}Us(Vo,Br);var jo="",Bo=/^https?$/i,qo=["POST","PUT"];function Ho(t){return"content-type"==t.toLowerCase()}function $o(t,e){t.h=!1,t.g&&(t.l=!0,t.g.abort(),t.l=!1),t.j=e,t.m=5,Ko(t),Go(t)}function Ko(t){t.D||(t.D=!0,qr(t,"complete"),qr(t,"error"))}function zo(t){if(t.h&&void 0!==ks&&(!t.C[1]||4!=Jo(t)||2!=t.ba()))if(t.v&&4==Jo(t))ni(t.Fa,0,t);else if(qr(t,"readystatechange"),4==Jo(t)){t.h=!1;try{const a=t.ba();t:switch(a){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var e=!0;break t;default:e=!1}var n;if(!(n=e)){var s;if(s=0===a){var r=String(t.H).match(Xi)[1]||null;if(!r&&As.self&&As.self.location){var i=As.self.location.protocol;r=i.substr(0,i.length-1)}s=!Bo.test(r?r.toLowerCase():"")}n=s}if(n)qr(t,"complete"),qr(t,"success");else{t.m=6;try{var o=2n)e=Math.max(0,r[o].h-100),i=!1;else try{Ro(a,t,"req"+n+"_")}catch(t){s&&s(a)}}if(i){s=t.join("&");break t}}}return t=t.l.splice(0,n),e.D=t,s}function ca(t){t.g||t.u||(t.Y=1,Xr(t.Ga,t),t.A=0)}function ua(t){return!(t.g||t.u||3<=t.A||(t.Y++,t.u=wi(Ms(t.Ga,t),pa(t,t.A)),t.A++,0))}function ha(t){null!=t.B&&(As.clearTimeout(t.B),t.B=null)}function la(t){t.g=new Ri(t,t.h,"rpc",t.Y),null===t.o&&(t.g.H=t.s),t.g.O=0;var e=Yi(t.oa);so(e,"RID","rpc"),so(e,"SID",t.J),so(e,"CI",t.N?"0":"1"),so(e,"AID",t.U),oa(t,e),so(e,"TYPE","xmlhttp"),t.o&&t.s&&Qo(e,t.o,t.s),t.K&&t.g.setTimeout(t.K);var n=t.g;t=t.la,n.K=1,n.v=ro(Yi(e)),n.s=null,n.U=!0,xi(n,t)}function da(t){null!=t.v&&(As.clearTimeout(t.v),t.v=null)}function fa(t,e){var n=null;if(t.g==e){da(t),ha(t),t.g=null;var s=2}else{if(!_o(t.i,e))return;n=e.D,ko(t.i,e),s=1}if(t.I=e.N,0!=t.G)if(e.i)if(1==s){n=e.s?e.s.length:0,e=Date.now()-e.F;var r=t.C;qr(s=fi(),new vi(s,n,e,r)),ra(t)}else ca(t);else if(3==(r=e.o)||0==r&&0=t.i.j-(t.m?1:0)||(t.m?(t.l=e.D.concat(t.l),0):1==t.G||2==t.G||t.C>=(t.Xa?0:t.Ya)||(t.m=wi(Ms(t.Ha,t,e),pa(t,t.C)),t.C++,0)))}(t,e)||2==s&&ua(t)))switch(n&&0e?null:"string"==typeof t?t.charAt(e):t[e]}(r.T()),n=As.FormData&&t instanceof As.FormData,!(0<=js(qo,e))||s||n||r.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),r.forEach((function(t,e){this.g.setRequestHeader(e,t)}),this),this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{Wo(this),0=this.O)){var t=2*this.O;this.h.info("BP detection timer enabled: "+t),this.B=wi(Ms(this.bb,this),t)}},Is.bb=function(){this.B&&(this.B=null,this.h.info("BP detection timeout reached."),this.h.info("Buffering proxy detected and switch to long-polling!"),this.N=!1,this.L=!0,yi(10),ea(this),la(this))},Is.ab=function(){null!=this.v&&(this.v=null,ea(this),ua(this),yi(19))},Is.jb=function(t){t?(this.h.info("Successfully pinged google.com"),yi(2)):(this.h.info("Failed to ping google.com"),yi(1))},(Is=wa.prototype).xa=function(){},Is.wa=function(){},Is.va=function(){},Is.ua=function(){},Is.Oa=function(){},ba.prototype.g=function(t,e){return new Ta(t,e)},Us(Ta,Br),Ta.prototype.m=function(){this.g.j=this.j,this.A&&(this.g.H=!0);var t=this.g,e=this.l,n=this.h||void 0;t.Wa&&(t.h.info("Origin Trials enabled."),Xr(Ms(t.hb,t,e))),yi(0),t.W=e,t.aa=n||{},t.N=t.X,t.F=ya(t,null,t.W),ra(t)},Ta.prototype.close=function(){ta(this.g)},Ta.prototype.u=function(t){if("string"==typeof t){var e={};e.__data__=t,sa(this.g,e)}else this.v?((e={}).__data__=$r(t),sa(this.g,e)):sa(this.g,t)},Ta.prototype.M=function(){this.g.j=null,delete this.j,ta(this.g),delete this.g,Ta.Z.M.call(this)},Us(Ea,Ai),Us(Ia,Ci),Us(_a,wa),_a.prototype.xa=function(){qr(this.g,"a")},_a.prototype.wa=function(t){qr(this.g,new Ea(t))},_a.prototype.va=function(t){qr(this.g,new Ia(t))},_a.prototype.ua=function(){qr(this.g,"b")},ba.prototype.createWebChannel=ba.prototype.g,Ta.prototype.send=Ta.prototype.u,Ta.prototype.open=Ta.prototype.m,Ta.prototype.close=Ta.prototype.close,bi.NO_ERROR=0,bi.TIMEOUT=8,bi.HTTP_ERROR=6,Ti.COMPLETE="complete",_i.EventType=ki,ki.OPEN="a",ki.CLOSE="b",ki.ERROR="c",ki.MESSAGE="d",Br.prototype.listen=Br.prototype.N,Vo.prototype.listenOnce=Vo.prototype.O,Vo.prototype.getLastError=Vo.prototype.La,Vo.prototype.getLastErrorCode=Vo.prototype.Da,Vo.prototype.getStatus=Vo.prototype.ba,Vo.prototype.getResponseJson=Vo.prototype.Qa,Vo.prototype.getResponseText=Vo.prototype.ga,Vo.prototype.send=Vo.prototype.ea;var Sa=Ss.createWebChannelTransport=function(){return new ba},ka=Ss.getStatEventTarget=function(){return fi()},Aa=Ss.ErrorCode=bi,Ca=Ss.EventType=Ti,Na=Ss.Event=li,Ra=Ss.Stat={rb:0,ub:1,vb:2,Ob:3,Tb:4,Qb:5,Rb:6,Pb:7,Nb:8,Sb:9,PROXY:10,NOPROXY:11,Lb:12,Hb:13,Ib:14,Gb:15,Jb:16,Kb:17,nb:18,mb:19,ob:20},La=Ss.FetchXmlHttpFactory=Do,Da=Ss.WebChannel=_i,Oa=Ss.XhrIo=Vo;const Pa="@firebase/firestore";class Ma{constructor(t){this.uid=t}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(t){return t.uid===this.uid}}Ma.UNAUTHENTICATED=new Ma(null),Ma.GOOGLE_CREDENTIALS=new Ma("google-credentials-uid"),Ma.FIRST_PARTY=new Ma("first-party-uid"),Ma.MOCK_USER=new Ma("mock-user");let xa="9.6.1";const Ua=new D("@firebase/firestore");function Fa(){return Ua.logLevel}function Va(t,...e){if(Ua.logLevel<=k.DEBUG){const n=e.map(qa);Ua.debug(`Firestore (${xa}): ${t}`,...n)}}function ja(t,...e){if(Ua.logLevel<=k.ERROR){const n=e.map(qa);Ua.error(`Firestore (${xa}): ${t}`,...n)}}function Ba(t,...e){if(Ua.logLevel<=k.WARN){const n=e.map(qa);Ua.warn(`Firestore (${xa}): ${t}`,...n)}}function qa(t){if("string"==typeof t)return t;try{return e=t,JSON.stringify(e)}catch(e){return t}var e}function Ha(t="Unexpected state"){const e=`FIRESTORE (${xa}) INTERNAL ASSERTION FAILED: `+t;throw ja(e),new Error(e)}function $a(t,e){t||Ha()}function Ka(t,e){return t}const za={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 Ga extends Error{constructor(t,e){super(e),this.code=t,this.message=e,this.name="FirebaseError",this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class Wa{constructor(){this.promise=new Promise(((t,e)=>{this.resolve=t,this.reject=e}))}}class Ja{constructor(t,e){this.user=e,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${t}`)}}class Xa{getToken(){return Promise.resolve(null)}invalidateToken(){}start(t,e){t.enqueueRetryable((()=>e(Ma.UNAUTHENTICATED)))}shutdown(){}}class Qa{constructor(t){this.t=t,this.currentUser=Ma.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,e){let n=this.i;const s=t=>this.i!==n?(n=this.i,e(t)):Promise.resolve();let r=new Wa;this.o=()=>{this.i++,this.currentUser=this.u(),r.resolve(),r=new Wa,t.enqueueRetryable((()=>s(this.currentUser)))};const i=()=>{const e=r;t.enqueueRetryable((async()=>{await e.promise,await s(this.currentUser)}))},o=t=>{Va("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=t,this.auth.addAuthTokenListener(this.o),i()};this.t.onInit((t=>o(t))),setTimeout((()=>{if(!this.auth){const t=this.t.getImmediate({optional:!0});t?o(t):(Va("FirebaseAuthCredentialsProvider","Auth not yet detected"),r.resolve(),r=new Wa)}}),0),i()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then((e=>this.i!==t?(Va("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?($a("string"==typeof e.accessToken),new Ja(e.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){const t=this.auth&&this.auth.getUid();return $a(null===t||"string"==typeof t),new Ma(t)}}class Ya{constructor(t,e,n){this.type="FirstParty",this.user=Ma.FIRST_PARTY,this.headers=new Map,this.headers.set("X-Goog-AuthUser",e);const s=t.auth.getAuthHeaderValueForFirstParty([]);s&&this.headers.set("Authorization",s),n&&this.headers.set("X-Goog-Iam-Authorization-Token",n)}}class Za{constructor(t,e,n){this.h=t,this.l=e,this.m=n}getToken(){return Promise.resolve(new Ya(this.h,this.l,this.m))}start(t,e){t.enqueueRetryable((()=>e(Ma.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class tc{constructor(t){this.value=t,this.type="AppCheck",this.headers=new Map,t&&t.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class ec{constructor(t){this.g=t,this.forceRefresh=!1,this.appCheck=null}start(t,e){this.o=n=>{t.enqueueRetryable((()=>(t=>(null!=t.error&&Va("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${t.error.message}`),e(t.token)))(n)))};const n=t=>{Va("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=t,this.appCheck.addTokenListener(this.o)};this.g.onInit((t=>n(t))),setTimeout((()=>{if(!this.appCheck){const t=this.g.getImmediate({optional:!0});t?n(t):Va("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const t=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(t).then((t=>t?($a("string"==typeof t.token),new tc(t.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class nc{constructor(t,e){this.previousValue=t,e&&(e.sequenceNumberHandler=t=>this.p(t),this.T=t=>e.writeSequenceNumber(t))}p(t){return this.previousValue=Math.max(t,this.previousValue),this.previousValue}next(){const t=++this.previousValue;return this.T&&this.T(t),t}}function sc(t){const e="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(t);if(e&&"function"==typeof e.getRandomValues)e.getRandomValues(n);else for(let e=0;ee?1:0}function oc(t,e,n){return t.length===e.length&&t.every(((t,s)=>n(t,e[s])))}class ac{constructor(t,e){if(this.seconds=t,this.nanoseconds=e,e<0)throw new Ga(za.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(e>=1e9)throw new Ga(za.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(t<-62135596800)throw new Ga(za.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(t>=253402300800)throw new Ga(za.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}static now(){return ac.fromMillis(Date.now())}static fromDate(t){return ac.fromMillis(t.getTime())}static fromMillis(t){const e=Math.floor(t/1e3),n=Math.floor(1e6*(t-1e3*e));return new ac(e,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(t){return this.seconds===t.seconds?ic(this.nanoseconds,t.nanoseconds):ic(this.seconds,t.seconds)}isEqual(t){return t.seconds===this.seconds&&t.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const t=this.seconds- -62135596800;return String(t).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class cc{constructor(t){this.timestamp=t}static fromTimestamp(t){return new cc(t)}static min(){return new cc(new ac(0,0))}compareTo(t){return this.timestamp._compareTo(t.timestamp)}isEqual(t){return this.timestamp.isEqual(t.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}function uc(t){let e=0;for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}function hc(t,e){for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(n,t[n])}function lc(t){for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}class dc{constructor(t,e,n){void 0===e?e=0:e>t.length&&Ha(),void 0===n?n=t.length-e:n>t.length-e&&Ha(),this.segments=t,this.offset=e,this.len=n}get length(){return this.len}isEqual(t){return 0===dc.comparator(this,t)}child(t){const e=this.segments.slice(this.offset,this.limit());return t instanceof dc?t.forEach((t=>{e.push(t)})):e.push(t),this.construct(e)}limit(){return this.offset+this.length}popFirst(t){return t=void 0===t?1:t,this.construct(this.segments,this.offset+t,this.length-t)}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(t){return this.segments[this.offset+t]}isEmpty(){return 0===this.length}isPrefixOf(t){if(t.lengthr)return 1}return t.lengthe.length?1:0}}class fc extends dc{construct(t,e,n){return new fc(t,e,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...t){const e=[];for(const n of t){if(n.indexOf("//")>=0)throw new Ga(za.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);e.push(...n.split("/").filter((t=>t.length>0)))}return new fc(e)}static emptyPath(){return new fc([])}}const pc=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class mc extends dc{construct(t,e,n){return new mc(t,e,n)}static isValidIdentifier(t){return pc.test(t)}canonicalString(){return this.toArray().map((t=>(t=t.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),mc.isValidIdentifier(t)||(t="`"+t+"`"),t))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new mc(["__name__"])}static fromServerFormat(t){const e=[];let n="",s=0;const r=()=>{if(0===n.length)throw new Ga(za.INVALID_ARGUMENT,`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);e.push(n),n=""};let i=!1;for(;st.isEqual(e)))}}class yc{constructor(t){this.binaryString=t}static fromBase64String(t){const e=atob(t);return new yc(e)}static fromUint8Array(t){const e=function(t){let e="";for(let n=0;n=2&&this.path.get(this.path.length-2)===t}isEqual(t){return null!==t&&0===fc.comparator(this.path,t.path)}toString(){return this.path.toString()}static comparator(t,e){return fc.comparator(t.path,e.path)}static isDocumentKey(t){return t.length%2==0}static fromSegments(t){return new Ac(new fc(t.slice()))}}function Cc(t){return"nullValue"in t?0:"booleanValue"in t?1:"integerValue"in t||"doubleValue"in t?2:"timestampValue"in t?3:"stringValue"in t?5:"bytesValue"in t?6:"referenceValue"in t?7:"geoPointValue"in t?8:"arrayValue"in t?9:"mapValue"in t?Ec(t)?4:10:Ha()}function Nc(t,e){const n=Cc(t);if(n!==Cc(e))return!1;switch(n){case 0:return!0;case 1:return t.booleanValue===e.booleanValue;case 4:return _c(t).isEqual(_c(e));case 3:return function(t,e){if("string"==typeof t.timestampValue&&"string"==typeof e.timestampValue&&t.timestampValue.length===e.timestampValue.length)return t.timestampValue===e.timestampValue;const n=wc(t.timestampValue),s=wc(e.timestampValue);return n.seconds===s.seconds&&n.nanos===s.nanos}(t,e);case 5:return t.stringValue===e.stringValue;case 6:return function(t,e){return Tc(t.bytesValue).isEqual(Tc(e.bytesValue))}(t,e);case 7:return t.referenceValue===e.referenceValue;case 8:return function(t,e){return bc(t.geoPointValue.latitude)===bc(e.geoPointValue.latitude)&&bc(t.geoPointValue.longitude)===bc(e.geoPointValue.longitude)}(t,e);case 2:return function(t,e){if("integerValue"in t&&"integerValue"in e)return bc(t.integerValue)===bc(e.integerValue);if("doubleValue"in t&&"doubleValue"in e){const n=bc(t.doubleValue),s=bc(e.doubleValue);return n===s?kc(n)===kc(s):isNaN(n)&&isNaN(s)}return!1}(t,e);case 9:return oc(t.arrayValue.values||[],e.arrayValue.values||[],Nc);case 10:return function(t,e){const n=t.mapValue.fields||{},s=e.mapValue.fields||{};if(uc(n)!==uc(s))return!1;for(const t in n)if(n.hasOwnProperty(t)&&(void 0===s[t]||!Nc(n[t],s[t])))return!1;return!0}(t,e);default:return Ha()}}function Rc(t,e){return void 0!==(t.values||[]).find((t=>Nc(t,e)))}function Lc(t,e){const n=Cc(t),s=Cc(e);if(n!==s)return ic(n,s);switch(n){case 0:return 0;case 1:return ic(t.booleanValue,e.booleanValue);case 2:return function(t,e){const n=bc(t.integerValue||t.doubleValue),s=bc(e.integerValue||e.doubleValue);return ns?1:n===s?0:isNaN(n)?isNaN(s)?0:-1:1}(t,e);case 3:return Dc(t.timestampValue,e.timestampValue);case 4:return Dc(_c(t),_c(e));case 5:return ic(t.stringValue,e.stringValue);case 6:return function(t,e){const n=Tc(t),s=Tc(e);return n.compareTo(s)}(t.bytesValue,e.bytesValue);case 7:return function(t,e){const n=t.split("/"),s=e.split("/");for(let t=0;te.mapValue.fields[t]=jc(n))),e}if(t.arrayValue){const e={arrayValue:{values:[]}};for(let n=0;n<(t.arrayValue.values||[]).length;++n)e.arrayValue.values[n]=jc(t.arrayValue.values[n]);return e}return Object.assign({},t)}class Bc{constructor(t){this.value=t}static empty(){return new Bc({mapValue:{}})}field(t){if(t.isEmpty())return this.value;{let e=this.value;for(let n=0;n{if(!e.isImmediateParentOf(r)){const t=this.getFieldsMap(e);this.applyChanges(t,n,s),n={},s=[],e=r.popLast()}t?n[r.lastSegment()]=jc(t):s.push(r.lastSegment())}));const r=this.getFieldsMap(e);this.applyChanges(r,n,s)}delete(t){const e=this.field(t.popLast());Vc(e)&&e.mapValue.fields&&delete e.mapValue.fields[t.lastSegment()]}isEqual(t){return Nc(this.value,t.value)}getFieldsMap(t){let e=this.value;e.mapValue.fields||(e.mapValue={fields:{}});for(let n=0;nt[e]=n));for(const e of n)delete t[e]}clone(){return new Bc(jc(this.value))}}function qc(t){const e=[];return hc(t.fields,((t,n)=>{const s=new mc([t]);if(Vc(n)){const t=qc(n.mapValue).fields;if(0===t.length)e.push(s);else for(const n of t)e.push(s.child(n))}else e.push(s)})),new gc(e)}class Hc{constructor(t,e,n,s,r){this.key=t,this.documentType=e,this.version=n,this.data=s,this.documentState=r}static newInvalidDocument(t){return new Hc(t,0,cc.min(),Bc.empty(),0)}static newFoundDocument(t,e,n){return new Hc(t,1,e,n,0)}static newNoDocument(t,e){return new Hc(t,2,e,Bc.empty(),0)}static newUnknownDocument(t,e){return new Hc(t,3,e,Bc.empty(),2)}convertToFoundDocument(t,e){return this.version=t,this.documentType=1,this.data=e,this.documentState=0,this}convertToNoDocument(t){return this.version=t,this.documentType=2,this.data=Bc.empty(),this.documentState=0,this}convertToUnknownDocument(t){return this.version=t,this.documentType=3,this.data=Bc.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(t){return t instanceof Hc&&this.key.isEqual(t.key)&&this.version.isEqual(t.version)&&this.documentType===t.documentType&&this.documentState===t.documentState&&this.data.isEqual(t.data)}clone(){return new Hc(this.key,this.documentType,this.version,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class $c{constructor(t,e=null,n=[],s=[],r=null,i=null,o=null){this.path=t,this.collectionGroup=e,this.orderBy=n,this.filters=s,this.limit=r,this.startAt=i,this.endAt=o,this.R=null}}function Kc(t,e=null,n=[],s=[],r=null,i=null,o=null){return new $c(t,e,n,s,r,i,o)}function zc(t){const e=Ka(t);if(null===e.R){let t=e.path.canonicalString();null!==e.collectionGroup&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map((t=>function(t){return t.field.canonicalString()+t.op.toString()+Oc(t.value)}(t))).join(","),t+="|ob:",t+=e.orderBy.map((t=>function(t){return t.field.canonicalString()+t.dir}(t))).join(","),Sc(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=iu(e.startAt)),e.endAt&&(t+="|ub:",t+=iu(e.endAt)),e.R=t}return e.R}function Gc(t,e){if(t.limit!==e.limit)return!1;if(t.orderBy.length!==e.orderBy.length)return!1;for(let n=0;n":return t>0;case">=":return t>=0;default:return Ha()}}V(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}}class Xc extends Jc{constructor(t,e,n){super(t,e,n),this.key=Ac.fromName(n.referenceValue)}matches(t){const e=Ac.comparator(t.key,this.key);return this.v(e)}}class Qc extends Jc{constructor(t,e){super(t,"in",e),this.keys=Zc(0,e)}matches(t){return this.keys.some((e=>e.isEqual(t.key)))}}class Yc extends Jc{constructor(t,e){super(t,"not-in",e),this.keys=Zc(0,e)}matches(t){return!this.keys.some((e=>e.isEqual(t.key)))}}function Zc(t,e){var n;return((null===(n=e.arrayValue)||void 0===n?void 0:n.values)||[]).map((t=>Ac.fromName(t.referenceValue)))}class tu extends Jc{constructor(t,e){super(t,"array-contains",e)}matches(t){const e=t.data.field(this.field);return xc(e)&&Rc(e.arrayValue,this.value)}}class eu extends Jc{constructor(t,e){super(t,"in",e)}matches(t){const e=t.data.field(this.field);return null!==e&&Rc(this.value.arrayValue,e)}}class nu extends Jc{constructor(t,e){super(t,"not-in",e)}matches(t){if(Rc(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const e=t.data.field(this.field);return null!==e&&!Rc(this.value.arrayValue,e)}}class su extends Jc{constructor(t,e){super(t,"array-contains-any",e)}matches(t){const e=t.data.field(this.field);return!(!xc(e)||!e.arrayValue.values)&&e.arrayValue.values.some((t=>Rc(this.value.arrayValue,t)))}}class ru{constructor(t,e){this.position=t,this.before=e}}function iu(t){return`${t.before?"b":"a"}:${t.position.map((t=>Oc(t))).join(",")}`}class ou{constructor(t,e="asc"){this.field=t,this.dir=e}}function au(t,e){return t.dir===e.dir&&t.field.isEqual(e.field)}function cu(t,e,n){let s=0;for(let r=0;r0?t.explicitOrderBy[0].field:null}function mu(t){for(const e of t.filters)if(e.V())return e.field;return null}function gu(t){const e=Ka(t);if(null===e.S){e.S=[];const t=mu(e),n=pu(e);if(null!==t&&null===n)t.isKeyField()||e.S.push(new ou(t)),e.S.push(new ou(mc.keyField(),"asc"));else{let t=!1;for(const n of e.explicitOrderBy)e.S.push(n),n.field.isKeyField()&&(t=!0);if(!t){const t=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";e.S.push(new ou(mc.keyField(),t))}}}return e.S}function yu(t){const e=Ka(t);if(!e.D)if("F"===e.limitType)e.D=Kc(e.path,e.collectionGroup,gu(e),e.filters,e.limit,e.startAt,e.endAt);else{const t=[];for(const n of gu(e)){const e="desc"===n.dir?"asc":"desc";t.push(new ou(n.field,e))}const n=e.endAt?new ru(e.endAt.position,!e.endAt.before):null,s=e.startAt?new ru(e.startAt.position,!e.startAt.before):null;e.D=Kc(e.path,e.collectionGroup,t,e.filters,e.limit,n,s)}return e.D}function vu(t,e,n){return new hu(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),e,n,t.startAt,t.endAt)}function wu(t,e){return Gc(yu(t),yu(e))&&t.limitType===e.limitType}function bu(t){return`${zc(yu(t))}|lt:${t.limitType}`}function Tu(t){return`Query(target=${function(t){let e=t.path.canonicalString();return null!==t.collectionGroup&&(e+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(e+=`, filters: [${t.filters.map((t=>{return`${(e=t).field.canonicalString()} ${e.op} ${Oc(e.value)}`;var e})).join(", ")}]`),Sc(t.limit)||(e+=", limit: "+t.limit),t.orderBy.length>0&&(e+=`, orderBy: [${t.orderBy.map((t=>function(t){return`${t.field.canonicalString()} (${t.dir})`}(t))).join(", ")}]`),t.startAt&&(e+=", startAt: "+iu(t.startAt)),t.endAt&&(e+=", endAt: "+iu(t.endAt)),`Target(${e})`}(yu(t))}; limitType=${t.limitType})`}function Eu(t,e){return e.isFoundDocument()&&function(t,e){const n=e.key.path;return null!==t.collectionGroup?e.key.hasCollectionId(t.collectionGroup)&&t.path.isPrefixOf(n):Ac.isDocumentKey(t.path)?t.path.isEqual(n):t.path.isImmediateParentOf(n)}(t,e)&&function(t,e){for(const n of t.explicitOrderBy)if(!n.field.isKeyField()&&null===e.data.field(n.field))return!1;return!0}(t,e)&&function(t,e){for(const n of t.filters)if(!n.matches(e))return!1;return!0}(t,e)&&function(t,e){return!(t.startAt&&!cu(t.startAt,gu(t),e)||t.endAt&&cu(t.endAt,gu(t),e))}(t,e)}function Iu(t){return(e,n)=>{let s=!1;for(const r of gu(t)){const t=_u(r,e,n);if(0!==t)return t;s=s||r.field.isKeyField()}return 0}}function _u(t,e,n){const s=t.field.isKeyField()?Ac.comparator(e.key,n.key):function(t,e,n){const s=e.data.field(t),r=n.data.field(t);return null!==s&&null!==r?Lc(s,r):Ha()}(t.field,e,n);switch(t.dir){case"asc":return s;case"desc":return-1*s;default:return Ha()}}function Su(t,e){if(t.C){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:kc(e)?"-0":e}}function ku(t){return{integerValue:""+t}}function Au(t,e){return function(t){return"number"==typeof t&&Number.isInteger(t)&&!kc(t)&&t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER}(e)?ku(e):Su(t,e)}class Cu{constructor(){this._=void 0}}function Nu(t,e,n){return t instanceof Du?function(t,e){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:t.seconds,nanos:t.nanoseconds}}}};return e&&(n.fields.__previous_value__=e),{mapValue:n}}(n,e):t instanceof Ou?Pu(t,e):t instanceof Mu?xu(t,e):function(t,e){const n=Lu(t,e),s=Fu(n)+Fu(t.N);return Mc(n)&&Mc(t.N)?ku(s):Su(t.k,s)}(t,e)}function Ru(t,e,n){return t instanceof Ou?Pu(t,e):t instanceof Mu?xu(t,e):n}function Lu(t,e){return t instanceof Uu?Mc(n=e)||function(t){return!!t&&"doubleValue"in t}(n)?e:{integerValue:0}:null;var n}class Du extends Cu{}class Ou extends Cu{constructor(t){super(),this.elements=t}}function Pu(t,e){const n=Vu(e);for(const e of t.elements)n.some((t=>Nc(t,e)))||n.push(e);return{arrayValue:{values:n}}}class Mu extends Cu{constructor(t){super(),this.elements=t}}function xu(t,e){let n=Vu(e);for(const e of t.elements)n=n.filter((t=>!Nc(t,e)));return{arrayValue:{values:n}}}class Uu extends Cu{constructor(t,e){super(),this.k=t,this.N=e}}function Fu(t){return bc(t.integerValue||t.doubleValue)}function Vu(t){return xc(t)&&t.arrayValue.values?t.arrayValue.values.slice():[]}class ju{constructor(t,e){this.version=t,this.transformResults=e}}class Bu{constructor(t,e){this.updateTime=t,this.exists=e}static none(){return new Bu}static exists(t){return new Bu(void 0,t)}static updateTime(t){return new Bu(t)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(t){return this.exists===t.exists&&(this.updateTime?!!t.updateTime&&this.updateTime.isEqual(t.updateTime):!t.updateTime)}}function qu(t,e){return void 0!==t.updateTime?e.isFoundDocument()&&e.version.isEqual(t.updateTime):void 0===t.exists||t.exists===e.isFoundDocument()}class Hu{}function $u(t,e,n){t instanceof Ju?function(t,e,n){const s=t.value.clone(),r=Yu(t.fieldTransforms,e,n.transformResults);s.setAll(r),e.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(t,e,n):t instanceof Xu?function(t,e,n){if(!qu(t.precondition,e))return void e.convertToUnknownDocument(n.version);const s=Yu(t.fieldTransforms,e,n.transformResults),r=e.data;r.setAll(Qu(t)),r.setAll(s),e.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(t,e,n):function(t,e,n){e.convertToNoDocument(n.version).setHasCommittedMutations()}(0,e,n)}function Ku(t,e,n){t instanceof Ju?function(t,e,n){if(!qu(t.precondition,e))return;const s=t.value.clone(),r=Zu(t.fieldTransforms,n,e);s.setAll(r),e.convertToFoundDocument(Wu(e),s).setHasLocalMutations()}(t,e,n):t instanceof Xu?function(t,e,n){if(!qu(t.precondition,e))return;const s=Zu(t.fieldTransforms,n,e),r=e.data;r.setAll(Qu(t)),r.setAll(s),e.convertToFoundDocument(Wu(e),r).setHasLocalMutations()}(t,e,n):function(t,e){qu(t.precondition,e)&&e.convertToNoDocument(cc.min())}(t,e)}function zu(t,e){let n=null;for(const s of t.fieldTransforms){const t=e.data.field(s.field),r=Lu(s.transform,t||null);null!=r&&(null==n&&(n=Bc.empty()),n.set(s.field,r))}return n||null}function Gu(t,e){return t.type===e.type&&!!t.key.isEqual(e.key)&&!!t.precondition.isEqual(e.precondition)&&!!function(t,e){return void 0===t&&void 0===e||!(!t||!e)&&oc(t,e,((t,e)=>function(t,e){return t.field.isEqual(e.field)&&function(t,e){return t instanceof Ou&&e instanceof Ou||t instanceof Mu&&e instanceof Mu?oc(t.elements,e.elements,Nc):t instanceof Uu&&e instanceof Uu?Nc(t.N,e.N):t instanceof Du&&e instanceof Du}(t.transform,e.transform)}(t,e)))}(t.fieldTransforms,e.fieldTransforms)&&(0===t.type?t.value.isEqual(e.value):1!==t.type||t.data.isEqual(e.data)&&t.fieldMask.isEqual(e.fieldMask))}function Wu(t){return t.isFoundDocument()?t.version:cc.min()}class Ju extends Hu{constructor(t,e,n,s=[]){super(),this.key=t,this.value=e,this.precondition=n,this.fieldTransforms=s,this.type=0}}class Xu extends Hu{constructor(t,e,n,s,r=[]){super(),this.key=t,this.data=e,this.fieldMask=n,this.precondition=s,this.fieldTransforms=r,this.type=1}}function Qu(t){const e=new Map;return t.fieldMask.fields.forEach((n=>{if(!n.isEmpty()){const s=t.data.field(n);e.set(n,s)}})),e}function Yu(t,e,n){const s=new Map;$a(t.length===n.length);for(let r=0;r0&&(e=e.right)}return null}indexOf(t){let e=0,n=this.root;for(;!n.isEmpty();){const s=this.comparator(t,n.key);if(0===s)return e+n.left.size;s<0?n=n.left:(e+=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(t){return this.root.inorderTraversal(t)}forEach(t){this.inorderTraversal(((e,n)=>(t(e,n),!1)))}toString(){const t=[];return this.inorderTraversal(((e,n)=>(t.push(`${e}:${n}`),!1))),`{${t.join(", ")}}`}reverseTraversal(t){return this.root.reverseTraversal(t)}getIterator(){return new ah(this.root,null,this.comparator,!1)}getIteratorFrom(t){return new ah(this.root,t,this.comparator,!1)}getReverseIterator(){return new ah(this.root,null,this.comparator,!0)}getReverseIteratorFrom(t){return new ah(this.root,t,this.comparator,!0)}}class ah{constructor(t,e,n,s){this.isReverse=s,this.nodeStack=[];let r=1;for(;!t.isEmpty();)if(r=e?n(t.key,e):1,s&&(r*=-1),r<0)t=this.isReverse?t.left:t.right;else{if(0===r){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}getNext(){let t=this.nodeStack.pop();const e={key:t.key,value:t.value};if(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 t=this.nodeStack[this.nodeStack.length-1];return{key:t.key,value:t.value}}}class ch{constructor(t,e,n,s,r){this.key=t,this.value=e,this.color=null!=n?n:ch.RED,this.left=null!=s?s:ch.EMPTY,this.right=null!=r?r:ch.EMPTY,this.size=this.left.size+1+this.right.size}copy(t,e,n,s,r){return new ch(null!=t?t:this.key,null!=e?e:this.value,null!=n?n:this.color,null!=s?s:this.left,null!=r?r:this.right)}isEmpty(){return!1}inorderTraversal(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)}reverseTraversal(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)}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(t,e,n){let s=this;const r=n(t,s.key);return s=r<0?s.copy(null,null,null,s.left.insert(t,e,n),null):0===r?s.copy(null,e,null,null,null):s.copy(null,null,null,null,s.right.insert(t,e,n)),s.fixUp()}removeMin(){if(this.left.isEmpty())return ch.EMPTY;let t=this;return t.left.isRed()||t.left.left.isRed()||(t=t.moveRedLeft()),t=t.copy(null,null,null,t.left.removeMin(),null),t.fixUp()}remove(t,e){let n,s=this;if(e(t,s.key)<0)s.left.isEmpty()||s.left.isRed()||s.left.left.isRed()||(s=s.moveRedLeft()),s=s.copy(null,null,null,s.left.remove(t,e),null);else{if(s.left.isRed()&&(s=s.rotateRight()),s.right.isEmpty()||s.right.isRed()||s.right.left.isRed()||(s=s.moveRedRight()),0===e(t,s.key)){if(s.right.isEmpty())return ch.EMPTY;n=s.right.min(),s=s.copy(n.key,n.value,null,null,s.right.removeMin())}s=s.copy(null,null,null,null,s.right.remove(t,e))}return s.fixUp()}isRed(){return this.color}fixUp(){let t=this;return t.right.isRed()&&!t.left.isRed()&&(t=t.rotateLeft()),t.left.isRed()&&t.left.left.isRed()&&(t=t.rotateRight()),t.left.isRed()&&t.right.isRed()&&(t=t.colorFlip()),t}moveRedLeft(){let t=this.colorFlip();return t.right.left.isRed()&&(t=t.copy(null,null,null,null,t.right.rotateRight()),t=t.rotateLeft(),t=t.colorFlip()),t}moveRedRight(){let t=this.colorFlip();return t.left.left.isRed()&&(t=t.rotateRight(),t=t.colorFlip()),t}rotateLeft(){const t=this.copy(null,null,ch.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)}rotateRight(){const t=this.copy(null,null,ch.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)}colorFlip(){const t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)}checkMaxDepth(){const t=this.check();return Math.pow(2,t)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw Ha();if(this.right.isRed())throw Ha();const t=this.left.check();if(t!==this.right.check())throw Ha();return t+(this.isRed()?0:1)}}ch.EMPTY=null,ch.RED=!0,ch.BLACK=!1,ch.EMPTY=new class{constructor(){this.size=0}get key(){throw Ha()}get value(){throw Ha()}get color(){throw Ha()}get left(){throw Ha()}get right(){throw Ha()}copy(t,e,n,s,r){return this}insert(t,e,n){return new ch(t,e)}remove(t,e){return this}isEmpty(){return!0}inorderTraversal(t){return!1}reverseTraversal(t){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class uh{constructor(t){this.comparator=t,this.data=new oh(this.comparator)}has(t){return null!==this.data.get(t)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(t){return this.data.indexOf(t)}forEach(t){this.data.inorderTraversal(((e,n)=>(t(e),!1)))}forEachInRange(t,e){const n=this.data.getIteratorFrom(t[0]);for(;n.hasNext();){const s=n.getNext();if(this.comparator(s.key,t[1])>=0)return;e(s.key)}}forEachWhile(t,e){let n;for(n=void 0!==e?this.data.getIteratorFrom(e):this.data.getIterator();n.hasNext();)if(!t(n.getNext().key))return}firstAfterOrEqual(t){const e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null}getIterator(){return new hh(this.data.getIterator())}getIteratorFrom(t){return new hh(this.data.getIteratorFrom(t))}add(t){return this.copy(this.data.remove(t).insert(t,!0))}delete(t){return this.has(t)?this.copy(this.data.remove(t)):this}isEmpty(){return this.data.isEmpty()}unionWith(t){let e=this;return e.size{e=e.add(t)})),e}isEqual(t){if(!(t instanceof uh))return!1;if(this.size!==t.size)return!1;const e=this.data.getIterator(),n=t.data.getIterator();for(;e.hasNext();){const t=e.getNext().key,s=n.getNext().key;if(0!==this.comparator(t,s))return!1}return!0}toArray(){const t=[];return this.forEach((e=>{t.push(e)})),t}toString(){const t=[];return this.forEach((e=>t.push(e))),"SortedSet("+t.toString()+")"}copy(t){const e=new uh(this.comparator);return e.data=t,e}}class hh{constructor(t){this.iter=t}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}const lh=new oh(Ac.comparator);function dh(){return lh}const fh=new oh(Ac.comparator);function ph(){return fh}const mh=new oh(Ac.comparator);const gh=new uh(Ac.comparator);function yh(...t){let e=gh;for(const n of t)e=e.add(n);return e}const vh=new uh(ic);function wh(){return vh}class bh{constructor(t,e,n,s,r){this.snapshotVersion=t,this.targetChanges=e,this.targetMismatches=n,this.documentUpdates=s,this.resolvedLimboDocuments=r}static createSynthesizedRemoteEventForCurrentChange(t,e){const n=new Map;return n.set(t,Th.createSynthesizedTargetChangeForCurrentChange(t,e)),new bh(cc.min(),n,wh(),dh(),yh())}}class Th{constructor(t,e,n,s,r){this.resumeToken=t,this.current=e,this.addedDocuments=n,this.modifiedDocuments=s,this.removedDocuments=r}static createSynthesizedTargetChangeForCurrentChange(t,e){return new Th(yc.EMPTY_BYTE_STRING,e,yh(),yh(),yh())}}class Eh{constructor(t,e,n,s){this.$=t,this.removedTargetIds=e,this.key=n,this.F=s}}class Ih{constructor(t,e){this.targetId=t,this.O=e}}class _h{constructor(t,e,n=yc.EMPTY_BYTE_STRING,s=null){this.state=t,this.targetIds=e,this.resumeToken=n,this.cause=s}}class Sh{constructor(){this.M=0,this.L=Ch(),this.B=yc.EMPTY_BYTE_STRING,this.U=!1,this.q=!0}get current(){return this.U}get resumeToken(){return this.B}get K(){return 0!==this.M}get j(){return this.q}W(t){t.approximateByteSize()>0&&(this.q=!0,this.B=t)}G(){let t=yh(),e=yh(),n=yh();return this.L.forEach(((s,r)=>{switch(r){case 0:t=t.add(s);break;case 2:e=e.add(s);break;case 1:n=n.add(s);break;default:Ha()}})),new Th(this.B,this.U,t,e,n)}H(){this.q=!1,this.L=Ch()}J(t,e){this.q=!0,this.L=this.L.insert(t,e)}Y(t){this.q=!0,this.L=this.L.remove(t)}X(){this.M+=1}Z(){this.M-=1}tt(){this.q=!0,this.U=!0}}class kh{constructor(t){this.et=t,this.nt=new Map,this.st=dh(),this.it=Ah(),this.rt=new uh(ic)}ot(t){for(const e of t.$)t.F&&t.F.isFoundDocument()?this.at(e,t.F):this.ct(e,t.key,t.F);for(const e of t.removedTargetIds)this.ct(e,t.key,t.F)}ut(t){this.forEachTarget(t,(e=>{const n=this.ht(e);switch(t.state){case 0:this.lt(e)&&n.W(t.resumeToken);break;case 1:n.Z(),n.K||n.H(),n.W(t.resumeToken);break;case 2:n.Z(),n.K||this.removeTarget(e);break;case 3:this.lt(e)&&(n.tt(),n.W(t.resumeToken));break;case 4:this.lt(e)&&(this.ft(e),n.W(t.resumeToken));break;default:Ha()}}))}forEachTarget(t,e){t.targetIds.length>0?t.targetIds.forEach(e):this.nt.forEach(((t,n)=>{this.lt(n)&&e(n)}))}dt(t){const e=t.targetId,n=t.O.count,s=this.wt(e);if(s){const t=s.target;if(Wc(t))if(0===n){const n=new Ac(t.path);this.ct(e,n,Hc.newNoDocument(n,cc.min()))}else $a(1===n);else this._t(e)!==n&&(this.ft(e),this.rt=this.rt.add(e))}}gt(t){const e=new Map;this.nt.forEach(((n,s)=>{const r=this.wt(s);if(r){if(n.current&&Wc(r.target)){const e=new Ac(r.target.path);null!==this.st.get(e)||this.yt(s,e)||this.ct(s,e,Hc.newNoDocument(e,t))}n.j&&(e.set(s,n.G()),n.H())}}));let n=yh();this.it.forEach(((t,e)=>{let s=!0;e.forEachWhile((t=>{const e=this.wt(t);return!e||2===e.purpose||(s=!1,!1)})),s&&(n=n.add(t))}));const s=new bh(t,e,this.rt,this.st,n);return this.st=dh(),this.it=Ah(),this.rt=new uh(ic),s}at(t,e){if(!this.lt(t))return;const n=this.yt(t,e.key)?2:0;this.ht(t).J(e.key,n),this.st=this.st.insert(e.key,e),this.it=this.it.insert(e.key,this.Tt(e.key).add(t))}ct(t,e,n){if(!this.lt(t))return;const s=this.ht(t);this.yt(t,e)?s.J(e,1):s.Y(e),this.it=this.it.insert(e,this.Tt(e).delete(t)),n&&(this.st=this.st.insert(e,n))}removeTarget(t){this.nt.delete(t)}_t(t){const e=this.ht(t).G();return this.et.getRemoteKeysForTarget(t).size+e.addedDocuments.size-e.removedDocuments.size}X(t){this.ht(t).X()}ht(t){let e=this.nt.get(t);return e||(e=new Sh,this.nt.set(t,e)),e}Tt(t){let e=this.it.get(t);return e||(e=new uh(ic),this.it=this.it.insert(t,e)),e}lt(t){const e=null!==this.wt(t);return e||Va("WatchChangeAggregator","Detected inactive target",t),e}wt(t){const e=this.nt.get(t);return e&&e.K?null:this.et.Et(t)}ft(t){this.nt.set(t,new Sh),this.et.getRemoteKeysForTarget(t).forEach((e=>{this.ct(t,e,null)}))}yt(t,e){return this.et.getRemoteKeysForTarget(t).has(e)}}function Ah(){return new oh(Ac.comparator)}function Ch(){return new oh(Ac.comparator)}const Nh={asc:"ASCENDING",desc:"DESCENDING"},Rh={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"};class Lh{constructor(t,e){this.databaseId=t,this.C=e}}function Dh(t,e){return t.C?`${new Date(1e3*e.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+e.nanoseconds).slice(-9)}Z`:{seconds:""+e.seconds,nanos:e.nanoseconds}}function Oh(t,e){return t.C?e.toBase64():e.toUint8Array()}function Ph(t,e){return Dh(t,e.toTimestamp())}function Mh(t){return $a(!!t),cc.fromTimestamp(function(t){const e=wc(t);return new ac(e.seconds,e.nanos)}(t))}function xh(t,e){return function(t){return new fc(["projects",t.projectId,"databases",t.database])}(t).child("documents").child(e).canonicalString()}function Uh(t){const e=fc.fromString(t);return $a(sl(e)),e}function Fh(t,e){return xh(t.databaseId,e.path)}function Vh(t,e){const n=Uh(e);if(n.get(1)!==t.databaseId.projectId)throw new Ga(za.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+t.databaseId.projectId);if(n.get(3)!==t.databaseId.database)throw new Ga(za.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+t.databaseId.database);return new Ac(qh(n))}function jh(t,e){return xh(t.databaseId,e)}function Bh(t){return new fc(["projects",t.databaseId.projectId,"databases",t.databaseId.database]).canonicalString()}function qh(t){return $a(t.length>4&&"documents"===t.get(4)),t.popFirst(5)}function Hh(t,e,n){return{name:Fh(t,e),fields:n.value.mapValue.fields}}function $h(t,e){return{documents:[jh(t,e.path)]}}function Kh(t,e){const n={structuredQuery:{}},s=e.path;null!==e.collectionGroup?(n.parent=jh(t,s),n.structuredQuery.from=[{collectionId:e.collectionGroup,allDescendants:!0}]):(n.parent=jh(t,s.popLast()),n.structuredQuery.from=[{collectionId:s.lastSegment()}]);const r=function(t){if(0===t.length)return;const e=t.map((t=>function(t){if("=="===t.op){if(Fc(t.value))return{unaryFilter:{field:Yh(t.field),op:"IS_NAN"}};if(Uc(t.value))return{unaryFilter:{field:Yh(t.field),op:"IS_NULL"}}}else if("!="===t.op){if(Fc(t.value))return{unaryFilter:{field:Yh(t.field),op:"IS_NOT_NAN"}};if(Uc(t.value))return{unaryFilter:{field:Yh(t.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Yh(t.field),op:Qh(t.op),value:t.value}}}(t)));return 1===e.length?e[0]:{compositeFilter:{op:"AND",filters:e}}}(e.filters);r&&(n.structuredQuery.where=r);const i=function(t){if(0!==t.length)return t.map((t=>function(t){return{field:Yh(t.field),direction:Xh(t.dir)}}(t)))}(e.orderBy);i&&(n.structuredQuery.orderBy=i);const o=function(t,e){return t.C||Sc(e)?e:{value:e}}(t,e.limit);return null!==o&&(n.structuredQuery.limit=o),e.startAt&&(n.structuredQuery.startAt=Wh(e.startAt)),e.endAt&&(n.structuredQuery.endAt=Wh(e.endAt)),n}function zh(t){let e=function(t){const e=Uh(t);return 4===e.length?fc.emptyPath():qh(e)}(t.parent);const n=t.structuredQuery,s=n.from?n.from.length:0;let r=null;if(s>0){$a(1===s);const t=n.from[0];t.allDescendants?r=t.collectionId:e=e.child(t.collectionId)}let i=[];n.where&&(i=Gh(n.where));let o=[];n.orderBy&&(o=n.orderBy.map((t=>function(t){return new ou(Zh(t.field),function(t){switch(t){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(t.direction))}(t))));let a=null;n.limit&&(a=function(t){let e;return e="object"==typeof t?t.value:t,Sc(e)?null:e}(n.limit));let c=null;n.startAt&&(c=Jh(n.startAt));let u=null;return n.endAt&&(u=Jh(n.endAt)),function(t,e,n,s,r,i,o,a){return new hu(t,e,n,s,r,i,o,a)}(e,r,o,i,a,"F",c,u)}function Gh(t){return t?void 0!==t.unaryFilter?[el(t)]:void 0!==t.fieldFilter?[tl(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map((t=>Gh(t))).reduce(((t,e)=>t.concat(e))):Ha():[]}function Wh(t){return{before:t.before,values:t.position}}function Jh(t){const e=!!t.before,n=t.values||[];return new ru(n,e)}function Xh(t){return Nh[t]}function Qh(t){return Rh[t]}function Yh(t){return{fieldPath:t.canonicalString()}}function Zh(t){return mc.fromServerFormat(t.fieldPath)}function tl(t){return Jc.create(Zh(t.fieldFilter.field),function(t){switch(t){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 Ha()}}(t.fieldFilter.op),t.fieldFilter.value)}function el(t){switch(t.unaryFilter.op){case"IS_NAN":const e=Zh(t.unaryFilter.field);return Jc.create(e,"==",{doubleValue:NaN});case"IS_NULL":const n=Zh(t.unaryFilter.field);return Jc.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const s=Zh(t.unaryFilter.field);return Jc.create(s,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const r=Zh(t.unaryFilter.field);return Jc.create(r,"!=",{nullValue:"NULL_VALUE"});default:return Ha()}}function nl(t){const e=[];return t.fields.forEach((t=>e.push(t.canonicalString()))),{fieldPaths:e}}function sl(t){return t.length>=4&&"projects"===t.get(0)&&"databases"===t.get(2)}function rl(t){let e="";for(let n=0;n0&&(e=ol(e)),e=il(t.get(n),e);return ol(e)}function il(t,e){let n=e;const s=t.length;for(let e=0;e{this.isDone=!0,this.result=t,this.nextCallback&&this.nextCallback(t)}),(t=>{this.isDone=!0,this.error=t,this.catchCallback&&this.catchCallback(t)}))}catch(t){return this.next(void 0,t)}next(t,e){return this.callbackAttached&&Ha(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(e,this.error):this.wrapSuccess(t,this.result):new bl(((n,s)=>{this.nextCallback=e=>{this.wrapSuccess(t,e).next(n,s)},this.catchCallback=t=>{this.wrapFailure(e,t).next(n,s)}}))}toPromise(){return new Promise(((t,e)=>{this.next(t,e)}))}wrapUserFunction(t){try{const e=t();return e instanceof bl?e:bl.resolve(e)}catch(t){return bl.reject(t)}}wrapSuccess(t,e){return t?this.wrapUserFunction((()=>t(e))):bl.resolve(e)}wrapFailure(t,e){return t?this.wrapUserFunction((()=>t(e))):bl.reject(e)}static resolve(t){return new bl(((e,n)=>{e(t)}))}static reject(t){return new bl(((e,n)=>{n(t)}))}static waitFor(t){return new bl(((e,n)=>{let s=0,r=0,i=!1;t.forEach((t=>{++s,t.next((()=>{++r,i&&r===s&&e()}),(t=>n(t)))})),i=!0,r===s&&e()}))}static or(t){let e=bl.resolve(!1);for(const n of t)e=e.next((t=>t?bl.resolve(t):n()));return e}static forEach(t,e){const n=[];return t.forEach(((t,s)=>{n.push(e.call(this,t,s))})),this.waitFor(n)}}function Tl(t){return"IndexedDbTransactionError"===t.name}class El{constructor(t,e,n,s){this.batchId=t,this.localWriteTime=e,this.baseMutations=n,this.mutations=s}applyToRemoteDocument(t,e){const n=e.mutationResults;for(let e=0;e{const n=t.get(e.key),s=n;this.applyToLocalView(s),n.isValidDocument()||s.convertToNoDocument(cc.min())}))}keys(){return this.mutations.reduce(((t,e)=>t.add(e.key)),yh())}isEqual(t){return this.batchId===t.batchId&&oc(this.mutations,t.mutations,((t,e)=>Gu(t,e)))&&oc(this.baseMutations,t.baseMutations,((t,e)=>Gu(t,e)))}}class Il{constructor(t,e,n,s){this.batch=t,this.commitVersion=e,this.mutationResults=n,this.docVersions=s}static from(t,e,n){$a(t.mutations.length===n.length);let s=mh;const r=t.mutations;for(let t=0;t{for(const[e,s]of n)t(e,s)}))}isEmpty(){return lc(this.inner)}}class Ol{constructor(t,e,n){this.Je=t,this.An=e,this.Jt=n}Rn(t,e){return this.An.getAllMutationBatchesAffectingDocumentKey(t,e).next((n=>this.Pn(t,e,n)))}Pn(t,e,n){return this.Je.getEntry(t,e).next((t=>{for(const e of n)e.applyToLocalView(t);return t}))}bn(t,e){t.forEach(((t,n)=>{for(const t of e)t.applyToLocalView(n)}))}vn(t,e){return this.Je.getEntries(t,e).next((e=>this.Vn(t,e).next((()=>e))))}Vn(t,e){return this.An.getAllMutationBatchesAffectingDocumentKeys(t,e).next((t=>this.bn(e,t)))}getDocumentsMatchingQuery(t,e,n){return function(t){return Ac.isDocumentKey(t.path)&&null===t.collectionGroup&&0===t.filters.length}(e)?this.Sn(t,e.path):function(t){return null!==t.collectionGroup}(e)?this.Dn(t,e,n):this.Cn(t,e,n)}Sn(t,e){return this.Rn(t,new Ac(e)).next((t=>{let e=ph();return t.isFoundDocument()&&(e=e.insert(t.key,t)),e}))}Dn(t,e,n){const s=e.collectionGroup;let r=ph();return this.Jt.getCollectionParents(t,s).next((i=>bl.forEach(i,(i=>{const o=function(t,e){return new hu(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt)}(e,i.child(s));return this.Cn(t,o,n).next((t=>{t.forEach(((t,e)=>{r=r.insert(t,e)}))}))})).next((()=>r))))}Cn(t,e,n){let s,r;return this.Je.getDocumentsMatchingQuery(t,e,n).next((n=>(s=n,this.An.getAllMutationBatchesAffectingQuery(t,e)))).next((e=>(r=e,this.Nn(t,r,s).next((t=>{s=t;for(const t of r)for(const e of t.mutations){const n=e.key;let r=s.get(n);null==r&&(r=Hc.newInvalidDocument(n),s=s.insert(n,r)),Ku(e,r,t.localWriteTime),r.isFoundDocument()||(s=s.remove(n))}}))))).next((()=>(s.forEach(((t,n)=>{Eu(e,n)||(s=s.remove(t))})),s)))}Nn(t,e,n){let s=yh();for(const t of e)for(const e of t.mutations)e instanceof Xu&&null===n.get(e.key)&&(s=s.add(e.key));let r=n;return this.Je.getEntries(t,s).next((t=>(t.forEach(((t,e)=>{e.isFoundDocument()&&(r=r.insert(t,e))})),r)))}}class Pl{constructor(t,e,n,s){this.targetId=t,this.fromCache=e,this.kn=n,this.xn=s}static $n(t,e){let n=yh(),s=yh();for(const t of e.docChanges)switch(t.type){case 0:n=n.add(t.doc.key);break;case 1:s=s.add(t.doc.key)}return new Pl(t,e.fromCache,n,s)}}class Ml{Fn(t){this.On=t}getDocumentsMatchingQuery(t,e,n,s){return function(t){return 0===t.filters.length&&null===t.limit&&null==t.startAt&&null==t.endAt&&(0===t.explicitOrderBy.length||1===t.explicitOrderBy.length&&t.explicitOrderBy[0].field.isKeyField())}(e)||n.isEqual(cc.min())?this.Mn(t,e):this.On.vn(t,s).next((r=>{const i=this.Ln(e,r);return(du(e)||fu(e))&&this.Bn(e.limitType,i,s,n)?this.Mn(t,e):(Fa()<=k.DEBUG&&Va("QueryEngine","Re-using previous result from %s to execute query: %s",n.toString(),Tu(e)),this.On.getDocumentsMatchingQuery(t,e,n).next((t=>(i.forEach((e=>{t=t.insert(e.key,e)})),t))))}))}Ln(t,e){let n=new uh(Iu(t));return e.forEach(((e,s)=>{Eu(t,s)&&(n=n.add(s))})),n}Bn(t,e,n,s){if(n.size!==e.size)return!0;const r="F"===t?e.last():e.first();return!!r&&(r.hasPendingWrites||r.version.compareTo(s)>0)}Mn(t,e){return Fa()<=k.DEBUG&&Va("QueryEngine","Using full collection scan to execute query:",Tu(e)),this.On.getDocumentsMatchingQuery(t,e,cc.min())}}class xl{constructor(t,e,n,s){this.persistence=t,this.Un=e,this.k=s,this.qn=new oh(ic),this.Kn=new Dl((t=>zc(t)),Gc),this.jn=cc.min(),this.An=t.getMutationQueue(n),this.Qn=t.getRemoteDocumentCache(),this.He=t.getTargetCache(),this.Wn=new Ol(this.Qn,this.An,this.persistence.getIndexManager()),this.Ye=t.getBundleCache(),this.Un.Fn(this.Wn)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(e=>t.collect(e,this.qn)))}}async function Ul(t,e){const n=Ka(t);let s=n.An,r=n.Wn;const i=await n.persistence.runTransaction("Handle user change","readonly",(t=>{let i;return n.An.getAllMutationBatches(t).next((o=>(i=o,s=n.persistence.getMutationQueue(e),r=new Ol(n.Qn,s,n.persistence.getIndexManager()),s.getAllMutationBatches(t)))).next((e=>{const n=[],s=[];let o=yh();for(const t of i){n.push(t.batchId);for(const e of t.mutations)o=o.add(e.key)}for(const t of e){s.push(t.batchId);for(const e of t.mutations)o=o.add(e.key)}return r.vn(t,o).next((t=>({Gn:t,removedBatchIds:n,addedBatchIds:s})))}))}));return n.An=s,n.Wn=r,n.Un.Fn(n.Wn),i}function Fl(t){const e=Ka(t);return e.persistence.runTransaction("Get last remote snapshot version","readonly",(t=>e.He.getLastRemoteSnapshotVersion(t)))}function Vl(t,e){const n=Ka(t);return n.persistence.runTransaction("Get next mutation batch","readonly",(t=>(void 0===e&&(e=-1),n.An.getNextMutationBatchAfterBatchId(t,e))))}async function jl(t,e,n){const s=Ka(t),r=s.qn.get(e),i=n?"readwrite":"readwrite-primary";try{n||await s.persistence.runTransaction("Release target",i,(t=>s.persistence.referenceDelegate.removeTarget(t,r)))}catch(t){if(!Tl(t))throw t;Va("LocalStore",`Failed to update sequence numbers for target ${e}: ${t}`)}s.qn=s.qn.remove(e),s.Kn.delete(r.target)}function Bl(t,e,n){const s=Ka(t);let r=cc.min(),i=yh();return s.persistence.runTransaction("Execute query","readonly",(t=>function(t,e,n){const s=Ka(t),r=s.Kn.get(n);return void 0!==r?bl.resolve(s.qn.get(r)):s.He.getTargetData(e,n)}(s,t,yu(e)).next((e=>{if(e)return r=e.lastLimboFreeSnapshotVersion,s.He.getMatchingKeysForTargetId(t,e.targetId).next((t=>{i=t}))})).next((()=>s.Un.getDocumentsMatchingQuery(t,e,n?r:cc.min(),n?i:yh()))).next((t=>({documents:t,zn:i})))))}class ql{constructor(t){this.k=t,this.Xn=new Map,this.Zn=new Map}getBundleMetadata(t,e){return bl.resolve(this.Xn.get(e))}saveBundleMetadata(t,e){var n;return this.Xn.set(e.id,{id:(n=e).id,version:n.version,createTime:Mh(n.createTime)}),bl.resolve()}getNamedQuery(t,e){return bl.resolve(this.Zn.get(e))}saveNamedQuery(t,e){return this.Zn.set(e.name,function(t){return{name:t.name,query:kl(t.bundledQuery),readTime:Mh(t.readTime)}}(e)),bl.resolve()}}class Hl{constructor(){this.ts=new uh($l.es),this.ns=new uh($l.ss)}isEmpty(){return this.ts.isEmpty()}addReference(t,e){const n=new $l(t,e);this.ts=this.ts.add(n),this.ns=this.ns.add(n)}rs(t,e){t.forEach((t=>this.addReference(t,e)))}removeReference(t,e){this.os(new $l(t,e))}cs(t,e){t.forEach((t=>this.removeReference(t,e)))}us(t){const e=new Ac(new fc([])),n=new $l(e,t),s=new $l(e,t+1),r=[];return this.ns.forEachInRange([n,s],(t=>{this.os(t),r.push(t.key)})),r}hs(){this.ts.forEach((t=>this.os(t)))}os(t){this.ts=this.ts.delete(t),this.ns=this.ns.delete(t)}ls(t){const e=new Ac(new fc([])),n=new $l(e,t),s=new $l(e,t+1);let r=yh();return this.ns.forEachInRange([n,s],(t=>{r=r.add(t.key)})),r}containsKey(t){const e=new $l(t,0),n=this.ts.firstAfterOrEqual(e);return null!==n&&t.isEqual(n.key)}}class $l{constructor(t,e){this.key=t,this.fs=e}static es(t,e){return Ac.comparator(t.key,e.key)||ic(t.fs,e.fs)}static ss(t,e){return ic(t.fs,e.fs)||Ac.comparator(t.key,e.key)}}class Kl{constructor(t,e){this.Jt=t,this.referenceDelegate=e,this.An=[],this.ds=1,this.ws=new uh($l.es)}checkEmpty(t){return bl.resolve(0===this.An.length)}addMutationBatch(t,e,n,s){const r=this.ds;this.ds++,this.An.length>0&&this.An[this.An.length-1];const i=new El(r,e,n,s);this.An.push(i);for(const e of s)this.ws=this.ws.add(new $l(e.key,r)),this.Jt.addToCollectionParentIndex(t,e.key.path.popLast());return bl.resolve(i)}lookupMutationBatch(t,e){return bl.resolve(this._s(e))}getNextMutationBatchAfterBatchId(t,e){const n=e+1,s=this.gs(n),r=s<0?0:s;return bl.resolve(this.An.length>r?this.An[r]:null)}getHighestUnacknowledgedBatchId(){return bl.resolve(0===this.An.length?-1:this.ds-1)}getAllMutationBatches(t){return bl.resolve(this.An.slice())}getAllMutationBatchesAffectingDocumentKey(t,e){const n=new $l(e,0),s=new $l(e,Number.POSITIVE_INFINITY),r=[];return this.ws.forEachInRange([n,s],(t=>{const e=this._s(t.fs);r.push(e)})),bl.resolve(r)}getAllMutationBatchesAffectingDocumentKeys(t,e){let n=new uh(ic);return e.forEach((t=>{const e=new $l(t,0),s=new $l(t,Number.POSITIVE_INFINITY);this.ws.forEachInRange([e,s],(t=>{n=n.add(t.fs)}))})),bl.resolve(this.ys(n))}getAllMutationBatchesAffectingQuery(t,e){const n=e.path,s=n.length+1;let r=n;Ac.isDocumentKey(r)||(r=r.child(""));const i=new $l(new Ac(r),0);let o=new uh(ic);return this.ws.forEachWhile((t=>{const e=t.key.path;return!!n.isPrefixOf(e)&&(e.length===s&&(o=o.add(t.fs)),!0)}),i),bl.resolve(this.ys(o))}ys(t){const e=[];return t.forEach((t=>{const n=this._s(t);null!==n&&e.push(n)})),e}removeMutationBatch(t,e){$a(0===this.ps(e.batchId,"removed")),this.An.shift();let n=this.ws;return bl.forEach(e.mutations,(s=>{const r=new $l(s.key,e.batchId);return n=n.delete(r),this.referenceDelegate.markPotentiallyOrphaned(t,s.key)})).next((()=>{this.ws=n}))}ee(t){}containsKey(t,e){const n=new $l(e,0),s=this.ws.firstAfterOrEqual(n);return bl.resolve(e.isEqual(s&&s.key))}performConsistencyCheck(t){return this.An.length,bl.resolve()}ps(t,e){return this.gs(t)}gs(t){return 0===this.An.length?0:t-this.An[0].batchId}_s(t){const e=this.gs(t);return e<0||e>=this.An.length?null:this.An[e]}}class zl{constructor(t,e){this.Jt=t,this.Ts=e,this.docs=new oh(Ac.comparator),this.size=0}addEntry(t,e,n){const s=e.key,r=this.docs.get(s),i=r?r.size:0,o=this.Ts(e);return this.docs=this.docs.insert(s,{document:e.clone(),size:o,readTime:n}),this.size+=o-i,this.Jt.addToCollectionParentIndex(t,s.path.popLast())}removeEntry(t){const e=this.docs.get(t);e&&(this.docs=this.docs.remove(t),this.size-=e.size)}getEntry(t,e){const n=this.docs.get(e);return bl.resolve(n?n.document.clone():Hc.newInvalidDocument(e))}getEntries(t,e){let n=dh();return e.forEach((t=>{const e=this.docs.get(t);n=n.insert(t,e?e.document.clone():Hc.newInvalidDocument(t))})),bl.resolve(n)}getDocumentsMatchingQuery(t,e,n){let s=dh();const r=new Ac(e.path.child("")),i=this.docs.getIteratorFrom(r);for(;i.hasNext();){const{key:t,value:{document:r,readTime:o}}=i.getNext();if(!e.path.isPrefixOf(t.path))break;o.compareTo(n)<=0||Eu(e,r)&&(s=s.insert(r.key,r.clone()))}return bl.resolve(s)}Es(t,e){return bl.forEach(this.docs,(t=>e(t)))}newChangeBuffer(t){return new Gl(this)}getSize(t){return bl.resolve(this.size)}}class Gl extends class{constructor(){this.changes=new Dl((t=>t.toString()),((t,e)=>t.isEqual(e))),this.changesApplied=!1}getReadTime(t){const e=this.changes.get(t);return e?e.readTime:cc.min()}addEntry(t,e){this.assertNotApplied(),this.changes.set(t.key,{document:t,readTime:e})}removeEntry(t,e=null){this.assertNotApplied(),this.changes.set(t,{document:Hc.newInvalidDocument(t),readTime:e})}getEntry(t,e){this.assertNotApplied();const n=this.changes.get(e);return void 0!==n?bl.resolve(n.document):this.getFromCache(t,e)}getEntries(t,e){return this.getAllFromCache(t,e)}apply(t){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(t)}assertNotApplied(){}}{constructor(t){super(),this.De=t}applyChanges(t){const e=[];return this.changes.forEach(((n,s)=>{s.document.isValidDocument()?e.push(this.De.addEntry(t,s.document,this.getReadTime(n))):this.De.removeEntry(n)})),bl.waitFor(e)}getFromCache(t,e){return this.De.getEntry(t,e)}getAllFromCache(t,e){return this.De.getEntries(t,e)}}class Wl{constructor(t){this.persistence=t,this.Is=new Dl((t=>zc(t)),Gc),this.lastRemoteSnapshotVersion=cc.min(),this.highestTargetId=0,this.As=0,this.Rs=new Hl,this.targetCount=0,this.Ps=Rl.ie()}forEachTarget(t,e){return this.Is.forEach(((t,n)=>e(n))),bl.resolve()}getLastRemoteSnapshotVersion(t){return bl.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(t){return bl.resolve(this.As)}allocateTargetId(t){return this.highestTargetId=this.Ps.next(),bl.resolve(this.highestTargetId)}setTargetsMetadata(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.As&&(this.As=e),bl.resolve()}ce(t){this.Is.set(t.target,t);const e=t.targetId;e>this.highestTargetId&&(this.Ps=new Rl(e),this.highestTargetId=e),t.sequenceNumber>this.As&&(this.As=t.sequenceNumber)}addTargetData(t,e){return this.ce(e),this.targetCount+=1,bl.resolve()}updateTargetData(t,e){return this.ce(e),bl.resolve()}removeTargetData(t,e){return this.Is.delete(e.target),this.Rs.us(e.targetId),this.targetCount-=1,bl.resolve()}removeTargets(t,e,n){let s=0;const r=[];return this.Is.forEach(((i,o)=>{o.sequenceNumber<=e&&null===n.get(o.targetId)&&(this.Is.delete(i),r.push(this.removeMatchingKeysForTargetId(t,o.targetId)),s++)})),bl.waitFor(r).next((()=>s))}getTargetCount(t){return bl.resolve(this.targetCount)}getTargetData(t,e){const n=this.Is.get(e)||null;return bl.resolve(n)}addMatchingKeys(t,e,n){return this.Rs.rs(e,n),bl.resolve()}removeMatchingKeys(t,e,n){this.Rs.cs(e,n);const s=this.persistence.referenceDelegate,r=[];return s&&e.forEach((e=>{r.push(s.markPotentiallyOrphaned(t,e))})),bl.waitFor(r)}removeMatchingKeysForTargetId(t,e){return this.Rs.us(e),bl.resolve()}getMatchingKeysForTargetId(t,e){const n=this.Rs.ls(e);return bl.resolve(n)}containsKey(t,e){return bl.resolve(this.Rs.containsKey(e))}}class Jl{constructor(t,e){this.bs={},this.Be=new nc(0),this.Ue=!1,this.Ue=!0,this.referenceDelegate=t(this),this.He=new Wl(this),this.Jt=new Al,this.Je=function(t,e){return new zl(t,e)}(this.Jt,(t=>this.referenceDelegate.vs(t))),this.k=new Sl(e),this.Ye=new ql(this.k)}start(){return Promise.resolve()}shutdown(){return this.Ue=!1,Promise.resolve()}get started(){return this.Ue}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(){return this.Jt}getMutationQueue(t){let e=this.bs[t.toKey()];return e||(e=new Kl(this.Jt,this.referenceDelegate),this.bs[t.toKey()]=e),e}getTargetCache(){return this.He}getRemoteDocumentCache(){return this.Je}getBundleCache(){return this.Ye}runTransaction(t,e,n){Va("MemoryPersistence","Starting transaction:",t);const s=new Xl(this.Be.next());return this.referenceDelegate.Vs(),n(s).next((t=>this.referenceDelegate.Ss(s).next((()=>t)))).toPromise().then((t=>(s.raiseOnCommittedEvent(),t)))}Ds(t,e){return bl.or(Object.values(this.bs).map((n=>()=>n.containsKey(t,e))))}}class Xl extends class{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(t){this.onCommittedListeners.push(t)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((t=>t()))}}{constructor(t){super(),this.currentSequenceNumber=t}}class Ql{constructor(t){this.persistence=t,this.Cs=new Hl,this.Ns=null}static ks(t){return new Ql(t)}get xs(){if(this.Ns)return this.Ns;throw Ha()}addReference(t,e,n){return this.Cs.addReference(n,e),this.xs.delete(n.toString()),bl.resolve()}removeReference(t,e,n){return this.Cs.removeReference(n,e),this.xs.add(n.toString()),bl.resolve()}markPotentiallyOrphaned(t,e){return this.xs.add(e.toString()),bl.resolve()}removeTarget(t,e){this.Cs.us(e.targetId).forEach((t=>this.xs.add(t.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(t,e.targetId).next((t=>{t.forEach((t=>this.xs.add(t.toString())))})).next((()=>n.removeTargetData(t,e)))}Vs(){this.Ns=new Set}Ss(t){const e=this.persistence.getRemoteDocumentCache().newChangeBuffer();return bl.forEach(this.xs,(n=>{const s=Ac.fromPath(n);return this.$s(t,s).next((t=>{t||e.removeEntry(s)}))})).next((()=>(this.Ns=null,e.apply(t))))}updateLimboDocument(t,e){return this.$s(t,e).next((t=>{t?this.xs.delete(e.toString()):this.xs.add(e.toString())}))}vs(t){return 0}$s(t,e){return bl.or([()=>bl.resolve(this.Cs.containsKey(e)),()=>this.persistence.getTargetCache().containsKey(t,e),()=>this.persistence.Ds(t,e)])}}class Yl{constructor(){this.activeTargetIds=wh()}Ms(t){this.activeTargetIds=this.activeTargetIds.add(t)}Ls(t){this.activeTargetIds=this.activeTargetIds.delete(t)}Os(){const t={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(t)}}class Zl{constructor(){this.pi=new Yl,this.Ti={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(t){}updateMutationState(t,e,n){}addLocalQueryTarget(t){return this.pi.Ms(t),this.Ti[t]||"not-current"}updateQueryState(t,e,n){this.Ti[t]=e}removeLocalQueryTarget(t){this.pi.Ls(t)}isLocalQueryTarget(t){return this.pi.activeTargetIds.has(t)}clearQueryState(t){delete this.Ti[t]}getAllActiveQueryTargets(){return this.pi.activeTargetIds}isActiveQueryTarget(t){return this.pi.activeTargetIds.has(t)}start(){return this.pi=new Yl,Promise.resolve()}handleUserChange(t,e,n){}setOnlineState(t){}shutdown(){}writeSequenceNumber(t){}notifyBundleLoaded(){}}class td{Ei(t){}shutdown(){}}class ed{constructor(){this.Ii=()=>this.Ai(),this.Ri=()=>this.Pi(),this.bi=[],this.vi()}Ei(t){this.bi.push(t)}shutdown(){window.removeEventListener("online",this.Ii),window.removeEventListener("offline",this.Ri)}vi(){window.addEventListener("online",this.Ii),window.addEventListener("offline",this.Ri)}Ai(){Va("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const t of this.bi)t(0)}Pi(){Va("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const t of this.bi)t(1)}static bt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const nd={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class sd{constructor(t){this.Vi=t.Vi,this.Si=t.Si}Di(t){this.Ci=t}Ni(t){this.ki=t}onMessage(t){this.xi=t}close(){this.Si()}send(t){this.Vi(t)}$i(){this.Ci()}Fi(t){this.ki(t)}Oi(t){this.xi(t)}}class rd extends class{constructor(t){this.databaseInfo=t,this.databaseId=t.databaseId;const e=t.ssl?"https":"http";this.Mi=e+"://"+t.host,this.Li="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}Bi(t,e,n,s,r){const i=this.Ui(t,e);Va("RestConnection","Sending: ",i,n);const o={};return this.qi(o,s,r),this.Ki(t,i,o,n).then((t=>(Va("RestConnection","Received: ",t),t)),(e=>{throw Ba("RestConnection",`${t} failed with error: `,e,"url: ",i,"request:",n),e}))}ji(t,e,n,s,r){return this.Bi(t,e,n,s,r)}qi(t,e,n){t["X-Goog-Api-Client"]="gl-js/ fire/"+xa,t["Content-Type"]="text/plain",this.databaseInfo.appId&&(t["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach(((e,n)=>t[n]=e)),n&&n.headers.forEach(((e,n)=>t[n]=e))}Ui(t,e){const n=nd[t];return`${this.Mi}/v1/${e}:${n}`}}{constructor(t){super(t),this.forceLongPolling=t.forceLongPolling,this.autoDetectLongPolling=t.autoDetectLongPolling,this.useFetchStreams=t.useFetchStreams}Ki(t,e,n,s){return new Promise(((r,i)=>{const o=new Oa;o.listenOnce(Ca.COMPLETE,(()=>{try{switch(o.getLastErrorCode()){case Aa.NO_ERROR:const e=o.getResponseJson();Va("Connection","XHR received:",JSON.stringify(e)),r(e);break;case Aa.TIMEOUT:Va("Connection",'RPC "'+t+'" timed out'),i(new Ga(za.DEADLINE_EXCEEDED,"Request time out"));break;case Aa.HTTP_ERROR:const n=o.getStatus();if(Va("Connection",'RPC "'+t+'" failed with status:',n,"response text:",o.getResponseText()),n>0){const t=o.getResponseJson().error;if(t&&t.status&&t.message){const e=function(t){const e=t.toLowerCase().replace(/_/g,"-");return Object.values(za).indexOf(e)>=0?e:za.UNKNOWN}(t.status);i(new Ga(e,t.message))}else i(new Ga(za.UNKNOWN,"Server responded with status "+o.getStatus()))}else i(new Ga(za.UNAVAILABLE,"Connection failed."));break;default:Ha()}}finally{Va("Connection",'RPC "'+t+'" completed.')}}));const a=JSON.stringify(s);o.send(e,"POST",a,n,15)}))}Qi(t,e,n){const s=[this.Mi,"/","google.firestore.v1.Firestore","/",t,"/channel"],u=Sa(),h=ka(),l={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(l.xmlHttpFactory=new La({})),this.qi(l.initMessageHeaders,e,n),i()||a()||r().indexOf("Electron/")>=0||c()||r().indexOf("MSAppHost/")>=0||o()||(l.httpHeadersOverwriteParam="$httpHeaders");const d=s.join("");Va("Connection","Creating WebChannel: "+d,l);const f=u.createWebChannel(d,l);let p=!1,m=!1;const g=new sd({Vi:t=>{m?Va("Connection","Not sending because WebChannel is closed:",t):(p||(Va("Connection","Opening WebChannel transport."),f.open(),p=!0),Va("Connection","WebChannel sending:",t),f.send(t))},Si:()=>f.close()}),y=(t,e,n)=>{t.listen(e,(t=>{try{n(t)}catch(t){setTimeout((()=>{throw t}),0)}}))};return y(f,Da.EventType.OPEN,(()=>{m||Va("Connection","WebChannel transport opened.")})),y(f,Da.EventType.CLOSE,(()=>{m||(m=!0,Va("Connection","WebChannel transport closed"),g.Fi())})),y(f,Da.EventType.ERROR,(t=>{m||(m=!0,Ba("Connection","WebChannel transport errored:",t),g.Fi(new Ga(za.UNAVAILABLE,"The operation could not be completed")))})),y(f,Da.EventType.MESSAGE,(t=>{var e;if(!m){const n=t.data[0];$a(!!n);const s=n,r=s.error||(null===(e=s[0])||void 0===e?void 0:e.error);if(r){Va("Connection","WebChannel received error:",r);const t=r.status;let e=function(t){const e=sh[t];if(void 0!==e)return ih(e)}(t),n=r.message;void 0===e&&(e=za.INTERNAL,n="Unknown error status: "+t+" with message "+r.message),m=!0,g.Fi(new Ga(e,n)),f.close()}else Va("Connection","WebChannel received:",n),g.Oi(n)}})),y(h,Na.STAT_EVENT,(t=>{t.stat===Ra.PROXY?Va("Connection","Detected buffering proxy"):t.stat===Ra.NOPROXY&&Va("Connection","Detected no buffering proxy")})),setTimeout((()=>{g.$i()}),0),g}}function id(){return"undefined"!=typeof document?document:null}function od(t){return new Lh(t,!0)}class ad{constructor(t,e,n=1e3,s=1.5,r=6e4){this.Oe=t,this.timerId=e,this.Wi=n,this.Gi=s,this.zi=r,this.Hi=0,this.Ji=null,this.Yi=Date.now(),this.reset()}reset(){this.Hi=0}Xi(){this.Hi=this.zi}Zi(t){this.cancel();const e=Math.floor(this.Hi+this.tr()),n=Math.max(0,Date.now()-this.Yi),s=Math.max(0,e-n);s>0&&Va("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.Hi} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`),this.Ji=this.Oe.enqueueAfterDelay(this.timerId,s,(()=>(this.Yi=Date.now(),t()))),this.Hi*=this.Gi,this.Hithis.zi&&(this.Hi=this.zi)}er(){null!==this.Ji&&(this.Ji.skipDelay(),this.Ji=null)}cancel(){null!==this.Ji&&(this.Ji.cancel(),this.Ji=null)}tr(){return(Math.random()-.5)*this.Hi}}class cd{constructor(t,e,n,s,r,i,o,a){this.Oe=t,this.nr=n,this.sr=s,this.ir=r,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.rr=0,this.ar=null,this.cr=null,this.stream=null,this.ur=new ad(t,e)}hr(){return 1===this.state||5===this.state||this.lr()}lr(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.dr()}async stop(){this.hr()&&await this.close(0)}wr(){this.state=0,this.ur.reset()}_r(){this.lr()&&null===this.ar&&(this.ar=this.Oe.enqueueAfterDelay(this.nr,6e4,(()=>this.mr())))}gr(t){this.yr(),this.stream.send(t)}async mr(){if(this.lr())return this.close(0)}yr(){this.ar&&(this.ar.cancel(),this.ar=null)}pr(){this.cr&&(this.cr.cancel(),this.cr=null)}async close(t,e){this.yr(),this.pr(),this.ur.cancel(),this.rr++,4!==t?this.ur.reset():e&&e.code===za.RESOURCE_EXHAUSTED?(ja(e.toString()),ja("Using maximum backoff delay to prevent overloading the backend."),this.ur.Xi()):e&&e.code===za.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Tr(),this.stream.close(),this.stream=null),this.state=t,await this.listener.Ni(e)}Tr(){}auth(){this.state=1;const t=this.Er(this.rr),e=this.rr;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([t,n])=>{this.rr===e&&this.Ir(t,n)}),(e=>{t((()=>{const t=new Ga(za.UNKNOWN,"Fetching auth token failed: "+e.message);return this.Ar(t)}))}))}Ir(t,e){const n=this.Er(this.rr);this.stream=this.Rr(t,e),this.stream.Di((()=>{n((()=>(this.state=2,this.cr=this.Oe.enqueueAfterDelay(this.sr,1e4,(()=>(this.lr()&&(this.state=3),Promise.resolve()))),this.listener.Di())))})),this.stream.Ni((t=>{n((()=>this.Ar(t)))})),this.stream.onMessage((t=>{n((()=>this.onMessage(t)))}))}dr(){this.state=5,this.ur.Zi((async()=>{this.state=0,this.start()}))}Ar(t){return Va("PersistentStream",`close with error: ${t}`),this.stream=null,this.close(4,t)}Er(t){return e=>{this.Oe.enqueueAndForget((()=>this.rr===t?e():(Va("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class ud extends cd{constructor(t,e,n,s,r,i){super(t,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",e,n,s,i),this.k=r}Rr(t,e){return this.ir.Qi("Listen",t,e)}onMessage(t){this.ur.reset();const e=function(t,e){let n;if("targetChange"in e){e.targetChange;const s=function(t){return"NO_CHANGE"===t?0:"ADD"===t?1:"REMOVE"===t?2:"CURRENT"===t?3:"RESET"===t?4:Ha()}(e.targetChange.targetChangeType||"NO_CHANGE"),r=e.targetChange.targetIds||[],i=function(t,e){return t.C?($a(void 0===e||"string"==typeof e),yc.fromBase64String(e||"")):($a(void 0===e||e instanceof Uint8Array),yc.fromUint8Array(e||new Uint8Array))}(t,e.targetChange.resumeToken),o=e.targetChange.cause,a=o&&function(t){const e=void 0===t.code?za.UNKNOWN:ih(t.code);return new Ga(e,t.message||"")}(o);n=new _h(s,r,i,a||null)}else if("documentChange"in e){e.documentChange;const s=e.documentChange;s.document,s.document.name,s.document.updateTime;const r=Vh(t,s.document.name),i=Mh(s.document.updateTime),o=new Bc({mapValue:{fields:s.document.fields}}),a=Hc.newFoundDocument(r,i,o),c=s.targetIds||[],u=s.removedTargetIds||[];n=new Eh(c,u,a.key,a)}else if("documentDelete"in e){e.documentDelete;const s=e.documentDelete;s.document;const r=Vh(t,s.document),i=s.readTime?Mh(s.readTime):cc.min(),o=Hc.newNoDocument(r,i),a=s.removedTargetIds||[];n=new Eh([],a,o.key,o)}else if("documentRemove"in e){e.documentRemove;const s=e.documentRemove;s.document;const r=Vh(t,s.document),i=s.removedTargetIds||[];n=new Eh([],i,r,null)}else{if(!("filter"in e))return Ha();{e.filter;const t=e.filter;t.targetId;const s=t.count||0,r=new nh(s),i=t.targetId;n=new Ih(i,r)}}return n}(this.k,t),n=function(t){if(!("targetChange"in t))return cc.min();const e=t.targetChange;return e.targetIds&&e.targetIds.length?cc.min():e.readTime?Mh(e.readTime):cc.min()}(t);return this.listener.Pr(e,n)}br(t){const e={};e.database=Bh(this.k),e.addTarget=function(t,e){let n;const s=e.target;return n=Wc(s)?{documents:$h(t,s)}:{query:Kh(t,s)},n.targetId=e.targetId,e.resumeToken.approximateByteSize()>0?n.resumeToken=Oh(t,e.resumeToken):e.snapshotVersion.compareTo(cc.min())>0&&(n.readTime=Dh(t,e.snapshotVersion.toTimestamp())),n}(this.k,t);const n=function(t,e){const n=function(t,e){switch(e){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return Ha()}}(0,e.purpose);return null==n?null:{"goog-listen-tags":n}}(this.k,t);n&&(e.labels=n),this.gr(e)}vr(t){const e={};e.database=Bh(this.k),e.removeTarget=t,this.gr(e)}}class hd extends cd{constructor(t,e,n,s,r,i){super(t,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",e,n,s,i),this.k=r,this.Vr=!1}get Sr(){return this.Vr}start(){this.Vr=!1,this.lastStreamToken=void 0,super.start()}Tr(){this.Vr&&this.Dr([])}Rr(t,e){return this.ir.Qi("Write",t,e)}onMessage(t){if($a(!!t.streamToken),this.lastStreamToken=t.streamToken,this.Vr){this.ur.reset();const e=function(t,e){return t&&t.length>0?($a(void 0!==e),t.map((t=>function(t,e){let n=t.updateTime?Mh(t.updateTime):Mh(e);return n.isEqual(cc.min())&&(n=Mh(e)),new ju(n,t.transformResults||[])}(t,e)))):[]}(t.writeResults,t.commitTime),n=Mh(t.commitTime);return this.listener.Cr(n,e)}return $a(!t.writeResults||0===t.writeResults.length),this.Vr=!0,this.listener.Nr()}kr(){const t={};t.database=Bh(this.k),this.gr(t)}Dr(t){const e={streamToken:this.lastStreamToken,writes:t.map((t=>function(t,e){let n;if(e instanceof Ju)n={update:Hh(t,e.key,e.value)};else if(e instanceof th)n={delete:Fh(t,e.key)};else if(e instanceof Xu)n={update:Hh(t,e.key,e.data),updateMask:nl(e.fieldMask)};else{if(!(e instanceof eh))return Ha();n={verify:Fh(t,e.key)}}return e.fieldTransforms.length>0&&(n.updateTransforms=e.fieldTransforms.map((t=>function(t,e){const n=e.transform;if(n instanceof Du)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof Ou)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof Mu)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof Uu)return{fieldPath:e.field.canonicalString(),increment:n.N};throw Ha()}(0,t)))),e.precondition.isNone||(n.currentDocument=function(t,e){return void 0!==e.updateTime?{updateTime:Ph(t,e.updateTime)}:void 0!==e.exists?{exists:e.exists}:Ha()}(t,e.precondition)),n}(this.k,t)))};this.gr(e)}}class ld extends class{}{constructor(t,e,n,s){super(),this.authCredentials=t,this.appCheckCredentials=e,this.ir=n,this.k=s,this.$r=!1}Fr(){if(this.$r)throw new Ga(za.FAILED_PRECONDITION,"The client has already been terminated.")}Bi(t,e,n){return this.Fr(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([s,r])=>this.ir.Bi(t,e,n,s,r))).catch((t=>{throw"FirebaseError"===t.name?(t.code===za.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),t):new Ga(za.UNKNOWN,t.toString())}))}ji(t,e,n){return this.Fr(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([s,r])=>this.ir.ji(t,e,n,s,r))).catch((t=>{throw"FirebaseError"===t.name?(t.code===za.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),t):new Ga(za.UNKNOWN,t.toString())}))}terminate(){this.$r=!0}}class dd{constructor(t,e){this.asyncQueue=t,this.onlineStateHandler=e,this.state="Unknown",this.Or=0,this.Mr=null,this.Lr=!0}Br(){0===this.Or&&(this.Ur("Unknown"),this.Mr=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.Mr=null,this.qr("Backend didn't respond within 10 seconds."),this.Ur("Offline"),Promise.resolve()))))}Kr(t){"Online"===this.state?this.Ur("Unknown"):(this.Or++,this.Or>=1&&(this.jr(),this.qr(`Connection failed 1 times. Most recent error: ${t.toString()}`),this.Ur("Offline")))}set(t){this.jr(),this.Or=0,"Online"===t&&(this.Lr=!1),this.Ur(t)}Ur(t){t!==this.state&&(this.state=t,this.onlineStateHandler(t))}qr(t){const e=`Could not reach Cloud Firestore backend. ${t}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.Lr?(ja(e),this.Lr=!1):Va("OnlineStateTracker",e)}jr(){null!==this.Mr&&(this.Mr.cancel(),this.Mr=null)}}class fd{constructor(t,e,n,s,r){this.localStore=t,this.datastore=e,this.asyncQueue=n,this.remoteSyncer={},this.Qr=[],this.Wr=new Map,this.Gr=new Set,this.zr=[],this.Hr=r,this.Hr.Ei((t=>{n.enqueueAndForget((async()=>{Ed(this)&&(Va("RemoteStore","Restarting streams for network reachability change."),await async function(t){const e=Ka(t);e.Gr.add(4),await md(e),e.Jr.set("Unknown"),e.Gr.delete(4),await pd(e)}(this))}))})),this.Jr=new dd(n,s)}}async function pd(t){if(Ed(t))for(const e of t.zr)await e(!0)}async function md(t){for(const e of t.zr)await e(!1)}function gd(t,e){const n=Ka(t);n.Wr.has(e.targetId)||(n.Wr.set(e.targetId,e),Td(n)?bd(n):Fd(n).lr()&&vd(n,e))}function yd(t,e){const n=Ka(t),s=Fd(n);n.Wr.delete(e),s.lr()&&wd(n,e),0===n.Wr.size&&(s.lr()?s._r():Ed(n)&&n.Jr.set("Unknown"))}function vd(t,e){t.Yr.X(e.targetId),Fd(t).br(e)}function wd(t,e){t.Yr.X(e),Fd(t).vr(e)}function bd(t){t.Yr=new kh({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),Et:e=>t.Wr.get(e)||null}),Fd(t).start(),t.Jr.Br()}function Td(t){return Ed(t)&&!Fd(t).hr()&&t.Wr.size>0}function Ed(t){return 0===Ka(t).Gr.size}function Id(t){t.Yr=void 0}async function _d(t){t.Wr.forEach(((e,n)=>{vd(t,e)}))}async function Sd(t,e){Id(t),Td(t)?(t.Jr.Kr(e),bd(t)):t.Jr.set("Unknown")}async function kd(t,e,n){if(t.Jr.set("Online"),e instanceof _h&&2===e.state&&e.cause)try{await async function(t,e){const n=e.cause;for(const s of e.targetIds)t.Wr.has(s)&&(await t.remoteSyncer.rejectListen(s,n),t.Wr.delete(s),t.Yr.removeTarget(s))}(t,e)}catch(n){Va("RemoteStore","Failed to remove targets %s: %s ",e.targetIds.join(","),n),await Ad(t,n)}else if(e instanceof Eh?t.Yr.ot(e):e instanceof Ih?t.Yr.dt(e):t.Yr.ut(e),!n.isEqual(cc.min()))try{const e=await Fl(t.localStore);n.compareTo(e)>=0&&await function(t,e){const n=t.Yr.gt(e);return n.targetChanges.forEach(((n,s)=>{if(n.resumeToken.approximateByteSize()>0){const r=t.Wr.get(s);r&&t.Wr.set(s,r.withResumeToken(n.resumeToken,e))}})),n.targetMismatches.forEach((e=>{const n=t.Wr.get(e);if(!n)return;t.Wr.set(e,n.withResumeToken(yc.EMPTY_BYTE_STRING,n.snapshotVersion)),wd(t,e);const s=new _l(n.target,e,1,n.sequenceNumber);vd(t,s)})),t.remoteSyncer.applyRemoteEvent(n)}(t,n)}catch(e){Va("RemoteStore","Failed to raise snapshot:",e),await Ad(t,e)}}async function Ad(t,e,n){if(!Tl(e))throw e;t.Gr.add(1),await md(t),t.Jr.set("Offline"),n||(n=()=>Fl(t.localStore)),t.asyncQueue.enqueueRetryable((async()=>{Va("RemoteStore","Retrying IndexedDB access"),await n(),t.Gr.delete(1),await pd(t)}))}function Cd(t,e){return e().catch((n=>Ad(t,n,e)))}async function Nd(t){const e=Ka(t),n=Vd(e);let s=e.Qr.length>0?e.Qr[e.Qr.length-1].batchId:-1;for(;Rd(e);)try{const t=await Vl(e.localStore,s);if(null===t){0===e.Qr.length&&n._r();break}s=t.batchId,Ld(e,t)}catch(t){await Ad(e,t)}Dd(e)&&Od(e)}function Rd(t){return Ed(t)&&t.Qr.length<10}function Ld(t,e){t.Qr.push(e);const n=Vd(t);n.lr()&&n.Sr&&n.Dr(e.mutations)}function Dd(t){return Ed(t)&&!Vd(t).hr()&&t.Qr.length>0}function Od(t){Vd(t).start()}async function Pd(t){Vd(t).kr()}async function Md(t){const e=Vd(t);for(const n of t.Qr)e.Dr(n.mutations)}async function xd(t,e,n){const s=t.Qr.shift(),r=Il.from(s,e,n);await Cd(t,(()=>t.remoteSyncer.applySuccessfulWrite(r))),await Nd(t)}async function Ud(t,e){e&&Vd(t).Sr&&await async function(t,e){if(function(t){switch(t){default:return Ha();case za.CANCELLED:case za.UNKNOWN:case za.DEADLINE_EXCEEDED:case za.RESOURCE_EXHAUSTED:case za.INTERNAL:case za.UNAVAILABLE:case za.UNAUTHENTICATED:return!1;case za.INVALID_ARGUMENT:case za.NOT_FOUND:case za.ALREADY_EXISTS:case za.PERMISSION_DENIED:case za.FAILED_PRECONDITION:case za.ABORTED:case za.OUT_OF_RANGE:case za.UNIMPLEMENTED:case za.DATA_LOSS:return!0}}(n=e.code)&&n!==za.ABORTED){const n=t.Qr.shift();Vd(t).wr(),await Cd(t,(()=>t.remoteSyncer.rejectFailedWrite(n.batchId,e))),await Nd(t)}var n}(t,e),Dd(t)&&Od(t)}function Fd(t){return t.Xr||(t.Xr=function(t,e,n){const s=Ka(t);return s.Fr(),new ud(e,s.ir,s.authCredentials,s.appCheckCredentials,s.k,n)}(t.datastore,t.asyncQueue,{Di:_d.bind(null,t),Ni:Sd.bind(null,t),Pr:kd.bind(null,t)}),t.zr.push((async e=>{e?(t.Xr.wr(),Td(t)?bd(t):t.Jr.set("Unknown")):(await t.Xr.stop(),Id(t))}))),t.Xr}function Vd(t){return t.Zr||(t.Zr=function(t,e,n){const s=Ka(t);return s.Fr(),new hd(e,s.ir,s.authCredentials,s.appCheckCredentials,s.k,n)}(t.datastore,t.asyncQueue,{Di:Pd.bind(null,t),Ni:Ud.bind(null,t),Nr:Md.bind(null,t),Cr:xd.bind(null,t)}),t.zr.push((async e=>{e?(t.Zr.wr(),await Nd(t)):(await t.Zr.stop(),t.Qr.length>0&&(Va("RemoteStore",`Stopping write stream with ${t.Qr.length} pending writes`),t.Qr=[]))}))),t.Zr}class jd{constructor(t,e,n,s,r){this.asyncQueue=t,this.timerId=e,this.targetTimeMs=n,this.op=s,this.removalCallback=r,this.deferred=new Wa,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((t=>{}))}static createAndSchedule(t,e,n,s,r){const i=Date.now()+n,o=new jd(t,e,i,s,r);return o.start(n),o}start(t){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),t)}skipDelay(){return this.handleDelayElapsed()}cancel(t){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new Ga(za.CANCELLED,"Operation cancelled"+(t?": "+t:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then((t=>this.deferred.resolve(t)))):Promise.resolve()))}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function Bd(t,e){if(ja("AsyncQueue",`${e}: ${t}`),Tl(t))return new Ga(za.UNAVAILABLE,`${e}: ${t}`);throw t}class qd{constructor(t){this.comparator=t?(e,n)=>t(e,n)||Ac.comparator(e.key,n.key):(t,e)=>Ac.comparator(t.key,e.key),this.keyedMap=ph(),this.sortedSet=new oh(this.comparator)}static emptySet(t){return new qd(t.comparator)}has(t){return null!=this.keyedMap.get(t)}get(t){return this.keyedMap.get(t)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(t){const e=this.keyedMap.get(t);return e?this.sortedSet.indexOf(e):-1}get size(){return this.sortedSet.size}forEach(t){this.sortedSet.inorderTraversal(((e,n)=>(t(e),!1)))}add(t){const e=this.delete(t.key);return e.copy(e.keyedMap.insert(t.key,t),e.sortedSet.insert(t,null))}delete(t){const e=this.get(t);return e?this.copy(this.keyedMap.remove(t),this.sortedSet.remove(e)):this}isEqual(t){if(!(t instanceof qd))return!1;if(this.size!==t.size)return!1;const e=this.sortedSet.getIterator(),n=t.sortedSet.getIterator();for(;e.hasNext();){const t=e.getNext().key,s=n.getNext().key;if(!t.isEqual(s))return!1}return!0}toString(){const t=[];return this.forEach((e=>{t.push(e.toString())})),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(t,e){const n=new qd;return n.comparator=this.comparator,n.keyedMap=t,n.sortedSet=e,n}}class Hd{constructor(){this.eo=new oh(Ac.comparator)}track(t){const e=t.doc.key,n=this.eo.get(e);n?0!==t.type&&3===n.type?this.eo=this.eo.insert(e,t):3===t.type&&1!==n.type?this.eo=this.eo.insert(e,{type:n.type,doc:t.doc}):2===t.type&&2===n.type?this.eo=this.eo.insert(e,{type:2,doc:t.doc}):2===t.type&&0===n.type?this.eo=this.eo.insert(e,{type:0,doc:t.doc}):1===t.type&&0===n.type?this.eo=this.eo.remove(e):1===t.type&&2===n.type?this.eo=this.eo.insert(e,{type:1,doc:n.doc}):0===t.type&&1===n.type?this.eo=this.eo.insert(e,{type:2,doc:t.doc}):Ha():this.eo=this.eo.insert(e,t)}no(){const t=[];return this.eo.inorderTraversal(((e,n)=>{t.push(n)})),t}}class $d{constructor(t,e,n,s,r,i,o,a){this.query=t,this.docs=e,this.oldDocs=n,this.docChanges=s,this.mutatedKeys=r,this.fromCache=i,this.syncStateChanged=o,this.excludesMetadataChanges=a}static fromInitialDocuments(t,e,n,s){const r=[];return e.forEach((t=>{r.push({type:0,doc:t})})),new $d(t,e,qd.emptySet(e),r,n,s,!0,!1)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(t){if(!(this.fromCache===t.fromCache&&this.syncStateChanged===t.syncStateChanged&&this.mutatedKeys.isEqual(t.mutatedKeys)&&wu(this.query,t.query)&&this.docs.isEqual(t.docs)&&this.oldDocs.isEqual(t.oldDocs)))return!1;const e=this.docChanges,n=t.docChanges;if(e.length!==n.length)return!1;for(let t=0;tbu(t)),wu),this.onlineState="Unknown",this.io=new Set}}async function Gd(t,e){const n=Ka(t),s=e.query;let r=!1,i=n.queries.get(s);if(i||(r=!0,i=new Kd),r)try{i.so=await n.onListen(s)}catch(t){const n=Bd(t,`Initialization of query '${Tu(e.query)}' failed`);return void e.onError(n)}n.queries.set(s,i),i.listeners.push(e),e.ro(n.onlineState),i.so&&e.oo(i.so)&&Qd(n)}async function Wd(t,e){const n=Ka(t),s=e.query;let r=!1;const i=n.queries.get(s);if(i){const t=i.listeners.indexOf(e);t>=0&&(i.listeners.splice(t,1),r=0===i.listeners.length)}if(r)return n.queries.delete(s),n.onUnlisten(s)}function Jd(t,e){const n=Ka(t);let s=!1;for(const t of e){const e=t.query,r=n.queries.get(e);if(r){for(const e of r.listeners)e.oo(t)&&(s=!0);r.so=t}}s&&Qd(n)}function Xd(t,e,n){const s=Ka(t),r=s.queries.get(e);if(r)for(const t of r.listeners)t.onError(n);s.queries.delete(e)}function Qd(t){t.io.forEach((t=>{t.next()}))}class Yd{constructor(t,e,n){this.query=t,this.ao=e,this.co=!1,this.uo=null,this.onlineState="Unknown",this.options=n||{}}oo(t){if(!this.options.includeMetadataChanges){const e=[];for(const n of t.docChanges)3!==n.type&&e.push(n);t=new $d(t.query,t.docs,t.oldDocs,e,t.mutatedKeys,t.fromCache,t.syncStateChanged,!0)}let e=!1;return this.co?this.ho(t)&&(this.ao.next(t),e=!0):this.lo(t,this.onlineState)&&(this.fo(t),e=!0),this.uo=t,e}onError(t){this.ao.error(t)}ro(t){this.onlineState=t;let e=!1;return this.uo&&!this.co&&this.lo(this.uo,t)&&(this.fo(this.uo),e=!0),e}lo(t,e){if(!t.fromCache)return!0;const n="Offline"!==e;return!(this.options.wo&&n||t.docs.isEmpty()&&"Offline"!==e)}ho(t){if(t.docChanges.length>0)return!0;const e=this.uo&&this.uo.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&!0===this.options.includeMetadataChanges}fo(t){t=$d.fromInitialDocuments(t.query,t.docs,t.mutatedKeys,t.fromCache),this.co=!0,this.ao.next(t)}}class Zd{constructor(t){this.key=t}}class tf{constructor(t){this.key=t}}class ef{constructor(t,e){this.query=t,this.To=e,this.Eo=null,this.current=!1,this.Io=yh(),this.mutatedKeys=yh(),this.Ao=Iu(t),this.Ro=new qd(this.Ao)}get Po(){return this.To}bo(t,e){const n=e?e.vo:new Hd,s=e?e.Ro:this.Ro;let r=e?e.mutatedKeys:this.mutatedKeys,i=s,o=!1;const a=du(this.query)&&s.size===this.query.limit?s.last():null,c=fu(this.query)&&s.size===this.query.limit?s.first():null;if(t.inorderTraversal(((t,e)=>{const u=s.get(t),h=Eu(this.query,e)?e:null,l=!!u&&this.mutatedKeys.has(u.key),d=!!h&&(h.hasLocalMutations||this.mutatedKeys.has(h.key)&&h.hasCommittedMutations);let f=!1;u&&h?u.data.isEqual(h.data)?l!==d&&(n.track({type:3,doc:h}),f=!0):this.Vo(u,h)||(n.track({type:2,doc:h}),f=!0,(a&&this.Ao(h,a)>0||c&&this.Ao(h,c)<0)&&(o=!0)):!u&&h?(n.track({type:0,doc:h}),f=!0):u&&!h&&(n.track({type:1,doc:u}),f=!0,(a||c)&&(o=!0)),f&&(h?(i=i.add(h),r=d?r.add(t):r.delete(t)):(i=i.delete(t),r=r.delete(t)))})),du(this.query)||fu(this.query))for(;i.size>this.query.limit;){const t=du(this.query)?i.last():i.first();i=i.delete(t.key),r=r.delete(t.key),n.track({type:1,doc:t})}return{Ro:i,vo:n,Bn:o,mutatedKeys:r}}Vo(t,e){return t.hasLocalMutations&&e.hasCommittedMutations&&!e.hasLocalMutations}applyChanges(t,e,n){const s=this.Ro;this.Ro=t.Ro,this.mutatedKeys=t.mutatedKeys;const r=t.vo.no();r.sort(((t,e)=>function(t,e){const n=t=>{switch(t){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Ha()}};return n(t)-n(e)}(t.type,e.type)||this.Ao(t.doc,e.doc))),this.So(n);const i=e?this.Do():[],o=0===this.Io.size&&this.current?1:0,a=o!==this.Eo;return this.Eo=o,0!==r.length||a?{snapshot:new $d(this.query,t.Ro,s,r,t.mutatedKeys,0===o,a,!1),Co:i}:{Co:i}}ro(t){return this.current&&"Offline"===t?(this.current=!1,this.applyChanges({Ro:this.Ro,vo:new Hd,mutatedKeys:this.mutatedKeys,Bn:!1},!1)):{Co:[]}}No(t){return!this.To.has(t)&&!!this.Ro.has(t)&&!this.Ro.get(t).hasLocalMutations}So(t){t&&(t.addedDocuments.forEach((t=>this.To=this.To.add(t))),t.modifiedDocuments.forEach((t=>{})),t.removedDocuments.forEach((t=>this.To=this.To.delete(t))),this.current=t.current)}Do(){if(!this.current)return[];const t=this.Io;this.Io=yh(),this.Ro.forEach((t=>{this.No(t.key)&&(this.Io=this.Io.add(t.key))}));const e=[];return t.forEach((t=>{this.Io.has(t)||e.push(new tf(t))})),this.Io.forEach((n=>{t.has(n)||e.push(new Zd(n))})),e}ko(t){this.To=t.zn,this.Io=yh();const e=this.bo(t.documents);return this.applyChanges(e,!0)}xo(){return $d.fromInitialDocuments(this.query,this.Ro,this.mutatedKeys,0===this.Eo)}}class nf{constructor(t,e,n){this.query=t,this.targetId=e,this.view=n}}class sf{constructor(t){this.key=t,this.$o=!1}}class rf{constructor(t,e,n,s,r,i){this.localStore=t,this.remoteStore=e,this.eventManager=n,this.sharedClientState=s,this.currentUser=r,this.maxConcurrentLimboResolutions=i,this.Fo={},this.Oo=new Dl((t=>bu(t)),wu),this.Mo=new Map,this.Lo=new Set,this.Bo=new oh(Ac.comparator),this.Uo=new Map,this.qo=new Hl,this.Ko={},this.jo=new Map,this.Qo=Rl.re(),this.onlineState="Unknown",this.Wo=void 0}get isPrimaryClient(){return!0===this.Wo}}async function of(t,e){const n=function(t){const e=Ka(t);return e.remoteStore.remoteSyncer.applyRemoteEvent=cf.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=Ef.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=hf.bind(null,e),e.Fo.Pr=Jd.bind(null,e.eventManager),e.Fo.zo=Xd.bind(null,e.eventManager),e}(t);let s,r;const i=n.Oo.get(e);if(i)s=i.targetId,n.sharedClientState.addLocalQueryTarget(s),r=i.view.xo();else{const t=await function(t,e){const n=Ka(t);return n.persistence.runTransaction("Allocate target","readwrite",(t=>{let s;return n.He.getTargetData(t,e).next((r=>r?(s=r,bl.resolve(s)):n.He.allocateTargetId(t).next((r=>(s=new _l(e,r,0,t.currentSequenceNumber),n.He.addTargetData(t,s).next((()=>s)))))))})).then((t=>{const s=n.qn.get(t.targetId);return(null===s||t.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(n.qn=n.qn.insert(t.targetId,t),n.Kn.set(e,t.targetId)),t}))}(n.localStore,yu(e)),i=n.sharedClientState.addLocalQueryTarget(t.targetId);s=t.targetId,r=await async function(t,e,n,s){t.Go=(e,n,s)=>async function(t,e,n,s){let r=e.view.bo(n);r.Bn&&(r=await Bl(t.localStore,e.query,!1).then((({documents:t})=>e.view.bo(t,r))));const i=s&&s.targetChanges.get(e.targetId),o=e.view.applyChanges(r,t.isPrimaryClient,i);return yf(t,e.targetId,o.Co),o.snapshot}(t,e,n,s);const r=await Bl(t.localStore,e,!0),i=new ef(e,r.zn),o=i.bo(r.documents),a=Th.createSynthesizedTargetChangeForCurrentChange(n,s&&"Offline"!==t.onlineState),c=i.applyChanges(o,t.isPrimaryClient,a);yf(t,n,c.Co);const u=new nf(e,n,i);return t.Oo.set(e,u),t.Mo.has(n)?t.Mo.get(n).push(e):t.Mo.set(n,[e]),c.snapshot}(n,e,s,"current"===i),n.isPrimaryClient&&gd(n.remoteStore,t)}return r}async function af(t,e){const n=Ka(t),s=n.Oo.get(e),r=n.Mo.get(s.targetId);if(r.length>1)return n.Mo.set(s.targetId,r.filter((t=>!wu(t,e)))),void n.Oo.delete(e);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(s.targetId),n.sharedClientState.isActiveQueryTarget(s.targetId)||await jl(n.localStore,s.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(s.targetId),yd(n.remoteStore,s.targetId),mf(n,s.targetId)})).catch(Ll)):(mf(n,s.targetId),await jl(n.localStore,s.targetId,!0))}async function cf(t,e){const n=Ka(t);try{const t=await function(t,e){const n=Ka(t),s=e.snapshotVersion;let r=n.qn;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(t=>{const i=n.Qn.newChangeBuffer({trackRemovals:!0});r=n.qn;const o=[];e.targetChanges.forEach(((e,i)=>{const a=r.get(i);if(!a)return;o.push(n.He.removeMatchingKeys(t,e.removedDocuments,i).next((()=>n.He.addMatchingKeys(t,e.addedDocuments,i))));const c=e.resumeToken;if(c.approximateByteSize()>0){const u=a.withResumeToken(c,s).withSequenceNumber(t.currentSequenceNumber);r=r.insert(i,u),function(t,e,n){return $a(e.resumeToken.approximateByteSize()>0),0===t.resumeToken.approximateByteSize()||e.snapshotVersion.toMicroseconds()-t.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(a,u,e)&&o.push(n.He.updateTargetData(t,u))}}));let a=dh();if(e.documentUpdates.forEach(((s,r)=>{e.resolvedLimboDocuments.has(s)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(t,s))})),o.push(function(t,e,n,s,r){let i=yh();return n.forEach((t=>i=i.add(t))),e.getEntries(t,i).next((t=>{let i=dh();return n.forEach(((n,o)=>{const a=t.get(n),c=(null==r?void 0:r.get(n))||s;o.isNoDocument()&&o.version.isEqual(cc.min())?(e.removeEntry(n,c),i=i.insert(n,o)):!a.isValidDocument()||o.version.compareTo(a.version)>0||0===o.version.compareTo(a.version)&&a.hasPendingWrites?(e.addEntry(o,c),i=i.insert(n,o)):Va("LocalStore","Ignoring outdated watch update for ",n,". Current version:",a.version," Watch version:",o.version)})),i}))}(t,i,e.documentUpdates,s,void 0).next((t=>{a=t}))),!s.isEqual(cc.min())){const e=n.He.getLastRemoteSnapshotVersion(t).next((e=>n.He.setTargetsMetadata(t,t.currentSequenceNumber,s)));o.push(e)}return bl.waitFor(o).next((()=>i.apply(t))).next((()=>n.Wn.Vn(t,a))).next((()=>a))})).then((t=>(n.qn=r,t)))}(n.localStore,e);e.targetChanges.forEach(((t,e)=>{const s=n.Uo.get(e);s&&($a(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1),t.addedDocuments.size>0?s.$o=!0:t.modifiedDocuments.size>0?$a(s.$o):t.removedDocuments.size>0&&($a(s.$o),s.$o=!1))})),await bf(n,t,e)}catch(t){await Ll(t)}}function uf(t,e,n){const s=Ka(t);if(s.isPrimaryClient&&0===n||!s.isPrimaryClient&&1===n){const t=[];s.Oo.forEach(((n,s)=>{const r=s.view.ro(e);r.snapshot&&t.push(r.snapshot)})),function(t,e){const n=Ka(t);n.onlineState=e;let s=!1;n.queries.forEach(((t,n)=>{for(const t of n.listeners)t.ro(e)&&(s=!0)})),s&&Qd(n)}(s.eventManager,e),t.length&&s.Fo.Pr(t),s.onlineState=e,s.isPrimaryClient&&s.sharedClientState.setOnlineState(e)}}async function hf(t,e,n){const s=Ka(t);s.sharedClientState.updateQueryState(e,"rejected",n);const r=s.Uo.get(e),i=r&&r.key;if(i){let t=new oh(Ac.comparator);t=t.insert(i,Hc.newNoDocument(i,cc.min()));const n=yh().add(i),r=new bh(cc.min(),new Map,new uh(ic),t,n);await cf(s,r),s.Bo=s.Bo.remove(i),s.Uo.delete(e),wf(s)}else await jl(s.localStore,e,!1).then((()=>mf(s,e,n))).catch(Ll)}async function lf(t,e){const n=Ka(t),s=e.batch.batchId;try{const t=await function(t,e){const n=Ka(t);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",(t=>{const s=e.batch.keys(),r=n.Qn.newChangeBuffer({trackRemovals:!0});return function(t,e,n,s){const r=n.batch,i=r.keys();let o=bl.resolve();return i.forEach((t=>{o=o.next((()=>s.getEntry(e,t))).next((e=>{const i=n.docVersions.get(t);$a(null!==i),e.version.compareTo(i)<0&&(r.applyToRemoteDocument(e,n),e.isValidDocument()&&s.addEntry(e,n.commitVersion))}))})),o.next((()=>t.An.removeMutationBatch(e,r)))}(n,t,e,r).next((()=>r.apply(t))).next((()=>n.An.performConsistencyCheck(t))).next((()=>n.Wn.vn(t,s)))}))}(n.localStore,e);pf(n,s,null),ff(n,s),n.sharedClientState.updateMutationState(s,"acknowledged"),await bf(n,t)}catch(t){await Ll(t)}}async function df(t,e,n){const s=Ka(t);try{const t=await function(t,e){const n=Ka(t);return n.persistence.runTransaction("Reject batch","readwrite-primary",(t=>{let s;return n.An.lookupMutationBatch(t,e).next((e=>($a(null!==e),s=e.keys(),n.An.removeMutationBatch(t,e)))).next((()=>n.An.performConsistencyCheck(t))).next((()=>n.Wn.vn(t,s)))}))}(s.localStore,e);pf(s,e,n),ff(s,e),s.sharedClientState.updateMutationState(e,"rejected",n),await bf(s,t)}catch(n){await Ll(n)}}function ff(t,e){(t.jo.get(e)||[]).forEach((t=>{t.resolve()})),t.jo.delete(e)}function pf(t,e,n){const s=Ka(t);let r=s.Ko[s.currentUser.toKey()];if(r){const t=r.get(e);t&&(n?t.reject(n):t.resolve(),r=r.remove(e)),s.Ko[s.currentUser.toKey()]=r}}function mf(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const s of t.Mo.get(e))t.Oo.delete(s),n&&t.Fo.zo(s,n);t.Mo.delete(e),t.isPrimaryClient&&t.qo.us(e).forEach((e=>{t.qo.containsKey(e)||gf(t,e)}))}function gf(t,e){t.Lo.delete(e.path.canonicalString());const n=t.Bo.get(e);null!==n&&(yd(t.remoteStore,n),t.Bo=t.Bo.remove(e),t.Uo.delete(n),wf(t))}function yf(t,e,n){for(const s of n)s instanceof Zd?(t.qo.addReference(s.key,e),vf(t,s)):s instanceof tf?(Va("SyncEngine","Document no longer in limbo: "+s.key),t.qo.removeReference(s.key,e),t.qo.containsKey(s.key)||gf(t,s.key)):Ha()}function vf(t,e){const n=e.key,s=n.path.canonicalString();t.Bo.get(n)||t.Lo.has(s)||(Va("SyncEngine","New document in limbo: "+n),t.Lo.add(s),wf(t))}function wf(t){for(;t.Lo.size>0&&t.Bo.size{o.push(s.Go(a,e,n).then((t=>{if(t){s.isPrimaryClient&&s.sharedClientState.updateQueryState(a.targetId,t.fromCache?"not-current":"current"),r.push(t);const e=Pl.$n(a.targetId,t);i.push(e)}})))})),await Promise.all(o),s.Fo.Pr(r),await async function(t,e){const n=Ka(t);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(t=>bl.forEach(e,(e=>bl.forEach(e.kn,(s=>n.persistence.referenceDelegate.addReference(t,e.targetId,s))).next((()=>bl.forEach(e.xn,(s=>n.persistence.referenceDelegate.removeReference(t,e.targetId,s)))))))))}catch(t){if(!Tl(t))throw t;Va("LocalStore","Failed to update sequence numbers: "+t)}for(const t of e){const e=t.targetId;if(!t.fromCache){const t=n.qn.get(e),s=t.snapshotVersion,r=t.withLastLimboFreeSnapshotVersion(s);n.qn=n.qn.insert(e,r)}}}(s.localStore,i))}async function Tf(t,e){const n=Ka(t);if(!n.currentUser.isEqual(e)){Va("SyncEngine","User change. New user:",e.toKey());const t=await Ul(n.localStore,e);n.currentUser=e,function(t,e){t.jo.forEach((t=>{t.forEach((t=>{t.reject(new Ga(za.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))}))})),t.jo.clear()}(n),n.sharedClientState.handleUserChange(e,t.removedBatchIds,t.addedBatchIds),await bf(n,t.Gn)}}function Ef(t,e){const n=Ka(t),s=n.Uo.get(e);if(s&&s.$o)return yh().add(s.key);{let t=yh();const s=n.Mo.get(e);if(!s)return t;for(const e of s){const s=n.Oo.get(e);t=t.unionWith(s.view.Po)}return t}}function If(t){const e=Ka(t);return e.remoteStore.remoteSyncer.applySuccessfulWrite=lf.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=df.bind(null,e),e}class _f{constructor(){this.synchronizeTabs=!1}async initialize(t){this.k=od(t.databaseInfo.databaseId),this.sharedClientState=this.Jo(t),this.persistence=this.Yo(t),await this.persistence.start(),this.gcScheduler=this.Xo(t),this.localStore=this.Zo(t)}Xo(t){return null}Zo(t){return function(t,e,n,s){return new xl(t,e,n,s)}(this.persistence,new Ml,t.initialUser,this.k)}Yo(t){return new Jl(Ql.ks,this.k)}Jo(t){return new Zl}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class Sf{async initialize(t,e){this.localStore||(this.localStore=t.localStore,this.sharedClientState=t.sharedClientState,this.datastore=this.createDatastore(e),this.remoteStore=this.createRemoteStore(e),this.eventManager=this.createEventManager(e),this.syncEngine=this.createSyncEngine(e,!t.synchronizeTabs),this.sharedClientState.onlineStateHandler=t=>uf(this.syncEngine,t,1),this.remoteStore.remoteSyncer.handleCredentialChange=Tf.bind(null,this.syncEngine),await async function(t,e){const n=Ka(t);e?(n.Gr.delete(2),await pd(n)):e||(n.Gr.add(2),await md(n),n.Jr.set("Unknown"))}(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(t){return new zd}createDatastore(t){const e=od(t.databaseInfo.databaseId),n=(s=t.databaseInfo,new rd(s));var s;return function(t,e,n,s){return new ld(t,e,n,s)}(t.authCredentials,t.appCheckCredentials,n,e)}createRemoteStore(t){return e=this.localStore,n=this.datastore,s=t.asyncQueue,r=t=>uf(this.syncEngine,t,0),i=ed.bt()?new ed:new td,new fd(e,n,s,r,i);var e,n,s,r,i}createSyncEngine(t,e){return function(t,e,n,s,r,i,o){const a=new rf(t,e,n,s,r,i);return o&&(a.Wo=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,t.initialUser,t.maxConcurrentLimboResolutions,e)}terminate(){return async function(t){const e=Ka(t);Va("RemoteStore","RemoteStore shutting down."),e.Gr.add(5),await md(e),e.Hr.shutdown(),e.Jr.set("Unknown")}(this.remoteStore)}}class kf{constructor(t){this.observer=t,this.muted=!1}next(t){this.observer.next&&this.ea(this.observer.next,t)}error(t){this.observer.error?this.ea(this.observer.error,t):console.error("Uncaught Error in snapshot listener:",t)}na(){this.muted=!0}ea(t,e){this.muted||setTimeout((()=>{this.muted||t(e)}),0)}}class Af{constructor(t,e,n,s){this.authCredentials=t,this.appCheckCredentials=e,this.asyncQueue=n,this.databaseInfo=s,this.user=Ma.UNAUTHENTICATED,this.clientId=rc.A(),this.authCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,(async t=>{Va("FirestoreClient","Received user=",t.uid),await this.authCredentialListener(t),this.user=t})),this.appCheckCredentials.start(n,(()=>Promise.resolve()))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(t){this.authCredentialListener=t}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new Ga(za.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const t=new Wa;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),t.resolve()}catch(e){const n=Bd(e,"Failed to shutdown persistence");t.reject(n)}})),t.promise}}async function Cf(t,e){t.asyncQueue.verifyOperationInProgress();const n=await async function(t){return t.offlineComponents||(Va("FirestoreClient","Using default OfflineComponentProvider"),await async function(t,e){t.asyncQueue.verifyOperationInProgress(),Va("FirestoreClient","Initializing OfflineComponentProvider");const n=await t.getConfiguration();await e.initialize(n);let s=n.initialUser;t.setCredentialChangeListener((async t=>{s.isEqual(t)||(await Ul(e.localStore,t),s=t)})),e.persistence.setDatabaseDeletedListener((()=>t.terminate())),t.offlineComponents=e}(t,new _f)),t.offlineComponents}(t);Va("FirestoreClient","Initializing OnlineComponentProvider");const s=await t.getConfiguration();await e.initialize(n,s),t.setCredentialChangeListener((t=>async function(t,e){const n=Ka(t);n.asyncQueue.verifyOperationInProgress(),Va("RemoteStore","RemoteStore received new credentials");const s=Ed(n);n.Gr.add(3),await md(n),s&&n.Jr.set("Unknown"),await n.remoteSyncer.handleCredentialChange(e),n.Gr.delete(3),await pd(n)}(e.remoteStore,t))),t.onlineComponents=e}async function Nf(t){return t.onlineComponents||(Va("FirestoreClient","Using default OnlineComponentProvider"),await Cf(t,new Sf)),t.onlineComponents}async function Rf(t){const e=await Nf(t),n=e.eventManager;return n.onListen=of.bind(null,e.syncEngine),n.onUnlisten=af.bind(null,e.syncEngine),n}class Lf{constructor(t,e,n,s,r,i,o,a){this.databaseId=t,this.appId=e,this.persistenceKey=n,this.host=s,this.ssl=r,this.forceLongPolling=i,this.autoDetectLongPolling=o,this.useFetchStreams=a}}class Df{constructor(t,e){this.projectId=t,this.database=e||"(default)"}get isDefaultDatabase(){return"(default)"===this.database}isEqual(t){return t instanceof Df&&t.projectId===this.projectId&&t.database===this.database}}const Of=new Map;function Pf(t,e,n){if(!n)throw new Ga(za.INVALID_ARGUMENT,`Function ${t}() cannot be called with an empty ${e}.`)}function Mf(t){if(!Ac.isDocumentKey(t))throw new Ga(za.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`)}function xf(t){if(Ac.isDocumentKey(t))throw new Ga(za.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`)}function Uf(t){if(void 0===t)return"undefined";if(null===t)return"null";if("string"==typeof t)return t.length>20&&(t=`${t.substring(0,20)}...`),JSON.stringify(t);if("number"==typeof t||"boolean"==typeof t)return""+t;if("object"==typeof t){if(t instanceof Array)return"an array";{const e=function(t){return t.constructor?t.constructor.name:null}(t);return e?`a custom ${e} object`:"an object"}}return"function"==typeof t?"a function":Ha()}function Ff(t,e){if("_delegate"in t&&(t=t._delegate),!(t instanceof e)){if(e.name===t.constructor.name)throw new Ga(za.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=Uf(t);throw new Ga(za.INVALID_ARGUMENT,`Expected type '${e.name}', but it was: ${n}`)}}return t}class Vf{constructor(t){var e;if(void 0===t.host){if(void 0!==t.ssl)throw new Ga(za.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=t.host,this.ssl=null===(e=t.ssl)||void 0===e||e;if(this.credentials=t.credentials,this.ignoreUndefinedProperties=!!t.ignoreUndefinedProperties,void 0===t.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==t.cacheSizeBytes&&t.cacheSizeBytes<1048576)throw new Ga(za.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=t.cacheSizeBytes}this.experimentalForceLongPolling=!!t.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!t.experimentalAutoDetectLongPolling,this.useFetchStreams=!!t.useFetchStreams,function(t,e,n,s){if(!0===e&&!0===s)throw new Ga(za.INVALID_ARGUMENT,"experimentalForceLongPolling and experimentalAutoDetectLongPolling cannot be used together.")}(0,t.experimentalForceLongPolling,0,t.experimentalAutoDetectLongPolling)}isEqual(t){return this.host===t.host&&this.ssl===t.ssl&&this.credentials===t.credentials&&this.cacheSizeBytes===t.cacheSizeBytes&&this.experimentalForceLongPolling===t.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===t.experimentalAutoDetectLongPolling&&this.ignoreUndefinedProperties===t.ignoreUndefinedProperties&&this.useFetchStreams===t.useFetchStreams}}class jf{constructor(t,e,n){this._authCredentials=e,this._appCheckCredentials=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Vf({}),this._settingsFrozen=!1,t instanceof Df?this._databaseId=t:(this._app=t,this._databaseId=function(t){if(!Object.prototype.hasOwnProperty.apply(t.options,["projectId"]))throw new Ga(za.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Df(t.options.projectId)}(t))}get app(){if(!this._app)throw new Ga(za.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(t){if(this._settingsFrozen)throw new Ga(za.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 Vf(t),void 0!==t.credentials&&(this._authCredentials=function(t){if(!t)return new Xa;switch(t.type){case"gapi":const e=t.client;return $a(!("object"!=typeof e||null===e||!e.auth||!e.auth.getAuthHeaderValueForFirstParty)),new Za(e,t.sessionIndex||"0",t.iamToken||null);case"provider":return t.client;default:throw new Ga(za.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(t.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(t){const e=Of.get(t);e&&(Va("ComponentProvider","Removing Datastore"),Of.delete(t),e.terminate())}(this),Promise.resolve()}}class Bf{constructor(t,e,n){this.converter=e,this._key=n,this.type="document",this.firestore=t}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Hf(this.firestore,this.converter,this._key.path.popLast())}withConverter(t){return new Bf(this.firestore,t,this._key)}}class qf{constructor(t,e,n){this.converter=e,this._query=n,this.type="query",this.firestore=t}withConverter(t){return new qf(this.firestore,t,this._query)}}class Hf extends qf{constructor(t,e,n){super(t,e,lu(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const t=this._path.popLast();return t.isEmpty()?null:new Bf(this.firestore,null,new Ac(t))}withConverter(t){return new Hf(this.firestore,t,this._path)}}function $f(t,e,...n){if(t=b(t),1===arguments.length&&(e=rc.A()),Pf("doc","path",e),t instanceof jf){const s=fc.fromString(e,...n);return Mf(s),new Bf(t,null,new Ac(s))}{if(!(t instanceof Bf||t instanceof Hf))throw new Ga(za.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const s=t._path.child(fc.fromString(e,...n));return Mf(s),new Bf(t.firestore,t instanceof Hf?t.converter:null,new Ac(s))}}class Kf{constructor(){this.ma=Promise.resolve(),this.ga=[],this.ya=!1,this.pa=[],this.Ta=null,this.Ea=!1,this.Ia=!1,this.Aa=[],this.ur=new ad(this,"async_queue_retry"),this.Ra=()=>{const t=id();t&&Va("AsyncQueue","Visibility state changed to "+t.visibilityState),this.ur.er()};const t=id();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.Ra)}get isShuttingDown(){return this.ya}enqueueAndForget(t){this.enqueue(t)}enqueueAndForgetEvenWhileRestricted(t){this.Pa(),this.ba(t)}enterRestrictedMode(t){if(!this.ya){this.ya=!0,this.Ia=t||!1;const e=id();e&&"function"==typeof e.removeEventListener&&e.removeEventListener("visibilitychange",this.Ra)}}enqueue(t){if(this.Pa(),this.ya)return new Promise((()=>{}));const e=new Wa;return this.ba((()=>this.ya&&this.Ia?Promise.resolve():(t().then(e.resolve,e.reject),e.promise))).then((()=>e.promise))}enqueueRetryable(t){this.enqueueAndForget((()=>(this.ga.push(t),this.va())))}async va(){if(0!==this.ga.length){try{await this.ga[0](),this.ga.shift(),this.ur.reset()}catch(t){if(!Tl(t))throw t;Va("AsyncQueue","Operation failed with retryable error: "+t)}this.ga.length>0&&this.ur.Zi((()=>this.va()))}}ba(t){const e=this.ma.then((()=>(this.Ea=!0,t().catch((t=>{this.Ta=t,this.Ea=!1;const e=function(t){let e=t.message||"";return t.stack&&(e=t.stack.includes(t.message)?t.stack:t.message+"\n"+t.stack),e}(t);throw ja("INTERNAL UNHANDLED ERROR: ",e),t})).then((t=>(this.Ea=!1,t))))));return this.ma=e,e}enqueueAfterDelay(t,e,n){this.Pa(),this.Aa.indexOf(t)>-1&&(e=0);const s=jd.createAndSchedule(this,t,e,n,(t=>this.Va(t)));return this.pa.push(s),s}Pa(){this.Ta&&Ha()}verifyOperationInProgress(){}async Sa(){let t;do{t=this.ma,await t}while(t!==this.ma)}Da(t){for(const e of this.pa)if(e.timerId===t)return!0;return!1}Ca(t){return this.Sa().then((()=>{this.pa.sort(((t,e)=>t.targetTimeMs-e.targetTimeMs));for(const e of this.pa)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Sa()}))}Na(t){this.Aa.push(t)}Va(t){const e=this.pa.indexOf(t);this.pa.splice(e,1)}}function zf(t){return function(t,e){if("object"!=typeof t||null===t)return!1;const n=t;for(const t of["next","error","complete"])if(t in n&&"function"==typeof n[t])return!0;return!1}(t)}class Gf extends jf{constructor(t,e,n){super(t,e,n),this.type="firestore",this._queue=new Kf,this._persistenceKey="name"in t?t.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||Jf(this),this._firestoreClient.terminate()}}function Wf(t){return t._firestoreClient||Jf(t),t._firestoreClient.verifyNotTerminated(),t._firestoreClient}function Jf(t){var e;const n=t._freezeSettings(),s=function(t,e,n,s){return new Lf(t,e,n,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,s.useFetchStreams)}(t._databaseId,(null===(e=t._app)||void 0===e?void 0:e.options.appId)||"",t._persistenceKey,n);t._firestoreClient=new Af(t._authCredentials,t._appCheckCredentials,t._queue,s)}class Xf{constructor(...t){for(let e=0;e90)throw new Ga(za.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new Ga(za.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this._long=e}get latitude(){return this._lat}get longitude(){return this._long}isEqual(t){return this._lat===t._lat&&this._long===t._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(t){return ic(this._lat,t._lat)||ic(this._long,t._long)}}const tp=/^__.*__$/;class ep{constructor(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}toMutation(t,e){return null!==this.fieldMask?new Xu(t,this.data,this.fieldMask,e,this.fieldTransforms):new Ju(t,this.data,e,this.fieldTransforms)}}function np(t){switch(t){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw Ha()}}class sp{constructor(t,e,n,s,r,i){this.settings=t,this.databaseId=e,this.k=n,this.ignoreUndefinedProperties=s,void 0===r&&this.ka(),this.fieldTransforms=r||[],this.fieldMask=i||[]}get path(){return this.settings.path}get xa(){return this.settings.xa}$a(t){return new sp(Object.assign(Object.assign({},this.settings),t),this.databaseId,this.k,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Fa(t){var e;const n=null===(e=this.path)||void 0===e?void 0:e.child(t),s=this.$a({path:n,Oa:!1});return s.Ma(t),s}La(t){var e;const n=null===(e=this.path)||void 0===e?void 0:e.child(t),s=this.$a({path:n,Oa:!1});return s.ka(),s}Ba(t){return this.$a({path:void 0,Oa:!0})}Ua(t){return pp(t,this.settings.methodName,this.settings.qa||!1,this.path,this.settings.Ka)}contains(t){return void 0!==this.fieldMask.find((e=>t.isPrefixOf(e)))||void 0!==this.fieldTransforms.find((e=>t.isPrefixOf(e.field)))}ka(){if(this.path)for(let t=0;tc.covers(t.field)))}else c=null,u=o.fieldTransforms;return new ep(new Bc(a),c,u)}function ap(t,e){if(up(t=b(t)))return hp("Unsupported field value:",e,t),cp(t,e);if(t instanceof Yf)return function(t,e){if(!np(e.xa))throw e.Ua(`${t._methodName}() can only be used with update() and set()`);if(!e.path)throw e.Ua(`${t._methodName}() is not currently supported inside arrays`);const n=t._toFieldTransform(e);n&&e.fieldTransforms.push(n)}(t,e),null;if(void 0===t&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),t instanceof Array){if(e.settings.Oa&&4!==e.xa)throw e.Ua("Nested arrays are not supported");return function(t,e){const n=[];let s=0;for(const r of t){let t=ap(r,e.Ba(s));null==t&&(t={nullValue:"NULL_VALUE"}),n.push(t),s++}return{arrayValue:{values:n}}}(t,e)}return function(t,e){if(null===(t=b(t)))return{nullValue:"NULL_VALUE"};if("number"==typeof t)return Au(e.k,t);if("boolean"==typeof t)return{booleanValue:t};if("string"==typeof t)return{stringValue:t};if(t instanceof Date){const n=ac.fromDate(t);return{timestampValue:Dh(e.k,n)}}if(t instanceof ac){const n=new ac(t.seconds,1e3*Math.floor(t.nanoseconds/1e3));return{timestampValue:Dh(e.k,n)}}if(t instanceof Zf)return{geoPointValue:{latitude:t.latitude,longitude:t.longitude}};if(t instanceof Qf)return{bytesValue:Oh(e.k,t._byteString)};if(t instanceof Bf){const n=e.databaseId,s=t.firestore._databaseId;if(!s.isEqual(n))throw e.Ua(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:xh(t.firestore._databaseId||e.databaseId,t._key.path)}}throw e.Ua(`Unsupported field value: ${Uf(t)}`)}(t,e)}function cp(t,e){const n={};return lc(t)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):hc(t,((t,s)=>{const r=ap(s,e.Fa(t));null!=r&&(n[t]=r)})),{mapValue:{fields:n}}}function up(t){return!("object"!=typeof t||null===t||t instanceof Array||t instanceof Date||t instanceof ac||t instanceof Zf||t instanceof Qf||t instanceof Bf||t instanceof Yf)}function hp(t,e,n){if(!up(n)||!function(t){return"object"==typeof t&&null!==t&&(Object.getPrototypeOf(t)===Object.prototype||null===Object.getPrototypeOf(t))}(n)){const s=Uf(n);throw"an object"===s?e.Ua(t+" a custom object"):e.Ua(t+" "+s)}}function lp(t,e,n){if((e=b(e))instanceof Xf)return e._internalPath;if("string"==typeof e)return fp(t,e);throw pp("Field path arguments must be of type string or FieldPath.",t,!1,void 0,n)}const dp=new RegExp("[~\\*/\\[\\]]");function fp(t,e,n){if(e.search(dp)>=0)throw pp(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,n);try{return new Xf(...e.split("."))._internalPath}catch(s){throw pp(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,n)}}function pp(t,e,n,s,r){const i=s&&!s.isEmpty(),o=void 0!==r;let a=`Function ${e}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(i||o)&&(c+=" (found",i&&(c+=` in field ${s}`),o&&(c+=` in document ${r}`),c+=")"),new Ga(za.INVALID_ARGUMENT,a+t+c)}function mp(t,e){return t.some((t=>t.isEqual(e)))}class gp{constructor(t,e,n,s,r){this._firestore=t,this._userDataWriter=e,this._key=n,this._document=s,this._converter=r}get id(){return this._key.path.lastSegment()}get ref(){return new Bf(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const t=new yp(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(t)}return this._userDataWriter.convertValue(this._document.data.value)}}get(t){if(this._document){const e=this._document.data.field(vp("DocumentSnapshot.get",t));if(null!==e)return this._userDataWriter.convertValue(e)}}}class yp extends gp{data(){return super.data()}}function vp(t,e){return"string"==typeof e?fp(t,e):e instanceof Xf?e._internalPath:e._delegate._internalPath}class wp{constructor(t,e){this.hasPendingWrites=t,this.fromCache=e}isEqual(t){return this.hasPendingWrites===t.hasPendingWrites&&this.fromCache===t.fromCache}}class bp extends gp{constructor(t,e,n,s,r,i){super(t,e,n,s,i),this._firestore=t,this._firestoreImpl=t,this.metadata=r}exists(){return super.exists()}data(t={}){if(this._document){if(this._converter){const e=new Tp(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(e,t)}return this._userDataWriter.convertValue(this._document.data.value,t.serverTimestamps)}}get(t,e={}){if(this._document){const n=this._document.data.field(vp("DocumentSnapshot.get",t));if(null!==n)return this._userDataWriter.convertValue(n,e.serverTimestamps)}}}class Tp extends bp{data(t={}){return super.data(t)}}class Ep{constructor(t,e,n,s){this._firestore=t,this._userDataWriter=e,this._snapshot=s,this.metadata=new wp(s.hasPendingWrites,s.fromCache),this.query=n}get docs(){const t=[];return this.forEach((e=>t.push(e))),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,e){this._snapshot.docs.forEach((n=>{t.call(e,new Tp(this._firestore,this._userDataWriter,n.key,n,new wp(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(t={}){const e=!!t.includeMetadataChanges;if(e&&this._snapshot.excludesMetadataChanges)throw new Ga(za.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=function(t,e){if(t._snapshot.oldDocs.isEmpty()){let e=0;return t._snapshot.docChanges.map((n=>({type:"added",doc:new Tp(t._firestore,t._userDataWriter,n.doc.key,n.doc,new wp(t._snapshot.mutatedKeys.has(n.doc.key),t._snapshot.fromCache),t.query.converter),oldIndex:-1,newIndex:e++})))}{let n=t._snapshot.oldDocs;return t._snapshot.docChanges.filter((t=>e||3!==t.type)).map((e=>{const s=new Tp(t._firestore,t._userDataWriter,e.doc.key,e.doc,new wp(t._snapshot.mutatedKeys.has(e.doc.key),t._snapshot.fromCache),t.query.converter);let r=-1,i=-1;return 0!==e.type&&(r=n.indexOf(e.doc.key),n=n.delete(e.doc.key)),1!==e.type&&(n=n.add(e.doc),i=n.indexOf(e.doc.key)),{type:Ip(e.type),doc:s,oldIndex:r,newIndex:i}}))}}(this,e),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges}}function Ip(t){switch(t){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Ha()}}class _p{}class Sp extends _p{constructor(t,e){super(),this.Ga=t,this.Ja=e,this.type="orderBy"}_apply(t){const e=function(t,e,n){if(null!==t.startAt)throw new Ga(za.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==t.endAt)throw new Ga(za.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");const s=new ou(e,n);return function(t,e){if(null===pu(t)){const n=mu(t);null!==n&&function(t,e,n){if(!n.isEqual(e))throw new Ga(za.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}(0,n,e.field)}}(t,s),s}(t._query,this.Ga,this.Ja);return new qf(t.firestore,t.converter,function(t,e){const n=t.explicitOrderBy.concat([e]);return new hu(t.path,t.collectionGroup,n,t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt)}(t._query,e))}}class kp extends _p{constructor(t,e,n){super(),this.type=t,this.Ya=e,this.Xa=n}_apply(t){return new qf(t.firestore,t.converter,vu(t._query,this.Ya,this.Xa))}}class Ap extends class{convertValue(t,e="none"){switch(Cc(t)){case 0:return null;case 1:return t.booleanValue;case 2:return bc(t.integerValue||t.doubleValue);case 3:return this.convertTimestamp(t.timestampValue);case 4:return this.convertServerTimestamp(t,e);case 5:return t.stringValue;case 6:return this.convertBytes(Tc(t.bytesValue));case 7:return this.convertReference(t.referenceValue);case 8:return this.convertGeoPoint(t.geoPointValue);case 9:return this.convertArray(t.arrayValue,e);case 10:return this.convertObject(t.mapValue,e);default:throw Ha()}}convertObject(t,e){const n={};return hc(t.fields,((t,s)=>{n[t]=this.convertValue(s,e)})),n}convertGeoPoint(t){return new Zf(bc(t.latitude),bc(t.longitude))}convertArray(t,e){return(t.values||[]).map((t=>this.convertValue(t,e)))}convertServerTimestamp(t,e){switch(e){case"previous":const n=Ic(t);return null==n?null:this.convertValue(n,e);case"estimate":return this.convertTimestamp(_c(t));default:return null}}convertTimestamp(t){const e=wc(t);return new ac(e.seconds,e.nanos)}convertDocumentKey(t,e){const n=fc.fromString(t);$a(sl(n));const s=new Df(n.get(1),n.get(3)),r=new Ac(n.popFirst(5));return s.isEqual(e)||ja(`Document ${r} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`),r}}{constructor(t){super(),this.firestore=t}convertBytes(t){return new Qf(t)}convertReference(t){const e=this.convertDocumentKey(t,this.firestore._databaseId);return new Bf(this.firestore,null,e)}}function Cp(t,e){return function(t,e){const n=new Wa;return t.asyncQueue.enqueueAndForget((async()=>async function(t,e,n){const s=If(t);try{const t=await function(t,e){const n=Ka(t),s=ac.now(),r=e.reduce(((t,e)=>t.add(e.key)),yh());let i;return n.persistence.runTransaction("Locally write mutations","readwrite",(t=>n.Wn.vn(t,r).next((r=>{i=r;const o=[];for(const t of e){const e=zu(t,i.get(t.key));null!=e&&o.push(new Xu(t.key,e,qc(e.value.mapValue),Bu.exists(!0)))}return n.An.addMutationBatch(t,s,o,e)})))).then((t=>(t.applyToLocalDocumentSet(i),{batchId:t.batchId,changes:i})))}(s.localStore,e);s.sharedClientState.addPendingMutation(t.batchId),function(t,e,n){let s=t.Ko[t.currentUser.toKey()];s||(s=new oh(ic)),s=s.insert(e,n),t.Ko[t.currentUser.toKey()]=s}(s,t.batchId,n),await bf(s,t.changes),await Nd(s.remoteStore)}catch(t){const e=Bd(t,"Failed to persist write");n.reject(e)}}(await function(t){return Nf(t).then((t=>t.syncEngine))}(t),e,n))),n.promise}(Wf(t),e)}function Np(t,e,n){const s=n.docs.get(e._key),r=new Ap(t);return new bp(t,r,e._key,s,new wp(n.hasPendingWrites,n.fromCache),e.converter)}!function(t,e=!0){xa="9.6.1",B(new T("firestore",((t,{options:n})=>{const s=t.getProvider("app").getImmediate(),r=new Gf(s,new Qa(t.getProvider("auth-internal")),new ec(t.getProvider("app-check-internal")));return n=Object.assign({useFetchStreams:e},n),r._setSettings(n),r}),"PUBLIC")),G(Pa,"3.4.1",t),G(Pa,"3.4.1","esm2017")}();const Rp=document.querySelector("body"),Lp=document.querySelector(".saveStats"),Dp=document.querySelector(".profile>.routs>.signUp"),Op=document.querySelector(".windowTop>.options>.signupBtn"),Pp=document.querySelector(".profileBtn"),Mp=document.querySelector(".profile"),xp=document.querySelectorAll(".options>.close"),Up=document.querySelectorAll(".windowTop>.move"),Fp=document.querySelector(".settingsBtn"),Vp=document.querySelector(".settings"),jp=document.querySelector(".themeSelector"),Bp=document.querySelector(".profile>.routs"),qp=document.querySelector(".text"),Hp=document.querySelector(".stats"),$p=document.querySelector(".containerStats>.speed"),Kp=document.querySelector(".loginBtn"),zp=document.querySelector(".profile>.routs>.signIn"),Gp=document.querySelector(".updateBtn"),Wp=document.querySelector(".profile>.routs>.update"),Jp=document.querySelector(".logoutBtn"),Xp=document.querySelector(".info"),Qp=document.querySelector(".loader"),Yp=(document.querySelector(".options"),document.querySelector(".leaderBoard")),Zp=document.querySelector(".leaderBoard>.content"),tm=document.querySelector(".leaderBoardBtn"),em=document.querySelector(".container>.info"),nm=document.querySelector(".username"),sm=document.querySelector(".textOptions"),rm=document.querySelector(".nextBtn"),im=document.querySelector(".infoPopup"),om=document.querySelector(".mpBtn"),am=document.querySelector(".mpContainer"),cm=document.querySelector(".joinRoom"),um=document.querySelector(".createRoom"),hm=document.querySelector(".playArea"),lm=document.querySelector(".roomHeader"),dm=document.querySelector(".copyRoomId"),fm=document.querySelector("span.roomId");function pm(t,e){if(e){let n=`${t}${e.userName}${e.speed}`,s=document.createElement("li");s.innerHTML=n,s.classList.add("leaderBoardListItem"),Zp.appendChild(s)}}const mm=function(t=z()){return q(t,"firestore").getImmediate()}(Qt),gm=async()=>{let t=Es(),e=t.currentUser&&t.currentUser.uid;if(e){const t=$f(mm,`scores/${e}`);let n=t&&await function(t){t=Ff(t,Bf);const e=Ff(t.firestore,Gf);return function(t,e,n={}){const s=new Wa;return t.asyncQueue.enqueueAndForget((async()=>function(t,e,n,s,r){const i=new kf({next:i=>{e.enqueueAndForget((()=>Wd(t,o)));const a=i.docs.has(n);!a&&i.fromCache?r.reject(new Ga(za.UNAVAILABLE,"Failed to get document because the client is offline.")):a&&i.fromCache&&s&&"server"===s.source?r.reject(new Ga(za.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.)')):r.resolve(i)},error:t=>r.reject(t)}),o=new Yd(lu(n.path),i,{includeMetadataChanges:!0,wo:!0});return Gd(t,o)}(await Rf(t),t.asyncQueue,e,n,s))),s.promise}(Wf(e),t._key).then((n=>Np(e,t,n)))}(t);return n.exists()?n.data():null}return null},ym=t=>{(function(t,e,n){t=Ff(t,Bf);const s=Ff(t.firestore,Gf),r=function(t,e,n){let s;return s=t?n&&(n.merge||n.mergeFields)?t.toFirestore(e,n):t.toFirestore(e):e,s}(t.converter,e,n);return Cp(s,[op(ip(s),"setDoc",t._key,r,null!==t.converter,n).toMutation(t._key,Bu.none())])})($f(mm,`scores/${t.uId}`),t,{merge:!0}).then(console.log("added successfully")).catch((t=>console.error("I got an error",t)))};let vm;const wm="user.data";async function bm(){return navigator.onLine?await gm():JSON.parse(localStorage.getItem(wm))}function Tm(){return JSON.parse(localStorage.getItem(wm))}function Em(t){return localStorage.setItem(wm,JSON.stringify(t)),t}function Im(t){return localStorage.setItem(wm,JSON.stringify(t)),ym(t),t}var _m=n(187),Sm=n(58);const km="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Am(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||Sm))return new XMLHttpRequest}catch(t){}if(!e)try{return new(km[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}function Cm(t,...e){return e.reduce(((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e)),{})}const Nm=setTimeout,Rm=clearTimeout;function Lm(t,e){e.useNativeTimers?(t.setTimeoutFn=Nm.bind(km),t.clearTimeoutFn=Rm.bind(km)):(t.setTimeoutFn=setTimeout.bind(km),t.clearTimeoutFn=clearTimeout.bind(km))}var Dm=n(63);const Om=Object.create(null);Om.open="0",Om.close="1",Om.ping="2",Om.pong="3",Om.message="4",Om.upgrade="5",Om.noop="6";const Pm=Object.create(null);Object.keys(Om).forEach((t=>{Pm[Om[t]]=t}));const Mm={type:"error",data:"parser error"},xm="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Um="function"==typeof ArrayBuffer,Fm=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+t)},n.readAsDataURL(t)},Vm=({type:t,data:e},n,s)=>{return xm&&e instanceof Blob?n?s(e):Fm(e,s):Um&&(e instanceof ArrayBuffer||(r=e,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer))?n?s(e):Fm(new Blob([e]),s):s(Om[t]+(e||""));var r};for(var jm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Bm="undefined"==typeof Uint8Array?[]:new Uint8Array(256),qm=0;qm{if(Hm){const n=function(t){var e,n,s,r,i,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);var u=new ArrayBuffer(o),h=new Uint8Array(u);for(e=0;e>4,h[c++]=(15&s)<<4|r>>2,h[c++]=(3&r)<<6|63&i;return u}(t);return Km(n,e)}return{base64:!0,data:t}},Km=(t,e)=>"blob"===e&&t instanceof ArrayBuffer?new Blob([t]):t,zm=(t,e)=>{if("string"!=typeof t)return{type:"message",data:Km(t,e)};const n=t.charAt(0);return"b"===n?{type:"message",data:$m(t.substring(1),e)}:Pm[n]?t.length>1?{type:Pm[n],data:t.substring(1)}:{type:Pm[n]}:Mm},Gm=String.fromCharCode(30);class Wm extends Dm.Q{constructor(t){super(),this.writable=!1,Lm(this,t),this.opts=t,this.query=t.query,this.readyState="",this.socket=t.socket}onError(t,e){const n=new Error(t);return n.type="TransportError",n.description=e,super.emit("error",n),this}open(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emit("open")}onData(t){const e=zm(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emit("packet",t)}onClose(){this.readyState="closed",super.emit("close")}}var Jm=n(281),Xm=n(830);class Qm extends Wm{constructor(){super(...arguments),this.polling=!1}get name(){return"polling"}doOpen(){this.poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.polling||!this.writable){let t=0;this.polling&&(t++,this.once("pollComplete",(function(){--t||e()}))),this.writable||(t++,this.once("drain",(function(){--t||e()})))}else e()}poll(){this.polling=!0,this.doPoll(),this.emit("poll")}onData(t){((t,e)=>{const n=t.split(Gm),s=[];for(let t=0;t{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose(),!1;this.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const n=t.length,s=new Array(n);let r=0;t.forEach(((t,i)=>{Vm(t,!1,(t=>{s[i]=t,++r===n&&e(s.join(Gm))}))}))})(t,(t=>{this.doWrite(t,(()=>{this.writable=!0,this.emit("drain")}))}))}uri(){let t=this.query||{};const e=this.opts.secure?"https":"http";let n="";!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Jm()),this.supportsBinary||t.sid||(t.b64=1),this.opts.port&&("https"===e&&443!==Number(this.opts.port)||"http"===e&&80!==Number(this.opts.port))&&(n=":"+this.opts.port);const s=Xm.encode(t);return e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+n+this.opts.path+(s.length?"?"+s:"")}}function Ym(){}const Zm=null!=new Am({xdomain:!1}).responseType;class tg extends Dm.Q{constructor(t,e){super(),Lm(this,e),this.opts=e,this.method=e.method||"GET",this.uri=t,this.async=!1!==e.async,this.data=void 0!==e.data?e.data:null,this.create()}create(){const t=Cm(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd,t.xscheme=!!this.opts.xs;const e=this.xhr=new Am(t);try{e.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0);for(let t in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(t)&&e.setRequestHeader(t,this.opts.extraHeaders[t])}}catch(t){}if("POST"===this.method)try{e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(e.timeout=this.opts.requestTimeout),e.onreadystatechange=()=>{4===e.readyState&&(200===e.status||1223===e.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof e.status?e.status:0)}),0))},e.send(this.data)}catch(t){return void this.setTimeoutFn((()=>{this.onError(t)}),0)}"undefined"!=typeof document&&(this.index=tg.requestsCount++,tg.requests[this.index]=this)}onSuccess(){this.emit("success"),this.cleanup()}onData(t){this.emit("data",t),this.onSuccess()}onError(t){this.emit("error",t),this.cleanup(!0)}cleanup(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Ym,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete tg.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;null!==t&&this.onData(t)}abort(){this.cleanup()}}function eg(){for(let t in tg.requests)tg.requests.hasOwnProperty(t)&&tg.requests[t].abort()}tg.requestsCount=0,tg.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",eg):"function"==typeof addEventListener&&addEventListener("onpagehide"in km?"pagehide":"unload",eg,!1));const ng="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),sg=km.WebSocket||km.MozWebSocket,rg="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class ig extends Wm{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),e=this.opts.protocols,n=rg?{}:Cm(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=rg?new sg(t,e,n):e?new sg(t,e):new sg(t)}catch(t){return this.emit("error",t)}this.ws.binaryType=this.socket.binaryType||"arraybuffer",this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=this.onClose.bind(this),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e{try{this.ws.send(t)}catch(t){}s&&ng((()=>{this.writable=!0,this.emit("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let t=this.query||{};const e=this.opts.secure?"wss":"ws";let n="";this.opts.port&&("wss"===e&&443!==Number(this.opts.port)||"ws"===e&&80!==Number(this.opts.port))&&(n=":"+this.opts.port),this.opts.timestampRequests&&(t[this.opts.timestampParam]=Jm()),this.supportsBinary||(t.b64=1);const s=Xm.encode(t);return e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+n+this.opts.path+(s.length?"?"+s:"")}check(){return!(!sg||"__initialize"in sg&&this.name===ig.prototype.name)}}const og={websocket:ig,polling:class extends Qm{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port,this.xs=t.secure!==e}const e=t&&t.forceBase64;this.supportsBinary=Zm&&!e}request(t={}){return Object.assign(t,{xd:this.xd,xs:this.xs},this.opts),new tg(this.uri(),t)}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(t=>{this.onError("xhr post error",t)}))}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t=>{this.onError("xhr poll error",t)})),this.pollXhr=t}}};class ag extends Dm.Q{constructor(t,e={}){super(),t&&"object"==typeof t&&(e=t,t=null),t?(t=_m(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=_m(e.host).host),Lm(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=e.transports||["polling","websocket"],this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},e),this.opts.path=this.opts.path.replace(/\/$/,"")+"/","string"==typeof this.opts.query&&(this.opts.query=Xm.decode(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&addEventListener("beforeunload",(()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())}),!1),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close")},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const e=function(t){const e={};for(let n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}(this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts.transportOptions[t],this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new og[t](n)}open(){let t;if(this.opts.rememberUpgrade&&ag.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(()=>{this.onClose("transport close")}))}probe(t){let e=this.createTransport(t),n=!1;ag.priorWebsocketSuccess=!1;const s=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",(t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;ag.priorWebsocketSuccess="websocket"===e.name,this.transport.pause((()=>{n||"closed"!==this.readyState&&(u(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())}))}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}})))};function r(){n||(n=!0,u(),e.close(),e=null)}const i=t=>{const n=new Error("probe error: "+t);n.transport=e.name,r(),this.emitReserved("upgradeError",n)};function o(){i("transport closed")}function a(){i("socket closed")}function c(t){e&&t.name!==e.name&&r()}const u=()=>{e.removeListener("open",s),e.removeListener("error",i),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",s),e.once("error",i),e.once("close",o),this.once("close",a),this.once("upgrading",c),e.open()}onOpen(){if(this.readyState="open",ag.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade&&this.transport.pause){let t=0;const e=this.upgrades.length;for(;t{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emitReserved("flush"))}write(t,e,n){return this.sendPacket("message",t,e,n),this}send(t,e,n){return this.sendPacket("message",t,e,n),this}sendPacket(t,e,n,s){if("function"==typeof e&&(s=e,e=void 0),"function"==typeof n&&(s=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const r={type:t,data:e,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),s&&this.once("flush",s),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?n():t()})):this.upgrading?n():t()),this}onError(t){ag.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&removeEventListener("offline",this.offlineEventListener,!1),this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const e=[];let n=0;const s=t.length;for(;n"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||hg&&t instanceof Blob||lg&&t instanceof File}function fg(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e0;case wg.ACK:case wg.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&this.reconstructor.finishedReconstruction()}}class Eg{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=gg(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function Ig(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const _g=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Sg extends Dm.Q{constructor(t,e,n){super(),this.connected=!1,this.disconnected=!0,this.receiveBuffer=[],this.sendBuffer=[],this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this.io._autoConnect&&this.open()}subEvents(){if(this.subs)return;const t=this.io;this.subs=[Ig(t,"open",this.onopen.bind(this)),Ig(t,"packet",this.onpacket.bind(this)),Ig(t,"error",this.onerror.bind(this)),Ig(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){if(_g.hasOwnProperty(t))throw new Error('"'+t+'" is a reserved event name');e.unshift(t);const n={type:wg.EVENT,data:e,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,s=e.pop();this._registerAckCallback(t,s),n.id=t}const s=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!s||!this.connected)||(this.connected?this.packet(n):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(t,e){const n=this.flags.timeout;if(void 0===n)return void(this.acks[t]=e);const s=this.io.setTimeoutFn((()=>{delete this.acks[t];for(let e=0;e{this.io.clearTimeoutFn(s),e.apply(this,[null,...t])}}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth((t=>{this.packet({type:wg.CONNECT,data:t})})):this.packet({type:wg.CONNECT,data:this.auth})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t){this.connected=!1,this.disconnected=!0,delete this.id,this.emitReserved("disconnect",t)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case wg.CONNECT:if(t.data&&t.data.sid){const e=t.data.sid;this.onconnect(e)}else this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case wg.EVENT:case wg.BINARY_EVENT:this.onevent(t);break;case wg.ACK:case wg.BINARY_ACK:this.onack(t);break;case wg.DISCONNECT:this.ondisconnect();break;case wg.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t)}ack(t){const e=this;let n=!1;return function(...s){n||(n=!0,e.packet({type:wg.ACK,id:t,data:s}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(e.apply(this,t.data),delete this.acks[t.id])}onconnect(t){this.id=t,this.connected=!0,this.disconnected=!1,this.emitBuffered(),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach((t=>this.emitEvent(t))),this.receiveBuffer=[],this.sendBuffer.forEach((t=>this.packet(t))),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((t=>t())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:wg.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n{n.cleanup(),n._readyState="closed",this.emitReserved("error",e),t?t(e):n.maybeReconnectOnOpen()}));if(!1!==this._timeout){const t=this._timeout;0===t&&s();const n=this.setTimeoutFn((()=>{s(),e.close(),e.emit("error",new Error("timeout"))}),t);this.opts.autoUnref&&n.unref(),this.subs.push((function(){clearTimeout(n)}))}return this.subs.push(s),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Ig(t,"ping",this.onping.bind(this)),Ig(t,"data",this.ondata.bind(this)),Ig(t,"error",this.onerror.bind(this)),Ig(t,"close",this.onclose.bind(this)),Ig(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){this.decoder.add(t)}ondecoded(t){this.emitReserved("packet",t)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n||(n=new Sg(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;nt())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn((()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open((e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()})))}),e);this.opts.autoUnref&&n.unref(),this.subs.push((function(){clearTimeout(n)}))}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Cg={};function Ng(t,e){"object"==typeof t&&(e=t,t=void 0);const n=function(t,e="",n){let s=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),s=_m(t)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+e,s.href=s.protocol+"://"+r+(n&&n.port===s.port?"":":"+s.port),s}(t,(e=e||{}).path||"/socket.io"),s=n.source,r=n.id,i=n.path,o=Cg[r]&&i in Cg[r].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new Ag(s,e):(Cg[r]||(Cg[r]=new Ag(s,e)),a=Cg[r]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}function Rg(t,e){im.classList.toggle("hide"),im.classList.remove("fadeOut"),im.innerHTML=t,setTimeout((()=>{im.classList.add("fadeOut"),setTimeout((()=>{im.classList.add("hide")}),200)}),e),document.addEventListener("click",(()=>{im.classList.contains("hide")||(im.classList.add("fadeOut"),setTimeout((()=>{im.classList.add("hide")}),200))}))}Object.assign(Ng,{Manager:Ag,Socket:Sg,io:Ng,connect:Ng});let Lg=!1,Dg=!0,Og="dark";var Pg=!1,Mg=!1;const xg=Ng("https://type-master-multiplayer.herokuapp.com/");let Ug;xg.on("connect",(()=>{console.log("connection established")})),xg.on("disconnect",(()=>{console.log("you are disconnected")})),xg.on("roomId",(t=>{cm.classList.add("hide"),lm.classList.remove("hide"),lm.children[1].innerText=t,Pg=!0,qp.innerText="...",!Mg&&(am.classList.add("scale0"),am.classList.add("fadeOut"),setTimeout((()=>{am.classList.add("hide")}),500))})),xg.on("unknownCode",(()=>{Rg("not a valid room 😞",1e3)})),xg.on("tooManyPlayers",(()=>{Rg("room is full 😞",1e3)})),xg.on("playerList",(t=>{let e=t.findIndex((t=>t.id==xg.id));-1!==e&&(Ug=t[e]),function(t){!function(){for(;hm.firstChild;)hm.firstChild.remove()}(),t&&(t.forEach((t=>{let e=`
${t.name}
\n
${t.speed}
`,n=document.createElement("span");n.innerHTML=e,n.children[0].firstChild.style.left=t.progress+"%",n.children[0].firstChild.style.transform="translateX(-"+t.progress+"%)",n.classList.add("player"),hm.appendChild(n)})),hm.classList.remove("hide"))}(t)})),xg.on("newText",(t=>{!async function(t){Qg(Bg=qp.innerText=t),ny(),Yg(qp),jg(Bg)}(t)})),xg.on("textTimer",(()=>{let t=5,e=setInterval((()=>{Rg(`text in ${t--} seconds`,500)}),1e3);setTimeout((()=>{Mg&&Hg(),clearInterval(e)}),5e3)}));const Fg=xg;var Vg;const jg=t=>{let e,n,s=!0,r=t,i=0,o=0,a=0,c=t.length,u=document.querySelectorAll(".text>span");u[i].classList.add("blink"),document.addEventListener("keypress",(h=>{if(h.key===r[0]){if(s&&(e=(new Date).getTime(),s=!1),a++,r=r.substr(1),u[i].classList.add("correctWord"),u[i].classList.remove("blink"),i{let n=t/(e/60);Vg=Math.floor(n),$p.innerText=Vg;let s=await bm();s&&Vg>s.topSpeed?(s={...s,topSpeed:Vg},console.log("setUserData called"),Im(s)):s&&Em({...s,lastSpeed:Vg}),Pg||Mg||(em.classList.toggle("hide"),em.classList.toggle("fadeOut"),setTimeout((()=>{$g(),em.classList.toggle("fadeOut"),setTimeout((()=>{em.classList.toggle("hide")}),500)}),500))})(c/5,(n-e)/1e3)),i++}else null!=u[i]&&u[i].classList.add("wrongWord")}))};var Bg;let qg=0;async function Hg(){Mg&&Fg.emit("getText",fm.innerText)}const $g=async()=>{await bm()||(qg++,5!=qg&&15!=qg||Rg("Login to save data 🙂",1e4));let t=await fetch("https://api.quotable.io/random").then((t=>t.json())).then((t=>t.content)).catch((t=>{console.error(t.message),qp.innerText="check your network connection"})),e=Tm();e.punctuationMode||(t=t.replace(/[^ \w]/g,"")),e.smallCaseMode&&(t=t.toLowerCase()),Qg(Bg=qp.innerText=t),ny(),Yg(qp),jg(Bg)};function Kg(t){t?(Jp.classList.remove("hide"),Gp.classList.remove("hide"),Op.classList.add("hide"),Kp.classList.add("hide")):(Jp.classList.add("hide"),Gp.classList.add("hide"),Op.classList.remove("hide"),Kp.classList.remove("hide"))}Kg();const zg=(t,e)=>{Bp.childNodes.forEach((n=>{n.classList&&(n==t?(n.classList.remove("hide"),n.classList.contains("stats")&&e?Lp.classList.remove("hide"):Lp.classList.add("hide")):!n.classList.contains("hide")&&n.classList.add("hide"))}))};n(162);var Gg=n(926),Wg=n.n(Gg);var Jg;const Xg=document.querySelector(".words");function Qg(t){let e,n=/ /g,s=[];for(;e=n.exec(t);)s.push(e.index);Jg=s.length+1}const Yg=t=>{let e=[];for(let t=0;t${Bg[t]}`);let n=e.join("");t.innerHTML=n};Pp.addEventListener("click",(async()=>{if(Mp.classList.contains("hide")){Mp.classList.toggle("hide");let t=await bm();Kg(t),!t||0===Object.entries(t).length&&t.constructor===Object?zg(Xp):(ty(t),Gp.classList.remove("hide"),Op.classList.add("hide"))}else Mp.classList.add("hide")})),xp.forEach((t=>{t.addEventListener("click",(t=>{let e=t.target.parentElement.parentElement.parentElement;zg(Qp),e.classList.toggle("hide")}))})),Up.forEach((t=>{t.addEventListener("drag",(t=>{t.target.parentElement.parentElement.style.filter="brightness(.7)"}))})),Up.forEach((t=>{t.addEventListener("dragend",(t=>{let e=t.target.parentElement.parentElement;e.style.filter="brightness(1)",Zg(t,e)}))}));const Zg=(t,e)=>{e.style.left=t.pageX-20+"px",e.style.top=t.pageY-20+"px"},ty=async t=>(!t||0===Object.entries(t).length&&t.constructor===Object?zg(Xp):(Hp.lastElementChild.lastElementChild.childNodes.forEach((e=>{e.classList&&(e.classList.contains("name")?(t.userName.length>10?e.style.fontSize=20:t.userName.length>20&&(e.style.fontSize=15),e.innerHTML=t.userName):e.classList.contains("speed")&&(t.userName.length>10&&(e.style.fontSize=30),e.innerHTML=t.topSpeed))})),zg(Hp,t)),t);Fp.addEventListener("click",(()=>{Vp.classList.toggle("hide")})),jp.addEventListener("change",(async t=>{let e=await bm();if(t.target.options.light.selected){if(Rp.classList.contains("light"))return;Rp.classList.remove("dark"),Rp.classList.add("light"),e?Im({...e,theme:"light"}):(e=Tm(),Em({...e,theme:"light"}))}else if(t.target.options.dark.selected){if(Rp.classList.contains("dark"))return;Rp.classList.remove("light"),Rp.classList.add("dark"),e?Im({...e,theme:"dark"}):(e=Tm(),Em({...e,theme:"dark"}))}})),Lp.addEventListener("click",(()=>{Wg().toBlob(Hp).then((async t=>{let e=await bm(),n=e.userName+e.topSpeed;window.saveAs(t,n)}))})),Dp.addEventListener("submit",(t=>{t.preventDefault(),iy({email:t.target.email.value,username:t.target.username.value,password:t.target.password.value}),zg(Qp)})),zp.addEventListener("submit",(t=>{t.preventDefault(),ry({email:t.target.email.value,password:t.target.password.value}),zg(Qp)})),Op.addEventListener("click",(()=>{zg(Dp)})),Kp.addEventListener("click",(()=>{zg(zp)})),Jp.addEventListener("click",(()=>{oy()})),Gp.addEventListener("click",(()=>{zg(Wp)})),Wp.addEventListener("submit",(t=>{t.preventDefault();let e=t.target.username.value;e&&" "!=e[0]&&e.length>0?ay(e):console.log("enter username",e)})),tm.addEventListener("click",(()=>{Zp.parentElement.classList.contains("hide")?(Zp.parentElement.classList.toggle("hide"),setTimeout((()=>{Zp.parentElement.classList.toggle("fadeOut")}),200)):(Zp.parentElement.classList.toggle("fadeOut"),setTimeout((()=>{Zp.parentElement.classList.toggle("hide")}),500))})),Yp.addEventListener("click",(t=>{t.target.classList.contains("leaderBoard")&&(Yp.classList.toggle("fadeOut"),setTimeout((()=>{Yp.classList.toggle("hide")}),200))})),sm.addEventListener("click",(async t=>{let e=await bm();t.target.classList.contains("smallCase")?(t.target.classList.contains("active")?(Lg=!1,t.target.classList.remove("active")):(Lg=!0,t.target.classList.add("active")),e?Im({...e,smallCaseMode:Lg}):(e=Tm(),Em({...e,smallCaseMode:Lg}))):t.target.classList.contains("punctuation")&&(t.target.classList.contains("active")?(Dg=!1,t.target.classList.remove("active")):(Dg=!0,t.target.classList.add("active")),e?Im({...e,punctuationMode:Dg}):(e=Tm(),Em({...e,punctuationMode:Dg})))})),rm.addEventListener("click",(()=>{Pg?Hg():$g()}));let ey=!0;document.addEventListener("keypress",(t=>{t.getModifierState("CapsLock")&&ey&&Rg("CapsLock",2e3),ey=!1})),om.addEventListener("click",(t=>{am.classList.contains("hide")?(am.classList.remove("hide"),am.classList.remove("scale0"),am.classList.remove("fadeOut")):(am.classList.add("scale0"),am.classList.add("fadeOut"),setTimeout((()=>{am.classList.add("hide")}),500))})),um.addEventListener("click",(t=>{!async function(){let t=await bm();Fg.emit("createRoom",t?t.userName:null,Fg.id),Mg=!0}()})),cm.addEventListener("submit",(t=>{t.preventDefault(),t.target.roomId.value&&" "!=t.target.roomId.value&&async function(t){let e=await bm();Fg.emit("joinRoom",e?e.userName:null,t)}(t.target.roomId.value)})),dm.addEventListener("click",(()=>{navigator.clipboard.writeText(fm.innerHTML).then((()=>{dm.innerText="✅",dm.classList.add("active")}))}));const ny=(t=0)=>{Xg.innerText=`${Jg}/${t}`},sy=Es(Qt),ry=async({email:t,password:e})=>{try{await function(t,e,n){return async function(t,e){return vn(Qe(t),e)}(b(t),an.credential(e,n))}(sy,t,e)}catch(t){alert(t.code)}},iy=async({email:t,password:e,username:n})=>{try{const s=await async function(t,e,n){const s=Qe(t),r=await async function(t,e){return Te(t,"POST","/v1/accounts:signUp",ve(t,e))}(s,{returnSecureToken:!0,email:e,password:n}),i=await pn._fromIdTokenResponse(s,"signIn",r);return await s._updateCurrentUser(i.user),i}(sy,t,e);await wn(s.user,{displayName:n||s.email.split("@")[0]}).then((()=>{console.log("updated the name"),Im({uId:s.user.uid,userName:s.user.displayName,topSpeed:0,theme:Og,punctuationMode:Dg,smallCaseMode:Lg,lastSpeed:0})}))}catch(t){alert(t.code)}},oy=()=>{try{!function(t){b(t).signOut()}(sy),console.log("user logged out")}catch(t){alert(t.code)}},ay=async t=>{try{let e=sy.currentUser;zg(Qp),await wn(e,{displayName:t}).then((()=>{console.log("updated the name"),function(t){ym(t);let e=getUserTheme();localStorage.setItem(wm,JSON.stringify({...e,userName:t.username}))}({uId:e.uid,userName:e.displayName}),bm().then((t=>{ty(t)}))}))}catch(t){alert("check your network")}};window.onload=()=>{if(Tm()){let t=Tm().theme;"dark"!=t&&(Rp.classList.remove("dark"),Rp.classList.add(t)),jp.options[t].selected=!0,Tm().punctuationMode?sm.children[0].classList.add("active"):sm.children[0].classList.remove("active"),Tm().smallCaseMode?sm.children[1].classList.add("active"):sm.children[1].classList.remove("active"),function(t){t&&($p.innerText=t)}(Tm().lastSpeed)}else Em({punctuationMode:Dg,smallCaseMode:Lg,theme:Og})},$g(),function(t,e,n,s){b(t).onAuthStateChanged((async t=>{t?(Kg(t=await bm()),ty(t),nm.innerText=t.userName):(Kg(t),ty(t),nm.innerText=" ")}),void 0,void 0)}(sy),function(){const t=function(t,e,...n){if(t=b(t),Pf("collection","path",e),t instanceof jf){const s=fc.fromString(e,...n);return xf(s),new Hf(t,null,s)}{if(!(t instanceof Bf||t instanceof Hf))throw new Ga(za.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const s=t._path.child(fc.fromString(e,...n));return xf(s),new Hf(t.firestore,null,s)}}(mm,"scores"),e=function(t,...e){for(const n of e)t=n._apply(t);return t}(t,function(t,e="asc"){const n=e,s=vp("orderBy","topSpeed");return new Sp(s,n)}(0,"desc"),(function(t,e){if(e<=0)throw new Ga(za.INVALID_ARGUMENT,`Function ${t}() requires a positive number, but it was: ${e}.`)}("limit",10),new kp("limit",10,"F")));vm=function(t,...e){var n,s,r;t=b(t);let i={includeMetadataChanges:!1},o=0;"object"!=typeof e[o]||zf(e[o])||(i=e[o],o++);const a={includeMetadataChanges:i.includeMetadataChanges};if(zf(e[o])){const t=e[o];e[o]=null===(n=t.next)||void 0===n?void 0:n.bind(t),e[o+1]=null===(s=t.error)||void 0===s?void 0:s.bind(t),e[o+2]=null===(r=t.complete)||void 0===r?void 0:r.bind(t)}let c,u,h;if(t instanceof Bf)u=Ff(t.firestore,Gf),h=lu(t._key.path),c={next:n=>{e[o]&&e[o](Np(u,t,n))},error:e[o+1],complete:e[o+2]};else{const n=Ff(t,qf);u=Ff(n.firestore,Gf),h=n._query;const s=new Ap(u);c={next:t=>{e[o]&&e[o](new Ep(u,s,n,t))},error:e[o+1],complete:e[o+2]},function(t){if(fu(t)&&0===t.explicitOrderBy.length)throw new Ga(za.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}(t._query)}return function(t,e,n,s){const r=new kf(s),i=new Yd(e,r,n);return t.asyncQueue.enqueueAndForget((async()=>Gd(await Rf(t),i))),()=>{r.na(),t.asyncQueue.enqueueAndForget((async()=>Wd(await Rf(t),i)))}}(Wf(u),h,a,c)}(e,t,(t=>{if(t){const e=[];!function(){for(;Zp.firstChild;)Zp.firstChild.remove()}(),function(){let t=document.createElement("li");t.classList.add("leaderBoardHeader"),t.innerText="leaderboard";let e=document.createElement("li");e.classList.add("leaderBoardInfo"),e.innerHTML='RankUsernameTop Speed',Zp.appendChild(t),Zp.appendChild(e)}(),t.forEach((t=>{let n=t.data();n.topSpeed>0&&e.push({userName:n.userName,speed:n.topSpeed})}));for(let t=0;t { } text = textContainer.innerText = data; + findTotalWords(text); setWords(); spanWrap(textContainer); start(text); @@ -51,6 +52,7 @@ export async function getTextSocket() { export async function setTextSocket(data) { text = textContainer.innerText = data; + findTotalWords(text); setWords(); spanWrap(textContainer); start(text); diff --git a/src/functions/speed.js b/src/functions/speed.js index 9f3260c..ed0915e 100644 --- a/src/functions/speed.js +++ b/src/functions/speed.js @@ -10,10 +10,9 @@ var speed; // this function is responsible for calculating the speed const speedCalc = async (totalWords, seconds) => { - var minutes = seconds.toPrecision(2) / 60; - // console.log( totalWords , " " , minutes.toPrecision(2)) + var minutes = seconds / 60; let tempSpeed = totalWords / minutes; - speed = Math.floor(tempSpeed.toPrecision(3)); + speed = Math.floor(tempSpeed); speedIndicator.innerText = speed; let user = await getUserData(); @@ -41,9 +40,7 @@ const speedCalc = async (totalWords, seconds) => { }; function setSpeed(speed) { - // console.log(speed, speedIndicator) speed ? (speedIndicator.innerText = speed) : speed; - // console.log("set speed called with ", speed); } export default speedCalc; diff --git a/src/functions/start.js b/src/functions/start.js index f6e99e9..a5a28e6 100644 --- a/src/functions/start.js +++ b/src/functions/start.js @@ -10,6 +10,9 @@ export default (text) => { let tempText = text; let index = 0; let typedWords = 0; + let typedChars = 0; + let totalChars = text.length; + let errorCount = 0; let start, end; let Words = document.querySelectorAll(".text>span"); Words[index].classList.add("blink"); @@ -19,6 +22,7 @@ export default (text) => { start = new Date().getTime(); firstCall = false; } + typedChars++; tempText = tempText.substr(1); @@ -40,21 +44,23 @@ export default (text) => { let progress = Math.ceil((typedWords / totalWords) * 100); let seconds = new Date().getTime(); seconds = (seconds - start) / 1000; - var minutes = seconds.toPrecision(2) / 60; - let tempSpeed = totalWords / minutes; - let speed = Math.floor(tempSpeed.toPrecision(3)); + var minutes = seconds / 60; + let tempSpeed = typedChars / 5 / minutes; + let speed = Math.floor(tempSpeed); multiplayerMode && typing(progress, speed); } if (index == text.length - 1) { end = new Date().getTime(); - speedCalc(totalWords, (end - start) / 1000); + + speedCalc(totalChars / 5, (end - start) / 1000); } index++; } else { if (Words[index] != null) { Words[index].classList.add("wrongWord"); + errorCount++; } } }); diff --git a/src/socket/socket.js b/src/socket/socket.js index e40f5ab..cb85b99 100644 --- a/src/socket/socket.js +++ b/src/socket/socket.js @@ -11,6 +11,7 @@ import { getTextSocket, setTextSocket } from "../functions/getText"; import { renderPlayers } from "./roomHandling"; const socket = io(process.env.SERVER_LINK || "http://localhost:3000"); +// const socket = io("http://localhost:3000"); // comment in production socket.on("connect", () => { console.log("connection established"); diff --git a/src/ui/uiListeners.js b/src/ui/uiListeners.js index 74ee704..3577bfd 100644 --- a/src/ui/uiListeners.js +++ b/src/ui/uiListeners.js @@ -50,7 +50,7 @@ var totalWords; //sets total word value const words = document.querySelector(".words"); -const setWords = (typedWords = 0) => { +export function findTotalWords(text) { let whitespace = / /g, result, indices = []; @@ -58,6 +58,9 @@ const setWords = (typedWords = 0) => { indices.push(result.index); } totalWords = indices.length + 1; +} + +const setWords = (typedWords = 0) => { words.innerText = `${totalWords}/${typedWords}`; };