@iebh/tera-fy 2.2.12 → 2.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,31 +1,31 @@
1
- var uw=Object.create;var Mi=Object.defineProperty;var cw=Object.getOwnPropertyDescriptor;var lw=Object.getOwnPropertyNames;var hw=Object.getPrototypeOf,dw=Object.prototype.hasOwnProperty;var fw=(r,e)=>()=>(r&&(e=r(r=0)),e);var Me=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),pw=(r,e)=>{for(var t in e)Mi(r,t,{get:e[t],enumerable:!0})},Vd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lw(e))!dw.call(r,s)&&s!==t&&Mi(r,s,{get:()=>e[s],enumerable:!(n=cw(e,s))||n.enumerable});return r};var hu=(r,e,t)=>(t=r!=null?uw(hw(r)):{},Vd(e||!r||!r.__esModule?Mi(t,"default",{value:r,enumerable:!0}):t,r)),mw=r=>Vd(Mi({},"__esModule",{value:!0}),r);var Ir={};pw(Ir,{Headers:()=>ih,Request:()=>rP,Response:()=>nP,default:()=>sh,fetch:()=>tP});var eP,jn,tP,sh,ih,rP,nP,sr=fw(()=>{"use strict";eP=function(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;throw new Error("unable to locate global object")},jn=eP(),tP=jn.fetch,sh=jn.fetch.bind(jn),ih=jn.Headers,rP=jn.Request,nP=jn.Response});var uh=Me(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var oh=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};ah.default=oh});var lh=Me(Ys=>{"use strict";var Zy=Ys&&Ys.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ys,"__esModule",{value:!0});var iP=Zy((sr(),mw(Ir))),oP=Zy(uh()),ch=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch=="undefined"?this.fetch=iP.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=Object.assign({},this.headers),this.headers[e]=t,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let n=this.fetch,s=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var a,u,c;let h=null,f=null,m=null,g=i.status,b=i.statusText;if(i.ok){if(this.method!=="HEAD"){let N=await i.text();N===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?f=N:f=JSON.parse(N))}let C=(a=this.headers.Prefer)===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),R=(u=i.headers.get("content-range"))===null||u===void 0?void 0:u.split("/");C&&R&&R.length>1&&(m=parseInt(R[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(f)&&(f.length>1?(h={code:"PGRST116",details:`Results contain ${f.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},f=null,m=null,g=406,b="Not Acceptable"):f.length===1?f=f[0]:f=null)}else{let C=await i.text();try{h=JSON.parse(C),Array.isArray(h)&&i.status===404&&(f=[],h=null,g=200,b="OK")}catch{i.status===404&&C===""?(g=204,b="No Content"):h={message:C}}if(h&&this.isMaybeSingle&&(!((c=h==null?void 0:h.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,g=200,b="OK"),h&&this.shouldThrowOnError)throw new oP.default(h)}return{error:h,data:f,count:m,status:g,statusText:b}});return this.shouldThrowOnError||(s=s.catch(i=>{var a,u,c;return{error:{message:`${(a=i==null?void 0:i.name)!==null&&a!==void 0?a:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(u=i==null?void 0:i.stack)!==null&&u!==void 0?u:""}`,hint:"",code:`${(c=i==null?void 0:i.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}returns(){return this}overrideTypes(){return this}};Ys.default=ch});var dh=Me(Xs=>{"use strict";var aP=Xs&&Xs.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xs,"__esModule",{value:!0});var uP=aP(lh()),hh=class extends uP.default{select(e){let t=!1,n=(e!=null?e:"*").split("").map(s=>/\s/.test(s)&&!t?"":(s==='"'&&(t=!t),s)).join("");return this.url.searchParams.set("select",n),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:s,referencedTable:i=s}={}){let a=i?`${i}.order`:"order",u=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${u?`${u},`:""}${e}.${t?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){let s=typeof n=="undefined"?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:s=n}={}){let i=typeof s=="undefined"?"offset":`${s}.offset`,a=typeof s=="undefined"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:s=!1,wal:i=!1,format:a="text"}={}){var u;let c=[e?"analyze":null,t?"verbose":null,n?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),h=(u=this.headers.Accept)!==null&&u!==void 0?u:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${a}; for="${h}"; options=${c};`,a==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};Xs.default=hh});var wa=Me(Zs=>{"use strict";var cP=Zs&&Zs.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Zs,"__esModule",{value:!0});var lP=cP(dh()),fh=class extends lP.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let n=Array.from(new Set(t)).map(s=>typeof s=="string"&&new RegExp("[,()]").test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(e,`in.(${n})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:n,type:s}={}){let i="";s==="plain"?i="pl":s==="phrase"?i="ph":s==="websearch"&&(i="w");let a=n===void 0?"":`(${n})`;return this.url.searchParams.append(e,`${i}fts${a}.${t}`),this}match(e){return Object.entries(e).forEach(([t,n])=>{this.url.searchParams.append(t,`eq.${n}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){let s=n?`${n}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}};Zs.default=fh});var mh=Me(ti=>{"use strict";var hP=ti&&ti.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ti,"__esModule",{value:!0});var ei=hP(wa()),ph=class{constructor(e,{headers:t={},schema:n,fetch:s}){this.url=e,this.headers=t,this.schema=n,this.fetch=s}select(e,{head:t=!1,count:n}={}){let s=t?"HEAD":"GET",i=!1,a=(e!=null?e:"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join("");return this.url.searchParams.set("select",a),n&&(this.headers.Prefer=`count=${n}`),new ei.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:n=!0}={}){let s="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),n||i.push("missing=default"),this.headers.Prefer=i.join(","),Array.isArray(e)){let a=e.reduce((u,c)=>u.concat(Object.keys(c)),[]);if(a.length>0){let u=[...new Set(a)].map(c=>`"${c}"`);this.url.searchParams.set("columns",u.join(","))}}return new ei.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:s,defaultToNull:i=!0}={}){let a="POST",u=[`resolution=${n?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&u.push(this.headers.Prefer),s&&u.push(`count=${s}`),i||u.push("missing=default"),this.headers.Prefer=u.join(","),Array.isArray(e)){let c=e.reduce((h,f)=>h.concat(Object.keys(f)),[]);if(c.length>0){let h=[...new Set(c)].map(f=>`"${f}"`);this.url.searchParams.set("columns",h.join(","))}}return new ei.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let n="PATCH",s=[];return this.headers.Prefer&&s.push(this.headers.Prefer),t&&s.push(`count=${t}`),this.headers.Prefer=s.join(","),new ei.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",n=[];return e&&n.push(`count=${e}`),this.headers.Prefer&&n.unshift(this.headers.Prefer),this.headers.Prefer=n.join(","),new ei.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ti.default=ph});var e_=Me(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.version=void 0;ba.version="0.0.0-automated"});var t_=Me(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.DEFAULT_HEADERS=void 0;var dP=e_();Ta.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${dP.version}`}});var n_=Me(ri=>{"use strict";var r_=ri&&ri.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ri,"__esModule",{value:!0});var fP=r_(mh()),pP=r_(wa()),mP=t_(),gh=class r{constructor(e,{headers:t={},schema:n,fetch:s}={}){this.url=e,this.headers=Object.assign(Object.assign({},mP.DEFAULT_HEADERS),t),this.schemaName=n,this.fetch=s}from(e){let t=new URL(`${this.url}/${e}`);return new fP.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:n=!1,get:s=!1,count:i}={}){let a,u=new URL(`${this.url}/rpc/${e}`),c;n||s?(a=n?"HEAD":"GET",Object.entries(t).filter(([f,m])=>m!==void 0).map(([f,m])=>[f,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([f,m])=>{u.searchParams.append(f,m)})):(a="POST",c=t);let h=Object.assign({},this.headers);return i&&(h.Prefer=`count=${i}`),new pP.default({method:a,url:u,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};ri.default=gh});var l_=Me(be=>{"use strict";var Un=be&&be.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(be,"__esModule",{value:!0});be.PostgrestError=be.PostgrestBuilder=be.PostgrestTransformBuilder=be.PostgrestFilterBuilder=be.PostgrestQueryBuilder=be.PostgrestClient=void 0;var s_=Un(n_());be.PostgrestClient=s_.default;var i_=Un(mh());be.PostgrestQueryBuilder=i_.default;var o_=Un(wa());be.PostgrestFilterBuilder=o_.default;var a_=Un(dh());be.PostgrestTransformBuilder=a_.default;var u_=Un(lh());be.PostgrestBuilder=u_.default;var c_=Un(uh());be.PostgrestError=c_.default;be.default={PostgrestClient:s_.default,PostgrestQueryBuilder:i_.default,PostgrestFilterBuilder:o_.default,PostgrestTransformBuilder:a_.default,PostgrestBuilder:u_.default,PostgrestError:c_.default}});var v_=Me((V2,__)=>{"use strict";__.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var hv=Me((kU,lv)=>{function Ge(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}lv.exports=Ge;Ge.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Ge.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Ge.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};Ge.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Ge.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Ge.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Ge.prototype.start=Ge.prototype.try;Ge.prototype.errors=function(){return this._errors};Ge.prototype.attempts=function(){return this._attempts};Ge.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var s=this._errors[n],i=s.message,a=(r[i]||0)+1;r[i]=a,a>=t&&(e=s,t=a)}return e}});var dv=Me(jr=>{var eC=hv();jr.operation=function(r){var e=jr.timeouts(r);return new eC(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};jr.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<e.retries;s++)n.push(this.createTimeout(s,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(s,e)),n.sort(function(i,a){return i-a}),n};jr.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};jr.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var s=0;s<t.length;s++){var i=t[s],a=r[i];r[i]=function(c){var h=jr.operation(e),f=Array.prototype.slice.call(arguments,1),m=f.pop();f.push(function(g){h.retry(g)||(g&&(arguments[0]=h.mainError()),m.apply(this,arguments))}),h.attempt(function(){c.apply(r,f)})}.bind(r,a),r[i].options=e}}});var pv=Me((OU,fv)=>{fv.exports=dv()});var gw=typeof global=="object"&&global&&global.Object===Object&&global,ji=gw;var yw=typeof self=="object"&&self&&self.Object===Object&&self,_w=ji||yw||Function("return this")(),ue=_w;var vw=ue.Symbol,ke=vw;var Ld=Object.prototype,ww=Ld.hasOwnProperty,bw=Ld.toString,ys=ke?ke.toStringTag:void 0;function Tw(r){var e=ww.call(r,ys),t=r[ys];try{r[ys]=void 0;var n=!0}catch{}var s=bw.call(r);return n&&(e?r[ys]=t:delete r[ys]),s}var Fd=Tw;var Ew=Object.prototype,Iw=Ew.toString;function Aw(r){return Iw.call(r)}var Md=Aw;var xw="[object Null]",Sw="[object Undefined]",jd=ke?ke.toStringTag:void 0;function Rw(r){return r==null?r===void 0?Sw:xw:jd&&jd in Object(r)?Fd(r):Md(r)}var He=Rw;function Pw(r){return r!=null&&typeof r=="object"}var De=Pw;var Cw="[object Symbol]";function kw(r){return typeof r=="symbol"||De(r)&&He(r)==Cw}var Ft=kw;function Dw(r,e){for(var t=-1,n=r==null?0:r.length,s=Array(n);++t<n;)s[t]=e(r[t],t,r);return s}var Ud=Dw;var Ow=Array.isArray,le=Ow;var Nw=1/0,Bd=ke?ke.prototype:void 0,$d=Bd?Bd.toString:void 0;function qd(r){if(typeof r=="string")return r;if(le(r))return Ud(r,qd)+"";if(Ft(r))return $d?$d.call(r):"";var e=r+"";return e=="0"&&1/r==-Nw?"-0":e}var zd=qd;var Vw=/\s/;function Lw(r){for(var e=r.length;e--&&Vw.test(r.charAt(e)););return e}var Gd=Lw;var Fw=/^\s+/;function Mw(r){return r&&r.slice(0,Gd(r)+1).replace(Fw,"")}var Kd=Mw;function jw(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Z=jw;var Hd=NaN,Uw=/^[-+]0x[0-9a-f]+$/i,Bw=/^0b[01]+$/i,$w=/^0o[0-7]+$/i,qw=parseInt;function zw(r){if(typeof r=="number")return r;if(Ft(r))return Hd;if(Z(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Z(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=Kd(r);var t=Bw.test(r);return t||$w.test(r)?qw(r.slice(2),t?2:8):Uw.test(r)?Hd:+r}var du=zw;function Gw(r){return r}var zr=Gw;var Kw="[object AsyncFunction]",Hw="[object Function]",Ww="[object GeneratorFunction]",Qw="[object Proxy]";function Jw(r){if(!Z(r))return!1;var e=He(r);return e==Hw||e==Ww||e==Kw||e==Qw}var Ui=Jw;var Yw=ue["__core-js_shared__"],Bi=Yw;var Wd=function(){var r=/[^.]+$/.exec(Bi&&Bi.keys&&Bi.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function Xw(r){return!!Wd&&Wd in r}var Qd=Xw;var Zw=Function.prototype,eb=Zw.toString;function tb(r){if(r!=null){try{return eb.call(r)}catch{}try{return r+""}catch{}}return""}var gt=tb;var rb=/[\\^$.*+?()[\]{}|]/g,nb=/^\[object .+?Constructor\]$/,sb=Function.prototype,ib=Object.prototype,ob=sb.toString,ab=ib.hasOwnProperty,ub=RegExp("^"+ob.call(ab).replace(rb,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function cb(r){if(!Z(r)||Qd(r))return!1;var e=Ui(r)?ub:nb;return e.test(gt(r))}var Jd=cb;function lb(r,e){return r==null?void 0:r[e]}var Yd=lb;function hb(r,e){var t=Yd(r,e);return Jd(t)?t:void 0}var Oe=hb;var db=Oe(ue,"WeakMap"),$i=db;var Xd=Object.create,fb=function(){function r(){}return function(e){if(!Z(e))return{};if(Xd)return Xd(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}}(),Zd=fb;function pb(r,e,t){switch(t.length){case 0:return r.call(e);case 1:return r.call(e,t[0]);case 2:return r.call(e,t[0],t[1]);case 3:return r.call(e,t[0],t[1],t[2])}return r.apply(e,t)}var ef=pb;function mb(r,e){var t=-1,n=r.length;for(e||(e=Array(n));++t<n;)e[t]=r[t];return e}var tf=mb;var gb=800,yb=16,_b=Date.now;function vb(r){var e=0,t=0;return function(){var n=_b(),s=yb-(n-t);if(t=n,s>0){if(++e>=gb)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}var rf=vb;function wb(r){return function(){return r}}var nf=wb;var bb=function(){try{var r=Oe(Object,"defineProperty");return r({},"",{}),r}catch{}}(),Gr=bb;var Tb=Gr?function(r,e){return Gr(r,"toString",{configurable:!0,enumerable:!1,value:nf(e),writable:!0})}:zr,sf=Tb;var Eb=rf(sf),of=Eb;function Ib(r,e){for(var t=-1,n=r==null?0:r.length;++t<n&&e(r[t],t,r)!==!1;);return r}var af=Ib;var Ab=9007199254740991,xb=/^(?:0|[1-9]\d*)$/;function Sb(r,e){var t=typeof r;return e=e==null?Ab:e,!!e&&(t=="number"||t!="symbol"&&xb.test(r))&&r>-1&&r%1==0&&r<e}var Mt=Sb;function Rb(r,e,t){e=="__proto__"&&Gr?Gr(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}var Kr=Rb;function Pb(r,e){return r===e||r!==r&&e!==e}var Xe=Pb;var Cb=Object.prototype,kb=Cb.hasOwnProperty;function Db(r,e,t){var n=r[e];(!(kb.call(r,e)&&Xe(n,t))||t===void 0&&!(e in r))&&Kr(r,e,t)}var Hr=Db;function Ob(r,e,t,n){var s=!t;t||(t={});for(var i=-1,a=e.length;++i<a;){var u=e[i],c=n?n(t[u],r[u],u,t,r):void 0;c===void 0&&(c=r[u]),s?Kr(t,u,c):Hr(t,u,c)}return t}var jt=Ob;var uf=Math.max;function Nb(r,e,t){return e=uf(e===void 0?r.length-1:e,0),function(){for(var n=arguments,s=-1,i=uf(n.length-e,0),a=Array(i);++s<i;)a[s]=n[e+s];s=-1;for(var u=Array(e+1);++s<e;)u[s]=n[s];return u[e]=t(a),ef(r,this,u)}}var cf=Nb;function Vb(r,e){return of(cf(r,e,zr),r+"")}var lf=Vb;var Lb=9007199254740991;function Fb(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Lb}var Wr=Fb;function Mb(r){return r!=null&&Wr(r.length)&&!Ui(r)}var Ut=Mb;function jb(r,e,t){if(!Z(t))return!1;var n=typeof e;return(n=="number"?Ut(t)&&Mt(e,t.length):n=="string"&&e in t)?Xe(t[e],r):!1}var hf=jb;var Ub=Object.prototype;function Bb(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Ub;return r===t}var Bt=Bb;function $b(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}var df=$b;var qb="[object Arguments]";function zb(r){return De(r)&&He(r)==qb}var fu=zb;var ff=Object.prototype,Gb=ff.hasOwnProperty,Kb=ff.propertyIsEnumerable,Hb=fu(function(){return arguments}())?fu:function(r){return De(r)&&Gb.call(r,"callee")&&!Kb.call(r,"callee")},Qr=Hb;function Wb(){return!1}var pf=Wb;var yf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,mf=yf&&typeof module=="object"&&module&&!module.nodeType&&module,Qb=mf&&mf.exports===yf,gf=Qb?ue.Buffer:void 0,Jb=gf?gf.isBuffer:void 0,Yb=Jb||pf,yt=Yb;var Xb="[object Arguments]",Zb="[object Array]",eT="[object Boolean]",tT="[object Date]",rT="[object Error]",nT="[object Function]",sT="[object Map]",iT="[object Number]",oT="[object Object]",aT="[object RegExp]",uT="[object Set]",cT="[object String]",lT="[object WeakMap]",hT="[object ArrayBuffer]",dT="[object DataView]",fT="[object Float32Array]",pT="[object Float64Array]",mT="[object Int8Array]",gT="[object Int16Array]",yT="[object Int32Array]",_T="[object Uint8Array]",vT="[object Uint8ClampedArray]",wT="[object Uint16Array]",bT="[object Uint32Array]",ie={};ie[fT]=ie[pT]=ie[mT]=ie[gT]=ie[yT]=ie[_T]=ie[vT]=ie[wT]=ie[bT]=!0;ie[Xb]=ie[Zb]=ie[hT]=ie[eT]=ie[dT]=ie[tT]=ie[rT]=ie[nT]=ie[sT]=ie[iT]=ie[oT]=ie[aT]=ie[uT]=ie[cT]=ie[lT]=!1;function TT(r){return De(r)&&Wr(r.length)&&!!ie[He(r)]}var _f=TT;function ET(r){return function(e){return r(e)}}var Jr=ET;var vf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,_s=vf&&typeof module=="object"&&module&&!module.nodeType&&module,IT=_s&&_s.exports===vf,pu=IT&&ji.process,AT=function(){try{var r=_s&&_s.require&&_s.require("util").types;return r||pu&&pu.binding&&pu.binding("util")}catch{}}(),_t=AT;var wf=_t&&_t.isTypedArray,xT=wf?Jr(wf):_f,Yr=xT;var ST=Object.prototype,RT=ST.hasOwnProperty;function PT(r,e){var t=le(r),n=!t&&Qr(r),s=!t&&!n&&yt(r),i=!t&&!n&&!s&&Yr(r),a=t||n||s||i,u=a?df(r.length,String):[],c=u.length;for(var h in r)(e||RT.call(r,h))&&!(a&&(h=="length"||s&&(h=="offset"||h=="parent")||i&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||Mt(h,c)))&&u.push(h);return u}var qi=PT;function CT(r,e){return function(t){return r(e(t))}}var zi=CT;var kT=zi(Object.keys,Object),bf=kT;var DT=Object.prototype,OT=DT.hasOwnProperty;function NT(r){if(!Bt(r))return bf(r);var e=[];for(var t in Object(r))OT.call(r,t)&&t!="constructor"&&e.push(t);return e}var Gi=NT;function VT(r){return Ut(r)?qi(r):Gi(r)}var xe=VT;function LT(r){var e=[];if(r!=null)for(var t in Object(r))e.push(t);return e}var Tf=LT;var FT=Object.prototype,MT=FT.hasOwnProperty;function jT(r){if(!Z(r))return Tf(r);var e=Bt(r),t=[];for(var n in r)n=="constructor"&&(e||!MT.call(r,n))||t.push(n);return t}var Ef=jT;function UT(r){return Ut(r)?qi(r,!0):Ef(r)}var $t=UT;var BT=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,$T=/^\w*$/;function qT(r,e){if(le(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Ft(r)?!0:$T.test(r)||!BT.test(r)||e!=null&&r in Object(e)}var Xr=qT;var zT=Oe(Object,"create"),vt=zT;function GT(){this.__data__=vt?vt(null):{},this.size=0}var If=GT;function KT(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Af=KT;var HT="__lodash_hash_undefined__",WT=Object.prototype,QT=WT.hasOwnProperty;function JT(r){var e=this.__data__;if(vt){var t=e[r];return t===HT?void 0:t}return QT.call(e,r)?e[r]:void 0}var xf=JT;var YT=Object.prototype,XT=YT.hasOwnProperty;function ZT(r){var e=this.__data__;return vt?e[r]!==void 0:XT.call(e,r)}var Sf=ZT;var e0="__lodash_hash_undefined__";function t0(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=vt&&e===void 0?e0:e,this}var Rf=t0;function Zr(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}Zr.prototype.clear=If;Zr.prototype.delete=Af;Zr.prototype.get=xf;Zr.prototype.has=Sf;Zr.prototype.set=Rf;var mu=Zr;function r0(){this.__data__=[],this.size=0}var Pf=r0;function n0(r,e){for(var t=r.length;t--;)if(Xe(r[t][0],e))return t;return-1}var qt=n0;var s0=Array.prototype,i0=s0.splice;function o0(r){var e=this.__data__,t=qt(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():i0.call(e,t,1),--this.size,!0}var Cf=o0;function a0(r){var e=this.__data__,t=qt(e,r);return t<0?void 0:e[t][1]}var kf=a0;function u0(r){return qt(this.__data__,r)>-1}var Df=u0;function c0(r,e){var t=this.__data__,n=qt(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}var Of=c0;function en(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}en.prototype.clear=Pf;en.prototype.delete=Cf;en.prototype.get=kf;en.prototype.has=Df;en.prototype.set=Of;var zt=en;var l0=Oe(ue,"Map"),Gt=l0;function h0(){this.size=0,this.__data__={hash:new mu,map:new(Gt||zt),string:new mu}}var Nf=h0;function d0(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var Vf=d0;function f0(r,e){var t=r.__data__;return Vf(e)?t[typeof e=="string"?"string":"hash"]:t.map}var Kt=f0;function p0(r){var e=Kt(this,r).delete(r);return this.size-=e?1:0,e}var Lf=p0;function m0(r){return Kt(this,r).get(r)}var Ff=m0;function g0(r){return Kt(this,r).has(r)}var Mf=g0;function y0(r,e){var t=Kt(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}var jf=y0;function tn(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}tn.prototype.clear=Nf;tn.prototype.delete=Lf;tn.prototype.get=Ff;tn.prototype.has=Mf;tn.prototype.set=jf;var hr=tn;var _0="Expected a function";function gu(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(_0);var t=function(){var n=arguments,s=e?e.apply(this,n):n[0],i=t.cache;if(i.has(s))return i.get(s);var a=r.apply(this,n);return t.cache=i.set(s,a)||i,a};return t.cache=new(gu.Cache||hr),t}gu.Cache=hr;var Uf=gu;var v0=500;function w0(r){var e=Uf(r,function(n){return t.size===v0&&t.clear(),n}),t=e.cache;return e}var Bf=w0;var b0=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,T0=/\\(\\)?/g,E0=Bf(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(b0,function(t,n,s,i){e.push(s?i.replace(T0,"$1"):n||t)}),e}),$f=E0;function I0(r){return r==null?"":zd(r)}var qf=I0;function A0(r,e){return le(r)?r:Xr(r,e)?[r]:$f(qf(r))}var rn=A0;var x0=1/0;function S0(r){if(typeof r=="string"||Ft(r))return r;var e=r+"";return e=="0"&&1/r==-x0?"-0":e}var Ze=S0;function R0(r,e){e=rn(e,r);for(var t=0,n=e.length;r!=null&&t<n;)r=r[Ze(e[t++])];return t&&t==n?r:void 0}var Ki=R0;function P0(r,e,t){var n=r==null?void 0:Ki(r,e);return n===void 0?t:n}var vs=P0;function C0(r,e){for(var t=-1,n=e.length,s=r.length;++t<n;)r[s+t]=e[t];return r}var Hi=C0;var k0=zi(Object.getPrototypeOf,Object),Wi=k0;function D0(){this.__data__=new zt,this.size=0}var zf=D0;function O0(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}var Gf=O0;function N0(r){return this.__data__.get(r)}var Kf=N0;function V0(r){return this.__data__.has(r)}var Hf=V0;var L0=200;function F0(r,e){var t=this.__data__;if(t instanceof zt){var n=t.__data__;if(!Gt||n.length<L0-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new hr(n)}return t.set(r,e),this.size=t.size,this}var Wf=F0;function nn(r){var e=this.__data__=new zt(r);this.size=e.size}nn.prototype.clear=zf;nn.prototype.delete=Gf;nn.prototype.get=Kf;nn.prototype.has=Hf;nn.prototype.set=Wf;var Ht=nn;function M0(r,e){return r&&jt(e,xe(e),r)}var Qf=M0;function j0(r,e){return r&&jt(e,$t(e),r)}var Jf=j0;var ep=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Yf=ep&&typeof module=="object"&&module&&!module.nodeType&&module,U0=Yf&&Yf.exports===ep,Xf=U0?ue.Buffer:void 0,Zf=Xf?Xf.allocUnsafe:void 0;function B0(r,e){if(e)return r.slice();var t=r.length,n=Zf?Zf(t):new r.constructor(t);return r.copy(n),n}var tp=B0;function $0(r,e){for(var t=-1,n=r==null?0:r.length,s=0,i=[];++t<n;){var a=r[t];e(a,t,r)&&(i[s++]=a)}return i}var rp=$0;function q0(){return[]}var Qi=q0;var z0=Object.prototype,G0=z0.propertyIsEnumerable,np=Object.getOwnPropertySymbols,K0=np?function(r){return r==null?[]:(r=Object(r),rp(np(r),function(e){return G0.call(r,e)}))}:Qi,sn=K0;function H0(r,e){return jt(r,sn(r),e)}var sp=H0;var W0=Object.getOwnPropertySymbols,Q0=W0?function(r){for(var e=[];r;)Hi(e,sn(r)),r=Wi(r);return e}:Qi,Ji=Q0;function J0(r,e){return jt(r,Ji(r),e)}var ip=J0;function Y0(r,e,t){var n=e(r);return le(r)?n:Hi(n,t(r))}var Yi=Y0;function X0(r){return Yi(r,xe,sn)}var ws=X0;function Z0(r){return Yi(r,$t,Ji)}var op=Z0;var eE=Oe(ue,"DataView"),Xi=eE;var tE=Oe(ue,"Promise"),Zi=tE;var rE=Oe(ue,"Set"),eo=rE;var ap="[object Map]",nE="[object Object]",up="[object Promise]",cp="[object Set]",lp="[object WeakMap]",hp="[object DataView]",sE=gt(Xi),iE=gt(Gt),oE=gt(Zi),aE=gt(eo),uE=gt($i),dr=He;(Xi&&dr(new Xi(new ArrayBuffer(1)))!=hp||Gt&&dr(new Gt)!=ap||Zi&&dr(Zi.resolve())!=up||eo&&dr(new eo)!=cp||$i&&dr(new $i)!=lp)&&(dr=function(r){var e=He(r),t=e==nE?r.constructor:void 0,n=t?gt(t):"";if(n)switch(n){case sE:return hp;case iE:return ap;case oE:return up;case aE:return cp;case uE:return lp}return e});var We=dr;var cE=Object.prototype,lE=cE.hasOwnProperty;function hE(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&lE.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var dp=hE;var dE=ue.Uint8Array,on=dE;function fE(r){var e=new r.constructor(r.byteLength);return new on(e).set(new on(r)),e}var an=fE;function pE(r,e){var t=e?an(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.byteLength)}var fp=pE;var mE=/\w*$/;function gE(r){var e=new r.constructor(r.source,mE.exec(r));return e.lastIndex=r.lastIndex,e}var pp=gE;var mp=ke?ke.prototype:void 0,gp=mp?mp.valueOf:void 0;function yE(r){return gp?Object(gp.call(r)):{}}var yp=yE;function _E(r,e){var t=e?an(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.length)}var _p=_E;var vE="[object Boolean]",wE="[object Date]",bE="[object Map]",TE="[object Number]",EE="[object RegExp]",IE="[object Set]",AE="[object String]",xE="[object Symbol]",SE="[object ArrayBuffer]",RE="[object DataView]",PE="[object Float32Array]",CE="[object Float64Array]",kE="[object Int8Array]",DE="[object Int16Array]",OE="[object Int32Array]",NE="[object Uint8Array]",VE="[object Uint8ClampedArray]",LE="[object Uint16Array]",FE="[object Uint32Array]";function ME(r,e,t){var n=r.constructor;switch(e){case SE:return an(r);case vE:case wE:return new n(+r);case RE:return fp(r,t);case PE:case CE:case kE:case DE:case OE:case NE:case VE:case LE:case FE:return _p(r,t);case bE:return new n;case TE:case AE:return new n(r);case EE:return pp(r);case IE:return new n;case xE:return yp(r)}}var vp=ME;function jE(r){return typeof r.constructor=="function"&&!Bt(r)?Zd(Wi(r)):{}}var wp=jE;var UE="[object Map]";function BE(r){return De(r)&&We(r)==UE}var bp=BE;var Tp=_t&&_t.isMap,$E=Tp?Jr(Tp):bp,Ep=$E;var qE="[object Set]";function zE(r){return De(r)&&We(r)==qE}var Ip=zE;var Ap=_t&&_t.isSet,GE=Ap?Jr(Ap):Ip,xp=GE;var KE=1,HE=2,WE=4,Sp="[object Arguments]",QE="[object Array]",JE="[object Boolean]",YE="[object Date]",XE="[object Error]",Rp="[object Function]",ZE="[object GeneratorFunction]",eI="[object Map]",tI="[object Number]",Pp="[object Object]",rI="[object RegExp]",nI="[object Set]",sI="[object String]",iI="[object Symbol]",oI="[object WeakMap]",aI="[object ArrayBuffer]",uI="[object DataView]",cI="[object Float32Array]",lI="[object Float64Array]",hI="[object Int8Array]",dI="[object Int16Array]",fI="[object Int32Array]",pI="[object Uint8Array]",mI="[object Uint8ClampedArray]",gI="[object Uint16Array]",yI="[object Uint32Array]",re={};re[Sp]=re[QE]=re[aI]=re[uI]=re[JE]=re[YE]=re[cI]=re[lI]=re[hI]=re[dI]=re[fI]=re[eI]=re[tI]=re[Pp]=re[rI]=re[nI]=re[sI]=re[iI]=re[pI]=re[mI]=re[gI]=re[yI]=!0;re[XE]=re[Rp]=re[oI]=!1;function to(r,e,t,n,s,i){var a,u=e&KE,c=e&HE,h=e&WE;if(t&&(a=s?t(r,n,s,i):t(r)),a!==void 0)return a;if(!Z(r))return r;var f=le(r);if(f){if(a=dp(r),!u)return tf(r,a)}else{var m=We(r),g=m==Rp||m==ZE;if(yt(r))return tp(r,u);if(m==Pp||m==Sp||g&&!s){if(a=c||g?{}:wp(r),!u)return c?ip(r,Jf(a,r)):sp(r,Qf(a,r))}else{if(!re[m])return s?r:{};a=vp(r,m,u)}}i||(i=new Ht);var b=i.get(r);if(b)return b;i.set(r,a),xp(r)?r.forEach(function(R){a.add(to(R,e,t,R,r,i))}):Ep(r)&&r.forEach(function(R,N){a.set(N,to(R,e,t,N,r,i))});var P=h?c?op:ws:c?$t:xe,C=f?void 0:P(r);return af(C||r,function(R,N){C&&(N=R,R=r[N]),Hr(a,N,to(R,e,t,N,r,i))}),a}var Cp=to;var _I=1,vI=4;function wI(r){return Cp(r,_I|vI)}var Wt=wI;var bI="__lodash_hash_undefined__";function TI(r){return this.__data__.set(r,bI),this}var kp=TI;function EI(r){return this.__data__.has(r)}var Dp=EI;function ro(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new hr;++e<t;)this.add(r[e])}ro.prototype.add=ro.prototype.push=kp;ro.prototype.has=Dp;var Op=ro;function II(r,e){for(var t=-1,n=r==null?0:r.length;++t<n;)if(e(r[t],t,r))return!0;return!1}var Np=II;function AI(r,e){return r.has(e)}var Vp=AI;var xI=1,SI=2;function RI(r,e,t,n,s,i){var a=t&xI,u=r.length,c=e.length;if(u!=c&&!(a&&c>u))return!1;var h=i.get(r),f=i.get(e);if(h&&f)return h==e&&f==r;var m=-1,g=!0,b=t&SI?new Op:void 0;for(i.set(r,e),i.set(e,r);++m<u;){var P=r[m],C=e[m];if(n)var R=a?n(C,P,m,e,r,i):n(P,C,m,r,e,i);if(R!==void 0){if(R)continue;g=!1;break}if(b){if(!Np(e,function(N,F){if(!Vp(b,F)&&(P===N||s(P,N,t,n,i)))return b.push(F)})){g=!1;break}}else if(!(P===C||s(P,C,t,n,i))){g=!1;break}}return i.delete(r),i.delete(e),g}var no=RI;function PI(r){var e=-1,t=Array(r.size);return r.forEach(function(n,s){t[++e]=[s,n]}),t}var Lp=PI;function CI(r){var e=-1,t=Array(r.size);return r.forEach(function(n){t[++e]=n}),t}var Fp=CI;var kI=1,DI=2,OI="[object Boolean]",NI="[object Date]",VI="[object Error]",LI="[object Map]",FI="[object Number]",MI="[object RegExp]",jI="[object Set]",UI="[object String]",BI="[object Symbol]",$I="[object ArrayBuffer]",qI="[object DataView]",Mp=ke?ke.prototype:void 0,yu=Mp?Mp.valueOf:void 0;function zI(r,e,t,n,s,i,a){switch(t){case qI:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case $I:return!(r.byteLength!=e.byteLength||!i(new on(r),new on(e)));case OI:case NI:case FI:return Xe(+r,+e);case VI:return r.name==e.name&&r.message==e.message;case MI:case UI:return r==e+"";case LI:var u=Lp;case jI:var c=n&kI;if(u||(u=Fp),r.size!=e.size&&!c)return!1;var h=a.get(r);if(h)return h==e;n|=DI,a.set(r,e);var f=no(u(r),u(e),n,s,i,a);return a.delete(r),f;case BI:if(yu)return yu.call(r)==yu.call(e)}return!1}var jp=zI;var GI=1,KI=Object.prototype,HI=KI.hasOwnProperty;function WI(r,e,t,n,s,i){var a=t&GI,u=ws(r),c=u.length,h=ws(e),f=h.length;if(c!=f&&!a)return!1;for(var m=c;m--;){var g=u[m];if(!(a?g in e:HI.call(e,g)))return!1}var b=i.get(r),P=i.get(e);if(b&&P)return b==e&&P==r;var C=!0;i.set(r,e),i.set(e,r);for(var R=a;++m<c;){g=u[m];var N=r[g],F=e[g];if(n)var U=a?n(F,N,g,e,r,i):n(N,F,g,r,e,i);if(!(U===void 0?N===F||s(N,F,t,n,i):U)){C=!1;break}R||(R=g=="constructor")}if(C&&!R){var G=r.constructor,Y=e.constructor;G!=Y&&"constructor"in r&&"constructor"in e&&!(typeof G=="function"&&G instanceof G&&typeof Y=="function"&&Y instanceof Y)&&(C=!1)}return i.delete(r),i.delete(e),C}var Up=WI;var QI=1,Bp="[object Arguments]",$p="[object Array]",so="[object Object]",JI=Object.prototype,qp=JI.hasOwnProperty;function YI(r,e,t,n,s,i){var a=le(r),u=le(e),c=a?$p:We(r),h=u?$p:We(e);c=c==Bp?so:c,h=h==Bp?so:h;var f=c==so,m=h==so,g=c==h;if(g&&yt(r)){if(!yt(e))return!1;a=!0,f=!1}if(g&&!f)return i||(i=new Ht),a||Yr(r)?no(r,e,t,n,s,i):jp(r,e,c,t,n,s,i);if(!(t&QI)){var b=f&&qp.call(r,"__wrapped__"),P=m&&qp.call(e,"__wrapped__");if(b||P){var C=b?r.value():r,R=P?e.value():e;return i||(i=new Ht),s(C,R,t,n,i)}}return g?(i||(i=new Ht),Up(r,e,t,n,s,i)):!1}var zp=YI;function Gp(r,e,t,n,s){return r===e?!0:r==null||e==null||!De(r)&&!De(e)?r!==r&&e!==e:zp(r,e,t,n,Gp,s)}var un=Gp;var XI=1,ZI=2;function eA(r,e,t,n){var s=t.length,i=s,a=!n;if(r==null)return!i;for(r=Object(r);s--;){var u=t[s];if(a&&u[2]?u[1]!==r[u[0]]:!(u[0]in r))return!1}for(;++s<i;){u=t[s];var c=u[0],h=r[c],f=u[1];if(a&&u[2]){if(h===void 0&&!(c in r))return!1}else{var m=new Ht;if(n)var g=n(h,f,c,r,e,m);if(!(g===void 0?un(f,h,XI|ZI,n,m):g))return!1}}return!0}var Kp=eA;function tA(r){return r===r&&!Z(r)}var io=tA;function rA(r){for(var e=xe(r),t=e.length;t--;){var n=e[t],s=r[n];e[t]=[n,s,io(s)]}return e}var Hp=rA;function nA(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}var oo=nA;function sA(r){var e=Hp(r);return e.length==1&&e[0][2]?oo(e[0][0],e[0][1]):function(t){return t===r||Kp(t,r,e)}}var Wp=sA;function iA(r,e){return r!=null&&e in Object(r)}var Qp=iA;function oA(r,e,t){e=rn(e,r);for(var n=-1,s=e.length,i=!1;++n<s;){var a=Ze(e[n]);if(!(i=r!=null&&t(r,a)))break;r=r[a]}return i||++n!=s?i:(s=r==null?0:r.length,!!s&&Wr(s)&&Mt(a,s)&&(le(r)||Qr(r)))}var Jp=oA;function aA(r,e){return r!=null&&Jp(r,e,Qp)}var Yp=aA;var uA=1,cA=2;function lA(r,e){return Xr(r)&&io(e)?oo(Ze(r),e):function(t){var n=vs(t,r);return n===void 0&&n===e?Yp(t,r):un(e,n,uA|cA)}}var Xp=lA;function hA(r){return function(e){return e==null?void 0:e[r]}}var Zp=hA;function dA(r){return function(e){return Ki(e,r)}}var em=dA;function fA(r){return Xr(r)?Zp(Ze(r)):em(r)}var tm=fA;function pA(r){return typeof r=="function"?r:r==null?zr:typeof r=="object"?le(r)?Xp(r[0],r[1]):Wp(r):tm(r)}var rm=pA;function mA(r){return function(e,t,n){for(var s=-1,i=Object(e),a=n(e),u=a.length;u--;){var c=a[r?u:++s];if(t(i[c],c,i)===!1)break}return e}}var nm=mA;var gA=nm(),sm=gA;function yA(r,e){return r&&sm(r,e,xe)}var im=yA;var _A=function(){return ue.Date.now()},ao=_A;var vA="Expected a function",wA=Math.max,bA=Math.min;function TA(r,e,t){var n,s,i,a,u,c,h=0,f=!1,m=!1,g=!0;if(typeof r!="function")throw new TypeError(vA);e=du(e)||0,Z(t)&&(f=!!t.leading,m="maxWait"in t,i=m?wA(du(t.maxWait)||0,e):i,g="trailing"in t?!!t.trailing:g);function b(B){var E=n,y=s;return n=s=void 0,h=B,a=r.apply(y,E),a}function P(B){return h=B,u=setTimeout(N,e),f?b(B):a}function C(B){var E=B-c,y=B-h,w=e-E;return m?bA(w,i-y):w}function R(B){var E=B-c,y=B-h;return c===void 0||E>=e||E<0||m&&y>=i}function N(){var B=ao();if(R(B))return F(B);u=setTimeout(N,C(B))}function F(B){return u=void 0,g&&n?b(B):(n=s=void 0,a)}function U(){u!==void 0&&clearTimeout(u),h=0,n=c=s=u=void 0}function G(){return u===void 0?a:F(ao())}function Y(){var B=ao(),E=R(B);if(n=arguments,s=this,c=B,E){if(u===void 0)return P(c);if(m)return clearTimeout(u),u=setTimeout(N,e),b(c)}return u===void 0&&(u=setTimeout(N,e)),a}return Y.cancel=U,Y.flush=G,Y}var om=TA;var am=Object.prototype,EA=am.hasOwnProperty,IA=lf(function(r,e){r=Object(r);var t=-1,n=e.length,s=n>2?e[2]:void 0;for(s&&hf(e[0],e[1],s)&&(n=1);++t<n;)for(var i=e[t],a=$t(i),u=-1,c=a.length;++u<c;){var h=a[u],f=r[h];(f===void 0||Xe(f,am[h])&&!EA.call(r,h))&&(r[h]=i[h])}return r}),uo=IA;var AA="[object Map]",xA="[object Set]",SA=Object.prototype,RA=SA.hasOwnProperty;function PA(r){if(r==null)return!0;if(Ut(r)&&(le(r)||typeof r=="string"||typeof r.splice=="function"||yt(r)||Yr(r)||Qr(r)))return!r.length;var e=We(r);if(e==AA||e==xA)return!r.size;if(Bt(r))return!Gi(r).length;for(var t in r)if(RA.call(r,t))return!1;return!0}var _u=PA;function CA(r,e){return un(r,e)}var bs=CA;function kA(r,e){var t={};return e=rm(e,3),im(r,function(n,s,i){Kr(t,e(n,s,i),n)}),t}var vu=kA;function DA(r,e,t,n){if(!Z(r))return r;e=rn(e,r);for(var s=-1,i=e.length,a=i-1,u=r;u!=null&&++s<i;){var c=Ze(e[s]),h=t;if(c==="__proto__"||c==="constructor"||c==="prototype")return r;if(s!=a){var f=u[c];h=n?n(f,c,u):void 0,h===void 0&&(h=Z(f)?f:Mt(e[s+1])?[]:{})}Hr(u,c,h),u=u[c]}return r}var um=DA;function OA(r,e,t){return r==null?r:um(r,e,t)}var Qt=OA;var NA="Expected a function";function VA(r,e,t){var n=!0,s=!0;if(typeof r!="function")throw new TypeError(NA);return Z(t)&&(n="leading"in t?!!t.leading:n,s="trailing"in t?!!t.trailing:s),om(r,e,{leading:n,maxWait:e,trailing:s})}var wu=VA;var cm=()=>{};var hm=function(r){let e=[],t=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(s=65536+((s&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128)}return e},LA=function(r){let e=[],t=0,n=0;for(;t<r.length;){let s=r[t++];if(s<128)e[n++]=String.fromCharCode(s);else if(s>191&&s<224){let i=r[t++];e[n++]=String.fromCharCode((s&31)<<6|i&63)}else if(s>239&&s<365){let i=r[t++],a=r[t++],u=r[t++],c=((s&7)<<18|(i&63)<<12|(a&63)<<6|u&63)-65536;e[n++]=String.fromCharCode(55296+(c>>10)),e[n++]=String.fromCharCode(56320+(c&1023))}else{let i=r[t++],a=r[t++];e[n++]=String.fromCharCode((s&15)<<12|(i&63)<<6|a&63)}}return e.join("")},dm={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:typeof atob=="function",encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();let t=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let s=0;s<r.length;s+=3){let i=r[s],a=s+1<r.length,u=a?r[s+1]:0,c=s+2<r.length,h=c?r[s+2]:0,f=i>>2,m=(i&3)<<4|u>>4,g=(u&15)<<2|h>>6,b=h&63;c||(b=64,a||(g=64)),n.push(t[f],t[m],t[g],t[b])}return n.join("")},encodeString(r,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(r):this.encodeByteArray(hm(r),e)},decodeString(r,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(r):LA(this.decodeStringToByteArray(r,e))},decodeStringToByteArray(r,e){this.init_();let t=e?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let s=0;s<r.length;){let i=t[r.charAt(s++)],u=s<r.length?t[r.charAt(s)]:0;++s;let h=s<r.length?t[r.charAt(s)]:64;++s;let m=s<r.length?t[r.charAt(s)]:64;if(++s,i==null||u==null||h==null||m==null)throw new bu;let g=i<<2|u>>4;if(n.push(g),h!==64){let b=u<<4&240|h>>2;if(n.push(b),m!==64){let P=h<<6&192|m;n.push(P)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let r=0;r<this.ENCODED_VALS.length;r++)this.byteToCharMap_[r]=this.ENCODED_VALS.charAt(r),this.charToByteMap_[this.byteToCharMap_[r]]=r,this.byteToCharMapWebSafe_[r]=this.ENCODED_VALS_WEBSAFE.charAt(r),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[r]]=r,r>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(r)]=r,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(r)]=r)}}},bu=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},FA=function(r){let e=hm(r);return dm.encodeByteArray(e,!0)},Ts=function(r){return FA(r).replace(/\./g,"")},fm=function(r){try{return dm.decodeString(r,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function MA(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;throw new Error("Unable to locate global object.")}var jA=()=>MA().__FIREBASE_DEFAULTS__,UA=()=>{if(typeof process=="undefined"||typeof process.env=="undefined")return;let r=process.env.__FIREBASE_DEFAULTS__;if(r)return JSON.parse(r)},BA=()=>{if(typeof document=="undefined")return;let r;try{r=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}let e=r&&fm(r[1]);return e&&JSON.parse(e)},Tu=()=>{try{return cm()||jA()||UA()||BA()}catch(r){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${r}`);return}},$A=r=>{var e,t;return(t=(e=Tu())===null||e===void 0?void 0:e.emulatorHosts)===null||t===void 0?void 0:t[r]},pm=r=>{let e=$A(r);if(!e)return;let t=e.lastIndexOf(":");if(t<=0||t+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);let n=parseInt(e.substring(t+1),10);return e[0]==="["?[e.substring(1,t-1),n]:[e.substring(0,t),n]},Eu=()=>{var r;return(r=Tu())===null||r===void 0?void 0:r.config};var co=class{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),typeof e=="function"&&(this.promise.catch(()=>{}),e.length===1?e(t):e(t,n))}}};function mm(r,e){if(r.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');let t={alg:"none",type:"JWT"},n=e||"demo-project",s=r.iat||0,i=r.sub||r.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");let a=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:s,exp:s+3600,auth_time:s,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},r);return[Ts(JSON.stringify(t)),Ts(JSON.stringify(a)),""].join(".")}function gm(){return typeof navigator!="undefined"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function qA(){var r;let e=(r=Tu())===null||r===void 0?void 0:r.forceEnvironment;if(e==="node")return!0;if(e==="browser")return!1;try{return Object.prototype.toString.call(global.process)==="[object process]"}catch{return!1}}function ym(){return!qA()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function Iu(){try{return typeof indexedDB=="object"}catch{return!1}}function _m(){return new Promise((r,e)=>{try{let t=!0,n="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(n);s.onsuccess=()=>{s.result.close(),t||self.indexedDB.deleteDatabase(n),r(!0)},s.onupgradeneeded=()=>{t=!1},s.onerror=()=>{var i;e(((i=s.error)===null||i===void 0?void 0:i.message)||"")}}catch(t){e(t)}})}var zA="FirebaseError",Qe=class r extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name=zA,Object.setPrototypeOf(this,r.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Es.prototype.create)}},Es=class{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){let n=t[0]||{},s=`${this.service}/${e}`,i=this.errors[e],a=i?GA(i,n):"Error",u=`${this.serviceName}: ${a} (${s}).`;return new Qe(s,u,n)}};function GA(r,e){return r.replace(KA,(t,n)=>{let s=e[n];return s!=null?String(s):`<${n}?>`})}var KA=/\{\$([^}]+)}/g;function cn(r,e){if(r===e)return!0;let t=Object.keys(r),n=Object.keys(e);for(let s of t){if(!n.includes(s))return!1;let i=r[s],a=e[s];if(lm(i)&&lm(a)){if(!cn(i,a))return!1}else if(i!==a)return!1}for(let s of n)if(!t.includes(s))return!1;return!0}function lm(r){return r!==null&&typeof r=="object"}var fM=4*60*60*1e3;function wt(r){return r&&r._delegate?r._delegate:r}var bt=class{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}};var fr="[DEFAULT]";var Au=class{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){let t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){let n=new co;if(this.instancesDeferred.set(t,n),this.isInitialized(t)||this.shouldAutoInitialize())try{let s=this.getOrInitializeService({instanceIdentifier:t});s&&n.resolve(s)}catch{}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;let n=this.normalizeInstanceIdentifier(e==null?void 0:e.identifier),s=(t=e==null?void 0:e.optional)!==null&&t!==void 0?t:!1;if(this.isInitialized(n)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:n})}catch(i){if(s)return null;throw i}else{if(s)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,!!this.shouldAutoInitialize()){if(WA(e))try{this.getOrInitializeService({instanceIdentifier:fr})}catch{}for(let[t,n]of this.instancesDeferred.entries()){let s=this.normalizeInstanceIdentifier(t);try{let i=this.getOrInitializeService({instanceIdentifier:s});n.resolve(i)}catch{}}}}clearInstance(e=fr){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){let e=Array.from(this.instances.values());await Promise.all([...e.filter(t=>"INTERNAL"in t).map(t=>t.INTERNAL.delete()),...e.filter(t=>"_delete"in t).map(t=>t._delete())])}isComponentSet(){return this.component!=null}isInitialized(e=fr){return this.instances.has(e)}getOptions(e=fr){return this.instancesOptions.get(e)||{}}initialize(e={}){let{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);let s=this.getOrInitializeService({instanceIdentifier:n,options:t});for(let[i,a]of this.instancesDeferred.entries()){let u=this.normalizeInstanceIdentifier(i);n===u&&a.resolve(s)}return s}onInit(e,t){var n;let s=this.normalizeInstanceIdentifier(t),i=(n=this.onInitCallbacks.get(s))!==null&&n!==void 0?n:new Set;i.add(e),this.onInitCallbacks.set(s,i);let a=this.instances.get(s);return a&&e(a,s),()=>{i.delete(e)}}invokeOnInitCallbacks(e,t){let n=this.onInitCallbacks.get(t);if(n)for(let s of n)try{s(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:HA(e),options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch{}return n||null}normalizeInstanceIdentifier(e=fr){return this.component?this.component.multipleInstances?e:fr:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}};function HA(r){return r===fr?void 0:r}function WA(r){return r.instantiationMode==="EAGER"}var lo=class{constructor(e){this.name=e,this.providers=new Map}addComponent(e){let t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);let t=new Au(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}};var QA=[],Q;(function(r){r[r.DEBUG=0]="DEBUG",r[r.VERBOSE=1]="VERBOSE",r[r.INFO=2]="INFO",r[r.WARN=3]="WARN",r[r.ERROR=4]="ERROR",r[r.SILENT=5]="SILENT"})(Q||(Q={}));var JA={debug:Q.DEBUG,verbose:Q.VERBOSE,info:Q.INFO,warn:Q.WARN,error:Q.ERROR,silent:Q.SILENT},YA=Q.INFO,XA={[Q.DEBUG]:"log",[Q.VERBOSE]:"log",[Q.INFO]:"info",[Q.WARN]:"warn",[Q.ERROR]:"error"},ZA=(r,e,...t)=>{if(e<r.logLevel)return;let n=new Date().toISOString(),s=XA[e];if(s)console[s](`[${n}] ${r.name}:`,...t);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},ln=class{constructor(e){this.name=e,this._logLevel=YA,this._logHandler=ZA,this._userLogHandler=null,QA.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in Q))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?JA[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,Q.DEBUG,...e),this._logHandler(this,Q.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,Q.VERBOSE,...e),this._logHandler(this,Q.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,Q.INFO,...e),this._logHandler(this,Q.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,Q.WARN,...e),this._logHandler(this,Q.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,Q.ERROR,...e),this._logHandler(this,Q.ERROR,...e)}};var ex=(r,e)=>e.some(t=>r instanceof t),vm,wm;function tx(){return vm||(vm=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function rx(){return wm||(wm=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var bm=new WeakMap,Su=new WeakMap,Tm=new WeakMap,xu=new WeakMap,Pu=new WeakMap;function nx(r){let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("success",i),r.removeEventListener("error",a)},i=()=>{t(et(r.result)),s()},a=()=>{n(r.error),s()};r.addEventListener("success",i),r.addEventListener("error",a)});return e.then(t=>{t instanceof IDBCursor&&bm.set(t,r)}).catch(()=>{}),Pu.set(e,r),e}function sx(r){if(Su.has(r))return;let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("complete",i),r.removeEventListener("error",a),r.removeEventListener("abort",a)},i=()=>{t(),s()},a=()=>{n(r.error||new DOMException("AbortError","AbortError")),s()};r.addEventListener("complete",i),r.addEventListener("error",a),r.addEventListener("abort",a)});Su.set(r,e)}var Ru={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return Su.get(r);if(e==="objectStoreNames")return r.objectStoreNames||Tm.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return et(r[e])},set(r,e,t){return r[e]=t,!0},has(r,e){return r instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in r}};function Em(r){Ru=r(Ru)}function ix(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let n=r.call(ho(this),e,...t);return Tm.set(n,e.sort?e.sort():[e]),et(n)}:rx().includes(r)?function(...e){return r.apply(ho(this),e),et(bm.get(this))}:function(...e){return et(r.apply(ho(this),e))}}function ox(r){return typeof r=="function"?ix(r):(r instanceof IDBTransaction&&sx(r),ex(r,tx())?new Proxy(r,Ru):r)}function et(r){if(r instanceof IDBRequest)return nx(r);if(xu.has(r))return xu.get(r);let e=ox(r);return e!==r&&(xu.set(r,e),Pu.set(e,r)),e}var ho=r=>Pu.get(r);function Am(r,e,{blocked:t,upgrade:n,blocking:s,terminated:i}={}){let a=indexedDB.open(r,e),u=et(a);return n&&a.addEventListener("upgradeneeded",c=>{n(et(a.result),c.oldVersion,c.newVersion,et(a.transaction),c)}),t&&a.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),u.then(c=>{i&&c.addEventListener("close",()=>i()),s&&c.addEventListener("versionchange",h=>s(h.oldVersion,h.newVersion,h))}).catch(()=>{}),u}var ax=["get","getKey","getAll","getAllKeys","count"],ux=["put","add","delete","clear"],Cu=new Map;function Im(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(Cu.get(e))return Cu.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,s=ux.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(s||ax.includes(t)))return;let i=async function(a,...u){let c=this.transaction(a,s?"readwrite":"readonly"),h=c.store;return n&&(h=h.index(u.shift())),(await Promise.all([h[t](...u),s&&c.done]))[0]};return Cu.set(e,i),i}Em(r=>({...r,get:(e,t,n)=>Im(e,t)||r.get(e,t,n),has:(e,t)=>!!Im(e,t)||r.has(e,t)}));var Du=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(t=>{if(cx(t)){let n=t.getImmediate();return`${n.library}/${n.version}`}else return null}).filter(t=>t).join(" ")}};function cx(r){let e=r.getComponent();return(e==null?void 0:e.type)==="VERSION"}var Ou="@firebase/app",xm="0.11.3";var Tt=new ln("@firebase/app"),lx="@firebase/app-compat",hx="@firebase/analytics-compat",dx="@firebase/analytics",fx="@firebase/app-check-compat",px="@firebase/app-check",mx="@firebase/auth",gx="@firebase/auth-compat",yx="@firebase/database",_x="@firebase/data-connect",vx="@firebase/database-compat",wx="@firebase/functions",bx="@firebase/functions-compat",Tx="@firebase/installations",Ex="@firebase/installations-compat",Ix="@firebase/messaging",Ax="@firebase/messaging-compat",xx="@firebase/performance",Sx="@firebase/performance-compat",Rx="@firebase/remote-config",Px="@firebase/remote-config-compat",Cx="@firebase/storage",kx="@firebase/storage-compat",Dx="@firebase/firestore",Ox="@firebase/vertexai",Nx="@firebase/firestore-compat",Vx="firebase",Lx="11.5.0";var Nu="[DEFAULT]",Fx={[Ou]:"fire-core",[lx]:"fire-core-compat",[dx]:"fire-analytics",[hx]:"fire-analytics-compat",[px]:"fire-app-check",[fx]:"fire-app-check-compat",[mx]:"fire-auth",[gx]:"fire-auth-compat",[yx]:"fire-rtdb",[_x]:"fire-data-connect",[vx]:"fire-rtdb-compat",[wx]:"fire-fn",[bx]:"fire-fn-compat",[Tx]:"fire-iid",[Ex]:"fire-iid-compat",[Ix]:"fire-fcm",[Ax]:"fire-fcm-compat",[xx]:"fire-perf",[Sx]:"fire-perf-compat",[Rx]:"fire-rc",[Px]:"fire-rc-compat",[Cx]:"fire-gcs",[kx]:"fire-gcs-compat",[Dx]:"fire-fst",[Nx]:"fire-fst-compat",[Ox]:"fire-vertex","fire-js":"fire-js",[Vx]:"fire-js-all"};var fo=new Map,Mx=new Map,Vu=new Map;function Sm(r,e){try{r.container.addComponent(e)}catch(t){Tt.debug(`Component ${e.name} failed to register with FirebaseApp ${r.name}`,t)}}function Is(r){let e=r.name;if(Vu.has(e))return Tt.debug(`There were multiple attempts to register component ${e}.`),!1;Vu.set(e,r);for(let t of fo.values())Sm(t,r);for(let t of Mx.values())Sm(t,r);return!0}function km(r,e){let t=r.container.getProvider("heartbeat").getImmediate({optional:!0});return t&&t.triggerHeartbeat(),r.container.getProvider(e)}function Dm(r){return r==null?!1:r.settings!==void 0}var jx={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},Jt=new Es("app","Firebase",jx);var Lu=class{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new bt("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw Jt.create("app-deleted",{appName:this._name})}};var Om=Lx;function ju(r,e={}){let t=r;typeof e!="object"&&(e={name:e});let n=Object.assign({name:Nu,automaticDataCollectionEnabled:!1},e),s=n.name;if(typeof s!="string"||!s)throw Jt.create("bad-app-name",{appName:String(s)});if(t||(t=Eu()),!t)throw Jt.create("no-options");let i=fo.get(s);if(i){if(cn(t,i.options)&&cn(n,i.config))return i;throw Jt.create("duplicate-app",{appName:s})}let a=new lo(s);for(let c of Vu.values())a.addComponent(c);let u=new Lu(t,n,a);return fo.set(s,u),u}function Nm(r=Nu){let e=fo.get(r);if(!e&&r===Nu&&Eu())return ju();if(!e)throw Jt.create("no-app",{appName:r});return e}function Yt(r,e,t){var n;let s=(n=Fx[r])!==null&&n!==void 0?n:r;t&&(s+=`-${t}`);let i=s.match(/\s|\//),a=e.match(/\s|\//);if(i||a){let u=[`Unable to register library "${s}" with version "${e}":`];i&&u.push(`library name "${s}" contains illegal characters (whitespace or "/")`),i&&a&&u.push("and"),a&&u.push(`version name "${e}" contains illegal characters (whitespace or "/")`),Tt.warn(u.join(" "));return}Is(new bt(`${s}-version`,()=>({library:s,version:e}),"VERSION"))}var Ux="firebase-heartbeat-database",Bx=1,As="firebase-heartbeat-store",ku=null;function Vm(){return ku||(ku=Am(Ux,Bx,{upgrade:(r,e)=>{switch(e){case 0:try{r.createObjectStore(As)}catch(t){console.warn(t)}}}}).catch(r=>{throw Jt.create("idb-open",{originalErrorMessage:r.message})})),ku}async function $x(r){try{let t=(await Vm()).transaction(As),n=await t.objectStore(As).get(Lm(r));return await t.done,n}catch(e){if(e instanceof Qe)Tt.warn(e.message);else{let t=Jt.create("idb-get",{originalErrorMessage:e==null?void 0:e.message});Tt.warn(t.message)}}}async function Rm(r,e){try{let n=(await Vm()).transaction(As,"readwrite");await n.objectStore(As).put(e,Lm(r)),await n.done}catch(t){if(t instanceof Qe)Tt.warn(t.message);else{let n=Jt.create("idb-set",{originalErrorMessage:t==null?void 0:t.message});Tt.warn(n.message)}}}function Lm(r){return`${r.name}!${r.options.appId}`}var qx=1024,zx=30,Fu=class{constructor(e){this.container=e,this._heartbeatsCache=null;let t=this.container.getProvider("app").getImmediate();this._storage=new Mu(t),this._heartbeatsCachePromise=this._storage.read().then(n=>(this._heartbeatsCache=n,n))}async triggerHeartbeat(){var e,t;try{let s=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),i=Pm();if(((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,((t=this._heartbeatsCache)===null||t===void 0?void 0:t.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===i||this._heartbeatsCache.heartbeats.some(a=>a.date===i))return;if(this._heartbeatsCache.heartbeats.push({date:i,agent:s}),this._heartbeatsCache.heartbeats.length>zx){let a=Kx(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(a,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(n){Tt.warn(n)}}async getHeartbeatsHeader(){var e;try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null||this._heartbeatsCache.heartbeats.length===0)return"";let t=Pm(),{heartbeatsToSend:n,unsentEntries:s}=Gx(this._heartbeatsCache.heartbeats),i=Ts(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,s.length>0?(this._heartbeatsCache.heartbeats=s,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(t){return Tt.warn(t),""}}};function Pm(){return new Date().toISOString().substring(0,10)}function Gx(r,e=qx){let t=[],n=r.slice();for(let s of r){let i=t.find(a=>a.agent===s.agent);if(i){if(i.dates.push(s.date),Cm(t)>e){i.dates.pop();break}}else if(t.push({agent:s.agent,dates:[s.date]}),Cm(t)>e){t.pop();break}n=n.slice(1)}return{heartbeatsToSend:t,unsentEntries:n}}var Mu=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return Iu()?_m().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let t=await $x(this.app);return t!=null&&t.heartbeats?t:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){let s=await this.read();return Rm(this.app,{lastSentHeartbeatDate:(t=e.lastSentHeartbeatDate)!==null&&t!==void 0?t:s.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){var t;if(await this._canUseIndexedDBPromise){let s=await this.read();return Rm(this.app,{lastSentHeartbeatDate:(t=e.lastSentHeartbeatDate)!==null&&t!==void 0?t:s.lastSentHeartbeatDate,heartbeats:[...s.heartbeats,...e.heartbeats]})}else return}};function Cm(r){return Ts(JSON.stringify({version:2,heartbeats:r})).length}function Kx(r){if(r.length===0)return-1;let e=0,t=r[0].date;for(let n=1;n<r.length;n++)r[n].date<t&&(t=r[n].date,e=n);return e}function Hx(r){Is(new bt("platform-logger",e=>new Du(e),"PRIVATE")),Is(new bt("heartbeat",e=>new Fu(e),"PRIVATE")),Yt(Ou,xm,r),Yt(Ou,xm,"esm2017"),Yt("fire-js","")}Hx("");var Wx="firebase",Qx="11.5.0";Yt(Wx,Qx,"app");var Fm=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Mm={};var Et,Uu;(function(){var r;function e(E,y){function w(){}w.prototype=y.prototype,E.D=y.prototype,E.prototype=new w,E.prototype.constructor=E,E.C=function(T,I,x){for(var _=Array(arguments.length-2),ft=2;ft<arguments.length;ft++)_[ft-2]=arguments[ft];return y.prototype[I].apply(T,_)}}function t(){this.blockSize=-1}function n(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}e(n,t),n.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function s(E,y,w){w||(w=0);var T=Array(16);if(typeof y=="string")for(var I=0;16>I;++I)T[I]=y.charCodeAt(w++)|y.charCodeAt(w++)<<8|y.charCodeAt(w++)<<16|y.charCodeAt(w++)<<24;else for(I=0;16>I;++I)T[I]=y[w++]|y[w++]<<8|y[w++]<<16|y[w++]<<24;y=E.g[0],w=E.g[1],I=E.g[2];var x=E.g[3],_=y+(x^w&(I^x))+T[0]+3614090360&4294967295;y=w+(_<<7&4294967295|_>>>25),_=x+(I^y&(w^I))+T[1]+3905402710&4294967295,x=y+(_<<12&4294967295|_>>>20),_=I+(w^x&(y^w))+T[2]+606105819&4294967295,I=x+(_<<17&4294967295|_>>>15),_=w+(y^I&(x^y))+T[3]+3250441966&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(x^w&(I^x))+T[4]+4118548399&4294967295,y=w+(_<<7&4294967295|_>>>25),_=x+(I^y&(w^I))+T[5]+1200080426&4294967295,x=y+(_<<12&4294967295|_>>>20),_=I+(w^x&(y^w))+T[6]+2821735955&4294967295,I=x+(_<<17&4294967295|_>>>15),_=w+(y^I&(x^y))+T[7]+4249261313&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(x^w&(I^x))+T[8]+1770035416&4294967295,y=w+(_<<7&4294967295|_>>>25),_=x+(I^y&(w^I))+T[9]+2336552879&4294967295,x=y+(_<<12&4294967295|_>>>20),_=I+(w^x&(y^w))+T[10]+4294925233&4294967295,I=x+(_<<17&4294967295|_>>>15),_=w+(y^I&(x^y))+T[11]+2304563134&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(x^w&(I^x))+T[12]+1804603682&4294967295,y=w+(_<<7&4294967295|_>>>25),_=x+(I^y&(w^I))+T[13]+4254626195&4294967295,x=y+(_<<12&4294967295|_>>>20),_=I+(w^x&(y^w))+T[14]+2792965006&4294967295,I=x+(_<<17&4294967295|_>>>15),_=w+(y^I&(x^y))+T[15]+1236535329&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(I^x&(w^I))+T[1]+4129170786&4294967295,y=w+(_<<5&4294967295|_>>>27),_=x+(w^I&(y^w))+T[6]+3225465664&4294967295,x=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(x^y))+T[11]+643717713&4294967295,I=x+(_<<14&4294967295|_>>>18),_=w+(x^y&(I^x))+T[0]+3921069994&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(I^x&(w^I))+T[5]+3593408605&4294967295,y=w+(_<<5&4294967295|_>>>27),_=x+(w^I&(y^w))+T[10]+38016083&4294967295,x=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(x^y))+T[15]+3634488961&4294967295,I=x+(_<<14&4294967295|_>>>18),_=w+(x^y&(I^x))+T[4]+3889429448&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(I^x&(w^I))+T[9]+568446438&4294967295,y=w+(_<<5&4294967295|_>>>27),_=x+(w^I&(y^w))+T[14]+3275163606&4294967295,x=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(x^y))+T[3]+4107603335&4294967295,I=x+(_<<14&4294967295|_>>>18),_=w+(x^y&(I^x))+T[8]+1163531501&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(I^x&(w^I))+T[13]+2850285829&4294967295,y=w+(_<<5&4294967295|_>>>27),_=x+(w^I&(y^w))+T[2]+4243563512&4294967295,x=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(x^y))+T[7]+1735328473&4294967295,I=x+(_<<14&4294967295|_>>>18),_=w+(x^y&(I^x))+T[12]+2368359562&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(w^I^x)+T[5]+4294588738&4294967295,y=w+(_<<4&4294967295|_>>>28),_=x+(y^w^I)+T[8]+2272392833&4294967295,x=y+(_<<11&4294967295|_>>>21),_=I+(x^y^w)+T[11]+1839030562&4294967295,I=x+(_<<16&4294967295|_>>>16),_=w+(I^x^y)+T[14]+4259657740&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(w^I^x)+T[1]+2763975236&4294967295,y=w+(_<<4&4294967295|_>>>28),_=x+(y^w^I)+T[4]+1272893353&4294967295,x=y+(_<<11&4294967295|_>>>21),_=I+(x^y^w)+T[7]+4139469664&4294967295,I=x+(_<<16&4294967295|_>>>16),_=w+(I^x^y)+T[10]+3200236656&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(w^I^x)+T[13]+681279174&4294967295,y=w+(_<<4&4294967295|_>>>28),_=x+(y^w^I)+T[0]+3936430074&4294967295,x=y+(_<<11&4294967295|_>>>21),_=I+(x^y^w)+T[3]+3572445317&4294967295,I=x+(_<<16&4294967295|_>>>16),_=w+(I^x^y)+T[6]+76029189&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(w^I^x)+T[9]+3654602809&4294967295,y=w+(_<<4&4294967295|_>>>28),_=x+(y^w^I)+T[12]+3873151461&4294967295,x=y+(_<<11&4294967295|_>>>21),_=I+(x^y^w)+T[15]+530742520&4294967295,I=x+(_<<16&4294967295|_>>>16),_=w+(I^x^y)+T[2]+3299628645&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(I^(w|~x))+T[0]+4096336452&4294967295,y=w+(_<<6&4294967295|_>>>26),_=x+(w^(y|~I))+T[7]+1126891415&4294967295,x=y+(_<<10&4294967295|_>>>22),_=I+(y^(x|~w))+T[14]+2878612391&4294967295,I=x+(_<<15&4294967295|_>>>17),_=w+(x^(I|~y))+T[5]+4237533241&4294967295,w=I+(_<<21&4294967295|_>>>11),_=y+(I^(w|~x))+T[12]+1700485571&4294967295,y=w+(_<<6&4294967295|_>>>26),_=x+(w^(y|~I))+T[3]+2399980690&4294967295,x=y+(_<<10&4294967295|_>>>22),_=I+(y^(x|~w))+T[10]+4293915773&4294967295,I=x+(_<<15&4294967295|_>>>17),_=w+(x^(I|~y))+T[1]+2240044497&4294967295,w=I+(_<<21&4294967295|_>>>11),_=y+(I^(w|~x))+T[8]+1873313359&4294967295,y=w+(_<<6&4294967295|_>>>26),_=x+(w^(y|~I))+T[15]+4264355552&4294967295,x=y+(_<<10&4294967295|_>>>22),_=I+(y^(x|~w))+T[6]+2734768916&4294967295,I=x+(_<<15&4294967295|_>>>17),_=w+(x^(I|~y))+T[13]+1309151649&4294967295,w=I+(_<<21&4294967295|_>>>11),_=y+(I^(w|~x))+T[4]+4149444226&4294967295,y=w+(_<<6&4294967295|_>>>26),_=x+(w^(y|~I))+T[11]+3174756917&4294967295,x=y+(_<<10&4294967295|_>>>22),_=I+(y^(x|~w))+T[2]+718787259&4294967295,I=x+(_<<15&4294967295|_>>>17),_=w+(x^(I|~y))+T[9]+3951481745&4294967295,E.g[0]=E.g[0]+y&4294967295,E.g[1]=E.g[1]+(I+(_<<21&4294967295|_>>>11))&4294967295,E.g[2]=E.g[2]+I&4294967295,E.g[3]=E.g[3]+x&4294967295}n.prototype.u=function(E,y){y===void 0&&(y=E.length);for(var w=y-this.blockSize,T=this.B,I=this.h,x=0;x<y;){if(I==0)for(;x<=w;)s(this,E,x),x+=this.blockSize;if(typeof E=="string"){for(;x<y;)if(T[I++]=E.charCodeAt(x++),I==this.blockSize){s(this,T),I=0;break}}else for(;x<y;)if(T[I++]=E[x++],I==this.blockSize){s(this,T),I=0;break}}this.h=I,this.o+=y},n.prototype.v=function(){var E=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);E[0]=128;for(var y=1;y<E.length-8;++y)E[y]=0;var w=8*this.o;for(y=E.length-8;y<E.length;++y)E[y]=w&255,w/=256;for(this.u(E),E=Array(16),y=w=0;4>y;++y)for(var T=0;32>T;T+=8)E[w++]=this.g[y]>>>T&255;return E};function i(E,y){var w=u;return Object.prototype.hasOwnProperty.call(w,E)?w[E]:w[E]=y(E)}function a(E,y){this.h=y;for(var w=[],T=!0,I=E.length-1;0<=I;I--){var x=E[I]|0;T&&x==y||(w[I]=x,T=!1)}this.g=w}var u={};function c(E){return-128<=E&&128>E?i(E,function(y){return new a([y|0],0>y?-1:0)}):new a([E|0],0>E?-1:0)}function h(E){if(isNaN(E)||!isFinite(E))return m;if(0>E)return R(h(-E));for(var y=[],w=1,T=0;E>=w;T++)y[T]=E/w|0,w*=4294967296;return new a(y,0)}function f(E,y){if(E.length==0)throw Error("number format error: empty string");if(y=y||10,2>y||36<y)throw Error("radix out of range: "+y);if(E.charAt(0)=="-")return R(f(E.substring(1),y));if(0<=E.indexOf("-"))throw Error('number format error: interior "-" character');for(var w=h(Math.pow(y,8)),T=m,I=0;I<E.length;I+=8){var x=Math.min(8,E.length-I),_=parseInt(E.substring(I,I+x),y);8>x?(x=h(Math.pow(y,x)),T=T.j(x).add(h(_))):(T=T.j(w),T=T.add(h(_)))}return T}var m=c(0),g=c(1),b=c(16777216);r=a.prototype,r.m=function(){if(C(this))return-R(this).m();for(var E=0,y=1,w=0;w<this.g.length;w++){var T=this.i(w);E+=(0<=T?T:4294967296+T)*y,y*=4294967296}return E},r.toString=function(E){if(E=E||10,2>E||36<E)throw Error("radix out of range: "+E);if(P(this))return"0";if(C(this))return"-"+R(this).toString(E);for(var y=h(Math.pow(E,6)),w=this,T="";;){var I=G(w,y).g;w=N(w,I.j(y));var x=((0<w.g.length?w.g[0]:w.h)>>>0).toString(E);if(w=I,P(w))return x+T;for(;6>x.length;)x="0"+x;T=x+T}},r.i=function(E){return 0>E?0:E<this.g.length?this.g[E]:this.h};function P(E){if(E.h!=0)return!1;for(var y=0;y<E.g.length;y++)if(E.g[y]!=0)return!1;return!0}function C(E){return E.h==-1}r.l=function(E){return E=N(this,E),C(E)?-1:P(E)?0:1};function R(E){for(var y=E.g.length,w=[],T=0;T<y;T++)w[T]=~E.g[T];return new a(w,~E.h).add(g)}r.abs=function(){return C(this)?R(this):this},r.add=function(E){for(var y=Math.max(this.g.length,E.g.length),w=[],T=0,I=0;I<=y;I++){var x=T+(this.i(I)&65535)+(E.i(I)&65535),_=(x>>>16)+(this.i(I)>>>16)+(E.i(I)>>>16);T=_>>>16,x&=65535,_&=65535,w[I]=_<<16|x}return new a(w,w[w.length-1]&-2147483648?-1:0)};function N(E,y){return E.add(R(y))}r.j=function(E){if(P(this)||P(E))return m;if(C(this))return C(E)?R(this).j(R(E)):R(R(this).j(E));if(C(E))return R(this.j(R(E)));if(0>this.l(b)&&0>E.l(b))return h(this.m()*E.m());for(var y=this.g.length+E.g.length,w=[],T=0;T<2*y;T++)w[T]=0;for(T=0;T<this.g.length;T++)for(var I=0;I<E.g.length;I++){var x=this.i(T)>>>16,_=this.i(T)&65535,ft=E.i(I)>>>16,Xn=E.i(I)&65535;w[2*T+2*I]+=_*Xn,F(w,2*T+2*I),w[2*T+2*I+1]+=x*Xn,F(w,2*T+2*I+1),w[2*T+2*I+1]+=_*ft,F(w,2*T+2*I+1),w[2*T+2*I+2]+=x*ft,F(w,2*T+2*I+2)}for(T=0;T<y;T++)w[T]=w[2*T+1]<<16|w[2*T];for(T=y;T<2*y;T++)w[T]=0;return new a(w,0)};function F(E,y){for(;(E[y]&65535)!=E[y];)E[y+1]+=E[y]>>>16,E[y]&=65535,y++}function U(E,y){this.g=E,this.h=y}function G(E,y){if(P(y))throw Error("division by zero");if(P(E))return new U(m,m);if(C(E))return y=G(R(E),y),new U(R(y.g),R(y.h));if(C(y))return y=G(E,R(y)),new U(R(y.g),y.h);if(30<E.g.length){if(C(E)||C(y))throw Error("slowDivide_ only works with positive integers.");for(var w=g,T=y;0>=T.l(E);)w=Y(w),T=Y(T);var I=B(w,1),x=B(T,1);for(T=B(T,2),w=B(w,2);!P(T);){var _=x.add(T);0>=_.l(E)&&(I=I.add(w),x=_),T=B(T,1),w=B(w,1)}return y=N(E,I.j(y)),new U(I,y)}for(I=m;0<=E.l(y);){for(w=Math.max(1,Math.floor(E.m()/y.m())),T=Math.ceil(Math.log(w)/Math.LN2),T=48>=T?1:Math.pow(2,T-48),x=h(w),_=x.j(y);C(_)||0<_.l(E);)w-=T,x=h(w),_=x.j(y);P(x)&&(x=g),I=I.add(x),E=N(E,_)}return new U(I,E)}r.A=function(E){return G(this,E).h},r.and=function(E){for(var y=Math.max(this.g.length,E.g.length),w=[],T=0;T<y;T++)w[T]=this.i(T)&E.i(T);return new a(w,this.h&E.h)},r.or=function(E){for(var y=Math.max(this.g.length,E.g.length),w=[],T=0;T<y;T++)w[T]=this.i(T)|E.i(T);return new a(w,this.h|E.h)},r.xor=function(E){for(var y=Math.max(this.g.length,E.g.length),w=[],T=0;T<y;T++)w[T]=this.i(T)^E.i(T);return new a(w,this.h^E.h)};function Y(E){for(var y=E.g.length+1,w=[],T=0;T<y;T++)w[T]=E.i(T)<<1|E.i(T-1)>>>31;return new a(w,E.h)}function B(E,y){var w=y>>5;y%=32;for(var T=E.g.length-w,I=[],x=0;x<T;x++)I[x]=0<y?E.i(x+w)>>>y|E.i(x+w+1)<<32-y:E.i(x+w);return new a(I,E.h)}n.prototype.digest=n.prototype.v,n.prototype.reset=n.prototype.s,n.prototype.update=n.prototype.u,Uu=Mm.Md5=n,a.prototype.add=a.prototype.add,a.prototype.multiply=a.prototype.j,a.prototype.modulo=a.prototype.A,a.prototype.compare=a.prototype.l,a.prototype.toNumber=a.prototype.m,a.prototype.toString=a.prototype.toString,a.prototype.getBits=a.prototype.i,a.fromNumber=h,a.fromString=f,Et=Mm.Integer=a}).apply(typeof Fm!="undefined"?Fm:typeof self!="undefined"?self:typeof window!="undefined"?window:{});var po=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},It={};var Bu,Jx,hn,$u,xs,mo,qu,zu,Gu;(function(){var r,e=typeof Object.defineProperties=="function"?Object.defineProperty:function(o,l,d){return o==Array.prototype||o==Object.prototype||(o[l]=d.value),o};function t(o){o=[typeof globalThis=="object"&&globalThis,o,typeof window=="object"&&window,typeof self=="object"&&self,typeof po=="object"&&po];for(var l=0;l<o.length;++l){var d=o[l];if(d&&d.Math==Math)return d}throw Error("Cannot find global object")}var n=t(this);function s(o,l){if(l)e:{var d=n;o=o.split(".");for(var p=0;p<o.length-1;p++){var A=o[p];if(!(A in d))break e;d=d[A]}o=o[o.length-1],p=d[o],l=l(p),l!=p&&l!=null&&e(d,o,{configurable:!0,writable:!0,value:l})}}function i(o,l){o instanceof String&&(o+="");var d=0,p=!1,A={next:function(){if(!p&&d<o.length){var S=d++;return{value:l(S,o[S]),done:!1}}return p=!0,{done:!0,value:void 0}}};return A[Symbol.iterator]=function(){return A},A}s("Array.prototype.values",function(o){return o||function(){return i(this,function(l,d){return d})}});var a=a||{},u=this||self;function c(o){var l=typeof o;return l=l!="object"?l:o?Array.isArray(o)?"array":l:"null",l=="array"||l=="object"&&typeof o.length=="number"}function h(o){var l=typeof o;return l=="object"&&o!=null||l=="function"}function f(o,l,d){return o.call.apply(o.bind,arguments)}function m(o,l,d){if(!o)throw Error();if(2<arguments.length){var p=Array.prototype.slice.call(arguments,2);return function(){var A=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(A,p),o.apply(l,A)}}return function(){return o.apply(l,arguments)}}function g(o,l,d){return g=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?f:m,g.apply(null,arguments)}function b(o,l){var d=Array.prototype.slice.call(arguments,1);return function(){var p=d.slice();return p.push.apply(p,arguments),o.apply(this,p)}}function P(o,l){function d(){}d.prototype=l.prototype,o.aa=l.prototype,o.prototype=new d,o.prototype.constructor=o,o.Qb=function(p,A,S){for(var O=Array(arguments.length-2),te=2;te<arguments.length;te++)O[te-2]=arguments[te];return l.prototype[A].apply(p,O)}}function C(o){let l=o.length;if(0<l){let d=Array(l);for(let p=0;p<l;p++)d[p]=o[p];return d}return[]}function R(o,l){for(let d=1;d<arguments.length;d++){let p=arguments[d];if(c(p)){let A=o.length||0,S=p.length||0;o.length=A+S;for(let O=0;O<S;O++)o[A+O]=p[O]}else o.push(p)}}class N{constructor(l,d){this.i=l,this.j=d,this.h=0,this.g=null}get(){let l;return 0<this.h?(this.h--,l=this.g,this.g=l.next,l.next=null):l=this.i(),l}}function F(o){return/^[\s\xa0]*$/.test(o)}function U(){var o=u.navigator;return o&&(o=o.userAgent)?o:""}function G(o){return G[" "](o),o}G[" "]=function(){};var Y=U().indexOf("Gecko")!=-1&&!(U().toLowerCase().indexOf("webkit")!=-1&&U().indexOf("Edge")==-1)&&!(U().indexOf("Trident")!=-1||U().indexOf("MSIE")!=-1)&&U().indexOf("Edge")==-1;function B(o,l,d){for(let p in o)l.call(d,o[p],p,o)}function E(o,l){for(let d in o)l.call(void 0,o[d],d,o)}function y(o){let l={};for(let d in o)l[d]=o[d];return l}let w="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function T(o,l){let d,p;for(let A=1;A<arguments.length;A++){p=arguments[A];for(d in p)o[d]=p[d];for(let S=0;S<w.length;S++)d=w[S],Object.prototype.hasOwnProperty.call(p,d)&&(o[d]=p[d])}}function I(o){var l=1;o=o.split(":");let d=[];for(;0<l&&o.length;)d.push(o.shift()),l--;return o.length&&d.push(o.join(":")),d}function x(o){u.setTimeout(()=>{throw o},0)}function _(){var o=Ua;let l=null;return o.g&&(l=o.g,o.g=o.g.next,o.g||(o.h=null),l.next=null),l}class ft{constructor(){this.h=this.g=null}add(l,d){let p=Xn.get();p.set(l,d),this.h?this.h.next=p:this.g=p,this.h=p}}var Xn=new N(()=>new Rv,o=>o.reset());class Rv{constructor(){this.next=this.g=this.h=null}set(l,d){this.h=l,this.g=d,this.next=null}reset(){this.next=this.g=this.h=null}}let Zn,es=!1,Ua=new ft,Nh=()=>{let o=u.Promise.resolve(void 0);Zn=()=>{o.then(Pv)}};var Pv=()=>{for(var o;o=_();){try{o.h.call(o.g)}catch(d){x(d)}var l=Xn;l.j(o),100>l.h&&(l.h++,o.next=l.g,l.g=o)}es=!1};function Ot(){this.s=this.s,this.C=this.C}Ot.prototype.s=!1,Ot.prototype.ma=function(){this.s||(this.s=!0,this.N())},Ot.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function Te(o,l){this.type=o,this.g=this.target=l,this.defaultPrevented=!1}Te.prototype.h=function(){this.defaultPrevented=!0};var Cv=function(){if(!u.addEventListener||!Object.defineProperty)return!1;var o=!1,l=Object.defineProperty({},"passive",{get:function(){o=!0}});try{let d=()=>{};u.addEventListener("test",d,l),u.removeEventListener("test",d,l)}catch{}return o}();function ts(o,l){if(Te.call(this,o?o.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,o){var d=this.type=o.type,p=o.changedTouches&&o.changedTouches.length?o.changedTouches[0]:null;if(this.target=o.target||o.srcElement,this.g=l,l=o.relatedTarget){if(Y){e:{try{G(l.nodeName);var A=!0;break e}catch{}A=!1}A||(l=null)}}else d=="mouseover"?l=o.fromElement:d=="mouseout"&&(l=o.toElement);this.relatedTarget=l,p?(this.clientX=p.clientX!==void 0?p.clientX:p.pageX,this.clientY=p.clientY!==void 0?p.clientY:p.pageY,this.screenX=p.screenX||0,this.screenY=p.screenY||0):(this.clientX=o.clientX!==void 0?o.clientX:o.pageX,this.clientY=o.clientY!==void 0?o.clientY:o.pageY,this.screenX=o.screenX||0,this.screenY=o.screenY||0),this.button=o.button,this.key=o.key||"",this.ctrlKey=o.ctrlKey,this.altKey=o.altKey,this.shiftKey=o.shiftKey,this.metaKey=o.metaKey,this.pointerId=o.pointerId||0,this.pointerType=typeof o.pointerType=="string"?o.pointerType:kv[o.pointerType]||"",this.state=o.state,this.i=o,o.defaultPrevented&&ts.aa.h.call(this)}}P(ts,Te);var kv={2:"touch",3:"pen",4:"mouse"};ts.prototype.h=function(){ts.aa.h.call(this);var o=this.i;o.preventDefault?o.preventDefault():o.returnValue=!1};var rs="closure_listenable_"+(1e6*Math.random()|0),Dv=0;function Ov(o,l,d,p,A){this.listener=o,this.proxy=null,this.src=l,this.type=d,this.capture=!!p,this.ha=A,this.key=++Dv,this.da=this.fa=!1}function bi(o){o.da=!0,o.listener=null,o.proxy=null,o.src=null,o.ha=null}function Ti(o){this.src=o,this.g={},this.h=0}Ti.prototype.add=function(o,l,d,p,A){var S=o.toString();o=this.g[S],o||(o=this.g[S]=[],this.h++);var O=$a(o,l,p,A);return-1<O?(l=o[O],d||(l.fa=!1)):(l=new Ov(l,this.src,S,!!p,A),l.fa=d,o.push(l)),l};function Ba(o,l){var d=l.type;if(d in o.g){var p=o.g[d],A=Array.prototype.indexOf.call(p,l,void 0),S;(S=0<=A)&&Array.prototype.splice.call(p,A,1),S&&(bi(l),o.g[d].length==0&&(delete o.g[d],o.h--))}}function $a(o,l,d,p){for(var A=0;A<o.length;++A){var S=o[A];if(!S.da&&S.listener==l&&S.capture==!!d&&S.ha==p)return A}return-1}var qa="closure_lm_"+(1e6*Math.random()|0),za={};function Vh(o,l,d,p,A){if(p&&p.once)return Fh(o,l,d,p,A);if(Array.isArray(l)){for(var S=0;S<l.length;S++)Vh(o,l[S],d,p,A);return null}return d=Wa(d),o&&o[rs]?o.K(l,d,h(p)?!!p.capture:!!p,A):Lh(o,l,d,!1,p,A)}function Lh(o,l,d,p,A,S){if(!l)throw Error("Invalid event type");var O=h(A)?!!A.capture:!!A,te=Ka(o);if(te||(o[qa]=te=new Ti(o)),d=te.add(l,d,p,O,S),d.proxy)return d;if(p=Nv(),d.proxy=p,p.src=o,p.listener=d,o.addEventListener)Cv||(A=O),A===void 0&&(A=!1),o.addEventListener(l.toString(),p,A);else if(o.attachEvent)o.attachEvent(jh(l.toString()),p);else if(o.addListener&&o.removeListener)o.addListener(p);else throw Error("addEventListener and attachEvent are unavailable.");return d}function Nv(){function o(d){return l.call(o.src,o.listener,d)}let l=Vv;return o}function Fh(o,l,d,p,A){if(Array.isArray(l)){for(var S=0;S<l.length;S++)Fh(o,l[S],d,p,A);return null}return d=Wa(d),o&&o[rs]?o.L(l,d,h(p)?!!p.capture:!!p,A):Lh(o,l,d,!0,p,A)}function Mh(o,l,d,p,A){if(Array.isArray(l))for(var S=0;S<l.length;S++)Mh(o,l[S],d,p,A);else p=h(p)?!!p.capture:!!p,d=Wa(d),o&&o[rs]?(o=o.i,l=String(l).toString(),l in o.g&&(S=o.g[l],d=$a(S,d,p,A),-1<d&&(bi(S[d]),Array.prototype.splice.call(S,d,1),S.length==0&&(delete o.g[l],o.h--)))):o&&(o=Ka(o))&&(l=o.g[l.toString()],o=-1,l&&(o=$a(l,d,p,A)),(d=-1<o?l[o]:null)&&Ga(d))}function Ga(o){if(typeof o!="number"&&o&&!o.da){var l=o.src;if(l&&l[rs])Ba(l.i,o);else{var d=o.type,p=o.proxy;l.removeEventListener?l.removeEventListener(d,p,o.capture):l.detachEvent?l.detachEvent(jh(d),p):l.addListener&&l.removeListener&&l.removeListener(p),(d=Ka(l))?(Ba(d,o),d.h==0&&(d.src=null,l[qa]=null)):bi(o)}}}function jh(o){return o in za?za[o]:za[o]="on"+o}function Vv(o,l){if(o.da)o=!0;else{l=new ts(l,this);var d=o.listener,p=o.ha||o.src;o.fa&&Ga(o),o=d.call(p,l)}return o}function Ka(o){return o=o[qa],o instanceof Ti?o:null}var Ha="__closure_events_fn_"+(1e9*Math.random()>>>0);function Wa(o){return typeof o=="function"?o:(o[Ha]||(o[Ha]=function(l){return o.handleEvent(l)}),o[Ha])}function Ee(){Ot.call(this),this.i=new Ti(this),this.M=this,this.F=null}P(Ee,Ot),Ee.prototype[rs]=!0,Ee.prototype.removeEventListener=function(o,l,d,p){Mh(this,o,l,d,p)};function Pe(o,l){var d,p=o.F;if(p)for(d=[];p;p=p.F)d.push(p);if(o=o.M,p=l.type||l,typeof l=="string")l=new Te(l,o);else if(l instanceof Te)l.target=l.target||o;else{var A=l;l=new Te(p,o),T(l,A)}if(A=!0,d)for(var S=d.length-1;0<=S;S--){var O=l.g=d[S];A=Ei(O,p,!0,l)&&A}if(O=l.g=o,A=Ei(O,p,!0,l)&&A,A=Ei(O,p,!1,l)&&A,d)for(S=0;S<d.length;S++)O=l.g=d[S],A=Ei(O,p,!1,l)&&A}Ee.prototype.N=function(){if(Ee.aa.N.call(this),this.i){var o=this.i,l;for(l in o.g){for(var d=o.g[l],p=0;p<d.length;p++)bi(d[p]);delete o.g[l],o.h--}}this.F=null},Ee.prototype.K=function(o,l,d,p){return this.i.add(String(o),l,!1,d,p)},Ee.prototype.L=function(o,l,d,p){return this.i.add(String(o),l,!0,d,p)};function Ei(o,l,d,p){if(l=o.i.g[String(l)],!l)return!0;l=l.concat();for(var A=!0,S=0;S<l.length;++S){var O=l[S];if(O&&!O.da&&O.capture==d){var te=O.listener,ve=O.ha||O.src;O.fa&&Ba(o.i,O),A=te.call(ve,p)!==!1&&A}}return A&&!p.defaultPrevented}function Uh(o,l,d){if(typeof o=="function")d&&(o=g(o,d));else if(o&&typeof o.handleEvent=="function")o=g(o.handleEvent,o);else throw Error("Invalid listener argument");return 2147483647<Number(l)?-1:u.setTimeout(o,l||0)}function Bh(o){o.g=Uh(()=>{o.g=null,o.i&&(o.i=!1,Bh(o))},o.l);let l=o.h;o.h=null,o.m.apply(null,l)}class Lv extends Ot{constructor(l,d){super(),this.m=l,this.l=d,this.h=null,this.i=!1,this.g=null}j(l){this.h=arguments,this.g?this.i=!0:Bh(this)}N(){super.N(),this.g&&(u.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function ns(o){Ot.call(this),this.h=o,this.g={}}P(ns,Ot);var $h=[];function qh(o){B(o.g,function(l,d){this.g.hasOwnProperty(d)&&Ga(l)},o),o.g={}}ns.prototype.N=function(){ns.aa.N.call(this),qh(this)},ns.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var Qa=u.JSON.stringify,Fv=u.JSON.parse,Mv=class{stringify(o){return u.JSON.stringify(o,void 0)}parse(o){return u.JSON.parse(o,void 0)}};function Ja(){}Ja.prototype.h=null;function zh(o){return o.h||(o.h=o.i())}function Gh(){}var ss={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function Ya(){Te.call(this,"d")}P(Ya,Te);function Xa(){Te.call(this,"c")}P(Xa,Te);var ar={},Kh=null;function Ii(){return Kh=Kh||new Ee}ar.La="serverreachability";function Hh(o){Te.call(this,ar.La,o)}P(Hh,Te);function is(o){let l=Ii();Pe(l,new Hh(l))}ar.STAT_EVENT="statevent";function Wh(o,l){Te.call(this,ar.STAT_EVENT,o),this.stat=l}P(Wh,Te);function Ce(o){let l=Ii();Pe(l,new Wh(l,o))}ar.Ma="timingevent";function Qh(o,l){Te.call(this,ar.Ma,o),this.size=l}P(Qh,Te);function os(o,l){if(typeof o!="function")throw Error("Fn must not be null and must be a function");return u.setTimeout(function(){o()},l)}function as(){this.g=!0}as.prototype.xa=function(){this.g=!1};function jv(o,l,d,p,A,S){o.info(function(){if(o.g)if(S)for(var O="",te=S.split("&"),ve=0;ve<te.length;ve++){var X=te[ve].split("=");if(1<X.length){var Ie=X[0];X=X[1];var Ae=Ie.split("_");O=2<=Ae.length&&Ae[1]=="type"?O+(Ie+"="+X+"&"):O+(Ie+"=redacted&")}}else O=null;else O=S;return"XMLHTTP REQ ("+p+") [attempt "+A+"]: "+l+`
1
+ var uw=Object.create;var Fi=Object.defineProperty;var cw=Object.getOwnPropertyDescriptor;var lw=Object.getOwnPropertyNames;var hw=Object.getPrototypeOf,dw=Object.prototype.hasOwnProperty;var fw=(r,e)=>()=>(r&&(e=r(r=0)),e);var Me=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),pw=(r,e)=>{for(var t in e)Fi(r,t,{get:e[t],enumerable:!0})},Vd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lw(e))!dw.call(r,s)&&s!==t&&Fi(r,s,{get:()=>e[s],enumerable:!(n=cw(e,s))||n.enumerable});return r};var hu=(r,e,t)=>(t=r!=null?uw(hw(r)):{},Vd(e||!r||!r.__esModule?Fi(t,"default",{value:r,enumerable:!0}):t,r)),mw=r=>Vd(Fi({},"__esModule",{value:!0}),r);var Ir={};pw(Ir,{Headers:()=>ih,Request:()=>rP,Response:()=>nP,default:()=>sh,fetch:()=>tP});var eP,jn,tP,sh,ih,rP,nP,sr=fw(()=>{"use strict";eP=function(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;throw new Error("unable to locate global object")},jn=eP(),tP=jn.fetch,sh=jn.fetch.bind(jn),ih=jn.Headers,rP=jn.Request,nP=jn.Response});var uh=Me(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var oh=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};ah.default=oh});var lh=Me(Ys=>{"use strict";var Zy=Ys&&Ys.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ys,"__esModule",{value:!0});var iP=Zy((sr(),mw(Ir))),oP=Zy(uh()),ch=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch=="undefined"?this.fetch=iP.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=Object.assign({},this.headers),this.headers[e]=t,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let n=this.fetch,s=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var a,u,c;let h=null,f=null,m=null,g=i.status,b=i.statusText;if(i.ok){if(this.method!=="HEAD"){let N=await i.text();N===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?f=N:f=JSON.parse(N))}let C=(a=this.headers.Prefer)===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),R=(u=i.headers.get("content-range"))===null||u===void 0?void 0:u.split("/");C&&R&&R.length>1&&(m=parseInt(R[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(f)&&(f.length>1?(h={code:"PGRST116",details:`Results contain ${f.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},f=null,m=null,g=406,b="Not Acceptable"):f.length===1?f=f[0]:f=null)}else{let C=await i.text();try{h=JSON.parse(C),Array.isArray(h)&&i.status===404&&(f=[],h=null,g=200,b="OK")}catch{i.status===404&&C===""?(g=204,b="No Content"):h={message:C}}if(h&&this.isMaybeSingle&&(!((c=h==null?void 0:h.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,g=200,b="OK"),h&&this.shouldThrowOnError)throw new oP.default(h)}return{error:h,data:f,count:m,status:g,statusText:b}});return this.shouldThrowOnError||(s=s.catch(i=>{var a,u,c;return{error:{message:`${(a=i==null?void 0:i.name)!==null&&a!==void 0?a:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(u=i==null?void 0:i.stack)!==null&&u!==void 0?u:""}`,hint:"",code:`${(c=i==null?void 0:i.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}returns(){return this}overrideTypes(){return this}};Ys.default=ch});var dh=Me(Xs=>{"use strict";var aP=Xs&&Xs.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xs,"__esModule",{value:!0});var uP=aP(lh()),hh=class extends uP.default{select(e){let t=!1,n=(e!=null?e:"*").split("").map(s=>/\s/.test(s)&&!t?"":(s==='"'&&(t=!t),s)).join("");return this.url.searchParams.set("select",n),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:s,referencedTable:i=s}={}){let a=i?`${i}.order`:"order",u=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${u?`${u},`:""}${e}.${t?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){let s=typeof n=="undefined"?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:s=n}={}){let i=typeof s=="undefined"?"offset":`${s}.offset`,a=typeof s=="undefined"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:s=!1,wal:i=!1,format:a="text"}={}){var u;let c=[e?"analyze":null,t?"verbose":null,n?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),h=(u=this.headers.Accept)!==null&&u!==void 0?u:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${a}; for="${h}"; options=${c};`,a==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};Xs.default=hh});var va=Me(Zs=>{"use strict";var cP=Zs&&Zs.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Zs,"__esModule",{value:!0});var lP=cP(dh()),fh=class extends lP.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let n=Array.from(new Set(t)).map(s=>typeof s=="string"&&new RegExp("[,()]").test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(e,`in.(${n})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:n,type:s}={}){let i="";s==="plain"?i="pl":s==="phrase"?i="ph":s==="websearch"&&(i="w");let a=n===void 0?"":`(${n})`;return this.url.searchParams.append(e,`${i}fts${a}.${t}`),this}match(e){return Object.entries(e).forEach(([t,n])=>{this.url.searchParams.append(t,`eq.${n}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){let s=n?`${n}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}};Zs.default=fh});var mh=Me(ti=>{"use strict";var hP=ti&&ti.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ti,"__esModule",{value:!0});var ei=hP(va()),ph=class{constructor(e,{headers:t={},schema:n,fetch:s}){this.url=e,this.headers=t,this.schema=n,this.fetch=s}select(e,{head:t=!1,count:n}={}){let s=t?"HEAD":"GET",i=!1,a=(e!=null?e:"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join("");return this.url.searchParams.set("select",a),n&&(this.headers.Prefer=`count=${n}`),new ei.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:n=!0}={}){let s="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),n||i.push("missing=default"),this.headers.Prefer=i.join(","),Array.isArray(e)){let a=e.reduce((u,c)=>u.concat(Object.keys(c)),[]);if(a.length>0){let u=[...new Set(a)].map(c=>`"${c}"`);this.url.searchParams.set("columns",u.join(","))}}return new ei.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:s,defaultToNull:i=!0}={}){let a="POST",u=[`resolution=${n?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&u.push(this.headers.Prefer),s&&u.push(`count=${s}`),i||u.push("missing=default"),this.headers.Prefer=u.join(","),Array.isArray(e)){let c=e.reduce((h,f)=>h.concat(Object.keys(f)),[]);if(c.length>0){let h=[...new Set(c)].map(f=>`"${f}"`);this.url.searchParams.set("columns",h.join(","))}}return new ei.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let n="PATCH",s=[];return this.headers.Prefer&&s.push(this.headers.Prefer),t&&s.push(`count=${t}`),this.headers.Prefer=s.join(","),new ei.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",n=[];return e&&n.push(`count=${e}`),this.headers.Prefer&&n.unshift(this.headers.Prefer),this.headers.Prefer=n.join(","),new ei.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ti.default=ph});var e_=Me(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.version=void 0;wa.version="0.0.0-automated"});var t_=Me(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.DEFAULT_HEADERS=void 0;var dP=e_();ba.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${dP.version}`}});var n_=Me(ri=>{"use strict";var r_=ri&&ri.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ri,"__esModule",{value:!0});var fP=r_(mh()),pP=r_(va()),mP=t_(),gh=class r{constructor(e,{headers:t={},schema:n,fetch:s}={}){this.url=e,this.headers=Object.assign(Object.assign({},mP.DEFAULT_HEADERS),t),this.schemaName=n,this.fetch=s}from(e){let t=new URL(`${this.url}/${e}`);return new fP.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:n=!1,get:s=!1,count:i}={}){let a,u=new URL(`${this.url}/rpc/${e}`),c;n||s?(a=n?"HEAD":"GET",Object.entries(t).filter(([f,m])=>m!==void 0).map(([f,m])=>[f,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([f,m])=>{u.searchParams.append(f,m)})):(a="POST",c=t);let h=Object.assign({},this.headers);return i&&(h.Prefer=`count=${i}`),new pP.default({method:a,url:u,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};ri.default=gh});var l_=Me(be=>{"use strict";var Un=be&&be.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(be,"__esModule",{value:!0});be.PostgrestError=be.PostgrestBuilder=be.PostgrestTransformBuilder=be.PostgrestFilterBuilder=be.PostgrestQueryBuilder=be.PostgrestClient=void 0;var s_=Un(n_());be.PostgrestClient=s_.default;var i_=Un(mh());be.PostgrestQueryBuilder=i_.default;var o_=Un(va());be.PostgrestFilterBuilder=o_.default;var a_=Un(dh());be.PostgrestTransformBuilder=a_.default;var u_=Un(lh());be.PostgrestBuilder=u_.default;var c_=Un(uh());be.PostgrestError=c_.default;be.default={PostgrestClient:s_.default,PostgrestQueryBuilder:i_.default,PostgrestFilterBuilder:o_.default,PostgrestTransformBuilder:a_.default,PostgrestBuilder:u_.default,PostgrestError:c_.default}});var v_=Me((V2,__)=>{"use strict";__.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var hv=Me((kU,lv)=>{function Ge(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}lv.exports=Ge;Ge.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Ge.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Ge.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};Ge.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Ge.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Ge.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Ge.prototype.start=Ge.prototype.try;Ge.prototype.errors=function(){return this._errors};Ge.prototype.attempts=function(){return this._attempts};Ge.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var s=this._errors[n],i=s.message,a=(r[i]||0)+1;r[i]=a,a>=t&&(e=s,t=a)}return e}});var dv=Me(jr=>{var eC=hv();jr.operation=function(r){var e=jr.timeouts(r);return new eC(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};jr.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<e.retries;s++)n.push(this.createTimeout(s,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(s,e)),n.sort(function(i,a){return i-a}),n};jr.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};jr.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var s=0;s<t.length;s++){var i=t[s],a=r[i];r[i]=function(c){var h=jr.operation(e),f=Array.prototype.slice.call(arguments,1),m=f.pop();f.push(function(g){h.retry(g)||(g&&(arguments[0]=h.mainError()),m.apply(this,arguments))}),h.attempt(function(){c.apply(r,f)})}.bind(r,a),r[i].options=e}}});var pv=Me((OU,fv)=>{fv.exports=dv()});var gw=typeof global=="object"&&global&&global.Object===Object&&global,Mi=gw;var yw=typeof self=="object"&&self&&self.Object===Object&&self,_w=Mi||yw||Function("return this")(),ue=_w;var vw=ue.Symbol,ke=vw;var Ld=Object.prototype,ww=Ld.hasOwnProperty,bw=Ld.toString,ys=ke?ke.toStringTag:void 0;function Tw(r){var e=ww.call(r,ys),t=r[ys];try{r[ys]=void 0;var n=!0}catch{}var s=bw.call(r);return n&&(e?r[ys]=t:delete r[ys]),s}var Fd=Tw;var Ew=Object.prototype,Iw=Ew.toString;function Aw(r){return Iw.call(r)}var Md=Aw;var xw="[object Null]",Sw="[object Undefined]",jd=ke?ke.toStringTag:void 0;function Rw(r){return r==null?r===void 0?Sw:xw:jd&&jd in Object(r)?Fd(r):Md(r)}var He=Rw;function Pw(r){return r!=null&&typeof r=="object"}var De=Pw;var Cw="[object Symbol]";function kw(r){return typeof r=="symbol"||De(r)&&He(r)==Cw}var Ft=kw;function Dw(r,e){for(var t=-1,n=r==null?0:r.length,s=Array(n);++t<n;)s[t]=e(r[t],t,r);return s}var Ud=Dw;var Ow=Array.isArray,le=Ow;var Nw=1/0,Bd=ke?ke.prototype:void 0,$d=Bd?Bd.toString:void 0;function qd(r){if(typeof r=="string")return r;if(le(r))return Ud(r,qd)+"";if(Ft(r))return $d?$d.call(r):"";var e=r+"";return e=="0"&&1/r==-Nw?"-0":e}var zd=qd;var Vw=/\s/;function Lw(r){for(var e=r.length;e--&&Vw.test(r.charAt(e)););return e}var Gd=Lw;var Fw=/^\s+/;function Mw(r){return r&&r.slice(0,Gd(r)+1).replace(Fw,"")}var Kd=Mw;function jw(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Z=jw;var Hd=NaN,Uw=/^[-+]0x[0-9a-f]+$/i,Bw=/^0b[01]+$/i,$w=/^0o[0-7]+$/i,qw=parseInt;function zw(r){if(typeof r=="number")return r;if(Ft(r))return Hd;if(Z(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Z(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=Kd(r);var t=Bw.test(r);return t||$w.test(r)?qw(r.slice(2),t?2:8):Uw.test(r)?Hd:+r}var du=zw;function Gw(r){return r}var zr=Gw;var Kw="[object AsyncFunction]",Hw="[object Function]",Ww="[object GeneratorFunction]",Qw="[object Proxy]";function Jw(r){if(!Z(r))return!1;var e=He(r);return e==Hw||e==Ww||e==Kw||e==Qw}var ji=Jw;var Yw=ue["__core-js_shared__"],Ui=Yw;var Wd=function(){var r=/[^.]+$/.exec(Ui&&Ui.keys&&Ui.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function Xw(r){return!!Wd&&Wd in r}var Qd=Xw;var Zw=Function.prototype,eb=Zw.toString;function tb(r){if(r!=null){try{return eb.call(r)}catch{}try{return r+""}catch{}}return""}var gt=tb;var rb=/[\\^$.*+?()[\]{}|]/g,nb=/^\[object .+?Constructor\]$/,sb=Function.prototype,ib=Object.prototype,ob=sb.toString,ab=ib.hasOwnProperty,ub=RegExp("^"+ob.call(ab).replace(rb,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function cb(r){if(!Z(r)||Qd(r))return!1;var e=ji(r)?ub:nb;return e.test(gt(r))}var Jd=cb;function lb(r,e){return r==null?void 0:r[e]}var Yd=lb;function hb(r,e){var t=Yd(r,e);return Jd(t)?t:void 0}var Oe=hb;var db=Oe(ue,"WeakMap"),Bi=db;var Xd=Object.create,fb=function(){function r(){}return function(e){if(!Z(e))return{};if(Xd)return Xd(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}}(),Zd=fb;function pb(r,e,t){switch(t.length){case 0:return r.call(e);case 1:return r.call(e,t[0]);case 2:return r.call(e,t[0],t[1]);case 3:return r.call(e,t[0],t[1],t[2])}return r.apply(e,t)}var ef=pb;function mb(r,e){var t=-1,n=r.length;for(e||(e=Array(n));++t<n;)e[t]=r[t];return e}var tf=mb;var gb=800,yb=16,_b=Date.now;function vb(r){var e=0,t=0;return function(){var n=_b(),s=yb-(n-t);if(t=n,s>0){if(++e>=gb)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}var rf=vb;function wb(r){return function(){return r}}var nf=wb;var bb=function(){try{var r=Oe(Object,"defineProperty");return r({},"",{}),r}catch{}}(),Gr=bb;var Tb=Gr?function(r,e){return Gr(r,"toString",{configurable:!0,enumerable:!1,value:nf(e),writable:!0})}:zr,sf=Tb;var Eb=rf(sf),of=Eb;function Ib(r,e){for(var t=-1,n=r==null?0:r.length;++t<n&&e(r[t],t,r)!==!1;);return r}var af=Ib;var Ab=9007199254740991,xb=/^(?:0|[1-9]\d*)$/;function Sb(r,e){var t=typeof r;return e=e==null?Ab:e,!!e&&(t=="number"||t!="symbol"&&xb.test(r))&&r>-1&&r%1==0&&r<e}var Mt=Sb;function Rb(r,e,t){e=="__proto__"&&Gr?Gr(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}var Kr=Rb;function Pb(r,e){return r===e||r!==r&&e!==e}var Xe=Pb;var Cb=Object.prototype,kb=Cb.hasOwnProperty;function Db(r,e,t){var n=r[e];(!(kb.call(r,e)&&Xe(n,t))||t===void 0&&!(e in r))&&Kr(r,e,t)}var Hr=Db;function Ob(r,e,t,n){var s=!t;t||(t={});for(var i=-1,a=e.length;++i<a;){var u=e[i],c=n?n(t[u],r[u],u,t,r):void 0;c===void 0&&(c=r[u]),s?Kr(t,u,c):Hr(t,u,c)}return t}var jt=Ob;var uf=Math.max;function Nb(r,e,t){return e=uf(e===void 0?r.length-1:e,0),function(){for(var n=arguments,s=-1,i=uf(n.length-e,0),a=Array(i);++s<i;)a[s]=n[e+s];s=-1;for(var u=Array(e+1);++s<e;)u[s]=n[s];return u[e]=t(a),ef(r,this,u)}}var cf=Nb;function Vb(r,e){return of(cf(r,e,zr),r+"")}var lf=Vb;var Lb=9007199254740991;function Fb(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Lb}var Wr=Fb;function Mb(r){return r!=null&&Wr(r.length)&&!ji(r)}var Ut=Mb;function jb(r,e,t){if(!Z(t))return!1;var n=typeof e;return(n=="number"?Ut(t)&&Mt(e,t.length):n=="string"&&e in t)?Xe(t[e],r):!1}var hf=jb;var Ub=Object.prototype;function Bb(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Ub;return r===t}var Bt=Bb;function $b(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}var df=$b;var qb="[object Arguments]";function zb(r){return De(r)&&He(r)==qb}var fu=zb;var ff=Object.prototype,Gb=ff.hasOwnProperty,Kb=ff.propertyIsEnumerable,Hb=fu(function(){return arguments}())?fu:function(r){return De(r)&&Gb.call(r,"callee")&&!Kb.call(r,"callee")},Qr=Hb;function Wb(){return!1}var pf=Wb;var yf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,mf=yf&&typeof module=="object"&&module&&!module.nodeType&&module,Qb=mf&&mf.exports===yf,gf=Qb?ue.Buffer:void 0,Jb=gf?gf.isBuffer:void 0,Yb=Jb||pf,yt=Yb;var Xb="[object Arguments]",Zb="[object Array]",eT="[object Boolean]",tT="[object Date]",rT="[object Error]",nT="[object Function]",sT="[object Map]",iT="[object Number]",oT="[object Object]",aT="[object RegExp]",uT="[object Set]",cT="[object String]",lT="[object WeakMap]",hT="[object ArrayBuffer]",dT="[object DataView]",fT="[object Float32Array]",pT="[object Float64Array]",mT="[object Int8Array]",gT="[object Int16Array]",yT="[object Int32Array]",_T="[object Uint8Array]",vT="[object Uint8ClampedArray]",wT="[object Uint16Array]",bT="[object Uint32Array]",ie={};ie[fT]=ie[pT]=ie[mT]=ie[gT]=ie[yT]=ie[_T]=ie[vT]=ie[wT]=ie[bT]=!0;ie[Xb]=ie[Zb]=ie[hT]=ie[eT]=ie[dT]=ie[tT]=ie[rT]=ie[nT]=ie[sT]=ie[iT]=ie[oT]=ie[aT]=ie[uT]=ie[cT]=ie[lT]=!1;function TT(r){return De(r)&&Wr(r.length)&&!!ie[He(r)]}var _f=TT;function ET(r){return function(e){return r(e)}}var Jr=ET;var vf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,_s=vf&&typeof module=="object"&&module&&!module.nodeType&&module,IT=_s&&_s.exports===vf,pu=IT&&Mi.process,AT=function(){try{var r=_s&&_s.require&&_s.require("util").types;return r||pu&&pu.binding&&pu.binding("util")}catch{}}(),_t=AT;var wf=_t&&_t.isTypedArray,xT=wf?Jr(wf):_f,Yr=xT;var ST=Object.prototype,RT=ST.hasOwnProperty;function PT(r,e){var t=le(r),n=!t&&Qr(r),s=!t&&!n&&yt(r),i=!t&&!n&&!s&&Yr(r),a=t||n||s||i,u=a?df(r.length,String):[],c=u.length;for(var h in r)(e||RT.call(r,h))&&!(a&&(h=="length"||s&&(h=="offset"||h=="parent")||i&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||Mt(h,c)))&&u.push(h);return u}var $i=PT;function CT(r,e){return function(t){return r(e(t))}}var qi=CT;var kT=qi(Object.keys,Object),bf=kT;var DT=Object.prototype,OT=DT.hasOwnProperty;function NT(r){if(!Bt(r))return bf(r);var e=[];for(var t in Object(r))OT.call(r,t)&&t!="constructor"&&e.push(t);return e}var zi=NT;function VT(r){return Ut(r)?$i(r):zi(r)}var xe=VT;function LT(r){var e=[];if(r!=null)for(var t in Object(r))e.push(t);return e}var Tf=LT;var FT=Object.prototype,MT=FT.hasOwnProperty;function jT(r){if(!Z(r))return Tf(r);var e=Bt(r),t=[];for(var n in r)n=="constructor"&&(e||!MT.call(r,n))||t.push(n);return t}var Ef=jT;function UT(r){return Ut(r)?$i(r,!0):Ef(r)}var $t=UT;var BT=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,$T=/^\w*$/;function qT(r,e){if(le(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Ft(r)?!0:$T.test(r)||!BT.test(r)||e!=null&&r in Object(e)}var Xr=qT;var zT=Oe(Object,"create"),vt=zT;function GT(){this.__data__=vt?vt(null):{},this.size=0}var If=GT;function KT(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Af=KT;var HT="__lodash_hash_undefined__",WT=Object.prototype,QT=WT.hasOwnProperty;function JT(r){var e=this.__data__;if(vt){var t=e[r];return t===HT?void 0:t}return QT.call(e,r)?e[r]:void 0}var xf=JT;var YT=Object.prototype,XT=YT.hasOwnProperty;function ZT(r){var e=this.__data__;return vt?e[r]!==void 0:XT.call(e,r)}var Sf=ZT;var e0="__lodash_hash_undefined__";function t0(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=vt&&e===void 0?e0:e,this}var Rf=t0;function Zr(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}Zr.prototype.clear=If;Zr.prototype.delete=Af;Zr.prototype.get=xf;Zr.prototype.has=Sf;Zr.prototype.set=Rf;var mu=Zr;function r0(){this.__data__=[],this.size=0}var Pf=r0;function n0(r,e){for(var t=r.length;t--;)if(Xe(r[t][0],e))return t;return-1}var qt=n0;var s0=Array.prototype,i0=s0.splice;function o0(r){var e=this.__data__,t=qt(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():i0.call(e,t,1),--this.size,!0}var Cf=o0;function a0(r){var e=this.__data__,t=qt(e,r);return t<0?void 0:e[t][1]}var kf=a0;function u0(r){return qt(this.__data__,r)>-1}var Df=u0;function c0(r,e){var t=this.__data__,n=qt(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}var Of=c0;function en(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}en.prototype.clear=Pf;en.prototype.delete=Cf;en.prototype.get=kf;en.prototype.has=Df;en.prototype.set=Of;var zt=en;var l0=Oe(ue,"Map"),Gt=l0;function h0(){this.size=0,this.__data__={hash:new mu,map:new(Gt||zt),string:new mu}}var Nf=h0;function d0(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var Vf=d0;function f0(r,e){var t=r.__data__;return Vf(e)?t[typeof e=="string"?"string":"hash"]:t.map}var Kt=f0;function p0(r){var e=Kt(this,r).delete(r);return this.size-=e?1:0,e}var Lf=p0;function m0(r){return Kt(this,r).get(r)}var Ff=m0;function g0(r){return Kt(this,r).has(r)}var Mf=g0;function y0(r,e){var t=Kt(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}var jf=y0;function tn(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}tn.prototype.clear=Nf;tn.prototype.delete=Lf;tn.prototype.get=Ff;tn.prototype.has=Mf;tn.prototype.set=jf;var hr=tn;var _0="Expected a function";function gu(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(_0);var t=function(){var n=arguments,s=e?e.apply(this,n):n[0],i=t.cache;if(i.has(s))return i.get(s);var a=r.apply(this,n);return t.cache=i.set(s,a)||i,a};return t.cache=new(gu.Cache||hr),t}gu.Cache=hr;var Uf=gu;var v0=500;function w0(r){var e=Uf(r,function(n){return t.size===v0&&t.clear(),n}),t=e.cache;return e}var Bf=w0;var b0=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,T0=/\\(\\)?/g,E0=Bf(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(b0,function(t,n,s,i){e.push(s?i.replace(T0,"$1"):n||t)}),e}),$f=E0;function I0(r){return r==null?"":zd(r)}var qf=I0;function A0(r,e){return le(r)?r:Xr(r,e)?[r]:$f(qf(r))}var rn=A0;var x0=1/0;function S0(r){if(typeof r=="string"||Ft(r))return r;var e=r+"";return e=="0"&&1/r==-x0?"-0":e}var Ze=S0;function R0(r,e){e=rn(e,r);for(var t=0,n=e.length;r!=null&&t<n;)r=r[Ze(e[t++])];return t&&t==n?r:void 0}var Gi=R0;function P0(r,e,t){var n=r==null?void 0:Gi(r,e);return n===void 0?t:n}var vs=P0;function C0(r,e){for(var t=-1,n=e.length,s=r.length;++t<n;)r[s+t]=e[t];return r}var Ki=C0;var k0=qi(Object.getPrototypeOf,Object),Hi=k0;function D0(){this.__data__=new zt,this.size=0}var zf=D0;function O0(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}var Gf=O0;function N0(r){return this.__data__.get(r)}var Kf=N0;function V0(r){return this.__data__.has(r)}var Hf=V0;var L0=200;function F0(r,e){var t=this.__data__;if(t instanceof zt){var n=t.__data__;if(!Gt||n.length<L0-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new hr(n)}return t.set(r,e),this.size=t.size,this}var Wf=F0;function nn(r){var e=this.__data__=new zt(r);this.size=e.size}nn.prototype.clear=zf;nn.prototype.delete=Gf;nn.prototype.get=Kf;nn.prototype.has=Hf;nn.prototype.set=Wf;var Ht=nn;function M0(r,e){return r&&jt(e,xe(e),r)}var Qf=M0;function j0(r,e){return r&&jt(e,$t(e),r)}var Jf=j0;var ep=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Yf=ep&&typeof module=="object"&&module&&!module.nodeType&&module,U0=Yf&&Yf.exports===ep,Xf=U0?ue.Buffer:void 0,Zf=Xf?Xf.allocUnsafe:void 0;function B0(r,e){if(e)return r.slice();var t=r.length,n=Zf?Zf(t):new r.constructor(t);return r.copy(n),n}var tp=B0;function $0(r,e){for(var t=-1,n=r==null?0:r.length,s=0,i=[];++t<n;){var a=r[t];e(a,t,r)&&(i[s++]=a)}return i}var rp=$0;function q0(){return[]}var Wi=q0;var z0=Object.prototype,G0=z0.propertyIsEnumerable,np=Object.getOwnPropertySymbols,K0=np?function(r){return r==null?[]:(r=Object(r),rp(np(r),function(e){return G0.call(r,e)}))}:Wi,sn=K0;function H0(r,e){return jt(r,sn(r),e)}var sp=H0;var W0=Object.getOwnPropertySymbols,Q0=W0?function(r){for(var e=[];r;)Ki(e,sn(r)),r=Hi(r);return e}:Wi,Qi=Q0;function J0(r,e){return jt(r,Qi(r),e)}var ip=J0;function Y0(r,e,t){var n=e(r);return le(r)?n:Ki(n,t(r))}var Ji=Y0;function X0(r){return Ji(r,xe,sn)}var ws=X0;function Z0(r){return Ji(r,$t,Qi)}var op=Z0;var eE=Oe(ue,"DataView"),Yi=eE;var tE=Oe(ue,"Promise"),Xi=tE;var rE=Oe(ue,"Set"),Zi=rE;var ap="[object Map]",nE="[object Object]",up="[object Promise]",cp="[object Set]",lp="[object WeakMap]",hp="[object DataView]",sE=gt(Yi),iE=gt(Gt),oE=gt(Xi),aE=gt(Zi),uE=gt(Bi),dr=He;(Yi&&dr(new Yi(new ArrayBuffer(1)))!=hp||Gt&&dr(new Gt)!=ap||Xi&&dr(Xi.resolve())!=up||Zi&&dr(new Zi)!=cp||Bi&&dr(new Bi)!=lp)&&(dr=function(r){var e=He(r),t=e==nE?r.constructor:void 0,n=t?gt(t):"";if(n)switch(n){case sE:return hp;case iE:return ap;case oE:return up;case aE:return cp;case uE:return lp}return e});var We=dr;var cE=Object.prototype,lE=cE.hasOwnProperty;function hE(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&lE.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var dp=hE;var dE=ue.Uint8Array,on=dE;function fE(r){var e=new r.constructor(r.byteLength);return new on(e).set(new on(r)),e}var an=fE;function pE(r,e){var t=e?an(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.byteLength)}var fp=pE;var mE=/\w*$/;function gE(r){var e=new r.constructor(r.source,mE.exec(r));return e.lastIndex=r.lastIndex,e}var pp=gE;var mp=ke?ke.prototype:void 0,gp=mp?mp.valueOf:void 0;function yE(r){return gp?Object(gp.call(r)):{}}var yp=yE;function _E(r,e){var t=e?an(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.length)}var _p=_E;var vE="[object Boolean]",wE="[object Date]",bE="[object Map]",TE="[object Number]",EE="[object RegExp]",IE="[object Set]",AE="[object String]",xE="[object Symbol]",SE="[object ArrayBuffer]",RE="[object DataView]",PE="[object Float32Array]",CE="[object Float64Array]",kE="[object Int8Array]",DE="[object Int16Array]",OE="[object Int32Array]",NE="[object Uint8Array]",VE="[object Uint8ClampedArray]",LE="[object Uint16Array]",FE="[object Uint32Array]";function ME(r,e,t){var n=r.constructor;switch(e){case SE:return an(r);case vE:case wE:return new n(+r);case RE:return fp(r,t);case PE:case CE:case kE:case DE:case OE:case NE:case VE:case LE:case FE:return _p(r,t);case bE:return new n;case TE:case AE:return new n(r);case EE:return pp(r);case IE:return new n;case xE:return yp(r)}}var vp=ME;function jE(r){return typeof r.constructor=="function"&&!Bt(r)?Zd(Hi(r)):{}}var wp=jE;var UE="[object Map]";function BE(r){return De(r)&&We(r)==UE}var bp=BE;var Tp=_t&&_t.isMap,$E=Tp?Jr(Tp):bp,Ep=$E;var qE="[object Set]";function zE(r){return De(r)&&We(r)==qE}var Ip=zE;var Ap=_t&&_t.isSet,GE=Ap?Jr(Ap):Ip,xp=GE;var KE=1,HE=2,WE=4,Sp="[object Arguments]",QE="[object Array]",JE="[object Boolean]",YE="[object Date]",XE="[object Error]",Rp="[object Function]",ZE="[object GeneratorFunction]",eI="[object Map]",tI="[object Number]",Pp="[object Object]",rI="[object RegExp]",nI="[object Set]",sI="[object String]",iI="[object Symbol]",oI="[object WeakMap]",aI="[object ArrayBuffer]",uI="[object DataView]",cI="[object Float32Array]",lI="[object Float64Array]",hI="[object Int8Array]",dI="[object Int16Array]",fI="[object Int32Array]",pI="[object Uint8Array]",mI="[object Uint8ClampedArray]",gI="[object Uint16Array]",yI="[object Uint32Array]",re={};re[Sp]=re[QE]=re[aI]=re[uI]=re[JE]=re[YE]=re[cI]=re[lI]=re[hI]=re[dI]=re[fI]=re[eI]=re[tI]=re[Pp]=re[rI]=re[nI]=re[sI]=re[iI]=re[pI]=re[mI]=re[gI]=re[yI]=!0;re[XE]=re[Rp]=re[oI]=!1;function eo(r,e,t,n,s,i){var a,u=e&KE,c=e&HE,h=e&WE;if(t&&(a=s?t(r,n,s,i):t(r)),a!==void 0)return a;if(!Z(r))return r;var f=le(r);if(f){if(a=dp(r),!u)return tf(r,a)}else{var m=We(r),g=m==Rp||m==ZE;if(yt(r))return tp(r,u);if(m==Pp||m==Sp||g&&!s){if(a=c||g?{}:wp(r),!u)return c?ip(r,Jf(a,r)):sp(r,Qf(a,r))}else{if(!re[m])return s?r:{};a=vp(r,m,u)}}i||(i=new Ht);var b=i.get(r);if(b)return b;i.set(r,a),xp(r)?r.forEach(function(R){a.add(eo(R,e,t,R,r,i))}):Ep(r)&&r.forEach(function(R,N){a.set(N,eo(R,e,t,N,r,i))});var P=h?c?op:ws:c?$t:xe,C=f?void 0:P(r);return af(C||r,function(R,N){C&&(N=R,R=r[N]),Hr(a,N,eo(R,e,t,N,r,i))}),a}var Cp=eo;var _I=1,vI=4;function wI(r){return Cp(r,_I|vI)}var Wt=wI;var bI="__lodash_hash_undefined__";function TI(r){return this.__data__.set(r,bI),this}var kp=TI;function EI(r){return this.__data__.has(r)}var Dp=EI;function to(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new hr;++e<t;)this.add(r[e])}to.prototype.add=to.prototype.push=kp;to.prototype.has=Dp;var Op=to;function II(r,e){for(var t=-1,n=r==null?0:r.length;++t<n;)if(e(r[t],t,r))return!0;return!1}var Np=II;function AI(r,e){return r.has(e)}var Vp=AI;var xI=1,SI=2;function RI(r,e,t,n,s,i){var a=t&xI,u=r.length,c=e.length;if(u!=c&&!(a&&c>u))return!1;var h=i.get(r),f=i.get(e);if(h&&f)return h==e&&f==r;var m=-1,g=!0,b=t&SI?new Op:void 0;for(i.set(r,e),i.set(e,r);++m<u;){var P=r[m],C=e[m];if(n)var R=a?n(C,P,m,e,r,i):n(P,C,m,r,e,i);if(R!==void 0){if(R)continue;g=!1;break}if(b){if(!Np(e,function(N,F){if(!Vp(b,F)&&(P===N||s(P,N,t,n,i)))return b.push(F)})){g=!1;break}}else if(!(P===C||s(P,C,t,n,i))){g=!1;break}}return i.delete(r),i.delete(e),g}var ro=RI;function PI(r){var e=-1,t=Array(r.size);return r.forEach(function(n,s){t[++e]=[s,n]}),t}var Lp=PI;function CI(r){var e=-1,t=Array(r.size);return r.forEach(function(n){t[++e]=n}),t}var Fp=CI;var kI=1,DI=2,OI="[object Boolean]",NI="[object Date]",VI="[object Error]",LI="[object Map]",FI="[object Number]",MI="[object RegExp]",jI="[object Set]",UI="[object String]",BI="[object Symbol]",$I="[object ArrayBuffer]",qI="[object DataView]",Mp=ke?ke.prototype:void 0,yu=Mp?Mp.valueOf:void 0;function zI(r,e,t,n,s,i,a){switch(t){case qI:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case $I:return!(r.byteLength!=e.byteLength||!i(new on(r),new on(e)));case OI:case NI:case FI:return Xe(+r,+e);case VI:return r.name==e.name&&r.message==e.message;case MI:case UI:return r==e+"";case LI:var u=Lp;case jI:var c=n&kI;if(u||(u=Fp),r.size!=e.size&&!c)return!1;var h=a.get(r);if(h)return h==e;n|=DI,a.set(r,e);var f=ro(u(r),u(e),n,s,i,a);return a.delete(r),f;case BI:if(yu)return yu.call(r)==yu.call(e)}return!1}var jp=zI;var GI=1,KI=Object.prototype,HI=KI.hasOwnProperty;function WI(r,e,t,n,s,i){var a=t&GI,u=ws(r),c=u.length,h=ws(e),f=h.length;if(c!=f&&!a)return!1;for(var m=c;m--;){var g=u[m];if(!(a?g in e:HI.call(e,g)))return!1}var b=i.get(r),P=i.get(e);if(b&&P)return b==e&&P==r;var C=!0;i.set(r,e),i.set(e,r);for(var R=a;++m<c;){g=u[m];var N=r[g],F=e[g];if(n)var U=a?n(F,N,g,e,r,i):n(N,F,g,r,e,i);if(!(U===void 0?N===F||s(N,F,t,n,i):U)){C=!1;break}R||(R=g=="constructor")}if(C&&!R){var G=r.constructor,Y=e.constructor;G!=Y&&"constructor"in r&&"constructor"in e&&!(typeof G=="function"&&G instanceof G&&typeof Y=="function"&&Y instanceof Y)&&(C=!1)}return i.delete(r),i.delete(e),C}var Up=WI;var QI=1,Bp="[object Arguments]",$p="[object Array]",no="[object Object]",JI=Object.prototype,qp=JI.hasOwnProperty;function YI(r,e,t,n,s,i){var a=le(r),u=le(e),c=a?$p:We(r),h=u?$p:We(e);c=c==Bp?no:c,h=h==Bp?no:h;var f=c==no,m=h==no,g=c==h;if(g&&yt(r)){if(!yt(e))return!1;a=!0,f=!1}if(g&&!f)return i||(i=new Ht),a||Yr(r)?ro(r,e,t,n,s,i):jp(r,e,c,t,n,s,i);if(!(t&QI)){var b=f&&qp.call(r,"__wrapped__"),P=m&&qp.call(e,"__wrapped__");if(b||P){var C=b?r.value():r,R=P?e.value():e;return i||(i=new Ht),s(C,R,t,n,i)}}return g?(i||(i=new Ht),Up(r,e,t,n,s,i)):!1}var zp=YI;function Gp(r,e,t,n,s){return r===e?!0:r==null||e==null||!De(r)&&!De(e)?r!==r&&e!==e:zp(r,e,t,n,Gp,s)}var un=Gp;var XI=1,ZI=2;function eA(r,e,t,n){var s=t.length,i=s,a=!n;if(r==null)return!i;for(r=Object(r);s--;){var u=t[s];if(a&&u[2]?u[1]!==r[u[0]]:!(u[0]in r))return!1}for(;++s<i;){u=t[s];var c=u[0],h=r[c],f=u[1];if(a&&u[2]){if(h===void 0&&!(c in r))return!1}else{var m=new Ht;if(n)var g=n(h,f,c,r,e,m);if(!(g===void 0?un(f,h,XI|ZI,n,m):g))return!1}}return!0}var Kp=eA;function tA(r){return r===r&&!Z(r)}var so=tA;function rA(r){for(var e=xe(r),t=e.length;t--;){var n=e[t],s=r[n];e[t]=[n,s,so(s)]}return e}var Hp=rA;function nA(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}var io=nA;function sA(r){var e=Hp(r);return e.length==1&&e[0][2]?io(e[0][0],e[0][1]):function(t){return t===r||Kp(t,r,e)}}var Wp=sA;function iA(r,e){return r!=null&&e in Object(r)}var Qp=iA;function oA(r,e,t){e=rn(e,r);for(var n=-1,s=e.length,i=!1;++n<s;){var a=Ze(e[n]);if(!(i=r!=null&&t(r,a)))break;r=r[a]}return i||++n!=s?i:(s=r==null?0:r.length,!!s&&Wr(s)&&Mt(a,s)&&(le(r)||Qr(r)))}var Jp=oA;function aA(r,e){return r!=null&&Jp(r,e,Qp)}var Yp=aA;var uA=1,cA=2;function lA(r,e){return Xr(r)&&so(e)?io(Ze(r),e):function(t){var n=vs(t,r);return n===void 0&&n===e?Yp(t,r):un(e,n,uA|cA)}}var Xp=lA;function hA(r){return function(e){return e==null?void 0:e[r]}}var Zp=hA;function dA(r){return function(e){return Gi(e,r)}}var em=dA;function fA(r){return Xr(r)?Zp(Ze(r)):em(r)}var tm=fA;function pA(r){return typeof r=="function"?r:r==null?zr:typeof r=="object"?le(r)?Xp(r[0],r[1]):Wp(r):tm(r)}var rm=pA;function mA(r){return function(e,t,n){for(var s=-1,i=Object(e),a=n(e),u=a.length;u--;){var c=a[r?u:++s];if(t(i[c],c,i)===!1)break}return e}}var nm=mA;var gA=nm(),sm=gA;function yA(r,e){return r&&sm(r,e,xe)}var im=yA;var _A=function(){return ue.Date.now()},oo=_A;var vA="Expected a function",wA=Math.max,bA=Math.min;function TA(r,e,t){var n,s,i,a,u,c,h=0,f=!1,m=!1,g=!0;if(typeof r!="function")throw new TypeError(vA);e=du(e)||0,Z(t)&&(f=!!t.leading,m="maxWait"in t,i=m?wA(du(t.maxWait)||0,e):i,g="trailing"in t?!!t.trailing:g);function b(B){var E=n,y=s;return n=s=void 0,h=B,a=r.apply(y,E),a}function P(B){return h=B,u=setTimeout(N,e),f?b(B):a}function C(B){var E=B-c,y=B-h,w=e-E;return m?bA(w,i-y):w}function R(B){var E=B-c,y=B-h;return c===void 0||E>=e||E<0||m&&y>=i}function N(){var B=oo();if(R(B))return F(B);u=setTimeout(N,C(B))}function F(B){return u=void 0,g&&n?b(B):(n=s=void 0,a)}function U(){u!==void 0&&clearTimeout(u),h=0,n=c=s=u=void 0}function G(){return u===void 0?a:F(oo())}function Y(){var B=oo(),E=R(B);if(n=arguments,s=this,c=B,E){if(u===void 0)return P(c);if(m)return clearTimeout(u),u=setTimeout(N,e),b(c)}return u===void 0&&(u=setTimeout(N,e)),a}return Y.cancel=U,Y.flush=G,Y}var om=TA;var am=Object.prototype,EA=am.hasOwnProperty,IA=lf(function(r,e){r=Object(r);var t=-1,n=e.length,s=n>2?e[2]:void 0;for(s&&hf(e[0],e[1],s)&&(n=1);++t<n;)for(var i=e[t],a=$t(i),u=-1,c=a.length;++u<c;){var h=a[u],f=r[h];(f===void 0||Xe(f,am[h])&&!EA.call(r,h))&&(r[h]=i[h])}return r}),ao=IA;var AA="[object Map]",xA="[object Set]",SA=Object.prototype,RA=SA.hasOwnProperty;function PA(r){if(r==null)return!0;if(Ut(r)&&(le(r)||typeof r=="string"||typeof r.splice=="function"||yt(r)||Yr(r)||Qr(r)))return!r.length;var e=We(r);if(e==AA||e==xA)return!r.size;if(Bt(r))return!zi(r).length;for(var t in r)if(RA.call(r,t))return!1;return!0}var _u=PA;function CA(r,e){return un(r,e)}var bs=CA;function kA(r,e){var t={};return e=rm(e,3),im(r,function(n,s,i){Kr(t,e(n,s,i),n)}),t}var vu=kA;function DA(r,e,t,n){if(!Z(r))return r;e=rn(e,r);for(var s=-1,i=e.length,a=i-1,u=r;u!=null&&++s<i;){var c=Ze(e[s]),h=t;if(c==="__proto__"||c==="constructor"||c==="prototype")return r;if(s!=a){var f=u[c];h=n?n(f,c,u):void 0,h===void 0&&(h=Z(f)?f:Mt(e[s+1])?[]:{})}Hr(u,c,h),u=u[c]}return r}var um=DA;function OA(r,e,t){return r==null?r:um(r,e,t)}var Qt=OA;var NA="Expected a function";function VA(r,e,t){var n=!0,s=!0;if(typeof r!="function")throw new TypeError(NA);return Z(t)&&(n="leading"in t?!!t.leading:n,s="trailing"in t?!!t.trailing:s),om(r,e,{leading:n,maxWait:e,trailing:s})}var wu=VA;var cm=()=>{};var hm=function(r){let e=[],t=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(s=65536+((s&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128)}return e},LA=function(r){let e=[],t=0,n=0;for(;t<r.length;){let s=r[t++];if(s<128)e[n++]=String.fromCharCode(s);else if(s>191&&s<224){let i=r[t++];e[n++]=String.fromCharCode((s&31)<<6|i&63)}else if(s>239&&s<365){let i=r[t++],a=r[t++],u=r[t++],c=((s&7)<<18|(i&63)<<12|(a&63)<<6|u&63)-65536;e[n++]=String.fromCharCode(55296+(c>>10)),e[n++]=String.fromCharCode(56320+(c&1023))}else{let i=r[t++],a=r[t++];e[n++]=String.fromCharCode((s&15)<<12|(i&63)<<6|a&63)}}return e.join("")},dm={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:typeof atob=="function",encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();let t=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let s=0;s<r.length;s+=3){let i=r[s],a=s+1<r.length,u=a?r[s+1]:0,c=s+2<r.length,h=c?r[s+2]:0,f=i>>2,m=(i&3)<<4|u>>4,g=(u&15)<<2|h>>6,b=h&63;c||(b=64,a||(g=64)),n.push(t[f],t[m],t[g],t[b])}return n.join("")},encodeString(r,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(r):this.encodeByteArray(hm(r),e)},decodeString(r,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(r):LA(this.decodeStringToByteArray(r,e))},decodeStringToByteArray(r,e){this.init_();let t=e?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let s=0;s<r.length;){let i=t[r.charAt(s++)],u=s<r.length?t[r.charAt(s)]:0;++s;let h=s<r.length?t[r.charAt(s)]:64;++s;let m=s<r.length?t[r.charAt(s)]:64;if(++s,i==null||u==null||h==null||m==null)throw new bu;let g=i<<2|u>>4;if(n.push(g),h!==64){let b=u<<4&240|h>>2;if(n.push(b),m!==64){let P=h<<6&192|m;n.push(P)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let r=0;r<this.ENCODED_VALS.length;r++)this.byteToCharMap_[r]=this.ENCODED_VALS.charAt(r),this.charToByteMap_[this.byteToCharMap_[r]]=r,this.byteToCharMapWebSafe_[r]=this.ENCODED_VALS_WEBSAFE.charAt(r),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[r]]=r,r>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(r)]=r,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(r)]=r)}}},bu=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},FA=function(r){let e=hm(r);return dm.encodeByteArray(e,!0)},Ts=function(r){return FA(r).replace(/\./g,"")},fm=function(r){try{return dm.decodeString(r,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function MA(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;throw new Error("Unable to locate global object.")}var jA=()=>MA().__FIREBASE_DEFAULTS__,UA=()=>{if(typeof process=="undefined"||typeof process.env=="undefined")return;let r=process.env.__FIREBASE_DEFAULTS__;if(r)return JSON.parse(r)},BA=()=>{if(typeof document=="undefined")return;let r;try{r=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}let e=r&&fm(r[1]);return e&&JSON.parse(e)},Tu=()=>{try{return cm()||jA()||UA()||BA()}catch(r){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${r}`);return}},$A=r=>{var e,t;return(t=(e=Tu())===null||e===void 0?void 0:e.emulatorHosts)===null||t===void 0?void 0:t[r]},pm=r=>{let e=$A(r);if(!e)return;let t=e.lastIndexOf(":");if(t<=0||t+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);let n=parseInt(e.substring(t+1),10);return e[0]==="["?[e.substring(1,t-1),n]:[e.substring(0,t),n]},Eu=()=>{var r;return(r=Tu())===null||r===void 0?void 0:r.config};var uo=class{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),typeof e=="function"&&(this.promise.catch(()=>{}),e.length===1?e(t):e(t,n))}}};function mm(r,e){if(r.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');let t={alg:"none",type:"JWT"},n=e||"demo-project",s=r.iat||0,i=r.sub||r.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");let a=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:s,exp:s+3600,auth_time:s,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},r);return[Ts(JSON.stringify(t)),Ts(JSON.stringify(a)),""].join(".")}function gm(){return typeof navigator!="undefined"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function qA(){var r;let e=(r=Tu())===null||r===void 0?void 0:r.forceEnvironment;if(e==="node")return!0;if(e==="browser")return!1;try{return Object.prototype.toString.call(global.process)==="[object process]"}catch{return!1}}function ym(){return!qA()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function Iu(){try{return typeof indexedDB=="object"}catch{return!1}}function _m(){return new Promise((r,e)=>{try{let t=!0,n="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(n);s.onsuccess=()=>{s.result.close(),t||self.indexedDB.deleteDatabase(n),r(!0)},s.onupgradeneeded=()=>{t=!1},s.onerror=()=>{var i;e(((i=s.error)===null||i===void 0?void 0:i.message)||"")}}catch(t){e(t)}})}var zA="FirebaseError",Qe=class r extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name=zA,Object.setPrototypeOf(this,r.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Es.prototype.create)}},Es=class{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){let n=t[0]||{},s=`${this.service}/${e}`,i=this.errors[e],a=i?GA(i,n):"Error",u=`${this.serviceName}: ${a} (${s}).`;return new Qe(s,u,n)}};function GA(r,e){return r.replace(KA,(t,n)=>{let s=e[n];return s!=null?String(s):`<${n}?>`})}var KA=/\{\$([^}]+)}/g;function cn(r,e){if(r===e)return!0;let t=Object.keys(r),n=Object.keys(e);for(let s of t){if(!n.includes(s))return!1;let i=r[s],a=e[s];if(lm(i)&&lm(a)){if(!cn(i,a))return!1}else if(i!==a)return!1}for(let s of n)if(!t.includes(s))return!1;return!0}function lm(r){return r!==null&&typeof r=="object"}var fM=4*60*60*1e3;function wt(r){return r&&r._delegate?r._delegate:r}var bt=class{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}};var fr="[DEFAULT]";var Au=class{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){let t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){let n=new uo;if(this.instancesDeferred.set(t,n),this.isInitialized(t)||this.shouldAutoInitialize())try{let s=this.getOrInitializeService({instanceIdentifier:t});s&&n.resolve(s)}catch{}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;let n=this.normalizeInstanceIdentifier(e==null?void 0:e.identifier),s=(t=e==null?void 0:e.optional)!==null&&t!==void 0?t:!1;if(this.isInitialized(n)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:n})}catch(i){if(s)return null;throw i}else{if(s)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,!!this.shouldAutoInitialize()){if(WA(e))try{this.getOrInitializeService({instanceIdentifier:fr})}catch{}for(let[t,n]of this.instancesDeferred.entries()){let s=this.normalizeInstanceIdentifier(t);try{let i=this.getOrInitializeService({instanceIdentifier:s});n.resolve(i)}catch{}}}}clearInstance(e=fr){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){let e=Array.from(this.instances.values());await Promise.all([...e.filter(t=>"INTERNAL"in t).map(t=>t.INTERNAL.delete()),...e.filter(t=>"_delete"in t).map(t=>t._delete())])}isComponentSet(){return this.component!=null}isInitialized(e=fr){return this.instances.has(e)}getOptions(e=fr){return this.instancesOptions.get(e)||{}}initialize(e={}){let{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);let s=this.getOrInitializeService({instanceIdentifier:n,options:t});for(let[i,a]of this.instancesDeferred.entries()){let u=this.normalizeInstanceIdentifier(i);n===u&&a.resolve(s)}return s}onInit(e,t){var n;let s=this.normalizeInstanceIdentifier(t),i=(n=this.onInitCallbacks.get(s))!==null&&n!==void 0?n:new Set;i.add(e),this.onInitCallbacks.set(s,i);let a=this.instances.get(s);return a&&e(a,s),()=>{i.delete(e)}}invokeOnInitCallbacks(e,t){let n=this.onInitCallbacks.get(t);if(n)for(let s of n)try{s(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:HA(e),options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch{}return n||null}normalizeInstanceIdentifier(e=fr){return this.component?this.component.multipleInstances?e:fr:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}};function HA(r){return r===fr?void 0:r}function WA(r){return r.instantiationMode==="EAGER"}var co=class{constructor(e){this.name=e,this.providers=new Map}addComponent(e){let t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);let t=new Au(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}};var QA=[],Q;(function(r){r[r.DEBUG=0]="DEBUG",r[r.VERBOSE=1]="VERBOSE",r[r.INFO=2]="INFO",r[r.WARN=3]="WARN",r[r.ERROR=4]="ERROR",r[r.SILENT=5]="SILENT"})(Q||(Q={}));var JA={debug:Q.DEBUG,verbose:Q.VERBOSE,info:Q.INFO,warn:Q.WARN,error:Q.ERROR,silent:Q.SILENT},YA=Q.INFO,XA={[Q.DEBUG]:"log",[Q.VERBOSE]:"log",[Q.INFO]:"info",[Q.WARN]:"warn",[Q.ERROR]:"error"},ZA=(r,e,...t)=>{if(e<r.logLevel)return;let n=new Date().toISOString(),s=XA[e];if(s)console[s](`[${n}] ${r.name}:`,...t);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},ln=class{constructor(e){this.name=e,this._logLevel=YA,this._logHandler=ZA,this._userLogHandler=null,QA.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in Q))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?JA[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,Q.DEBUG,...e),this._logHandler(this,Q.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,Q.VERBOSE,...e),this._logHandler(this,Q.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,Q.INFO,...e),this._logHandler(this,Q.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,Q.WARN,...e),this._logHandler(this,Q.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,Q.ERROR,...e),this._logHandler(this,Q.ERROR,...e)}};var ex=(r,e)=>e.some(t=>r instanceof t),vm,wm;function tx(){return vm||(vm=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function rx(){return wm||(wm=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var bm=new WeakMap,Su=new WeakMap,Tm=new WeakMap,xu=new WeakMap,Pu=new WeakMap;function nx(r){let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("success",i),r.removeEventListener("error",a)},i=()=>{t(et(r.result)),s()},a=()=>{n(r.error),s()};r.addEventListener("success",i),r.addEventListener("error",a)});return e.then(t=>{t instanceof IDBCursor&&bm.set(t,r)}).catch(()=>{}),Pu.set(e,r),e}function sx(r){if(Su.has(r))return;let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("complete",i),r.removeEventListener("error",a),r.removeEventListener("abort",a)},i=()=>{t(),s()},a=()=>{n(r.error||new DOMException("AbortError","AbortError")),s()};r.addEventListener("complete",i),r.addEventListener("error",a),r.addEventListener("abort",a)});Su.set(r,e)}var Ru={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return Su.get(r);if(e==="objectStoreNames")return r.objectStoreNames||Tm.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return et(r[e])},set(r,e,t){return r[e]=t,!0},has(r,e){return r instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in r}};function Em(r){Ru=r(Ru)}function ix(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let n=r.call(lo(this),e,...t);return Tm.set(n,e.sort?e.sort():[e]),et(n)}:rx().includes(r)?function(...e){return r.apply(lo(this),e),et(bm.get(this))}:function(...e){return et(r.apply(lo(this),e))}}function ox(r){return typeof r=="function"?ix(r):(r instanceof IDBTransaction&&sx(r),ex(r,tx())?new Proxy(r,Ru):r)}function et(r){if(r instanceof IDBRequest)return nx(r);if(xu.has(r))return xu.get(r);let e=ox(r);return e!==r&&(xu.set(r,e),Pu.set(e,r)),e}var lo=r=>Pu.get(r);function Am(r,e,{blocked:t,upgrade:n,blocking:s,terminated:i}={}){let a=indexedDB.open(r,e),u=et(a);return n&&a.addEventListener("upgradeneeded",c=>{n(et(a.result),c.oldVersion,c.newVersion,et(a.transaction),c)}),t&&a.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),u.then(c=>{i&&c.addEventListener("close",()=>i()),s&&c.addEventListener("versionchange",h=>s(h.oldVersion,h.newVersion,h))}).catch(()=>{}),u}var ax=["get","getKey","getAll","getAllKeys","count"],ux=["put","add","delete","clear"],Cu=new Map;function Im(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(Cu.get(e))return Cu.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,s=ux.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(s||ax.includes(t)))return;let i=async function(a,...u){let c=this.transaction(a,s?"readwrite":"readonly"),h=c.store;return n&&(h=h.index(u.shift())),(await Promise.all([h[t](...u),s&&c.done]))[0]};return Cu.set(e,i),i}Em(r=>({...r,get:(e,t,n)=>Im(e,t)||r.get(e,t,n),has:(e,t)=>!!Im(e,t)||r.has(e,t)}));var Du=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(t=>{if(cx(t)){let n=t.getImmediate();return`${n.library}/${n.version}`}else return null}).filter(t=>t).join(" ")}};function cx(r){let e=r.getComponent();return(e==null?void 0:e.type)==="VERSION"}var Ou="@firebase/app",xm="0.11.3";var Tt=new ln("@firebase/app"),lx="@firebase/app-compat",hx="@firebase/analytics-compat",dx="@firebase/analytics",fx="@firebase/app-check-compat",px="@firebase/app-check",mx="@firebase/auth",gx="@firebase/auth-compat",yx="@firebase/database",_x="@firebase/data-connect",vx="@firebase/database-compat",wx="@firebase/functions",bx="@firebase/functions-compat",Tx="@firebase/installations",Ex="@firebase/installations-compat",Ix="@firebase/messaging",Ax="@firebase/messaging-compat",xx="@firebase/performance",Sx="@firebase/performance-compat",Rx="@firebase/remote-config",Px="@firebase/remote-config-compat",Cx="@firebase/storage",kx="@firebase/storage-compat",Dx="@firebase/firestore",Ox="@firebase/vertexai",Nx="@firebase/firestore-compat",Vx="firebase",Lx="11.5.0";var Nu="[DEFAULT]",Fx={[Ou]:"fire-core",[lx]:"fire-core-compat",[dx]:"fire-analytics",[hx]:"fire-analytics-compat",[px]:"fire-app-check",[fx]:"fire-app-check-compat",[mx]:"fire-auth",[gx]:"fire-auth-compat",[yx]:"fire-rtdb",[_x]:"fire-data-connect",[vx]:"fire-rtdb-compat",[wx]:"fire-fn",[bx]:"fire-fn-compat",[Tx]:"fire-iid",[Ex]:"fire-iid-compat",[Ix]:"fire-fcm",[Ax]:"fire-fcm-compat",[xx]:"fire-perf",[Sx]:"fire-perf-compat",[Rx]:"fire-rc",[Px]:"fire-rc-compat",[Cx]:"fire-gcs",[kx]:"fire-gcs-compat",[Dx]:"fire-fst",[Nx]:"fire-fst-compat",[Ox]:"fire-vertex","fire-js":"fire-js",[Vx]:"fire-js-all"};var ho=new Map,Mx=new Map,Vu=new Map;function Sm(r,e){try{r.container.addComponent(e)}catch(t){Tt.debug(`Component ${e.name} failed to register with FirebaseApp ${r.name}`,t)}}function Is(r){let e=r.name;if(Vu.has(e))return Tt.debug(`There were multiple attempts to register component ${e}.`),!1;Vu.set(e,r);for(let t of ho.values())Sm(t,r);for(let t of Mx.values())Sm(t,r);return!0}function km(r,e){let t=r.container.getProvider("heartbeat").getImmediate({optional:!0});return t&&t.triggerHeartbeat(),r.container.getProvider(e)}function Dm(r){return r==null?!1:r.settings!==void 0}var jx={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},Jt=new Es("app","Firebase",jx);var Lu=class{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new bt("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw Jt.create("app-deleted",{appName:this._name})}};var Om=Lx;function ju(r,e={}){let t=r;typeof e!="object"&&(e={name:e});let n=Object.assign({name:Nu,automaticDataCollectionEnabled:!1},e),s=n.name;if(typeof s!="string"||!s)throw Jt.create("bad-app-name",{appName:String(s)});if(t||(t=Eu()),!t)throw Jt.create("no-options");let i=ho.get(s);if(i){if(cn(t,i.options)&&cn(n,i.config))return i;throw Jt.create("duplicate-app",{appName:s})}let a=new co(s);for(let c of Vu.values())a.addComponent(c);let u=new Lu(t,n,a);return ho.set(s,u),u}function Nm(r=Nu){let e=ho.get(r);if(!e&&r===Nu&&Eu())return ju();if(!e)throw Jt.create("no-app",{appName:r});return e}function Yt(r,e,t){var n;let s=(n=Fx[r])!==null&&n!==void 0?n:r;t&&(s+=`-${t}`);let i=s.match(/\s|\//),a=e.match(/\s|\//);if(i||a){let u=[`Unable to register library "${s}" with version "${e}":`];i&&u.push(`library name "${s}" contains illegal characters (whitespace or "/")`),i&&a&&u.push("and"),a&&u.push(`version name "${e}" contains illegal characters (whitespace or "/")`),Tt.warn(u.join(" "));return}Is(new bt(`${s}-version`,()=>({library:s,version:e}),"VERSION"))}var Ux="firebase-heartbeat-database",Bx=1,As="firebase-heartbeat-store",ku=null;function Vm(){return ku||(ku=Am(Ux,Bx,{upgrade:(r,e)=>{switch(e){case 0:try{r.createObjectStore(As)}catch(t){console.warn(t)}}}}).catch(r=>{throw Jt.create("idb-open",{originalErrorMessage:r.message})})),ku}async function $x(r){try{let t=(await Vm()).transaction(As),n=await t.objectStore(As).get(Lm(r));return await t.done,n}catch(e){if(e instanceof Qe)Tt.warn(e.message);else{let t=Jt.create("idb-get",{originalErrorMessage:e==null?void 0:e.message});Tt.warn(t.message)}}}async function Rm(r,e){try{let n=(await Vm()).transaction(As,"readwrite");await n.objectStore(As).put(e,Lm(r)),await n.done}catch(t){if(t instanceof Qe)Tt.warn(t.message);else{let n=Jt.create("idb-set",{originalErrorMessage:t==null?void 0:t.message});Tt.warn(n.message)}}}function Lm(r){return`${r.name}!${r.options.appId}`}var qx=1024,zx=30,Fu=class{constructor(e){this.container=e,this._heartbeatsCache=null;let t=this.container.getProvider("app").getImmediate();this._storage=new Mu(t),this._heartbeatsCachePromise=this._storage.read().then(n=>(this._heartbeatsCache=n,n))}async triggerHeartbeat(){var e,t;try{let s=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),i=Pm();if(((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,((t=this._heartbeatsCache)===null||t===void 0?void 0:t.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===i||this._heartbeatsCache.heartbeats.some(a=>a.date===i))return;if(this._heartbeatsCache.heartbeats.push({date:i,agent:s}),this._heartbeatsCache.heartbeats.length>zx){let a=Kx(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(a,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(n){Tt.warn(n)}}async getHeartbeatsHeader(){var e;try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null||this._heartbeatsCache.heartbeats.length===0)return"";let t=Pm(),{heartbeatsToSend:n,unsentEntries:s}=Gx(this._heartbeatsCache.heartbeats),i=Ts(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,s.length>0?(this._heartbeatsCache.heartbeats=s,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(t){return Tt.warn(t),""}}};function Pm(){return new Date().toISOString().substring(0,10)}function Gx(r,e=qx){let t=[],n=r.slice();for(let s of r){let i=t.find(a=>a.agent===s.agent);if(i){if(i.dates.push(s.date),Cm(t)>e){i.dates.pop();break}}else if(t.push({agent:s.agent,dates:[s.date]}),Cm(t)>e){t.pop();break}n=n.slice(1)}return{heartbeatsToSend:t,unsentEntries:n}}var Mu=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return Iu()?_m().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let t=await $x(this.app);return t!=null&&t.heartbeats?t:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){let s=await this.read();return Rm(this.app,{lastSentHeartbeatDate:(t=e.lastSentHeartbeatDate)!==null&&t!==void 0?t:s.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){var t;if(await this._canUseIndexedDBPromise){let s=await this.read();return Rm(this.app,{lastSentHeartbeatDate:(t=e.lastSentHeartbeatDate)!==null&&t!==void 0?t:s.lastSentHeartbeatDate,heartbeats:[...s.heartbeats,...e.heartbeats]})}else return}};function Cm(r){return Ts(JSON.stringify({version:2,heartbeats:r})).length}function Kx(r){if(r.length===0)return-1;let e=0,t=r[0].date;for(let n=1;n<r.length;n++)r[n].date<t&&(t=r[n].date,e=n);return e}function Hx(r){Is(new bt("platform-logger",e=>new Du(e),"PRIVATE")),Is(new bt("heartbeat",e=>new Fu(e),"PRIVATE")),Yt(Ou,xm,r),Yt(Ou,xm,"esm2017"),Yt("fire-js","")}Hx("");var Wx="firebase",Qx="11.5.0";Yt(Wx,Qx,"app");var Fm=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Mm={};var Et,Uu;(function(){var r;function e(E,y){function w(){}w.prototype=y.prototype,E.D=y.prototype,E.prototype=new w,E.prototype.constructor=E,E.C=function(T,I,x){for(var _=Array(arguments.length-2),ft=2;ft<arguments.length;ft++)_[ft-2]=arguments[ft];return y.prototype[I].apply(T,_)}}function t(){this.blockSize=-1}function n(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}e(n,t),n.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function s(E,y,w){w||(w=0);var T=Array(16);if(typeof y=="string")for(var I=0;16>I;++I)T[I]=y.charCodeAt(w++)|y.charCodeAt(w++)<<8|y.charCodeAt(w++)<<16|y.charCodeAt(w++)<<24;else for(I=0;16>I;++I)T[I]=y[w++]|y[w++]<<8|y[w++]<<16|y[w++]<<24;y=E.g[0],w=E.g[1],I=E.g[2];var x=E.g[3],_=y+(x^w&(I^x))+T[0]+3614090360&4294967295;y=w+(_<<7&4294967295|_>>>25),_=x+(I^y&(w^I))+T[1]+3905402710&4294967295,x=y+(_<<12&4294967295|_>>>20),_=I+(w^x&(y^w))+T[2]+606105819&4294967295,I=x+(_<<17&4294967295|_>>>15),_=w+(y^I&(x^y))+T[3]+3250441966&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(x^w&(I^x))+T[4]+4118548399&4294967295,y=w+(_<<7&4294967295|_>>>25),_=x+(I^y&(w^I))+T[5]+1200080426&4294967295,x=y+(_<<12&4294967295|_>>>20),_=I+(w^x&(y^w))+T[6]+2821735955&4294967295,I=x+(_<<17&4294967295|_>>>15),_=w+(y^I&(x^y))+T[7]+4249261313&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(x^w&(I^x))+T[8]+1770035416&4294967295,y=w+(_<<7&4294967295|_>>>25),_=x+(I^y&(w^I))+T[9]+2336552879&4294967295,x=y+(_<<12&4294967295|_>>>20),_=I+(w^x&(y^w))+T[10]+4294925233&4294967295,I=x+(_<<17&4294967295|_>>>15),_=w+(y^I&(x^y))+T[11]+2304563134&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(x^w&(I^x))+T[12]+1804603682&4294967295,y=w+(_<<7&4294967295|_>>>25),_=x+(I^y&(w^I))+T[13]+4254626195&4294967295,x=y+(_<<12&4294967295|_>>>20),_=I+(w^x&(y^w))+T[14]+2792965006&4294967295,I=x+(_<<17&4294967295|_>>>15),_=w+(y^I&(x^y))+T[15]+1236535329&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(I^x&(w^I))+T[1]+4129170786&4294967295,y=w+(_<<5&4294967295|_>>>27),_=x+(w^I&(y^w))+T[6]+3225465664&4294967295,x=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(x^y))+T[11]+643717713&4294967295,I=x+(_<<14&4294967295|_>>>18),_=w+(x^y&(I^x))+T[0]+3921069994&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(I^x&(w^I))+T[5]+3593408605&4294967295,y=w+(_<<5&4294967295|_>>>27),_=x+(w^I&(y^w))+T[10]+38016083&4294967295,x=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(x^y))+T[15]+3634488961&4294967295,I=x+(_<<14&4294967295|_>>>18),_=w+(x^y&(I^x))+T[4]+3889429448&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(I^x&(w^I))+T[9]+568446438&4294967295,y=w+(_<<5&4294967295|_>>>27),_=x+(w^I&(y^w))+T[14]+3275163606&4294967295,x=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(x^y))+T[3]+4107603335&4294967295,I=x+(_<<14&4294967295|_>>>18),_=w+(x^y&(I^x))+T[8]+1163531501&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(I^x&(w^I))+T[13]+2850285829&4294967295,y=w+(_<<5&4294967295|_>>>27),_=x+(w^I&(y^w))+T[2]+4243563512&4294967295,x=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(x^y))+T[7]+1735328473&4294967295,I=x+(_<<14&4294967295|_>>>18),_=w+(x^y&(I^x))+T[12]+2368359562&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(w^I^x)+T[5]+4294588738&4294967295,y=w+(_<<4&4294967295|_>>>28),_=x+(y^w^I)+T[8]+2272392833&4294967295,x=y+(_<<11&4294967295|_>>>21),_=I+(x^y^w)+T[11]+1839030562&4294967295,I=x+(_<<16&4294967295|_>>>16),_=w+(I^x^y)+T[14]+4259657740&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(w^I^x)+T[1]+2763975236&4294967295,y=w+(_<<4&4294967295|_>>>28),_=x+(y^w^I)+T[4]+1272893353&4294967295,x=y+(_<<11&4294967295|_>>>21),_=I+(x^y^w)+T[7]+4139469664&4294967295,I=x+(_<<16&4294967295|_>>>16),_=w+(I^x^y)+T[10]+3200236656&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(w^I^x)+T[13]+681279174&4294967295,y=w+(_<<4&4294967295|_>>>28),_=x+(y^w^I)+T[0]+3936430074&4294967295,x=y+(_<<11&4294967295|_>>>21),_=I+(x^y^w)+T[3]+3572445317&4294967295,I=x+(_<<16&4294967295|_>>>16),_=w+(I^x^y)+T[6]+76029189&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(w^I^x)+T[9]+3654602809&4294967295,y=w+(_<<4&4294967295|_>>>28),_=x+(y^w^I)+T[12]+3873151461&4294967295,x=y+(_<<11&4294967295|_>>>21),_=I+(x^y^w)+T[15]+530742520&4294967295,I=x+(_<<16&4294967295|_>>>16),_=w+(I^x^y)+T[2]+3299628645&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(I^(w|~x))+T[0]+4096336452&4294967295,y=w+(_<<6&4294967295|_>>>26),_=x+(w^(y|~I))+T[7]+1126891415&4294967295,x=y+(_<<10&4294967295|_>>>22),_=I+(y^(x|~w))+T[14]+2878612391&4294967295,I=x+(_<<15&4294967295|_>>>17),_=w+(x^(I|~y))+T[5]+4237533241&4294967295,w=I+(_<<21&4294967295|_>>>11),_=y+(I^(w|~x))+T[12]+1700485571&4294967295,y=w+(_<<6&4294967295|_>>>26),_=x+(w^(y|~I))+T[3]+2399980690&4294967295,x=y+(_<<10&4294967295|_>>>22),_=I+(y^(x|~w))+T[10]+4293915773&4294967295,I=x+(_<<15&4294967295|_>>>17),_=w+(x^(I|~y))+T[1]+2240044497&4294967295,w=I+(_<<21&4294967295|_>>>11),_=y+(I^(w|~x))+T[8]+1873313359&4294967295,y=w+(_<<6&4294967295|_>>>26),_=x+(w^(y|~I))+T[15]+4264355552&4294967295,x=y+(_<<10&4294967295|_>>>22),_=I+(y^(x|~w))+T[6]+2734768916&4294967295,I=x+(_<<15&4294967295|_>>>17),_=w+(x^(I|~y))+T[13]+1309151649&4294967295,w=I+(_<<21&4294967295|_>>>11),_=y+(I^(w|~x))+T[4]+4149444226&4294967295,y=w+(_<<6&4294967295|_>>>26),_=x+(w^(y|~I))+T[11]+3174756917&4294967295,x=y+(_<<10&4294967295|_>>>22),_=I+(y^(x|~w))+T[2]+718787259&4294967295,I=x+(_<<15&4294967295|_>>>17),_=w+(x^(I|~y))+T[9]+3951481745&4294967295,E.g[0]=E.g[0]+y&4294967295,E.g[1]=E.g[1]+(I+(_<<21&4294967295|_>>>11))&4294967295,E.g[2]=E.g[2]+I&4294967295,E.g[3]=E.g[3]+x&4294967295}n.prototype.u=function(E,y){y===void 0&&(y=E.length);for(var w=y-this.blockSize,T=this.B,I=this.h,x=0;x<y;){if(I==0)for(;x<=w;)s(this,E,x),x+=this.blockSize;if(typeof E=="string"){for(;x<y;)if(T[I++]=E.charCodeAt(x++),I==this.blockSize){s(this,T),I=0;break}}else for(;x<y;)if(T[I++]=E[x++],I==this.blockSize){s(this,T),I=0;break}}this.h=I,this.o+=y},n.prototype.v=function(){var E=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);E[0]=128;for(var y=1;y<E.length-8;++y)E[y]=0;var w=8*this.o;for(y=E.length-8;y<E.length;++y)E[y]=w&255,w/=256;for(this.u(E),E=Array(16),y=w=0;4>y;++y)for(var T=0;32>T;T+=8)E[w++]=this.g[y]>>>T&255;return E};function i(E,y){var w=u;return Object.prototype.hasOwnProperty.call(w,E)?w[E]:w[E]=y(E)}function a(E,y){this.h=y;for(var w=[],T=!0,I=E.length-1;0<=I;I--){var x=E[I]|0;T&&x==y||(w[I]=x,T=!1)}this.g=w}var u={};function c(E){return-128<=E&&128>E?i(E,function(y){return new a([y|0],0>y?-1:0)}):new a([E|0],0>E?-1:0)}function h(E){if(isNaN(E)||!isFinite(E))return m;if(0>E)return R(h(-E));for(var y=[],w=1,T=0;E>=w;T++)y[T]=E/w|0,w*=4294967296;return new a(y,0)}function f(E,y){if(E.length==0)throw Error("number format error: empty string");if(y=y||10,2>y||36<y)throw Error("radix out of range: "+y);if(E.charAt(0)=="-")return R(f(E.substring(1),y));if(0<=E.indexOf("-"))throw Error('number format error: interior "-" character');for(var w=h(Math.pow(y,8)),T=m,I=0;I<E.length;I+=8){var x=Math.min(8,E.length-I),_=parseInt(E.substring(I,I+x),y);8>x?(x=h(Math.pow(y,x)),T=T.j(x).add(h(_))):(T=T.j(w),T=T.add(h(_)))}return T}var m=c(0),g=c(1),b=c(16777216);r=a.prototype,r.m=function(){if(C(this))return-R(this).m();for(var E=0,y=1,w=0;w<this.g.length;w++){var T=this.i(w);E+=(0<=T?T:4294967296+T)*y,y*=4294967296}return E},r.toString=function(E){if(E=E||10,2>E||36<E)throw Error("radix out of range: "+E);if(P(this))return"0";if(C(this))return"-"+R(this).toString(E);for(var y=h(Math.pow(E,6)),w=this,T="";;){var I=G(w,y).g;w=N(w,I.j(y));var x=((0<w.g.length?w.g[0]:w.h)>>>0).toString(E);if(w=I,P(w))return x+T;for(;6>x.length;)x="0"+x;T=x+T}},r.i=function(E){return 0>E?0:E<this.g.length?this.g[E]:this.h};function P(E){if(E.h!=0)return!1;for(var y=0;y<E.g.length;y++)if(E.g[y]!=0)return!1;return!0}function C(E){return E.h==-1}r.l=function(E){return E=N(this,E),C(E)?-1:P(E)?0:1};function R(E){for(var y=E.g.length,w=[],T=0;T<y;T++)w[T]=~E.g[T];return new a(w,~E.h).add(g)}r.abs=function(){return C(this)?R(this):this},r.add=function(E){for(var y=Math.max(this.g.length,E.g.length),w=[],T=0,I=0;I<=y;I++){var x=T+(this.i(I)&65535)+(E.i(I)&65535),_=(x>>>16)+(this.i(I)>>>16)+(E.i(I)>>>16);T=_>>>16,x&=65535,_&=65535,w[I]=_<<16|x}return new a(w,w[w.length-1]&-2147483648?-1:0)};function N(E,y){return E.add(R(y))}r.j=function(E){if(P(this)||P(E))return m;if(C(this))return C(E)?R(this).j(R(E)):R(R(this).j(E));if(C(E))return R(this.j(R(E)));if(0>this.l(b)&&0>E.l(b))return h(this.m()*E.m());for(var y=this.g.length+E.g.length,w=[],T=0;T<2*y;T++)w[T]=0;for(T=0;T<this.g.length;T++)for(var I=0;I<E.g.length;I++){var x=this.i(T)>>>16,_=this.i(T)&65535,ft=E.i(I)>>>16,Xn=E.i(I)&65535;w[2*T+2*I]+=_*Xn,F(w,2*T+2*I),w[2*T+2*I+1]+=x*Xn,F(w,2*T+2*I+1),w[2*T+2*I+1]+=_*ft,F(w,2*T+2*I+1),w[2*T+2*I+2]+=x*ft,F(w,2*T+2*I+2)}for(T=0;T<y;T++)w[T]=w[2*T+1]<<16|w[2*T];for(T=y;T<2*y;T++)w[T]=0;return new a(w,0)};function F(E,y){for(;(E[y]&65535)!=E[y];)E[y+1]+=E[y]>>>16,E[y]&=65535,y++}function U(E,y){this.g=E,this.h=y}function G(E,y){if(P(y))throw Error("division by zero");if(P(E))return new U(m,m);if(C(E))return y=G(R(E),y),new U(R(y.g),R(y.h));if(C(y))return y=G(E,R(y)),new U(R(y.g),y.h);if(30<E.g.length){if(C(E)||C(y))throw Error("slowDivide_ only works with positive integers.");for(var w=g,T=y;0>=T.l(E);)w=Y(w),T=Y(T);var I=B(w,1),x=B(T,1);for(T=B(T,2),w=B(w,2);!P(T);){var _=x.add(T);0>=_.l(E)&&(I=I.add(w),x=_),T=B(T,1),w=B(w,1)}return y=N(E,I.j(y)),new U(I,y)}for(I=m;0<=E.l(y);){for(w=Math.max(1,Math.floor(E.m()/y.m())),T=Math.ceil(Math.log(w)/Math.LN2),T=48>=T?1:Math.pow(2,T-48),x=h(w),_=x.j(y);C(_)||0<_.l(E);)w-=T,x=h(w),_=x.j(y);P(x)&&(x=g),I=I.add(x),E=N(E,_)}return new U(I,E)}r.A=function(E){return G(this,E).h},r.and=function(E){for(var y=Math.max(this.g.length,E.g.length),w=[],T=0;T<y;T++)w[T]=this.i(T)&E.i(T);return new a(w,this.h&E.h)},r.or=function(E){for(var y=Math.max(this.g.length,E.g.length),w=[],T=0;T<y;T++)w[T]=this.i(T)|E.i(T);return new a(w,this.h|E.h)},r.xor=function(E){for(var y=Math.max(this.g.length,E.g.length),w=[],T=0;T<y;T++)w[T]=this.i(T)^E.i(T);return new a(w,this.h^E.h)};function Y(E){for(var y=E.g.length+1,w=[],T=0;T<y;T++)w[T]=E.i(T)<<1|E.i(T-1)>>>31;return new a(w,E.h)}function B(E,y){var w=y>>5;y%=32;for(var T=E.g.length-w,I=[],x=0;x<T;x++)I[x]=0<y?E.i(x+w)>>>y|E.i(x+w+1)<<32-y:E.i(x+w);return new a(I,E.h)}n.prototype.digest=n.prototype.v,n.prototype.reset=n.prototype.s,n.prototype.update=n.prototype.u,Uu=Mm.Md5=n,a.prototype.add=a.prototype.add,a.prototype.multiply=a.prototype.j,a.prototype.modulo=a.prototype.A,a.prototype.compare=a.prototype.l,a.prototype.toNumber=a.prototype.m,a.prototype.toString=a.prototype.toString,a.prototype.getBits=a.prototype.i,a.fromNumber=h,a.fromString=f,Et=Mm.Integer=a}).apply(typeof Fm!="undefined"?Fm:typeof self!="undefined"?self:typeof window!="undefined"?window:{});var fo=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},It={};var Bu,Jx,hn,$u,xs,po,qu,zu,Gu;(function(){var r,e=typeof Object.defineProperties=="function"?Object.defineProperty:function(o,l,d){return o==Array.prototype||o==Object.prototype||(o[l]=d.value),o};function t(o){o=[typeof globalThis=="object"&&globalThis,o,typeof window=="object"&&window,typeof self=="object"&&self,typeof fo=="object"&&fo];for(var l=0;l<o.length;++l){var d=o[l];if(d&&d.Math==Math)return d}throw Error("Cannot find global object")}var n=t(this);function s(o,l){if(l)e:{var d=n;o=o.split(".");for(var p=0;p<o.length-1;p++){var A=o[p];if(!(A in d))break e;d=d[A]}o=o[o.length-1],p=d[o],l=l(p),l!=p&&l!=null&&e(d,o,{configurable:!0,writable:!0,value:l})}}function i(o,l){o instanceof String&&(o+="");var d=0,p=!1,A={next:function(){if(!p&&d<o.length){var S=d++;return{value:l(S,o[S]),done:!1}}return p=!0,{done:!0,value:void 0}}};return A[Symbol.iterator]=function(){return A},A}s("Array.prototype.values",function(o){return o||function(){return i(this,function(l,d){return d})}});var a=a||{},u=this||self;function c(o){var l=typeof o;return l=l!="object"?l:o?Array.isArray(o)?"array":l:"null",l=="array"||l=="object"&&typeof o.length=="number"}function h(o){var l=typeof o;return l=="object"&&o!=null||l=="function"}function f(o,l,d){return o.call.apply(o.bind,arguments)}function m(o,l,d){if(!o)throw Error();if(2<arguments.length){var p=Array.prototype.slice.call(arguments,2);return function(){var A=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(A,p),o.apply(l,A)}}return function(){return o.apply(l,arguments)}}function g(o,l,d){return g=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?f:m,g.apply(null,arguments)}function b(o,l){var d=Array.prototype.slice.call(arguments,1);return function(){var p=d.slice();return p.push.apply(p,arguments),o.apply(this,p)}}function P(o,l){function d(){}d.prototype=l.prototype,o.aa=l.prototype,o.prototype=new d,o.prototype.constructor=o,o.Qb=function(p,A,S){for(var O=Array(arguments.length-2),te=2;te<arguments.length;te++)O[te-2]=arguments[te];return l.prototype[A].apply(p,O)}}function C(o){let l=o.length;if(0<l){let d=Array(l);for(let p=0;p<l;p++)d[p]=o[p];return d}return[]}function R(o,l){for(let d=1;d<arguments.length;d++){let p=arguments[d];if(c(p)){let A=o.length||0,S=p.length||0;o.length=A+S;for(let O=0;O<S;O++)o[A+O]=p[O]}else o.push(p)}}class N{constructor(l,d){this.i=l,this.j=d,this.h=0,this.g=null}get(){let l;return 0<this.h?(this.h--,l=this.g,this.g=l.next,l.next=null):l=this.i(),l}}function F(o){return/^[\s\xa0]*$/.test(o)}function U(){var o=u.navigator;return o&&(o=o.userAgent)?o:""}function G(o){return G[" "](o),o}G[" "]=function(){};var Y=U().indexOf("Gecko")!=-1&&!(U().toLowerCase().indexOf("webkit")!=-1&&U().indexOf("Edge")==-1)&&!(U().indexOf("Trident")!=-1||U().indexOf("MSIE")!=-1)&&U().indexOf("Edge")==-1;function B(o,l,d){for(let p in o)l.call(d,o[p],p,o)}function E(o,l){for(let d in o)l.call(void 0,o[d],d,o)}function y(o){let l={};for(let d in o)l[d]=o[d];return l}let w="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function T(o,l){let d,p;for(let A=1;A<arguments.length;A++){p=arguments[A];for(d in p)o[d]=p[d];for(let S=0;S<w.length;S++)d=w[S],Object.prototype.hasOwnProperty.call(p,d)&&(o[d]=p[d])}}function I(o){var l=1;o=o.split(":");let d=[];for(;0<l&&o.length;)d.push(o.shift()),l--;return o.length&&d.push(o.join(":")),d}function x(o){u.setTimeout(()=>{throw o},0)}function _(){var o=Ua;let l=null;return o.g&&(l=o.g,o.g=o.g.next,o.g||(o.h=null),l.next=null),l}class ft{constructor(){this.h=this.g=null}add(l,d){let p=Xn.get();p.set(l,d),this.h?this.h.next=p:this.g=p,this.h=p}}var Xn=new N(()=>new Rv,o=>o.reset());class Rv{constructor(){this.next=this.g=this.h=null}set(l,d){this.h=l,this.g=d,this.next=null}reset(){this.next=this.g=this.h=null}}let Zn,es=!1,Ua=new ft,Nh=()=>{let o=u.Promise.resolve(void 0);Zn=()=>{o.then(Pv)}};var Pv=()=>{for(var o;o=_();){try{o.h.call(o.g)}catch(d){x(d)}var l=Xn;l.j(o),100>l.h&&(l.h++,o.next=l.g,l.g=o)}es=!1};function Ot(){this.s=this.s,this.C=this.C}Ot.prototype.s=!1,Ot.prototype.ma=function(){this.s||(this.s=!0,this.N())},Ot.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function Te(o,l){this.type=o,this.g=this.target=l,this.defaultPrevented=!1}Te.prototype.h=function(){this.defaultPrevented=!0};var Cv=function(){if(!u.addEventListener||!Object.defineProperty)return!1;var o=!1,l=Object.defineProperty({},"passive",{get:function(){o=!0}});try{let d=()=>{};u.addEventListener("test",d,l),u.removeEventListener("test",d,l)}catch{}return o}();function ts(o,l){if(Te.call(this,o?o.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,o){var d=this.type=o.type,p=o.changedTouches&&o.changedTouches.length?o.changedTouches[0]:null;if(this.target=o.target||o.srcElement,this.g=l,l=o.relatedTarget){if(Y){e:{try{G(l.nodeName);var A=!0;break e}catch{}A=!1}A||(l=null)}}else d=="mouseover"?l=o.fromElement:d=="mouseout"&&(l=o.toElement);this.relatedTarget=l,p?(this.clientX=p.clientX!==void 0?p.clientX:p.pageX,this.clientY=p.clientY!==void 0?p.clientY:p.pageY,this.screenX=p.screenX||0,this.screenY=p.screenY||0):(this.clientX=o.clientX!==void 0?o.clientX:o.pageX,this.clientY=o.clientY!==void 0?o.clientY:o.pageY,this.screenX=o.screenX||0,this.screenY=o.screenY||0),this.button=o.button,this.key=o.key||"",this.ctrlKey=o.ctrlKey,this.altKey=o.altKey,this.shiftKey=o.shiftKey,this.metaKey=o.metaKey,this.pointerId=o.pointerId||0,this.pointerType=typeof o.pointerType=="string"?o.pointerType:kv[o.pointerType]||"",this.state=o.state,this.i=o,o.defaultPrevented&&ts.aa.h.call(this)}}P(ts,Te);var kv={2:"touch",3:"pen",4:"mouse"};ts.prototype.h=function(){ts.aa.h.call(this);var o=this.i;o.preventDefault?o.preventDefault():o.returnValue=!1};var rs="closure_listenable_"+(1e6*Math.random()|0),Dv=0;function Ov(o,l,d,p,A){this.listener=o,this.proxy=null,this.src=l,this.type=d,this.capture=!!p,this.ha=A,this.key=++Dv,this.da=this.fa=!1}function wi(o){o.da=!0,o.listener=null,o.proxy=null,o.src=null,o.ha=null}function bi(o){this.src=o,this.g={},this.h=0}bi.prototype.add=function(o,l,d,p,A){var S=o.toString();o=this.g[S],o||(o=this.g[S]=[],this.h++);var O=$a(o,l,p,A);return-1<O?(l=o[O],d||(l.fa=!1)):(l=new Ov(l,this.src,S,!!p,A),l.fa=d,o.push(l)),l};function Ba(o,l){var d=l.type;if(d in o.g){var p=o.g[d],A=Array.prototype.indexOf.call(p,l,void 0),S;(S=0<=A)&&Array.prototype.splice.call(p,A,1),S&&(wi(l),o.g[d].length==0&&(delete o.g[d],o.h--))}}function $a(o,l,d,p){for(var A=0;A<o.length;++A){var S=o[A];if(!S.da&&S.listener==l&&S.capture==!!d&&S.ha==p)return A}return-1}var qa="closure_lm_"+(1e6*Math.random()|0),za={};function Vh(o,l,d,p,A){if(p&&p.once)return Fh(o,l,d,p,A);if(Array.isArray(l)){for(var S=0;S<l.length;S++)Vh(o,l[S],d,p,A);return null}return d=Wa(d),o&&o[rs]?o.K(l,d,h(p)?!!p.capture:!!p,A):Lh(o,l,d,!1,p,A)}function Lh(o,l,d,p,A,S){if(!l)throw Error("Invalid event type");var O=h(A)?!!A.capture:!!A,te=Ka(o);if(te||(o[qa]=te=new bi(o)),d=te.add(l,d,p,O,S),d.proxy)return d;if(p=Nv(),d.proxy=p,p.src=o,p.listener=d,o.addEventListener)Cv||(A=O),A===void 0&&(A=!1),o.addEventListener(l.toString(),p,A);else if(o.attachEvent)o.attachEvent(jh(l.toString()),p);else if(o.addListener&&o.removeListener)o.addListener(p);else throw Error("addEventListener and attachEvent are unavailable.");return d}function Nv(){function o(d){return l.call(o.src,o.listener,d)}let l=Vv;return o}function Fh(o,l,d,p,A){if(Array.isArray(l)){for(var S=0;S<l.length;S++)Fh(o,l[S],d,p,A);return null}return d=Wa(d),o&&o[rs]?o.L(l,d,h(p)?!!p.capture:!!p,A):Lh(o,l,d,!0,p,A)}function Mh(o,l,d,p,A){if(Array.isArray(l))for(var S=0;S<l.length;S++)Mh(o,l[S],d,p,A);else p=h(p)?!!p.capture:!!p,d=Wa(d),o&&o[rs]?(o=o.i,l=String(l).toString(),l in o.g&&(S=o.g[l],d=$a(S,d,p,A),-1<d&&(wi(S[d]),Array.prototype.splice.call(S,d,1),S.length==0&&(delete o.g[l],o.h--)))):o&&(o=Ka(o))&&(l=o.g[l.toString()],o=-1,l&&(o=$a(l,d,p,A)),(d=-1<o?l[o]:null)&&Ga(d))}function Ga(o){if(typeof o!="number"&&o&&!o.da){var l=o.src;if(l&&l[rs])Ba(l.i,o);else{var d=o.type,p=o.proxy;l.removeEventListener?l.removeEventListener(d,p,o.capture):l.detachEvent?l.detachEvent(jh(d),p):l.addListener&&l.removeListener&&l.removeListener(p),(d=Ka(l))?(Ba(d,o),d.h==0&&(d.src=null,l[qa]=null)):wi(o)}}}function jh(o){return o in za?za[o]:za[o]="on"+o}function Vv(o,l){if(o.da)o=!0;else{l=new ts(l,this);var d=o.listener,p=o.ha||o.src;o.fa&&Ga(o),o=d.call(p,l)}return o}function Ka(o){return o=o[qa],o instanceof bi?o:null}var Ha="__closure_events_fn_"+(1e9*Math.random()>>>0);function Wa(o){return typeof o=="function"?o:(o[Ha]||(o[Ha]=function(l){return o.handleEvent(l)}),o[Ha])}function Ee(){Ot.call(this),this.i=new bi(this),this.M=this,this.F=null}P(Ee,Ot),Ee.prototype[rs]=!0,Ee.prototype.removeEventListener=function(o,l,d,p){Mh(this,o,l,d,p)};function Pe(o,l){var d,p=o.F;if(p)for(d=[];p;p=p.F)d.push(p);if(o=o.M,p=l.type||l,typeof l=="string")l=new Te(l,o);else if(l instanceof Te)l.target=l.target||o;else{var A=l;l=new Te(p,o),T(l,A)}if(A=!0,d)for(var S=d.length-1;0<=S;S--){var O=l.g=d[S];A=Ti(O,p,!0,l)&&A}if(O=l.g=o,A=Ti(O,p,!0,l)&&A,A=Ti(O,p,!1,l)&&A,d)for(S=0;S<d.length;S++)O=l.g=d[S],A=Ti(O,p,!1,l)&&A}Ee.prototype.N=function(){if(Ee.aa.N.call(this),this.i){var o=this.i,l;for(l in o.g){for(var d=o.g[l],p=0;p<d.length;p++)wi(d[p]);delete o.g[l],o.h--}}this.F=null},Ee.prototype.K=function(o,l,d,p){return this.i.add(String(o),l,!1,d,p)},Ee.prototype.L=function(o,l,d,p){return this.i.add(String(o),l,!0,d,p)};function Ti(o,l,d,p){if(l=o.i.g[String(l)],!l)return!0;l=l.concat();for(var A=!0,S=0;S<l.length;++S){var O=l[S];if(O&&!O.da&&O.capture==d){var te=O.listener,ve=O.ha||O.src;O.fa&&Ba(o.i,O),A=te.call(ve,p)!==!1&&A}}return A&&!p.defaultPrevented}function Uh(o,l,d){if(typeof o=="function")d&&(o=g(o,d));else if(o&&typeof o.handleEvent=="function")o=g(o.handleEvent,o);else throw Error("Invalid listener argument");return 2147483647<Number(l)?-1:u.setTimeout(o,l||0)}function Bh(o){o.g=Uh(()=>{o.g=null,o.i&&(o.i=!1,Bh(o))},o.l);let l=o.h;o.h=null,o.m.apply(null,l)}class Lv extends Ot{constructor(l,d){super(),this.m=l,this.l=d,this.h=null,this.i=!1,this.g=null}j(l){this.h=arguments,this.g?this.i=!0:Bh(this)}N(){super.N(),this.g&&(u.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function ns(o){Ot.call(this),this.h=o,this.g={}}P(ns,Ot);var $h=[];function qh(o){B(o.g,function(l,d){this.g.hasOwnProperty(d)&&Ga(l)},o),o.g={}}ns.prototype.N=function(){ns.aa.N.call(this),qh(this)},ns.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var Qa=u.JSON.stringify,Fv=u.JSON.parse,Mv=class{stringify(o){return u.JSON.stringify(o,void 0)}parse(o){return u.JSON.parse(o,void 0)}};function Ja(){}Ja.prototype.h=null;function zh(o){return o.h||(o.h=o.i())}function Gh(){}var ss={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function Ya(){Te.call(this,"d")}P(Ya,Te);function Xa(){Te.call(this,"c")}P(Xa,Te);var ar={},Kh=null;function Ei(){return Kh=Kh||new Ee}ar.La="serverreachability";function Hh(o){Te.call(this,ar.La,o)}P(Hh,Te);function is(o){let l=Ei();Pe(l,new Hh(l))}ar.STAT_EVENT="statevent";function Wh(o,l){Te.call(this,ar.STAT_EVENT,o),this.stat=l}P(Wh,Te);function Ce(o){let l=Ei();Pe(l,new Wh(l,o))}ar.Ma="timingevent";function Qh(o,l){Te.call(this,ar.Ma,o),this.size=l}P(Qh,Te);function os(o,l){if(typeof o!="function")throw Error("Fn must not be null and must be a function");return u.setTimeout(function(){o()},l)}function as(){this.g=!0}as.prototype.xa=function(){this.g=!1};function jv(o,l,d,p,A,S){o.info(function(){if(o.g)if(S)for(var O="",te=S.split("&"),ve=0;ve<te.length;ve++){var X=te[ve].split("=");if(1<X.length){var Ie=X[0];X=X[1];var Ae=Ie.split("_");O=2<=Ae.length&&Ae[1]=="type"?O+(Ie+"="+X+"&"):O+(Ie+"=redacted&")}}else O=null;else O=S;return"XMLHTTP REQ ("+p+") [attempt "+A+"]: "+l+`
2
2
  `+d+`
3
3
  `+O})}function Uv(o,l,d,p,A,S,O){o.info(function(){return"XMLHTTP RESP ("+p+") [ attempt "+A+"]: "+l+`
4
4
  `+d+`
5
- `+S+" "+O})}function Ur(o,l,d,p){o.info(function(){return"XMLHTTP TEXT ("+l+"): "+$v(o,d)+(p?" "+p:"")})}function Bv(o,l){o.info(function(){return"TIMEOUT: "+l})}as.prototype.info=function(){};function $v(o,l){if(!o.g)return l;if(!l)return null;try{var d=JSON.parse(l);if(d){for(o=0;o<d.length;o++)if(Array.isArray(d[o])){var p=d[o];if(!(2>p.length)){var A=p[1];if(Array.isArray(A)&&!(1>A.length)){var S=A[0];if(S!="noop"&&S!="stop"&&S!="close")for(var O=1;O<A.length;O++)A[O]=""}}}}return Qa(d)}catch{return l}}var Ai={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},Jh={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"},Za;function xi(){}P(xi,Ja),xi.prototype.g=function(){return new XMLHttpRequest},xi.prototype.i=function(){return{}},Za=new xi;function Nt(o,l,d,p){this.j=o,this.i=l,this.l=d,this.R=p||1,this.U=new ns(this),this.I=45e3,this.H=null,this.o=!1,this.m=this.A=this.v=this.L=this.F=this.S=this.B=null,this.D=[],this.g=null,this.C=0,this.s=this.u=null,this.X=-1,this.J=!1,this.O=0,this.M=null,this.W=this.K=this.T=this.P=!1,this.h=new Yh}function Yh(){this.i=null,this.g="",this.h=!1}var Xh={},eu={};function tu(o,l,d){o.L=1,o.v=Ci(pt(l)),o.m=d,o.P=!0,Zh(o,null)}function Zh(o,l){o.F=Date.now(),Si(o),o.A=pt(o.v);var d=o.A,p=o.R;Array.isArray(p)||(p=[String(p)]),fd(d.i,"t",p),o.C=0,d=o.j.J,o.h=new Yh,o.g=kd(o.j,d?l:null,!o.m),0<o.O&&(o.M=new Lv(g(o.Y,o,o.g),o.O)),l=o.U,d=o.g,p=o.ca;var A="readystatechange";Array.isArray(A)||(A&&($h[0]=A.toString()),A=$h);for(var S=0;S<A.length;S++){var O=Vh(d,A[S],p||l.handleEvent,!1,l.h||l);if(!O)break;l.g[O.key]=O}l=o.H?y(o.H):{},o.m?(o.u||(o.u="POST"),l["Content-Type"]="application/x-www-form-urlencoded",o.g.ea(o.A,o.u,o.m,l)):(o.u="GET",o.g.ea(o.A,o.u,null,l)),is(),jv(o.i,o.u,o.A,o.l,o.R,o.m)}Nt.prototype.ca=function(o){o=o.target;let l=this.M;l&&mt(o)==3?l.j():this.Y(o)},Nt.prototype.Y=function(o){try{if(o==this.g)e:{let Ae=mt(this.g);var l=this.g.Ba();let qr=this.g.Z();if(!(3>Ae)&&(Ae!=3||this.g&&(this.h.h||this.g.oa()||wd(this.g)))){this.J||Ae!=4||l==7||(l==8||0>=qr?is(3):is(2)),ru(this);var d=this.g.Z();this.X=d;t:if(ed(this)){var p=wd(this.g);o="";var A=p.length,S=mt(this.g)==4;if(!this.h.i){if(typeof TextDecoder=="undefined"){ur(this),us(this);var O="";break t}this.h.i=new u.TextDecoder}for(l=0;l<A;l++)this.h.h=!0,o+=this.h.i.decode(p[l],{stream:!(S&&l==A-1)});p.length=0,this.h.g+=o,this.C=0,O=this.h.g}else O=this.g.oa();if(this.o=d==200,Uv(this.i,this.u,this.A,this.l,this.R,Ae,d),this.o){if(this.T&&!this.K){t:{if(this.g){var te,ve=this.g;if((te=ve.g?ve.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!F(te)){var X=te;break t}}X=null}if(d=X)Ur(this.i,this.l,d,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,nu(this,d);else{this.o=!1,this.s=3,Ce(12),ur(this),us(this);break e}}if(this.P){d=!0;let Ke;for(;!this.J&&this.C<O.length;)if(Ke=qv(this,O),Ke==eu){Ae==4&&(this.s=4,Ce(14),d=!1),Ur(this.i,this.l,null,"[Incomplete Response]");break}else if(Ke==Xh){this.s=4,Ce(15),Ur(this.i,this.l,O,"[Invalid Chunk]"),d=!1;break}else Ur(this.i,this.l,Ke,null),nu(this,Ke);if(ed(this)&&this.C!=0&&(this.h.g=this.h.g.slice(this.C),this.C=0),Ae!=4||O.length!=0||this.h.h||(this.s=1,Ce(16),d=!1),this.o=this.o&&d,!d)Ur(this.i,this.l,O,"[Invalid Chunked Response]"),ur(this),us(this);else if(0<O.length&&!this.W){this.W=!0;var Ie=this.j;Ie.g==this&&Ie.ba&&!Ie.M&&(Ie.j.info("Great, no buffering proxy detected. Bytes received: "+O.length),cu(Ie),Ie.M=!0,Ce(11))}}else Ur(this.i,this.l,O,null),nu(this,O);Ae==4&&ur(this),this.o&&!this.J&&(Ae==4?Sd(this.j,this):(this.o=!1,Si(this)))}else ow(this.g),d==400&&0<O.indexOf("Unknown SID")?(this.s=3,Ce(12)):(this.s=0,Ce(13)),ur(this),us(this)}}}catch{}finally{}};function ed(o){return o.g?o.u=="GET"&&o.L!=2&&o.j.Ca:!1}function qv(o,l){var d=o.C,p=l.indexOf(`
6
- `,d);return p==-1?eu:(d=Number(l.substring(d,p)),isNaN(d)?Xh:(p+=1,p+d>l.length?eu:(l=l.slice(p,p+d),o.C=p+d,l)))}Nt.prototype.cancel=function(){this.J=!0,ur(this)};function Si(o){o.S=Date.now()+o.I,td(o,o.I)}function td(o,l){if(o.B!=null)throw Error("WatchDog timer not null");o.B=os(g(o.ba,o),l)}function ru(o){o.B&&(u.clearTimeout(o.B),o.B=null)}Nt.prototype.ba=function(){this.B=null;let o=Date.now();0<=o-this.S?(Bv(this.i,this.A),this.L!=2&&(is(),Ce(17)),ur(this),this.s=2,us(this)):td(this,this.S-o)};function us(o){o.j.G==0||o.J||Sd(o.j,o)}function ur(o){ru(o);var l=o.M;l&&typeof l.ma=="function"&&l.ma(),o.M=null,qh(o.U),o.g&&(l=o.g,o.g=null,l.abort(),l.ma())}function nu(o,l){try{var d=o.j;if(d.G!=0&&(d.g==o||su(d.h,o))){if(!o.K&&su(d.h,o)&&d.G==3){try{var p=d.Da.g.parse(l)}catch{p=null}if(Array.isArray(p)&&p.length==3){var A=p;if(A[0]==0){e:if(!d.u){if(d.g)if(d.g.F+3e3<o.F)Vi(d),Oi(d);else break e;uu(d),Ce(18)}}else d.za=A[1],0<d.za-d.T&&37500>A[2]&&d.F&&d.v==0&&!d.C&&(d.C=os(g(d.Za,d),6e3));if(1>=sd(d.h)&&d.ca){try{d.ca()}catch{}d.ca=void 0}}else lr(d,11)}else if((o.K||d.g==o)&&Vi(d),!F(l))for(A=d.Da.g.parse(l),l=0;l<A.length;l++){let X=A[l];if(d.T=X[0],X=X[1],d.G==2)if(X[0]=="c"){d.K=X[1],d.ia=X[2];let Ie=X[3];Ie!=null&&(d.la=Ie,d.j.info("VER="+d.la));let Ae=X[4];Ae!=null&&(d.Aa=Ae,d.j.info("SVER="+d.Aa));let qr=X[5];qr!=null&&typeof qr=="number"&&0<qr&&(p=1.5*qr,d.L=p,d.j.info("backChannelRequestTimeoutMs_="+p)),p=d;let Ke=o.g;if(Ke){let Fi=Ke.g?Ke.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(Fi){var S=p.h;S.g||Fi.indexOf("spdy")==-1&&Fi.indexOf("quic")==-1&&Fi.indexOf("h2")==-1||(S.j=S.l,S.g=new Set,S.h&&(iu(S,S.h),S.h=null))}if(p.D){let lu=Ke.g?Ke.g.getResponseHeader("X-HTTP-Session-Id"):null;lu&&(p.ya=lu,se(p.I,p.D,lu))}}d.G=3,d.l&&d.l.ua(),d.ba&&(d.R=Date.now()-o.F,d.j.info("Handshake RTT: "+d.R+"ms")),p=d;var O=o;if(p.qa=Cd(p,p.J?p.ia:null,p.W),O.K){id(p.h,O);var te=O,ve=p.L;ve&&(te.I=ve),te.B&&(ru(te),Si(te)),p.g=O}else Ad(p);0<d.i.length&&Ni(d)}else X[0]!="stop"&&X[0]!="close"||lr(d,7);else d.G==3&&(X[0]=="stop"||X[0]=="close"?X[0]=="stop"?lr(d,7):au(d):X[0]!="noop"&&d.l&&d.l.ta(X),d.v=0)}}is(4)}catch{}}var zv=class{constructor(o,l){this.g=o,this.map=l}};function rd(o){this.l=o||10,u.PerformanceNavigationTiming?(o=u.performance.getEntriesByType("navigation"),o=0<o.length&&(o[0].nextHopProtocol=="hq"||o[0].nextHopProtocol=="h2")):o=!!(u.chrome&&u.chrome.loadTimes&&u.chrome.loadTimes()&&u.chrome.loadTimes().wasFetchedViaSpdy),this.j=o?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function nd(o){return o.h?!0:o.g?o.g.size>=o.j:!1}function sd(o){return o.h?1:o.g?o.g.size:0}function su(o,l){return o.h?o.h==l:o.g?o.g.has(l):!1}function iu(o,l){o.g?o.g.add(l):o.h=l}function id(o,l){o.h&&o.h==l?o.h=null:o.g&&o.g.has(l)&&o.g.delete(l)}rd.prototype.cancel=function(){if(this.i=od(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&this.g.size!==0){for(let o of this.g.values())o.cancel();this.g.clear()}};function od(o){if(o.h!=null)return o.i.concat(o.h.D);if(o.g!=null&&o.g.size!==0){let l=o.i;for(let d of o.g.values())l=l.concat(d.D);return l}return C(o.i)}function Gv(o){if(o.V&&typeof o.V=="function")return o.V();if(typeof Map!="undefined"&&o instanceof Map||typeof Set!="undefined"&&o instanceof Set)return Array.from(o.values());if(typeof o=="string")return o.split("");if(c(o)){for(var l=[],d=o.length,p=0;p<d;p++)l.push(o[p]);return l}l=[],d=0;for(p in o)l[d++]=o[p];return l}function Kv(o){if(o.na&&typeof o.na=="function")return o.na();if(!o.V||typeof o.V!="function"){if(typeof Map!="undefined"&&o instanceof Map)return Array.from(o.keys());if(!(typeof Set!="undefined"&&o instanceof Set)){if(c(o)||typeof o=="string"){var l=[];o=o.length;for(var d=0;d<o;d++)l.push(d);return l}l=[],d=0;for(let p in o)l[d++]=p;return l}}}function ad(o,l){if(o.forEach&&typeof o.forEach=="function")o.forEach(l,void 0);else if(c(o)||typeof o=="string")Array.prototype.forEach.call(o,l,void 0);else for(var d=Kv(o),p=Gv(o),A=p.length,S=0;S<A;S++)l.call(void 0,p[S],d&&d[S],o)}var ud=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function Hv(o,l){if(o){o=o.split("&");for(var d=0;d<o.length;d++){var p=o[d].indexOf("="),A=null;if(0<=p){var S=o[d].substring(0,p);A=o[d].substring(p+1)}else S=o[d];l(S,A?decodeURIComponent(A.replace(/\+/g," ")):"")}}}function cr(o){if(this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,o instanceof cr){this.h=o.h,Ri(this,o.j),this.o=o.o,this.g=o.g,Pi(this,o.s),this.l=o.l;var l=o.i,d=new hs;d.i=l.i,l.g&&(d.g=new Map(l.g),d.h=l.h),cd(this,d),this.m=o.m}else o&&(l=String(o).match(ud))?(this.h=!1,Ri(this,l[1]||"",!0),this.o=cs(l[2]||""),this.g=cs(l[3]||"",!0),Pi(this,l[4]),this.l=cs(l[5]||"",!0),cd(this,l[6]||"",!0),this.m=cs(l[7]||"")):(this.h=!1,this.i=new hs(null,this.h))}cr.prototype.toString=function(){var o=[],l=this.j;l&&o.push(ls(l,ld,!0),":");var d=this.g;return(d||l=="file")&&(o.push("//"),(l=this.o)&&o.push(ls(l,ld,!0),"@"),o.push(encodeURIComponent(String(d)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),d=this.s,d!=null&&o.push(":",String(d))),(d=this.l)&&(this.g&&d.charAt(0)!="/"&&o.push("/"),o.push(ls(d,d.charAt(0)=="/"?Jv:Qv,!0))),(d=this.i.toString())&&o.push("?",d),(d=this.m)&&o.push("#",ls(d,Xv)),o.join("")};function pt(o){return new cr(o)}function Ri(o,l,d){o.j=d?cs(l,!0):l,o.j&&(o.j=o.j.replace(/:$/,""))}function Pi(o,l){if(l){if(l=Number(l),isNaN(l)||0>l)throw Error("Bad port number "+l);o.s=l}else o.s=null}function cd(o,l,d){l instanceof hs?(o.i=l,Zv(o.i,o.h)):(d||(l=ls(l,Yv)),o.i=new hs(l,o.h))}function se(o,l,d){o.i.set(l,d)}function Ci(o){return se(o,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),o}function cs(o,l){return o?l?decodeURI(o.replace(/%25/g,"%2525")):decodeURIComponent(o):""}function ls(o,l,d){return typeof o=="string"?(o=encodeURI(o).replace(l,Wv),d&&(o=o.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),o):null}function Wv(o){return o=o.charCodeAt(0),"%"+(o>>4&15).toString(16)+(o&15).toString(16)}var ld=/[#\/\?@]/g,Qv=/[#\?:]/g,Jv=/[#\?]/g,Yv=/[#\?@]/g,Xv=/#/g;function hs(o,l){this.h=this.g=null,this.i=o||null,this.j=!!l}function Vt(o){o.g||(o.g=new Map,o.h=0,o.i&&Hv(o.i,function(l,d){o.add(decodeURIComponent(l.replace(/\+/g," ")),d)}))}r=hs.prototype,r.add=function(o,l){Vt(this),this.i=null,o=Br(this,o);var d=this.g.get(o);return d||this.g.set(o,d=[]),d.push(l),this.h+=1,this};function hd(o,l){Vt(o),l=Br(o,l),o.g.has(l)&&(o.i=null,o.h-=o.g.get(l).length,o.g.delete(l))}function dd(o,l){return Vt(o),l=Br(o,l),o.g.has(l)}r.forEach=function(o,l){Vt(this),this.g.forEach(function(d,p){d.forEach(function(A){o.call(l,A,p,this)},this)},this)},r.na=function(){Vt(this);let o=Array.from(this.g.values()),l=Array.from(this.g.keys()),d=[];for(let p=0;p<l.length;p++){let A=o[p];for(let S=0;S<A.length;S++)d.push(l[p])}return d},r.V=function(o){Vt(this);let l=[];if(typeof o=="string")dd(this,o)&&(l=l.concat(this.g.get(Br(this,o))));else{o=Array.from(this.g.values());for(let d=0;d<o.length;d++)l=l.concat(o[d])}return l},r.set=function(o,l){return Vt(this),this.i=null,o=Br(this,o),dd(this,o)&&(this.h-=this.g.get(o).length),this.g.set(o,[l]),this.h+=1,this},r.get=function(o,l){return o?(o=this.V(o),0<o.length?String(o[0]):l):l};function fd(o,l,d){hd(o,l),0<d.length&&(o.i=null,o.g.set(Br(o,l),C(d)),o.h+=d.length)}r.toString=function(){if(this.i)return this.i;if(!this.g)return"";let o=[],l=Array.from(this.g.keys());for(var d=0;d<l.length;d++){var p=l[d];let S=encodeURIComponent(String(p)),O=this.V(p);for(p=0;p<O.length;p++){var A=S;O[p]!==""&&(A+="="+encodeURIComponent(String(O[p]))),o.push(A)}}return this.i=o.join("&")};function Br(o,l){return l=String(l),o.j&&(l=l.toLowerCase()),l}function Zv(o,l){l&&!o.j&&(Vt(o),o.i=null,o.g.forEach(function(d,p){var A=p.toLowerCase();p!=A&&(hd(this,p),fd(this,A,d))},o)),o.j=l}function ew(o,l){let d=new as;if(u.Image){let p=new Image;p.onload=b(Lt,d,"TestLoadImage: loaded",!0,l,p),p.onerror=b(Lt,d,"TestLoadImage: error",!1,l,p),p.onabort=b(Lt,d,"TestLoadImage: abort",!1,l,p),p.ontimeout=b(Lt,d,"TestLoadImage: timeout",!1,l,p),u.setTimeout(function(){p.ontimeout&&p.ontimeout()},1e4),p.src=o}else l(!1)}function tw(o,l){let d=new as,p=new AbortController,A=setTimeout(()=>{p.abort(),Lt(d,"TestPingServer: timeout",!1,l)},1e4);fetch(o,{signal:p.signal}).then(S=>{clearTimeout(A),S.ok?Lt(d,"TestPingServer: ok",!0,l):Lt(d,"TestPingServer: server error",!1,l)}).catch(()=>{clearTimeout(A),Lt(d,"TestPingServer: error",!1,l)})}function Lt(o,l,d,p,A){try{A&&(A.onload=null,A.onerror=null,A.onabort=null,A.ontimeout=null),p(d)}catch{}}function rw(){this.g=new Mv}function nw(o,l,d){let p=d||"";try{ad(o,function(A,S){let O=A;h(A)&&(O=Qa(A)),l.push(p+S+"="+encodeURIComponent(O))})}catch(A){throw l.push(p+"type="+encodeURIComponent("_badmap")),A}}function ds(o){this.l=o.Ub||null,this.j=o.eb||!1}P(ds,Ja),ds.prototype.g=function(){return new ki(this.l,this.j)},ds.prototype.i=function(o){return function(){return o}}({});function ki(o,l){Ee.call(this),this.D=o,this.o=l,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.u=new Headers,this.h=null,this.B="GET",this.A="",this.g=!1,this.v=this.j=this.l=null}P(ki,Ee),r=ki.prototype,r.open=function(o,l){if(this.readyState!=0)throw this.abort(),Error("Error reopening a connection");this.B=o,this.A=l,this.readyState=1,ps(this)},r.send=function(o){if(this.readyState!=1)throw this.abort(),Error("need to call open() first. ");this.g=!0;let l={headers:this.u,method:this.B,credentials:this.m,cache:void 0};o&&(l.body=o),(this.D||u).fetch(new Request(this.A,l)).then(this.Sa.bind(this),this.ga.bind(this))},r.abort=function(){this.response=this.responseText="",this.u=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&this.readyState!=4&&(this.g=!1,fs(this)),this.readyState=0},r.Sa=function(o){if(this.g&&(this.l=o,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=o.headers,this.readyState=2,ps(this)),this.g&&(this.readyState=3,ps(this),this.g)))if(this.responseType==="arraybuffer")o.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(typeof u.ReadableStream!="undefined"&&"body"in o){if(this.j=o.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.v=new TextDecoder;pd(this)}else o.text().then(this.Ra.bind(this),this.ga.bind(this))};function pd(o){o.j.read().then(o.Pa.bind(o)).catch(o.ga.bind(o))}r.Pa=function(o){if(this.g){if(this.o&&o.value)this.response.push(o.value);else if(!this.o){var l=o.value?o.value:new Uint8Array(0);(l=this.v.decode(l,{stream:!o.done}))&&(this.response=this.responseText+=l)}o.done?fs(this):ps(this),this.readyState==3&&pd(this)}},r.Ra=function(o){this.g&&(this.response=this.responseText=o,fs(this))},r.Qa=function(o){this.g&&(this.response=o,fs(this))},r.ga=function(){this.g&&fs(this)};function fs(o){o.readyState=4,o.l=null,o.j=null,o.v=null,ps(o)}r.setRequestHeader=function(o,l){this.u.append(o,l)},r.getResponseHeader=function(o){return this.h&&this.h.get(o.toLowerCase())||""},r.getAllResponseHeaders=function(){if(!this.h)return"";let o=[],l=this.h.entries();for(var d=l.next();!d.done;)d=d.value,o.push(d[0]+": "+d[1]),d=l.next();return o.join(`\r
7
- `)};function ps(o){o.onreadystatechange&&o.onreadystatechange.call(o)}Object.defineProperty(ki.prototype,"withCredentials",{get:function(){return this.m==="include"},set:function(o){this.m=o?"include":"same-origin"}});function md(o){let l="";return B(o,function(d,p){l+=p,l+=":",l+=d,l+=`\r
8
- `}),l}function ou(o,l,d){e:{for(p in d){var p=!1;break e}p=!0}p||(d=md(d),typeof o=="string"?d!=null&&encodeURIComponent(String(d)):se(o,l,d))}function ae(o){Ee.call(this),this.headers=new Map,this.o=o||null,this.h=!1,this.v=this.g=null,this.D="",this.m=0,this.l="",this.j=this.B=this.u=this.A=!1,this.I=null,this.H="",this.J=!1}P(ae,Ee);var sw=/^https?$/i,iw=["POST","PUT"];r=ae.prototype,r.Ha=function(o){this.J=o},r.ea=function(o,l,d,p){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+o);l=l?l.toUpperCase():"GET",this.D=o,this.l="",this.m=0,this.A=!1,this.h=!0,this.g=this.o?this.o.g():Za.g(),this.v=this.o?zh(this.o):zh(Za),this.g.onreadystatechange=g(this.Ea,this);try{this.B=!0,this.g.open(l,String(o),!0),this.B=!1}catch(S){gd(this,S);return}if(o=d||"",d=new Map(this.headers),p)if(Object.getPrototypeOf(p)===Object.prototype)for(var A in p)d.set(A,p[A]);else if(typeof p.keys=="function"&&typeof p.get=="function")for(let S of p.keys())d.set(S,p.get(S));else throw Error("Unknown input type for opt_headers: "+String(p));p=Array.from(d.keys()).find(S=>S.toLowerCase()=="content-type"),A=u.FormData&&o instanceof u.FormData,!(0<=Array.prototype.indexOf.call(iw,l,void 0))||p||A||d.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(let[S,O]of d)this.g.setRequestHeader(S,O);this.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{vd(this),this.u=!0,this.g.send(o),this.u=!1}catch(S){gd(this,S)}};function gd(o,l){o.h=!1,o.g&&(o.j=!0,o.g.abort(),o.j=!1),o.l=l,o.m=5,yd(o),Di(o)}function yd(o){o.A||(o.A=!0,Pe(o,"complete"),Pe(o,"error"))}r.abort=function(o){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=o||7,Pe(this,"complete"),Pe(this,"abort"),Di(this))},r.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Di(this,!0)),ae.aa.N.call(this)},r.Ea=function(){this.s||(this.B||this.u||this.j?_d(this):this.bb())},r.bb=function(){_d(this)};function _d(o){if(o.h&&typeof a!="undefined"&&(!o.v[1]||mt(o)!=4||o.Z()!=2)){if(o.u&&mt(o)==4)Uh(o.Ea,0,o);else if(Pe(o,"readystatechange"),mt(o)==4){o.h=!1;try{let O=o.Z();e:switch(O){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var l=!0;break e;default:l=!1}var d;if(!(d=l)){var p;if(p=O===0){var A=String(o.D).match(ud)[1]||null;!A&&u.self&&u.self.location&&(A=u.self.location.protocol.slice(0,-1)),p=!sw.test(A?A.toLowerCase():"")}d=p}if(d)Pe(o,"complete"),Pe(o,"success");else{o.m=6;try{var S=2<mt(o)?o.g.statusText:""}catch{S=""}o.l=S+" ["+o.Z()+"]",yd(o)}}finally{Di(o)}}}}function Di(o,l){if(o.g){vd(o);let d=o.g,p=o.v[0]?()=>{}:null;o.g=null,o.v=null,l||Pe(o,"ready");try{d.onreadystatechange=p}catch{}}}function vd(o){o.I&&(u.clearTimeout(o.I),o.I=null)}r.isActive=function(){return!!this.g};function mt(o){return o.g?o.g.readyState:0}r.Z=function(){try{return 2<mt(this)?this.g.status:-1}catch{return-1}},r.oa=function(){try{return this.g?this.g.responseText:""}catch{return""}},r.Oa=function(o){if(this.g){var l=this.g.responseText;return o&&l.indexOf(o)==0&&(l=l.substring(o.length)),Fv(l)}};function wd(o){try{if(!o.g)return null;if("response"in o.g)return o.g.response;switch(o.H){case"":case"text":return o.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in o.g)return o.g.mozResponseArrayBuffer}return null}catch{return null}}function ow(o){let l={};o=(o.g&&2<=mt(o)&&o.g.getAllResponseHeaders()||"").split(`\r
9
- `);for(let p=0;p<o.length;p++){if(F(o[p]))continue;var d=I(o[p]);let A=d[0];if(d=d[1],typeof d!="string")continue;d=d.trim();let S=l[A]||[];l[A]=S,S.push(d)}E(l,function(p){return p.join(", ")})}r.Ba=function(){return this.m},r.Ka=function(){return typeof this.l=="string"?this.l:String(this.l)};function ms(o,l,d){return d&&d.internalChannelParams&&d.internalChannelParams[o]||l}function bd(o){this.Aa=0,this.i=[],this.j=new as,this.ia=this.qa=this.I=this.W=this.g=this.ya=this.D=this.H=this.m=this.S=this.o=null,this.Ya=this.U=0,this.Va=ms("failFast",!1,o),this.F=this.C=this.u=this.s=this.l=null,this.X=!0,this.za=this.T=-1,this.Y=this.v=this.B=0,this.Ta=ms("baseRetryDelayMs",5e3,o),this.cb=ms("retryDelaySeedMs",1e4,o),this.Wa=ms("forwardChannelMaxRetries",2,o),this.wa=ms("forwardChannelRequestTimeoutMs",2e4,o),this.pa=o&&o.xmlHttpFactory||void 0,this.Xa=o&&o.Tb||void 0,this.Ca=o&&o.useFetchStreams||!1,this.L=void 0,this.J=o&&o.supportsCrossDomainXhr||!1,this.K="",this.h=new rd(o&&o.concurrentRequestLimit),this.Da=new rw,this.P=o&&o.fastHandshake||!1,this.O=o&&o.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=o&&o.Rb||!1,o&&o.xa&&this.j.xa(),o&&o.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&o&&o.detectBufferingProxy||!1,this.ja=void 0,o&&o.longPollingTimeout&&0<o.longPollingTimeout&&(this.ja=o.longPollingTimeout),this.ca=void 0,this.R=0,this.M=!1,this.ka=this.A=null}r=bd.prototype,r.la=8,r.G=1,r.connect=function(o,l,d,p){Ce(0),this.W=o,this.H=l||{},d&&p!==void 0&&(this.H.OSID=d,this.H.OAID=p),this.F=this.X,this.I=Cd(this,null,this.W),Ni(this)};function au(o){if(Td(o),o.G==3){var l=o.U++,d=pt(o.I);if(se(d,"SID",o.K),se(d,"RID",l),se(d,"TYPE","terminate"),gs(o,d),l=new Nt(o,o.j,l),l.L=2,l.v=Ci(pt(d)),d=!1,u.navigator&&u.navigator.sendBeacon)try{d=u.navigator.sendBeacon(l.v.toString(),"")}catch{}!d&&u.Image&&(new Image().src=l.v,d=!0),d||(l.g=kd(l.j,null),l.g.ea(l.v)),l.F=Date.now(),Si(l)}Pd(o)}function Oi(o){o.g&&(cu(o),o.g.cancel(),o.g=null)}function Td(o){Oi(o),o.u&&(u.clearTimeout(o.u),o.u=null),Vi(o),o.h.cancel(),o.s&&(typeof o.s=="number"&&u.clearTimeout(o.s),o.s=null)}function Ni(o){if(!nd(o.h)&&!o.s){o.s=!0;var l=o.Ga;Zn||Nh(),es||(Zn(),es=!0),Ua.add(l,o),o.B=0}}function aw(o,l){return sd(o.h)>=o.h.j-(o.s?1:0)?!1:o.s?(o.i=l.D.concat(o.i),!0):o.G==1||o.G==2||o.B>=(o.Va?0:o.Wa)?!1:(o.s=os(g(o.Ga,o,l),Rd(o,o.B)),o.B++,!0)}r.Ga=function(o){if(this.s)if(this.s=null,this.G==1){if(!o){this.U=Math.floor(1e5*Math.random()),o=this.U++;let A=new Nt(this,this.j,o),S=this.o;if(this.S&&(S?(S=y(S),T(S,this.S)):S=this.S),this.m!==null||this.O||(A.H=S,S=null),this.P)e:{for(var l=0,d=0;d<this.i.length;d++){t:{var p=this.i[d];if("__data__"in p.map&&(p=p.map.__data__,typeof p=="string")){p=p.length;break t}p=void 0}if(p===void 0)break;if(l+=p,4096<l){l=d;break e}if(l===4096||d===this.i.length-1){l=d+1;break e}}l=1e3}else l=1e3;l=Id(this,A,l),d=pt(this.I),se(d,"RID",o),se(d,"CVER",22),this.D&&se(d,"X-HTTP-Session-Id",this.D),gs(this,d),S&&(this.O?l="headers="+encodeURIComponent(String(md(S)))+"&"+l:this.m&&ou(d,this.m,S)),iu(this.h,A),this.Ua&&se(d,"TYPE","init"),this.P?(se(d,"$req",l),se(d,"SID","null"),A.T=!0,tu(A,d,null)):tu(A,d,l),this.G=2}}else this.G==3&&(o?Ed(this,o):this.i.length==0||nd(this.h)||Ed(this))};function Ed(o,l){var d;l?d=l.l:d=o.U++;let p=pt(o.I);se(p,"SID",o.K),se(p,"RID",d),se(p,"AID",o.T),gs(o,p),o.m&&o.o&&ou(p,o.m,o.o),d=new Nt(o,o.j,d,o.B+1),o.m===null&&(d.H=o.o),l&&(o.i=l.D.concat(o.i)),l=Id(o,d,1e3),d.I=Math.round(.5*o.wa)+Math.round(.5*o.wa*Math.random()),iu(o.h,d),tu(d,p,l)}function gs(o,l){o.H&&B(o.H,function(d,p){se(l,p,d)}),o.l&&ad({},function(d,p){se(l,p,d)})}function Id(o,l,d){d=Math.min(o.i.length,d);var p=o.l?g(o.l.Na,o.l,o):null;e:{var A=o.i;let S=-1;for(;;){let O=["count="+d];S==-1?0<d?(S=A[0].g,O.push("ofs="+S)):S=0:O.push("ofs="+S);let te=!0;for(let ve=0;ve<d;ve++){let X=A[ve].g,Ie=A[ve].map;if(X-=S,0>X)S=Math.max(0,A[ve].g-100),te=!1;else try{nw(Ie,O,"req"+X+"_")}catch{p&&p(Ie)}}if(te){p=O.join("&");break e}}}return o=o.i.splice(0,d),l.D=o,p}function Ad(o){if(!o.g&&!o.u){o.Y=1;var l=o.Fa;Zn||Nh(),es||(Zn(),es=!0),Ua.add(l,o),o.v=0}}function uu(o){return o.g||o.u||3<=o.v?!1:(o.Y++,o.u=os(g(o.Fa,o),Rd(o,o.v)),o.v++,!0)}r.Fa=function(){if(this.u=null,xd(this),this.ba&&!(this.M||this.g==null||0>=this.R)){var o=2*this.R;this.j.info("BP detection timer enabled: "+o),this.A=os(g(this.ab,this),o)}},r.ab=function(){this.A&&(this.A=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.M=!0,Ce(10),Oi(this),xd(this))};function cu(o){o.A!=null&&(u.clearTimeout(o.A),o.A=null)}function xd(o){o.g=new Nt(o,o.j,"rpc",o.Y),o.m===null&&(o.g.H=o.o),o.g.O=0;var l=pt(o.qa);se(l,"RID","rpc"),se(l,"SID",o.K),se(l,"AID",o.T),se(l,"CI",o.F?"0":"1"),!o.F&&o.ja&&se(l,"TO",o.ja),se(l,"TYPE","xmlhttp"),gs(o,l),o.m&&o.o&&ou(l,o.m,o.o),o.L&&(o.g.I=o.L);var d=o.g;o=o.ia,d.L=1,d.v=Ci(pt(l)),d.m=null,d.P=!0,Zh(d,o)}r.Za=function(){this.C!=null&&(this.C=null,Oi(this),uu(this),Ce(19))};function Vi(o){o.C!=null&&(u.clearTimeout(o.C),o.C=null)}function Sd(o,l){var d=null;if(o.g==l){Vi(o),cu(o),o.g=null;var p=2}else if(su(o.h,l))d=l.D,id(o.h,l),p=1;else return;if(o.G!=0){if(l.o)if(p==1){d=l.m?l.m.length:0,l=Date.now()-l.F;var A=o.B;p=Ii(),Pe(p,new Qh(p,d)),Ni(o)}else Ad(o);else if(A=l.s,A==3||A==0&&0<l.X||!(p==1&&aw(o,l)||p==2&&uu(o)))switch(d&&0<d.length&&(l=o.h,l.i=l.i.concat(d)),A){case 1:lr(o,5);break;case 4:lr(o,10);break;case 3:lr(o,6);break;default:lr(o,2)}}}function Rd(o,l){let d=o.Ta+Math.floor(Math.random()*o.cb);return o.isActive()||(d*=2),d*l}function lr(o,l){if(o.j.info("Error code "+l),l==2){var d=g(o.fb,o),p=o.Xa;let A=!p;p=new cr(p||"//www.google.com/images/cleardot.gif"),u.location&&u.location.protocol=="http"||Ri(p,"https"),Ci(p),A?ew(p.toString(),d):tw(p.toString(),d)}else Ce(2);o.G=0,o.l&&o.l.sa(l),Pd(o),Td(o)}r.fb=function(o){o?(this.j.info("Successfully pinged google.com"),Ce(2)):(this.j.info("Failed to ping google.com"),Ce(1))};function Pd(o){if(o.G=0,o.ka=[],o.l){let l=od(o.h);(l.length!=0||o.i.length!=0)&&(R(o.ka,l),R(o.ka,o.i),o.h.i.length=0,C(o.i),o.i.length=0),o.l.ra()}}function Cd(o,l,d){var p=d instanceof cr?pt(d):new cr(d);if(p.g!="")l&&(p.g=l+"."+p.g),Pi(p,p.s);else{var A=u.location;p=A.protocol,l=l?l+"."+A.hostname:A.hostname,A=+A.port;var S=new cr(null);p&&Ri(S,p),l&&(S.g=l),A&&Pi(S,A),d&&(S.l=d),p=S}return d=o.D,l=o.ya,d&&l&&se(p,d,l),se(p,"VER",o.la),gs(o,p),p}function kd(o,l,d){if(l&&!o.J)throw Error("Can't create secondary domain capable XhrIo object.");return l=o.Ca&&!o.pa?new ae(new ds({eb:d})):new ae(o.pa),l.Ha(o.J),l}r.isActive=function(){return!!this.l&&this.l.isActive(this)};function Dd(){}r=Dd.prototype,r.ua=function(){},r.ta=function(){},r.sa=function(){},r.ra=function(){},r.isActive=function(){return!0},r.Na=function(){};function Li(){}Li.prototype.g=function(o,l){return new Fe(o,l)};function Fe(o,l){Ee.call(this),this.g=new bd(l),this.l=o,this.h=l&&l.messageUrlParams||null,o=l&&l.messageHeaders||null,l&&l.clientProtocolHeaderRequired&&(o?o["X-Client-Protocol"]="webchannel":o={"X-Client-Protocol":"webchannel"}),this.g.o=o,o=l&&l.initMessageHeaders||null,l&&l.messageContentType&&(o?o["X-WebChannel-Content-Type"]=l.messageContentType:o={"X-WebChannel-Content-Type":l.messageContentType}),l&&l.va&&(o?o["X-WebChannel-Client-Profile"]=l.va:o={"X-WebChannel-Client-Profile":l.va}),this.g.S=o,(o=l&&l.Sb)&&!F(o)&&(this.g.m=o),this.v=l&&l.supportsCrossDomainXhr||!1,this.u=l&&l.sendRawJson||!1,(l=l&&l.httpSessionIdParam)&&!F(l)&&(this.g.D=l,o=this.h,o!==null&&l in o&&(o=this.h,l in o&&delete o[l])),this.j=new $r(this)}P(Fe,Ee),Fe.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},Fe.prototype.close=function(){au(this.g)},Fe.prototype.o=function(o){var l=this.g;if(typeof o=="string"){var d={};d.__data__=o,o=d}else this.u&&(d={},d.__data__=Qa(o),o=d);l.i.push(new zv(l.Ya++,o)),l.G==3&&Ni(l)},Fe.prototype.N=function(){this.g.l=null,delete this.j,au(this.g),delete this.g,Fe.aa.N.call(this)};function Od(o){Ya.call(this),o.__headers__&&(this.headers=o.__headers__,this.statusCode=o.__status__,delete o.__headers__,delete o.__status__);var l=o.__sm__;if(l){e:{for(let d in l){o=d;break e}o=void 0}(this.i=o)&&(o=this.i,l=l!==null&&o in l?l[o]:void 0),this.data=l}else this.data=o}P(Od,Ya);function Nd(){Xa.call(this),this.status=1}P(Nd,Xa);function $r(o){this.g=o}P($r,Dd),$r.prototype.ua=function(){Pe(this.g,"a")},$r.prototype.ta=function(o){Pe(this.g,new Od(o))},$r.prototype.sa=function(o){Pe(this.g,new Nd)},$r.prototype.ra=function(){Pe(this.g,"b")},Li.prototype.createWebChannel=Li.prototype.g,Fe.prototype.send=Fe.prototype.o,Fe.prototype.open=Fe.prototype.m,Fe.prototype.close=Fe.prototype.close,Gu=It.createWebChannelTransport=function(){return new Li},zu=It.getStatEventTarget=function(){return Ii()},qu=It.Event=ar,mo=It.Stat={mb:0,pb:1,qb:2,Jb:3,Ob:4,Lb:5,Mb:6,Kb:7,Ib:8,Nb:9,PROXY:10,NOPROXY:11,Gb:12,Cb:13,Db:14,Bb:15,Eb:16,Fb:17,ib:18,hb:19,jb:20},Ai.NO_ERROR=0,Ai.TIMEOUT=8,Ai.HTTP_ERROR=6,xs=It.ErrorCode=Ai,Jh.COMPLETE="complete",$u=It.EventType=Jh,Gh.EventType=ss,ss.OPEN="a",ss.CLOSE="b",ss.ERROR="c",ss.MESSAGE="d",Ee.prototype.listen=Ee.prototype.K,hn=It.WebChannel=Gh,Jx=It.FetchXmlHttpFactory=ds,ae.prototype.listenOnce=ae.prototype.L,ae.prototype.getLastError=ae.prototype.Ka,ae.prototype.getLastErrorCode=ae.prototype.Ba,ae.prototype.getStatus=ae.prototype.Z,ae.prototype.getResponseJson=ae.prototype.Oa,ae.prototype.getResponseText=ae.prototype.oa,ae.prototype.send=ae.prototype.ea,ae.prototype.setWithCredentials=ae.prototype.Ha,Bu=It.XhrIo=ae}).apply(typeof po!="undefined"?po:typeof self!="undefined"?self:typeof window!="undefined"?window:{});var jm="@firebase/firestore",Um="4.7.10";var ye=class{constructor(e){this.uid=e}isAuthenticated(){return this.uid!=null}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}};ye.UNAUTHENTICATED=new ye(null),ye.GOOGLE_CREDENTIALS=new ye("google-credentials-uid"),ye.FIRST_PARTY=new ye("first-party-uid"),ye.MOCK_USER=new ye("mock-user");var Vn="11.5.0";var yr=new ln("@firebase/firestore");function dn(){return yr.logLevel}function V(r,...e){if(yr.logLevel<=Q.DEBUG){let t=e.map(Dl);yr.debug(`Firestore (${Vn}): ${r}`,...t)}}function At(r,...e){if(yr.logLevel<=Q.ERROR){let t=e.map(Dl);yr.error(`Firestore (${Vn}): ${r}`,...t)}}function vn(r,...e){if(yr.logLevel<=Q.WARN){let t=e.map(Dl);yr.warn(`Firestore (${Vn}): ${r}`,...t)}}function Dl(r){if(typeof r=="string")return r;try{return function(t){return JSON.stringify(t)}(r)}catch{return r}}function M(r="Unexpected state"){let e=`FIRESTORE (${Vn}) INTERNAL ASSERTION FAILED: `+r;throw At(e),new Error(e)}function ee(r,e){r||M()}function $(r,e){return r}var D={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"},L=class extends Qe{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}};var tt=class{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}};var To=class{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}},Ju=class{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(ye.UNAUTHENTICATED))}shutdown(){}},Yu=class{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}},Xu=class{constructor(e){this.t=e,this.currentUser=ye.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){ee(this.o===void 0);let n=this.i,s=c=>this.i!==n?(n=this.i,t(c)):Promise.resolve(),i=new tt;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new tt,e.enqueueRetryable(()=>s(this.currentUser))};let a=()=>{let c=i;e.enqueueRetryable(async()=>{await c.promise,await s(this.currentUser)})},u=c=>{V("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=c,this.o&&(this.auth.addAuthTokenListener(this.o),a())};this.t.onInit(c=>u(c)),setTimeout(()=>{if(!this.auth){let c=this.t.getImmediate({optional:!0});c?u(c):(V("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new tt)}},0),a()}getToken(){let e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(n=>this.i!==e?(V("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):n?(ee(typeof n.accessToken=="string"),new To(n.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){let e=this.auth&&this.auth.getUid();return ee(e===null||typeof e=="string"),new ye(e)}},Zu=class{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=ye.FIRST_PARTY,this.T=new Map}I(){return this.P?this.P():null}get headers(){this.T.set("X-Goog-AuthUser",this.l);let e=this.I();return e&&this.T.set("Authorization",e),this.h&&this.T.set("X-Goog-Iam-Authorization-Token",this.h),this.T}},ec=class{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new Zu(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(ye.FIRST_PARTY))}shutdown(){}invalidateToken(){}},Eo=class{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}},tc=class{constructor(e,t){this.A=t,this.forceRefresh=!1,this.appCheck=null,this.R=null,this.V=null,Dm(e)&&e.settings.appCheckToken&&(this.V=e.settings.appCheckToken)}start(e,t){ee(this.o===void 0);let n=i=>{i.error!=null&&V("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${i.error.message}`);let a=i.token!==this.R;return this.R=i.token,V("FirebaseAppCheckTokenProvider",`Received ${a?"new":"existing"} token.`),a?t(i.token):Promise.resolve()};this.o=i=>{e.enqueueRetryable(()=>n(i))};let s=i=>{V("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=i,this.o&&this.appCheck.addTokenListener(this.o)};this.A.onInit(i=>s(i)),setTimeout(()=>{if(!this.appCheck){let i=this.A.getImmediate({optional:!0});i?s(i):V("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.V)return Promise.resolve(new Eo(this.V));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(t=>t?(ee(typeof t.token=="string"),this.R=t.token,new Eo(t.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}};function Yx(r){let e=typeof self!="undefined"&&(self.crypto||self.msCrypto),t=new Uint8Array(r);if(e&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let n=0;n<r;n++)t[n]=Math.floor(256*Math.random());return t}function Sg(){return new TextEncoder}var Io=class{static newId(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(4.129032258064516),n="";for(;n.length<20;){let s=Yx(40);for(let i=0;i<s.length;++i)n.length<20&&s[i]<t&&(n+=e.charAt(s[i]%62))}return n}};function K(r,e){return r<e?-1:r>e?1:0}function rc(r,e){let t=0;for(;t<r.length&&t<e.length;){let n=r.codePointAt(t),s=e.codePointAt(t);if(n!==s){if(n<128&&s<128)return K(n,s);{let i=Sg(),a=Xx(i.encode(Bm(r,t)),i.encode(Bm(e,t)));return a!==0?a:K(n,s)}}t+=n>65535?2:1}return K(r.length,e.length)}function Bm(r,e){return r.codePointAt(e)>65535?r.substring(e,e+2):r.substring(e,e+1)}function Xx(r,e){for(let t=0;t<r.length&&t<e.length;++t)if(r[t]!==e[t])return K(r[t],e[t]);return K(r.length,e.length)}function wn(r,e,t){return r.length===e.length&&r.every((n,s)=>t(n,e[s]))}var $m=-62135596800,qm=1e6,we=class r{static now(){return r.fromMillis(Date.now())}static fromDate(e){return r.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),n=Math.floor((e-1e3*t)*qm);return new r(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new L(D.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new L(D.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<$m)throw new L(D.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new L(D.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/qm}_compareTo(e){return this.seconds===e.seconds?K(this.nanoseconds,e.nanoseconds):K(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){let e=this.seconds-$m;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}};var q=class r{static fromTimestamp(e){return new r(e)}static min(){return new r(new we(0,0))}static max(){return new r(new we(253402300799,999999999))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}};var zm="__name__",Ao=class r{constructor(e,t,n){t===void 0?t=0:t>e.length&&M(),n===void 0?n=e.length-t:n>e.length-t&&M(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return r.comparator(this,e)===0}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof r?e.forEach(n=>{t.push(n)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=e===void 0?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return this.length===0}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){let n=Math.min(e.length,t.length);for(let s=0;s<n;s++){let i=r.compareSegments(e.get(s),t.get(s));if(i!==0)return i}return K(e.length,t.length)}static compareSegments(e,t){let n=r.isNumericId(e),s=r.isNumericId(t);return n&&!s?-1:!n&&s?1:n&&s?r.extractNumericId(e).compare(r.extractNumericId(t)):rc(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return Et.fromString(e.substring(4,e.length-2))}},fe=class r extends Ao{construct(e,t,n){return new r(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){let t=[];for(let n of e){if(n.indexOf("//")>=0)throw new L(D.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(s=>s.length>0))}return new r(t)}static emptyPath(){return new r([])}},Zx=/^[_a-zA-Z][_a-zA-Z0-9]*$/,Ue=class r extends Ao{construct(e,t,n){return new r(e,t,n)}static isValidIdentifier(e){return Zx.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),r.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return this.length===1&&this.get(0)===zm}static keyField(){return new r([zm])}static fromServerFormat(e){let t=[],n="",s=0,i=()=>{if(n.length===0)throw new L(D.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""},a=!1;for(;s<e.length;){let u=e[s];if(u==="\\"){if(s+1===e.length)throw new L(D.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let c=e[s+1];if(c!=="\\"&&c!=="."&&c!=="`")throw new L(D.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=c,s+=2}else u==="`"?(a=!a,s++):u!=="."||a?(n+=u,s++):(i(),s++)}if(i(),a)throw new L(D.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new r(t)}static emptyPath(){return new r([])}};var j=class r{constructor(e){this.path=e}static fromPath(e){return new r(fe.fromString(e))}static fromName(e){return new r(fe.fromString(e).popFirst(5))}static empty(){return new r(fe.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return e!==null&&fe.comparator(this.path,e.path)===0}toString(){return this.path.toString()}static comparator(e,t){return fe.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new r(new fe(e.slice()))}};var Ds=-1,nc=class{constructor(e,t,n,s){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=s}};nc.UNKNOWN_ID=-1;function eS(r,e){let t=r.toTimestamp().seconds,n=r.toTimestamp().nanoseconds+1,s=q.fromTimestamp(n===1e9?new we(t+1,0):new we(t,n));return new _r(s,j.empty(),e)}function tS(r){return new _r(r.readTime,r.key,Ds)}var _r=class r{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new r(q.min(),j.empty(),Ds)}static max(){return new r(q.max(),j.empty(),Ds)}};function rS(r,e){let t=r.readTime.compareTo(e.readTime);return t!==0?t:(t=j.comparator(r.documentKey,e.documentKey),t!==0?t:K(r.largestBatchId,e.largestBatchId))}var nS="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",sc=class{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}};async function Ln(r){if(r.code!==D.FAILED_PRECONDITION||r.message!==nS)throw r;V("LocalStore","Unexpectedly lost primary lease")}var k=class r{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(t=>{this.isDone=!0,this.result=t,this.nextCallback&&this.nextCallback(t)},t=>{this.isDone=!0,this.error=t,this.catchCallback&&this.catchCallback(t)})}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&M(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new r((n,s)=>{this.nextCallback=i=>{this.wrapSuccess(e,i).next(n,s)},this.catchCallback=i=>{this.wrapFailure(t,i).next(n,s)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{let t=e();return t instanceof r?t:r.resolve(t)}catch(t){return r.reject(t)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):r.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):r.reject(t)}static resolve(e){return new r((t,n)=>{t(e)})}static reject(e){return new r((t,n)=>{n(e)})}static waitFor(e){return new r((t,n)=>{let s=0,i=0,a=!1;e.forEach(u=>{++s,u.next(()=>{++i,a&&i===s&&t()},c=>n(c))}),a=!0,i===s&&t()})}static or(e){let t=r.resolve(!1);for(let n of e)t=t.next(s=>s?r.resolve(s):n());return t}static forEach(e,t){let n=[];return e.forEach((s,i)=>{n.push(t.call(this,s,i))}),this.waitFor(n)}static mapArray(e,t){return new r((n,s)=>{let i=e.length,a=new Array(i),u=0;for(let c=0;c<i;c++){let h=c;t(e[h]).next(f=>{a[h]=f,++u,u===i&&n(a)},f=>s(f))}})}static doWhile(e,t){return new r((n,s)=>{let i=()=>{e()===!0?t().next(()=>{i()},s):n()};i()})}};function sS(r){let e=r.match(/Android ([\d.]+)/i),t=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(t)}function Fn(r){return r.name==="IndexedDbTransactionError"}var bn=class{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=n=>this.oe(n),this._e=n=>t.writeSequenceNumber(n))}oe(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this._e&&this._e(e),e}};bn.ae=-1;var Ol=-1;function oa(r){return r==null}function Os(r){return r===0&&1/r==-1/0}function iS(r){return typeof r=="number"&&Number.isInteger(r)&&!Os(r)&&r<=Number.MAX_SAFE_INTEGER&&r>=Number.MIN_SAFE_INTEGER}var Rg="";function oS(r){let e="";for(let t=0;t<r.length;t++)e.length>0&&(e=Gm(e)),e=aS(r.get(t),e);return Gm(e)}function aS(r,e){let t=e,n=r.length;for(let s=0;s<n;s++){let i=r.charAt(s);switch(i){case"\0":t+="";break;case Rg:t+="";break;default:t+=i}}return t}function Gm(r){return r+Rg+""}var uS="remoteDocuments",Pg="owner";var Cg="mutationQueues";var kg="mutations";var Dg="documentMutations",cS="remoteDocumentsV14";var Og="remoteDocumentGlobal";var Ng="targets";var Vg="targetDocuments";var Lg="targetGlobal",Fg="collectionParents";var Mg="clientMetadata";var jg="bundles";var Ug="namedQueries";var lS="indexConfiguration";var hS="indexState";var dS="indexEntries";var Bg="documentOverlays";var fS="globals";var pS=[Cg,kg,Dg,uS,Ng,Pg,Lg,Vg,Mg,Og,Fg,jg,Ug],KM=[...pS,Bg],mS=[Cg,kg,Dg,cS,Ng,Pg,Lg,Vg,Mg,Og,Fg,jg,Ug,Bg],gS=mS,yS=[...gS,lS,hS,dS];var HM=[...yS,fS];function Km(r){let e=0;for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e++;return e}function nr(r,e){for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e(t,r[t])}function $g(r){for(let e in r)if(Object.prototype.hasOwnProperty.call(r,e))return!1;return!0}var ce=class r{constructor(e,t){this.comparator=e,this.root=t||rt.EMPTY}insert(e,t){return new r(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,rt.BLACK,null,null))}remove(e){return new r(this.comparator,this.root.remove(e,this.comparator).copy(null,null,rt.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){let n=this.comparator(e,t.key);if(n===0)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){let s=this.comparator(e,n.key);if(s===0)return t+n.left.size;s<0?n=n.left:(t+=n.left.size+1,n=n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal((t,n)=>(e(t,n),!1))}toString(){let e=[];return this.inorderTraversal((t,n)=>(e.push(`${t}:${n}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new gn(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new gn(this.root,e,this.comparator,!1)}getReverseIterator(){return new gn(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new gn(this.root,e,this.comparator,!0)}},gn=class{constructor(e,t,n,s){this.isReverse=s,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&s&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(i===0){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop(),t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(this.nodeStack.length===0)return null;let e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}},rt=class r{constructor(e,t,n,s,i){this.key=e,this.value=t,this.color=n!=null?n:r.RED,this.left=s!=null?s:r.EMPTY,this.right=i!=null?i:r.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,s,i){return new r(e!=null?e:this.key,t!=null?t:this.value,n!=null?n:this.color,s!=null?s:this.left,i!=null?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let s=this,i=n(e,s.key);return s=i<0?s.copy(null,null,null,s.left.insert(e,t,n),null):i===0?s.copy(null,t,null,null,null):s.copy(null,null,null,null,s.right.insert(e,t,n)),s.fixUp()}removeMin(){if(this.left.isEmpty())return r.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,s=this;if(t(e,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(e,t),null);else{if(s.left.isRed()&&(s=s.rotateRight()),s.right.isEmpty()||s.right.isRed()||s.right.left.isRed()||(s=s.moveRedRight()),t(e,s.key)===0){if(s.right.isEmpty())return r.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(e,t))}return s.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){let e=this.copy(null,null,r.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,r.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){let e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed()||this.right.isRed())throw M();let e=this.left.check();if(e!==this.right.check())throw M();return e+(this.isRed()?0:1)}};rt.EMPTY=null,rt.RED=!0,rt.BLACK=!1;rt.EMPTY=new class{constructor(){this.size=0}get key(){throw M()}get value(){throw M()}get color(){throw M()}get left(){throw M()}get right(){throw M()}copy(e,t,n,s,i){return this}insert(e,t,n){return new rt(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};var _e=class r{constructor(e){this.comparator=e,this.data=new ce(this.comparator)}has(e){return this.data.get(e)!==null}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal((t,n)=>(e(t),!1))}forEachInRange(e,t){let n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){let s=n.getNext();if(this.comparator(s.key,e[1])>=0)return;t(s.key)}}forEachWhile(e,t){let n;for(n=t!==void 0?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){let t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new xo(this.data.getIterator())}getIteratorFrom(e){return new xo(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(n=>{t=t.add(n)}),t}isEqual(e){if(!(e instanceof r)||this.size!==e.size)return!1;let t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){let s=t.getNext().key,i=n.getNext().key;if(this.comparator(s,i)!==0)return!1}return!0}toArray(){let e=[];return this.forEach(t=>{e.push(t)}),e}toString(){let e=[];return this.forEach(t=>e.push(t)),"SortedSet("+e.toString()+")"}copy(e){let t=new r(this.comparator);return t.data=e,t}},xo=class{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}};var qe=class r{constructor(e){this.fields=e,e.sort(Ue.comparator)}static empty(){return new r([])}unionWith(e){let t=new _e(Ue.comparator);for(let n of this.fields)t=t.add(n);for(let n of e)t=t.add(n);return new r(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return wn(this.fields,e.fields,(t,n)=>t.isEqual(n))}};var So=class extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}};var Re=class r{constructor(e){this.binaryString=e}static fromBase64String(e){let t=function(s){try{return atob(s)}catch(i){throw typeof DOMException!="undefined"&&i instanceof DOMException?new So("Invalid base64 string: "+i):i}}(e);return new r(t)}static fromUint8Array(e){let t=function(s){let i="";for(let a=0;a<s.length;++a)i+=String.fromCharCode(s[a]);return i}(e);return new r(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return function(t){return btoa(t)}(this.binaryString)}toUint8Array(){return function(t){let n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return K(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}};Re.EMPTY_BYTE_STRING=new Re("");var _S=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function xt(r){if(ee(!!r),typeof r=="string"){let e=0,t=_S.exec(r);if(ee(!!t),t[1]){let s=t[1];s=(s+"000000000").substr(0,9),e=Number(s)}let n=new Date(r);return{seconds:Math.floor(n.getTime()/1e3),nanos:e}}return{seconds:oe(r.seconds),nanos:oe(r.nanos)}}function oe(r){return typeof r=="number"?r:typeof r=="string"?Number(r):0}function St(r){return typeof r=="string"?Re.fromBase64String(r):Re.fromUint8Array(r)}var qg="server_timestamp",zg="__type__",Gg="__previous_value__",Kg="__local_write_time__";function Nl(r){var e,t;return((t=(((e=r==null?void 0:r.mapValue)===null||e===void 0?void 0:e.fields)||{})[zg])===null||t===void 0?void 0:t.stringValue)===qg}function aa(r){let e=r.mapValue.fields[Gg];return Nl(e)?aa(e):e}function Ns(r){let e=xt(r.mapValue.fields[Kg].timestampValue);return new we(e.seconds,e.nanos)}var ic=class{constructor(e,t,n,s,i,a,u,c,h){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=s,this.ssl=i,this.forceLongPolling=a,this.autoDetectLongPolling=u,this.longPollingOptions=c,this.useFetchStreams=h}},Ro="(default)",Po=class r{constructor(e,t){this.projectId=e,this.database=t||Ro}static empty(){return new r("","")}get isDefaultDatabase(){return this.database===Ro}isEqual(e){return e instanceof r&&e.projectId===this.projectId&&e.database===this.database}};var Vl="__type__",Hg="__max__",go={mapValue:{fields:{__type__:{stringValue:Hg}}}},Ll="__vector__",Tn="value";function Zt(r){return"nullValue"in r?0:"booleanValue"in r?1:"integerValue"in r||"doubleValue"in r?2:"timestampValue"in r?3:"stringValue"in r?5:"bytesValue"in r?6:"referenceValue"in r?7:"geoPointValue"in r?8:"arrayValue"in r?9:"mapValue"in r?Nl(r)?4:Qg(r)?9007199254740991:Wg(r)?10:11:M()}function ot(r,e){if(r===e)return!0;let t=Zt(r);if(t!==Zt(e))return!1;switch(t){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===e.booleanValue;case 4:return Ns(r).isEqual(Ns(e));case 3:return function(s,i){if(typeof s.timestampValue=="string"&&typeof i.timestampValue=="string"&&s.timestampValue.length===i.timestampValue.length)return s.timestampValue===i.timestampValue;let a=xt(s.timestampValue),u=xt(i.timestampValue);return a.seconds===u.seconds&&a.nanos===u.nanos}(r,e);case 5:return r.stringValue===e.stringValue;case 6:return function(s,i){return St(s.bytesValue).isEqual(St(i.bytesValue))}(r,e);case 7:return r.referenceValue===e.referenceValue;case 8:return function(s,i){return oe(s.geoPointValue.latitude)===oe(i.geoPointValue.latitude)&&oe(s.geoPointValue.longitude)===oe(i.geoPointValue.longitude)}(r,e);case 2:return function(s,i){if("integerValue"in s&&"integerValue"in i)return oe(s.integerValue)===oe(i.integerValue);if("doubleValue"in s&&"doubleValue"in i){let a=oe(s.doubleValue),u=oe(i.doubleValue);return a===u?Os(a)===Os(u):isNaN(a)&&isNaN(u)}return!1}(r,e);case 9:return wn(r.arrayValue.values||[],e.arrayValue.values||[],ot);case 10:case 11:return function(s,i){let a=s.mapValue.fields||{},u=i.mapValue.fields||{};if(Km(a)!==Km(u))return!1;for(let c in a)if(a.hasOwnProperty(c)&&(u[c]===void 0||!ot(a[c],u[c])))return!1;return!0}(r,e);default:return M()}}function Vs(r,e){return(r.values||[]).find(t=>ot(t,e))!==void 0}function En(r,e){if(r===e)return 0;let t=Zt(r),n=Zt(e);if(t!==n)return K(t,n);switch(t){case 0:case 9007199254740991:return 0;case 1:return K(r.booleanValue,e.booleanValue);case 2:return function(i,a){let u=oe(i.integerValue||i.doubleValue),c=oe(a.integerValue||a.doubleValue);return u<c?-1:u>c?1:u===c?0:isNaN(u)?isNaN(c)?0:-1:1}(r,e);case 3:return Hm(r.timestampValue,e.timestampValue);case 4:return Hm(Ns(r),Ns(e));case 5:return rc(r.stringValue,e.stringValue);case 6:return function(i,a){let u=St(i),c=St(a);return u.compareTo(c)}(r.bytesValue,e.bytesValue);case 7:return function(i,a){let u=i.split("/"),c=a.split("/");for(let h=0;h<u.length&&h<c.length;h++){let f=K(u[h],c[h]);if(f!==0)return f}return K(u.length,c.length)}(r.referenceValue,e.referenceValue);case 8:return function(i,a){let u=K(oe(i.latitude),oe(a.latitude));return u!==0?u:K(oe(i.longitude),oe(a.longitude))}(r.geoPointValue,e.geoPointValue);case 9:return Wm(r.arrayValue,e.arrayValue);case 10:return function(i,a){var u,c,h,f;let m=i.fields||{},g=a.fields||{},b=(u=m[Tn])===null||u===void 0?void 0:u.arrayValue,P=(c=g[Tn])===null||c===void 0?void 0:c.arrayValue,C=K(((h=b==null?void 0:b.values)===null||h===void 0?void 0:h.length)||0,((f=P==null?void 0:P.values)===null||f===void 0?void 0:f.length)||0);return C!==0?C:Wm(b,P)}(r.mapValue,e.mapValue);case 11:return function(i,a){if(i===go.mapValue&&a===go.mapValue)return 0;if(i===go.mapValue)return 1;if(a===go.mapValue)return-1;let u=i.fields||{},c=Object.keys(u),h=a.fields||{},f=Object.keys(h);c.sort(),f.sort();for(let m=0;m<c.length&&m<f.length;++m){let g=rc(c[m],f[m]);if(g!==0)return g;let b=En(u[c[m]],h[f[m]]);if(b!==0)return b}return K(c.length,f.length)}(r.mapValue,e.mapValue);default:throw M()}}function Hm(r,e){if(typeof r=="string"&&typeof e=="string"&&r.length===e.length)return K(r,e);let t=xt(r),n=xt(e),s=K(t.seconds,n.seconds);return s!==0?s:K(t.nanos,n.nanos)}function Wm(r,e){let t=r.values||[],n=e.values||[];for(let s=0;s<t.length&&s<n.length;++s){let i=En(t[s],n[s]);if(i)return i}return K(t.length,n.length)}function In(r){return oc(r)}function oc(r){return"nullValue"in r?"null":"booleanValue"in r?""+r.booleanValue:"integerValue"in r?""+r.integerValue:"doubleValue"in r?""+r.doubleValue:"timestampValue"in r?function(t){let n=xt(t);return`time(${n.seconds},${n.nanos})`}(r.timestampValue):"stringValue"in r?r.stringValue:"bytesValue"in r?function(t){return St(t).toBase64()}(r.bytesValue):"referenceValue"in r?function(t){return j.fromName(t).toString()}(r.referenceValue):"geoPointValue"in r?function(t){return`geo(${t.latitude},${t.longitude})`}(r.geoPointValue):"arrayValue"in r?function(t){let n="[",s=!0;for(let i of t.values||[])s?s=!1:n+=",",n+=oc(i);return n+"]"}(r.arrayValue):"mapValue"in r?function(t){let n=Object.keys(t.fields||{}).sort(),s="{",i=!0;for(let a of n)i?i=!1:s+=",",s+=`${a}:${oc(t.fields[a])}`;return s+"}"}(r.mapValue):M()}function vo(r){switch(Zt(r)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let e=aa(r);return e?16+vo(e):16;case 5:return 2*r.stringValue.length;case 6:return St(r.bytesValue).approximateByteSize();case 7:return r.referenceValue.length;case 9:return function(n){return(n.values||[]).reduce((s,i)=>s+vo(i),0)}(r.arrayValue);case 10:case 11:return function(n){let s=0;return nr(n.fields,(i,a)=>{s+=i.length+vo(a)}),s}(r.mapValue);default:throw M()}}function ac(r){return!!r&&"integerValue"in r}function Fl(r){return!!r&&"arrayValue"in r}function Qm(r){return!!r&&"nullValue"in r}function Jm(r){return!!r&&"doubleValue"in r&&isNaN(Number(r.doubleValue))}function wo(r){return!!r&&"mapValue"in r}function Wg(r){var e,t;return((t=(((e=r==null?void 0:r.mapValue)===null||e===void 0?void 0:e.fields)||{})[Vl])===null||t===void 0?void 0:t.stringValue)===Ll}function Rs(r){if(r.geoPointValue)return{geoPointValue:Object.assign({},r.geoPointValue)};if(r.timestampValue&&typeof r.timestampValue=="object")return{timestampValue:Object.assign({},r.timestampValue)};if(r.mapValue){let e={mapValue:{fields:{}}};return nr(r.mapValue.fields,(t,n)=>e.mapValue.fields[t]=Rs(n)),e}if(r.arrayValue){let e={arrayValue:{values:[]}};for(let t=0;t<(r.arrayValue.values||[]).length;++t)e.arrayValue.values[t]=Rs(r.arrayValue.values[t]);return e}return Object.assign({},r)}function Qg(r){return(((r.mapValue||{}).fields||{}).__type__||{}).stringValue===Hg}var QM={mapValue:{fields:{[Vl]:{stringValue:Ll},[Tn]:{arrayValue:{}}}}};var je=class r{constructor(e){this.value=e}static empty(){return new r({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(t=(t.mapValue.fields||{})[e.get(n)],!wo(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Rs(t)}setAll(e){let t=Ue.emptyPath(),n={},s=[];e.forEach((a,u)=>{if(!t.isImmediateParentOf(u)){let c=this.getFieldsMap(t);this.applyChanges(c,n,s),n={},s=[],t=u.popLast()}a?n[u.lastSegment()]=Rs(a):s.push(u.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,n,s)}delete(e){let t=this.field(e.popLast());wo(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return ot(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let s=t.mapValue.fields[e.get(n)];wo(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=s),t=s}return t.mapValue.fields}applyChanges(e,t,n){nr(t,(s,i)=>e[s]=i);for(let s of n)delete e[s]}clone(){return new r(Rs(this.value))}};function Jg(r){let e=[];return nr(r.fields,(t,n)=>{let s=new Ue([t]);if(wo(n)){let i=Jg(n.mapValue).fields;if(i.length===0)e.push(s);else for(let a of i)e.push(s.child(a))}else e.push(s)}),new qe(e)}var Je=class r{constructor(e,t,n,s,i,a,u){this.key=e,this.documentType=t,this.version=n,this.readTime=s,this.createTime=i,this.data=a,this.documentState=u}static newInvalidDocument(e){return new r(e,0,q.min(),q.min(),q.min(),je.empty(),0)}static newFoundDocument(e,t,n,s){return new r(e,1,t,q.min(),n,s,0)}static newNoDocument(e,t){return new r(e,2,t,q.min(),q.min(),je.empty(),0)}static newUnknownDocument(e,t){return new r(e,3,t,q.min(),q.min(),je.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(q.min())||this.documentType!==2&&this.documentType!==0||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=je.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=je.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=q.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return this.documentState===1}get hasCommittedMutations(){return this.documentState===2}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return this.documentType!==0}isFoundDocument(){return this.documentType===1}isNoDocument(){return this.documentType===2}isUnknownDocument(){return this.documentType===3}isEqual(e){return e instanceof r&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new r(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}};var An=class{constructor(e,t){this.position=e,this.inclusive=t}};function Ym(r,e,t){let n=0;for(let s=0;s<r.position.length;s++){let i=e[s],a=r.position[s];if(i.field.isKeyField()?n=j.comparator(j.fromName(a.referenceValue),t.key):n=En(a,t.data.field(i.field)),i.dir==="desc"&&(n*=-1),n!==0)break}return n}function Xm(r,e){if(r===null)return e===null;if(e===null||r.inclusive!==e.inclusive||r.position.length!==e.position.length)return!1;for(let t=0;t<r.position.length;t++)if(!ot(r.position[t],e.position[t]))return!1;return!0}var xn=class{constructor(e,t="asc"){this.field=e,this.dir=t}};function vS(r,e){return r.dir===e.dir&&r.field.isEqual(e.field)}var Co=class{},me=class r extends Co{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?t==="in"||t==="not-in"?this.createKeyFieldInFilter(e,t,n):new cc(e,t,n):t==="array-contains"?new dc(e,n):t==="in"?new fc(e,n):t==="not-in"?new pc(e,n):t==="array-contains-any"?new mc(e,n):new r(e,t,n)}static createKeyFieldInFilter(e,t,n){return t==="in"?new lc(e,n):new hc(e,n)}matches(e){let t=e.data.field(this.field);return this.op==="!="?t!==null&&this.matchesComparison(En(t,this.value)):t!==null&&Zt(this.value)===Zt(t)&&this.matchesComparison(En(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return e===0;case"!=":return e!==0;case">":return e>0;case">=":return e>=0;default:return M()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}},at=class r extends Co{constructor(e,t){super(),this.filters=e,this.op=t,this.ce=null}static create(e,t){return new r(e,t)}matches(e){return Yg(this)?this.filters.find(t=>!t.matches(e))===void 0:this.filters.find(t=>t.matches(e))!==void 0}getFlattenedFilters(){return this.ce!==null||(this.ce=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ce}getFilters(){return Object.assign([],this.filters)}};function Yg(r){return r.op==="and"}function Xg(r){return wS(r)&&Yg(r)}function wS(r){for(let e of r.filters)if(e instanceof at)return!1;return!0}function uc(r){if(r instanceof me)return r.field.canonicalString()+r.op.toString()+In(r.value);if(Xg(r))return r.filters.map(e=>uc(e)).join(",");{let e=r.filters.map(t=>uc(t)).join(",");return`${r.op}(${e})`}}function Zg(r,e){return r instanceof me?function(n,s){return s instanceof me&&n.op===s.op&&n.field.isEqual(s.field)&&ot(n.value,s.value)}(r,e):r instanceof at?function(n,s){return s instanceof at&&n.op===s.op&&n.filters.length===s.filters.length?n.filters.reduce((i,a,u)=>i&&Zg(a,s.filters[u]),!0):!1}(r,e):void M()}function ey(r){return r instanceof me?function(t){return`${t.field.canonicalString()} ${t.op} ${In(t.value)}`}(r):r instanceof at?function(t){return t.op.toString()+" {"+t.getFilters().map(ey).join(" ,")+"}"}(r):"Filter"}var cc=class extends me{constructor(e,t,n){super(e,t,n),this.key=j.fromName(n.referenceValue)}matches(e){let t=j.comparator(e.key,this.key);return this.matchesComparison(t)}},lc=class extends me{constructor(e,t){super(e,"in",t),this.keys=ty("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}},hc=class extends me{constructor(e,t){super(e,"not-in",t),this.keys=ty("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}};function ty(r,e){var t;return(((t=e.arrayValue)===null||t===void 0?void 0:t.values)||[]).map(n=>j.fromName(n.referenceValue))}var dc=class extends me{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return Fl(t)&&Vs(t.arrayValue,this.value)}},fc=class extends me{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return t!==null&&Vs(this.value.arrayValue,t)}},pc=class extends me{constructor(e,t){super(e,"not-in",t)}matches(e){if(Vs(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return t!==null&&!Vs(this.value.arrayValue,t)}},mc=class extends me{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!Fl(t)||!t.arrayValue.values)&&t.arrayValue.values.some(n=>Vs(this.value.arrayValue,n))}};var gc=class{constructor(e,t=null,n=[],s=[],i=null,a=null,u=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=s,this.limit=i,this.startAt=a,this.endAt=u,this.le=null}};function Zm(r,e=null,t=[],n=[],s=null,i=null,a=null){return new gc(r,e,t,n,s,i,a)}function Ml(r){let e=$(r);if(e.le===null){let t=e.path.canonicalString();e.collectionGroup!==null&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map(n=>uc(n)).join(","),t+="|ob:",t+=e.orderBy.map(n=>function(i){return i.field.canonicalString()+i.dir}(n)).join(","),oa(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(n=>In(n)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(n=>In(n)).join(",")),e.le=t}return e.le}function jl(r,e){if(r.limit!==e.limit||r.orderBy.length!==e.orderBy.length)return!1;for(let t=0;t<r.orderBy.length;t++)if(!vS(r.orderBy[t],e.orderBy[t]))return!1;if(r.filters.length!==e.filters.length)return!1;for(let t=0;t<r.filters.length;t++)if(!Zg(r.filters[t],e.filters[t]))return!1;return r.collectionGroup===e.collectionGroup&&!!r.path.isEqual(e.path)&&!!Xm(r.startAt,e.startAt)&&Xm(r.endAt,e.endAt)}function yc(r){return j.isDocumentKey(r.path)&&r.collectionGroup===null&&r.filters.length===0}var Sn=class{constructor(e,t=null,n=[],s=[],i=null,a="F",u=null,c=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=s,this.limit=i,this.limitType=a,this.startAt=u,this.endAt=c,this.he=null,this.Pe=null,this.Te=null,this.startAt,this.endAt}};function bS(r,e,t,n,s,i,a,u){return new Sn(r,e,t,n,s,i,a,u)}function ua(r){return new Sn(r)}function eg(r){return r.filters.length===0&&r.limit===null&&r.startAt==null&&r.endAt==null&&(r.explicitOrderBy.length===0||r.explicitOrderBy.length===1&&r.explicitOrderBy[0].field.isKeyField())}function TS(r){return r.collectionGroup!==null}function Ps(r){let e=$(r);if(e.he===null){e.he=[];let t=new Set;for(let i of e.explicitOrderBy)e.he.push(i),t.add(i.field.canonicalString());let n=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(function(a){let u=new _e(Ue.comparator);return a.filters.forEach(c=>{c.getFlattenedFilters().forEach(h=>{h.isInequality()&&(u=u.add(h.field))})}),u})(e).forEach(i=>{t.has(i.canonicalString())||i.isKeyField()||e.he.push(new xn(i,n))}),t.has(Ue.keyField().canonicalString())||e.he.push(new xn(Ue.keyField(),n))}return e.he}function nt(r){let e=$(r);return e.Pe||(e.Pe=ES(e,Ps(r))),e.Pe}function ES(r,e){if(r.limitType==="F")return Zm(r.path,r.collectionGroup,e,r.filters,r.limit,r.startAt,r.endAt);{e=e.map(s=>{let i=s.dir==="desc"?"asc":"desc";return new xn(s.field,i)});let t=r.endAt?new An(r.endAt.position,r.endAt.inclusive):null,n=r.startAt?new An(r.startAt.position,r.startAt.inclusive):null;return Zm(r.path,r.collectionGroup,e,r.filters,r.limit,t,n)}}function _c(r,e,t){return new Sn(r.path,r.collectionGroup,r.explicitOrderBy.slice(),r.filters.slice(),e,t,r.startAt,r.endAt)}function ca(r,e){return jl(nt(r),nt(e))&&r.limitType===e.limitType}function ry(r){return`${Ml(nt(r))}|lt:${r.limitType}`}function fn(r){return`Query(target=${function(t){let n=t.path.canonicalString();return t.collectionGroup!==null&&(n+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(n+=`, filters: [${t.filters.map(s=>ey(s)).join(", ")}]`),oa(t.limit)||(n+=", limit: "+t.limit),t.orderBy.length>0&&(n+=`, orderBy: [${t.orderBy.map(s=>function(a){return`${a.field.canonicalString()} (${a.dir})`}(s)).join(", ")}]`),t.startAt&&(n+=", startAt: ",n+=t.startAt.inclusive?"b:":"a:",n+=t.startAt.position.map(s=>In(s)).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(s=>In(s)).join(",")),`Target(${n})`}(nt(r))}; limitType=${r.limitType})`}function la(r,e){return e.isFoundDocument()&&function(n,s){let i=s.key.path;return n.collectionGroup!==null?s.key.hasCollectionId(n.collectionGroup)&&n.path.isPrefixOf(i):j.isDocumentKey(n.path)?n.path.isEqual(i):n.path.isImmediateParentOf(i)}(r,e)&&function(n,s){for(let i of Ps(n))if(!i.field.isKeyField()&&s.data.field(i.field)===null)return!1;return!0}(r,e)&&function(n,s){for(let i of n.filters)if(!i.matches(s))return!1;return!0}(r,e)&&function(n,s){return!(n.startAt&&!function(a,u,c){let h=Ym(a,u,c);return a.inclusive?h<=0:h<0}(n.startAt,Ps(n),s)||n.endAt&&!function(a,u,c){let h=Ym(a,u,c);return a.inclusive?h>=0:h>0}(n.endAt,Ps(n),s))}(r,e)}function IS(r){return r.collectionGroup||(r.path.length%2==1?r.path.lastSegment():r.path.get(r.path.length-2))}function ny(r){return(e,t)=>{let n=!1;for(let s of Ps(r)){let i=AS(s,e,t);if(i!==0)return i;n=n||s.field.isKeyField()}return 0}}function AS(r,e,t){let n=r.field.isKeyField()?j.comparator(e.key,t.key):function(i,a,u){let c=a.data.field(i),h=u.data.field(i);return c!==null&&h!==null?En(c,h):M()}(r.field,e,t);switch(r.dir){case"asc":return n;case"desc":return-1*n;default:return M()}}var Rt=class{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){let t=this.mapKeyFn(e),n=this.inner[t];if(n!==void 0){for(let[s,i]of n)if(this.equalsFn(s,e))return i}}has(e){return this.get(e)!==void 0}set(e,t){let n=this.mapKeyFn(e),s=this.inner[n];if(s===void 0)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<s.length;i++)if(this.equalsFn(s[i][0],e))return void(s[i]=[e,t]);s.push([e,t]),this.innerSize++}delete(e){let t=this.mapKeyFn(e),n=this.inner[t];if(n===void 0)return!1;for(let s=0;s<n.length;s++)if(this.equalsFn(n[s][0],e))return n.length===1?delete this.inner[t]:n.splice(s,1),this.innerSize--,!0;return!1}forEach(e){nr(this.inner,(t,n)=>{for(let[s,i]of n)e(s,i)})}isEmpty(){return $g(this.inner)}size(){return this.innerSize}};var xS=new ce(j.comparator);function Pt(){return xS}var sy=new ce(j.comparator);function Ss(...r){let e=sy;for(let t of r)e=e.insert(t.key,t);return e}function iy(r){let e=sy;return r.forEach((t,n)=>e=e.insert(t,n.overlayedDocument)),e}function pr(){return Cs()}function oy(){return Cs()}function Cs(){return new Rt(r=>r.toString(),(r,e)=>r.isEqual(e))}var SS=new ce(j.comparator),RS=new _e(j.comparator);function W(...r){let e=RS;for(let t of r)e=e.add(t);return e}var PS=new _e(K);function CS(){return PS}function Ul(r,e){if(r.useProto3Json){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Os(e)?"-0":e}}function ay(r){return{integerValue:""+r}}function kS(r,e){return iS(e)?ay(e):Ul(r,e)}var Rn=class{constructor(){this._=void 0}};function DS(r,e,t){return r instanceof Pn?function(s,i){let a={fields:{[zg]:{stringValue:qg},[Kg]:{timestampValue:{seconds:s.seconds,nanos:s.nanoseconds}}}};return i&&Nl(i)&&(i=aa(i)),i&&(a.fields[Gg]=i),{mapValue:a}}(t,e):r instanceof vr?cy(r,e):r instanceof wr?ly(r,e):function(s,i){let a=uy(s,i),u=tg(a)+tg(s.Ie);return ac(a)&&ac(s.Ie)?ay(u):Ul(s.serializer,u)}(r,e)}function OS(r,e,t){return r instanceof vr?cy(r,e):r instanceof wr?ly(r,e):t}function uy(r,e){return r instanceof Cn?function(n){return ac(n)||function(i){return!!i&&"doubleValue"in i}(n)}(e)?e:{integerValue:0}:null}var Pn=class extends Rn{},vr=class extends Rn{constructor(e){super(),this.elements=e}};function cy(r,e){let t=hy(e);for(let n of r.elements)t.some(s=>ot(s,n))||t.push(n);return{arrayValue:{values:t}}}var wr=class extends Rn{constructor(e){super(),this.elements=e}};function ly(r,e){let t=hy(e);for(let n of r.elements)t=t.filter(s=>!ot(s,n));return{arrayValue:{values:t}}}var Cn=class extends Rn{constructor(e,t){super(),this.serializer=e,this.Ie=t}};function tg(r){return oe(r.integerValue||r.doubleValue)}function hy(r){return Fl(r)&&r.arrayValue.values?r.arrayValue.values.slice():[]}function NS(r,e){return r.field.isEqual(e.field)&&function(n,s){return n instanceof vr&&s instanceof vr||n instanceof wr&&s instanceof wr?wn(n.elements,s.elements,ot):n instanceof Cn&&s instanceof Cn?ot(n.Ie,s.Ie):n instanceof Pn&&s instanceof Pn}(r.transform,e.transform)}var vc=class{constructor(e,t){this.version=e,this.transformResults=t}},Xt=class r{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new r}static exists(e){return new r(void 0,e)}static updateTime(e){return new r(e)}get isNone(){return this.updateTime===void 0&&this.exists===void 0}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}};function bo(r,e){return r.updateTime!==void 0?e.isFoundDocument()&&e.version.isEqual(r.updateTime):r.exists===void 0||r.exists===e.isFoundDocument()}var kn=class{};function dy(r,e){if(!r.hasLocalMutations||e&&e.fields.length===0)return null;if(e===null)return r.isNoDocument()?new ko(r.key,Xt.none()):new br(r.key,r.data,Xt.none());{let t=r.data,n=je.empty(),s=new _e(Ue.comparator);for(let i of e.fields)if(!s.has(i)){let a=t.field(i);a===null&&i.length>1&&(i=i.popLast(),a=t.field(i)),a===null?n.delete(i):n.set(i,a),s=s.add(i)}return new ut(r.key,n,new qe(s.toArray()),Xt.none())}}function VS(r,e,t){r instanceof br?function(s,i,a){let u=s.value.clone(),c=ng(s.fieldTransforms,i,a.transformResults);u.setAll(c),i.convertToFoundDocument(a.version,u).setHasCommittedMutations()}(r,e,t):r instanceof ut?function(s,i,a){if(!bo(s.precondition,i))return void i.convertToUnknownDocument(a.version);let u=ng(s.fieldTransforms,i,a.transformResults),c=i.data;c.setAll(fy(s)),c.setAll(u),i.convertToFoundDocument(a.version,c).setHasCommittedMutations()}(r,e,t):function(s,i,a){i.convertToNoDocument(a.version).setHasCommittedMutations()}(0,e,t)}function ks(r,e,t,n){return r instanceof br?function(i,a,u,c){if(!bo(i.precondition,a))return u;let h=i.value.clone(),f=sg(i.fieldTransforms,c,a);return h.setAll(f),a.convertToFoundDocument(a.version,h).setHasLocalMutations(),null}(r,e,t,n):r instanceof ut?function(i,a,u,c){if(!bo(i.precondition,a))return u;let h=sg(i.fieldTransforms,c,a),f=a.data;return f.setAll(fy(i)),f.setAll(h),a.convertToFoundDocument(a.version,f).setHasLocalMutations(),u===null?null:u.unionWith(i.fieldMask.fields).unionWith(i.fieldTransforms.map(m=>m.field))}(r,e,t,n):function(i,a,u){return bo(i.precondition,a)?(a.convertToNoDocument(a.version).setHasLocalMutations(),null):u}(r,e,t)}function LS(r,e){let t=null;for(let n of r.fieldTransforms){let s=e.data.field(n.field),i=uy(n.transform,s||null);i!=null&&(t===null&&(t=je.empty()),t.set(n.field,i))}return t||null}function rg(r,e){return r.type===e.type&&!!r.key.isEqual(e.key)&&!!r.precondition.isEqual(e.precondition)&&!!function(n,s){return n===void 0&&s===void 0||!(!n||!s)&&wn(n,s,(i,a)=>NS(i,a))}(r.fieldTransforms,e.fieldTransforms)&&(r.type===0?r.value.isEqual(e.value):r.type!==1||r.data.isEqual(e.data)&&r.fieldMask.isEqual(e.fieldMask))}var br=class extends kn{constructor(e,t,n,s=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}},ut=class extends kn{constructor(e,t,n,s,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=s,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}};function fy(r){let e=new Map;return r.fieldMask.fields.forEach(t=>{if(!t.isEmpty()){let n=r.data.field(t);e.set(t,n)}}),e}function ng(r,e,t){let n=new Map;ee(r.length===t.length);for(let s=0;s<t.length;s++){let i=r[s],a=i.transform,u=e.data.field(i.field);n.set(i.field,OS(a,u,t[s]))}return n}function sg(r,e,t){let n=new Map;for(let s of r){let i=s.transform,a=t.data.field(s.field);n.set(s.field,DS(i,a,e))}return n}var ko=class extends kn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}},wc=class extends kn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}};var bc=class{constructor(e,t,n,s){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=s}applyToRemoteDocument(e,t){let n=t.mutationResults;for(let s=0;s<this.mutations.length;s++){let i=this.mutations[s];i.key.isEqual(e.key)&&VS(i,e,n[s])}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=ks(n,e,t,this.localWriteTime));for(let n of this.mutations)n.key.isEqual(e.key)&&(t=ks(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let n=oy();return this.mutations.forEach(s=>{let i=e.get(s.key),a=i.overlayedDocument,u=this.applyToLocalView(a,i.mutatedFields);u=t.has(s.key)?null:u;let c=dy(a,u);c!==null&&n.set(s.key,c),a.isValidDocument()||a.convertToNoDocument(q.min())}),n}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),W())}isEqual(e){return this.batchId===e.batchId&&wn(this.mutations,e.mutations,(t,n)=>rg(t,n))&&wn(this.baseMutations,e.baseMutations,(t,n)=>rg(t,n))}},Tc=class r{constructor(e,t,n,s){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=s}static from(e,t,n){ee(e.mutations.length===n.length);let s=function(){return SS}(),i=e.mutations;for(let a=0;a<i.length;a++)s=s.insert(i[a].key,n[a].version);return new r(e,t,n,s)}};var Ec=class{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return e!==null&&this.mutation===e.mutation}toString(){return`Overlay{
5
+ `+S+" "+O})}function Ur(o,l,d,p){o.info(function(){return"XMLHTTP TEXT ("+l+"): "+$v(o,d)+(p?" "+p:"")})}function Bv(o,l){o.info(function(){return"TIMEOUT: "+l})}as.prototype.info=function(){};function $v(o,l){if(!o.g)return l;if(!l)return null;try{var d=JSON.parse(l);if(d){for(o=0;o<d.length;o++)if(Array.isArray(d[o])){var p=d[o];if(!(2>p.length)){var A=p[1];if(Array.isArray(A)&&!(1>A.length)){var S=A[0];if(S!="noop"&&S!="stop"&&S!="close")for(var O=1;O<A.length;O++)A[O]=""}}}}return Qa(d)}catch{return l}}var Ii={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},Jh={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"},Za;function Ai(){}P(Ai,Ja),Ai.prototype.g=function(){return new XMLHttpRequest},Ai.prototype.i=function(){return{}},Za=new Ai;function Nt(o,l,d,p){this.j=o,this.i=l,this.l=d,this.R=p||1,this.U=new ns(this),this.I=45e3,this.H=null,this.o=!1,this.m=this.A=this.v=this.L=this.F=this.S=this.B=null,this.D=[],this.g=null,this.C=0,this.s=this.u=null,this.X=-1,this.J=!1,this.O=0,this.M=null,this.W=this.K=this.T=this.P=!1,this.h=new Yh}function Yh(){this.i=null,this.g="",this.h=!1}var Xh={},eu={};function tu(o,l,d){o.L=1,o.v=Pi(pt(l)),o.m=d,o.P=!0,Zh(o,null)}function Zh(o,l){o.F=Date.now(),xi(o),o.A=pt(o.v);var d=o.A,p=o.R;Array.isArray(p)||(p=[String(p)]),fd(d.i,"t",p),o.C=0,d=o.j.J,o.h=new Yh,o.g=kd(o.j,d?l:null,!o.m),0<o.O&&(o.M=new Lv(g(o.Y,o,o.g),o.O)),l=o.U,d=o.g,p=o.ca;var A="readystatechange";Array.isArray(A)||(A&&($h[0]=A.toString()),A=$h);for(var S=0;S<A.length;S++){var O=Vh(d,A[S],p||l.handleEvent,!1,l.h||l);if(!O)break;l.g[O.key]=O}l=o.H?y(o.H):{},o.m?(o.u||(o.u="POST"),l["Content-Type"]="application/x-www-form-urlencoded",o.g.ea(o.A,o.u,o.m,l)):(o.u="GET",o.g.ea(o.A,o.u,null,l)),is(),jv(o.i,o.u,o.A,o.l,o.R,o.m)}Nt.prototype.ca=function(o){o=o.target;let l=this.M;l&&mt(o)==3?l.j():this.Y(o)},Nt.prototype.Y=function(o){try{if(o==this.g)e:{let Ae=mt(this.g);var l=this.g.Ba();let qr=this.g.Z();if(!(3>Ae)&&(Ae!=3||this.g&&(this.h.h||this.g.oa()||wd(this.g)))){this.J||Ae!=4||l==7||(l==8||0>=qr?is(3):is(2)),ru(this);var d=this.g.Z();this.X=d;t:if(ed(this)){var p=wd(this.g);o="";var A=p.length,S=mt(this.g)==4;if(!this.h.i){if(typeof TextDecoder=="undefined"){ur(this),us(this);var O="";break t}this.h.i=new u.TextDecoder}for(l=0;l<A;l++)this.h.h=!0,o+=this.h.i.decode(p[l],{stream:!(S&&l==A-1)});p.length=0,this.h.g+=o,this.C=0,O=this.h.g}else O=this.g.oa();if(this.o=d==200,Uv(this.i,this.u,this.A,this.l,this.R,Ae,d),this.o){if(this.T&&!this.K){t:{if(this.g){var te,ve=this.g;if((te=ve.g?ve.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!F(te)){var X=te;break t}}X=null}if(d=X)Ur(this.i,this.l,d,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,nu(this,d);else{this.o=!1,this.s=3,Ce(12),ur(this),us(this);break e}}if(this.P){d=!0;let Ke;for(;!this.J&&this.C<O.length;)if(Ke=qv(this,O),Ke==eu){Ae==4&&(this.s=4,Ce(14),d=!1),Ur(this.i,this.l,null,"[Incomplete Response]");break}else if(Ke==Xh){this.s=4,Ce(15),Ur(this.i,this.l,O,"[Invalid Chunk]"),d=!1;break}else Ur(this.i,this.l,Ke,null),nu(this,Ke);if(ed(this)&&this.C!=0&&(this.h.g=this.h.g.slice(this.C),this.C=0),Ae!=4||O.length!=0||this.h.h||(this.s=1,Ce(16),d=!1),this.o=this.o&&d,!d)Ur(this.i,this.l,O,"[Invalid Chunked Response]"),ur(this),us(this);else if(0<O.length&&!this.W){this.W=!0;var Ie=this.j;Ie.g==this&&Ie.ba&&!Ie.M&&(Ie.j.info("Great, no buffering proxy detected. Bytes received: "+O.length),cu(Ie),Ie.M=!0,Ce(11))}}else Ur(this.i,this.l,O,null),nu(this,O);Ae==4&&ur(this),this.o&&!this.J&&(Ae==4?Sd(this.j,this):(this.o=!1,xi(this)))}else ow(this.g),d==400&&0<O.indexOf("Unknown SID")?(this.s=3,Ce(12)):(this.s=0,Ce(13)),ur(this),us(this)}}}catch{}finally{}};function ed(o){return o.g?o.u=="GET"&&o.L!=2&&o.j.Ca:!1}function qv(o,l){var d=o.C,p=l.indexOf(`
6
+ `,d);return p==-1?eu:(d=Number(l.substring(d,p)),isNaN(d)?Xh:(p+=1,p+d>l.length?eu:(l=l.slice(p,p+d),o.C=p+d,l)))}Nt.prototype.cancel=function(){this.J=!0,ur(this)};function xi(o){o.S=Date.now()+o.I,td(o,o.I)}function td(o,l){if(o.B!=null)throw Error("WatchDog timer not null");o.B=os(g(o.ba,o),l)}function ru(o){o.B&&(u.clearTimeout(o.B),o.B=null)}Nt.prototype.ba=function(){this.B=null;let o=Date.now();0<=o-this.S?(Bv(this.i,this.A),this.L!=2&&(is(),Ce(17)),ur(this),this.s=2,us(this)):td(this,this.S-o)};function us(o){o.j.G==0||o.J||Sd(o.j,o)}function ur(o){ru(o);var l=o.M;l&&typeof l.ma=="function"&&l.ma(),o.M=null,qh(o.U),o.g&&(l=o.g,o.g=null,l.abort(),l.ma())}function nu(o,l){try{var d=o.j;if(d.G!=0&&(d.g==o||su(d.h,o))){if(!o.K&&su(d.h,o)&&d.G==3){try{var p=d.Da.g.parse(l)}catch{p=null}if(Array.isArray(p)&&p.length==3){var A=p;if(A[0]==0){e:if(!d.u){if(d.g)if(d.g.F+3e3<o.F)Ni(d),Di(d);else break e;uu(d),Ce(18)}}else d.za=A[1],0<d.za-d.T&&37500>A[2]&&d.F&&d.v==0&&!d.C&&(d.C=os(g(d.Za,d),6e3));if(1>=sd(d.h)&&d.ca){try{d.ca()}catch{}d.ca=void 0}}else lr(d,11)}else if((o.K||d.g==o)&&Ni(d),!F(l))for(A=d.Da.g.parse(l),l=0;l<A.length;l++){let X=A[l];if(d.T=X[0],X=X[1],d.G==2)if(X[0]=="c"){d.K=X[1],d.ia=X[2];let Ie=X[3];Ie!=null&&(d.la=Ie,d.j.info("VER="+d.la));let Ae=X[4];Ae!=null&&(d.Aa=Ae,d.j.info("SVER="+d.Aa));let qr=X[5];qr!=null&&typeof qr=="number"&&0<qr&&(p=1.5*qr,d.L=p,d.j.info("backChannelRequestTimeoutMs_="+p)),p=d;let Ke=o.g;if(Ke){let Li=Ke.g?Ke.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(Li){var S=p.h;S.g||Li.indexOf("spdy")==-1&&Li.indexOf("quic")==-1&&Li.indexOf("h2")==-1||(S.j=S.l,S.g=new Set,S.h&&(iu(S,S.h),S.h=null))}if(p.D){let lu=Ke.g?Ke.g.getResponseHeader("X-HTTP-Session-Id"):null;lu&&(p.ya=lu,se(p.I,p.D,lu))}}d.G=3,d.l&&d.l.ua(),d.ba&&(d.R=Date.now()-o.F,d.j.info("Handshake RTT: "+d.R+"ms")),p=d;var O=o;if(p.qa=Cd(p,p.J?p.ia:null,p.W),O.K){id(p.h,O);var te=O,ve=p.L;ve&&(te.I=ve),te.B&&(ru(te),xi(te)),p.g=O}else Ad(p);0<d.i.length&&Oi(d)}else X[0]!="stop"&&X[0]!="close"||lr(d,7);else d.G==3&&(X[0]=="stop"||X[0]=="close"?X[0]=="stop"?lr(d,7):au(d):X[0]!="noop"&&d.l&&d.l.ta(X),d.v=0)}}is(4)}catch{}}var zv=class{constructor(o,l){this.g=o,this.map=l}};function rd(o){this.l=o||10,u.PerformanceNavigationTiming?(o=u.performance.getEntriesByType("navigation"),o=0<o.length&&(o[0].nextHopProtocol=="hq"||o[0].nextHopProtocol=="h2")):o=!!(u.chrome&&u.chrome.loadTimes&&u.chrome.loadTimes()&&u.chrome.loadTimes().wasFetchedViaSpdy),this.j=o?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function nd(o){return o.h?!0:o.g?o.g.size>=o.j:!1}function sd(o){return o.h?1:o.g?o.g.size:0}function su(o,l){return o.h?o.h==l:o.g?o.g.has(l):!1}function iu(o,l){o.g?o.g.add(l):o.h=l}function id(o,l){o.h&&o.h==l?o.h=null:o.g&&o.g.has(l)&&o.g.delete(l)}rd.prototype.cancel=function(){if(this.i=od(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&this.g.size!==0){for(let o of this.g.values())o.cancel();this.g.clear()}};function od(o){if(o.h!=null)return o.i.concat(o.h.D);if(o.g!=null&&o.g.size!==0){let l=o.i;for(let d of o.g.values())l=l.concat(d.D);return l}return C(o.i)}function Gv(o){if(o.V&&typeof o.V=="function")return o.V();if(typeof Map!="undefined"&&o instanceof Map||typeof Set!="undefined"&&o instanceof Set)return Array.from(o.values());if(typeof o=="string")return o.split("");if(c(o)){for(var l=[],d=o.length,p=0;p<d;p++)l.push(o[p]);return l}l=[],d=0;for(p in o)l[d++]=o[p];return l}function Kv(o){if(o.na&&typeof o.na=="function")return o.na();if(!o.V||typeof o.V!="function"){if(typeof Map!="undefined"&&o instanceof Map)return Array.from(o.keys());if(!(typeof Set!="undefined"&&o instanceof Set)){if(c(o)||typeof o=="string"){var l=[];o=o.length;for(var d=0;d<o;d++)l.push(d);return l}l=[],d=0;for(let p in o)l[d++]=p;return l}}}function ad(o,l){if(o.forEach&&typeof o.forEach=="function")o.forEach(l,void 0);else if(c(o)||typeof o=="string")Array.prototype.forEach.call(o,l,void 0);else for(var d=Kv(o),p=Gv(o),A=p.length,S=0;S<A;S++)l.call(void 0,p[S],d&&d[S],o)}var ud=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function Hv(o,l){if(o){o=o.split("&");for(var d=0;d<o.length;d++){var p=o[d].indexOf("="),A=null;if(0<=p){var S=o[d].substring(0,p);A=o[d].substring(p+1)}else S=o[d];l(S,A?decodeURIComponent(A.replace(/\+/g," ")):"")}}}function cr(o){if(this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,o instanceof cr){this.h=o.h,Si(this,o.j),this.o=o.o,this.g=o.g,Ri(this,o.s),this.l=o.l;var l=o.i,d=new hs;d.i=l.i,l.g&&(d.g=new Map(l.g),d.h=l.h),cd(this,d),this.m=o.m}else o&&(l=String(o).match(ud))?(this.h=!1,Si(this,l[1]||"",!0),this.o=cs(l[2]||""),this.g=cs(l[3]||"",!0),Ri(this,l[4]),this.l=cs(l[5]||"",!0),cd(this,l[6]||"",!0),this.m=cs(l[7]||"")):(this.h=!1,this.i=new hs(null,this.h))}cr.prototype.toString=function(){var o=[],l=this.j;l&&o.push(ls(l,ld,!0),":");var d=this.g;return(d||l=="file")&&(o.push("//"),(l=this.o)&&o.push(ls(l,ld,!0),"@"),o.push(encodeURIComponent(String(d)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),d=this.s,d!=null&&o.push(":",String(d))),(d=this.l)&&(this.g&&d.charAt(0)!="/"&&o.push("/"),o.push(ls(d,d.charAt(0)=="/"?Jv:Qv,!0))),(d=this.i.toString())&&o.push("?",d),(d=this.m)&&o.push("#",ls(d,Xv)),o.join("")};function pt(o){return new cr(o)}function Si(o,l,d){o.j=d?cs(l,!0):l,o.j&&(o.j=o.j.replace(/:$/,""))}function Ri(o,l){if(l){if(l=Number(l),isNaN(l)||0>l)throw Error("Bad port number "+l);o.s=l}else o.s=null}function cd(o,l,d){l instanceof hs?(o.i=l,Zv(o.i,o.h)):(d||(l=ls(l,Yv)),o.i=new hs(l,o.h))}function se(o,l,d){o.i.set(l,d)}function Pi(o){return se(o,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),o}function cs(o,l){return o?l?decodeURI(o.replace(/%25/g,"%2525")):decodeURIComponent(o):""}function ls(o,l,d){return typeof o=="string"?(o=encodeURI(o).replace(l,Wv),d&&(o=o.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),o):null}function Wv(o){return o=o.charCodeAt(0),"%"+(o>>4&15).toString(16)+(o&15).toString(16)}var ld=/[#\/\?@]/g,Qv=/[#\?:]/g,Jv=/[#\?]/g,Yv=/[#\?@]/g,Xv=/#/g;function hs(o,l){this.h=this.g=null,this.i=o||null,this.j=!!l}function Vt(o){o.g||(o.g=new Map,o.h=0,o.i&&Hv(o.i,function(l,d){o.add(decodeURIComponent(l.replace(/\+/g," ")),d)}))}r=hs.prototype,r.add=function(o,l){Vt(this),this.i=null,o=Br(this,o);var d=this.g.get(o);return d||this.g.set(o,d=[]),d.push(l),this.h+=1,this};function hd(o,l){Vt(o),l=Br(o,l),o.g.has(l)&&(o.i=null,o.h-=o.g.get(l).length,o.g.delete(l))}function dd(o,l){return Vt(o),l=Br(o,l),o.g.has(l)}r.forEach=function(o,l){Vt(this),this.g.forEach(function(d,p){d.forEach(function(A){o.call(l,A,p,this)},this)},this)},r.na=function(){Vt(this);let o=Array.from(this.g.values()),l=Array.from(this.g.keys()),d=[];for(let p=0;p<l.length;p++){let A=o[p];for(let S=0;S<A.length;S++)d.push(l[p])}return d},r.V=function(o){Vt(this);let l=[];if(typeof o=="string")dd(this,o)&&(l=l.concat(this.g.get(Br(this,o))));else{o=Array.from(this.g.values());for(let d=0;d<o.length;d++)l=l.concat(o[d])}return l},r.set=function(o,l){return Vt(this),this.i=null,o=Br(this,o),dd(this,o)&&(this.h-=this.g.get(o).length),this.g.set(o,[l]),this.h+=1,this},r.get=function(o,l){return o?(o=this.V(o),0<o.length?String(o[0]):l):l};function fd(o,l,d){hd(o,l),0<d.length&&(o.i=null,o.g.set(Br(o,l),C(d)),o.h+=d.length)}r.toString=function(){if(this.i)return this.i;if(!this.g)return"";let o=[],l=Array.from(this.g.keys());for(var d=0;d<l.length;d++){var p=l[d];let S=encodeURIComponent(String(p)),O=this.V(p);for(p=0;p<O.length;p++){var A=S;O[p]!==""&&(A+="="+encodeURIComponent(String(O[p]))),o.push(A)}}return this.i=o.join("&")};function Br(o,l){return l=String(l),o.j&&(l=l.toLowerCase()),l}function Zv(o,l){l&&!o.j&&(Vt(o),o.i=null,o.g.forEach(function(d,p){var A=p.toLowerCase();p!=A&&(hd(this,p),fd(this,A,d))},o)),o.j=l}function ew(o,l){let d=new as;if(u.Image){let p=new Image;p.onload=b(Lt,d,"TestLoadImage: loaded",!0,l,p),p.onerror=b(Lt,d,"TestLoadImage: error",!1,l,p),p.onabort=b(Lt,d,"TestLoadImage: abort",!1,l,p),p.ontimeout=b(Lt,d,"TestLoadImage: timeout",!1,l,p),u.setTimeout(function(){p.ontimeout&&p.ontimeout()},1e4),p.src=o}else l(!1)}function tw(o,l){let d=new as,p=new AbortController,A=setTimeout(()=>{p.abort(),Lt(d,"TestPingServer: timeout",!1,l)},1e4);fetch(o,{signal:p.signal}).then(S=>{clearTimeout(A),S.ok?Lt(d,"TestPingServer: ok",!0,l):Lt(d,"TestPingServer: server error",!1,l)}).catch(()=>{clearTimeout(A),Lt(d,"TestPingServer: error",!1,l)})}function Lt(o,l,d,p,A){try{A&&(A.onload=null,A.onerror=null,A.onabort=null,A.ontimeout=null),p(d)}catch{}}function rw(){this.g=new Mv}function nw(o,l,d){let p=d||"";try{ad(o,function(A,S){let O=A;h(A)&&(O=Qa(A)),l.push(p+S+"="+encodeURIComponent(O))})}catch(A){throw l.push(p+"type="+encodeURIComponent("_badmap")),A}}function ds(o){this.l=o.Ub||null,this.j=o.eb||!1}P(ds,Ja),ds.prototype.g=function(){return new Ci(this.l,this.j)},ds.prototype.i=function(o){return function(){return o}}({});function Ci(o,l){Ee.call(this),this.D=o,this.o=l,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.u=new Headers,this.h=null,this.B="GET",this.A="",this.g=!1,this.v=this.j=this.l=null}P(Ci,Ee),r=Ci.prototype,r.open=function(o,l){if(this.readyState!=0)throw this.abort(),Error("Error reopening a connection");this.B=o,this.A=l,this.readyState=1,ps(this)},r.send=function(o){if(this.readyState!=1)throw this.abort(),Error("need to call open() first. ");this.g=!0;let l={headers:this.u,method:this.B,credentials:this.m,cache:void 0};o&&(l.body=o),(this.D||u).fetch(new Request(this.A,l)).then(this.Sa.bind(this),this.ga.bind(this))},r.abort=function(){this.response=this.responseText="",this.u=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&this.readyState!=4&&(this.g=!1,fs(this)),this.readyState=0},r.Sa=function(o){if(this.g&&(this.l=o,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=o.headers,this.readyState=2,ps(this)),this.g&&(this.readyState=3,ps(this),this.g)))if(this.responseType==="arraybuffer")o.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(typeof u.ReadableStream!="undefined"&&"body"in o){if(this.j=o.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.v=new TextDecoder;pd(this)}else o.text().then(this.Ra.bind(this),this.ga.bind(this))};function pd(o){o.j.read().then(o.Pa.bind(o)).catch(o.ga.bind(o))}r.Pa=function(o){if(this.g){if(this.o&&o.value)this.response.push(o.value);else if(!this.o){var l=o.value?o.value:new Uint8Array(0);(l=this.v.decode(l,{stream:!o.done}))&&(this.response=this.responseText+=l)}o.done?fs(this):ps(this),this.readyState==3&&pd(this)}},r.Ra=function(o){this.g&&(this.response=this.responseText=o,fs(this))},r.Qa=function(o){this.g&&(this.response=o,fs(this))},r.ga=function(){this.g&&fs(this)};function fs(o){o.readyState=4,o.l=null,o.j=null,o.v=null,ps(o)}r.setRequestHeader=function(o,l){this.u.append(o,l)},r.getResponseHeader=function(o){return this.h&&this.h.get(o.toLowerCase())||""},r.getAllResponseHeaders=function(){if(!this.h)return"";let o=[],l=this.h.entries();for(var d=l.next();!d.done;)d=d.value,o.push(d[0]+": "+d[1]),d=l.next();return o.join(`\r
7
+ `)};function ps(o){o.onreadystatechange&&o.onreadystatechange.call(o)}Object.defineProperty(Ci.prototype,"withCredentials",{get:function(){return this.m==="include"},set:function(o){this.m=o?"include":"same-origin"}});function md(o){let l="";return B(o,function(d,p){l+=p,l+=":",l+=d,l+=`\r
8
+ `}),l}function ou(o,l,d){e:{for(p in d){var p=!1;break e}p=!0}p||(d=md(d),typeof o=="string"?d!=null&&encodeURIComponent(String(d)):se(o,l,d))}function ae(o){Ee.call(this),this.headers=new Map,this.o=o||null,this.h=!1,this.v=this.g=null,this.D="",this.m=0,this.l="",this.j=this.B=this.u=this.A=!1,this.I=null,this.H="",this.J=!1}P(ae,Ee);var sw=/^https?$/i,iw=["POST","PUT"];r=ae.prototype,r.Ha=function(o){this.J=o},r.ea=function(o,l,d,p){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+o);l=l?l.toUpperCase():"GET",this.D=o,this.l="",this.m=0,this.A=!1,this.h=!0,this.g=this.o?this.o.g():Za.g(),this.v=this.o?zh(this.o):zh(Za),this.g.onreadystatechange=g(this.Ea,this);try{this.B=!0,this.g.open(l,String(o),!0),this.B=!1}catch(S){gd(this,S);return}if(o=d||"",d=new Map(this.headers),p)if(Object.getPrototypeOf(p)===Object.prototype)for(var A in p)d.set(A,p[A]);else if(typeof p.keys=="function"&&typeof p.get=="function")for(let S of p.keys())d.set(S,p.get(S));else throw Error("Unknown input type for opt_headers: "+String(p));p=Array.from(d.keys()).find(S=>S.toLowerCase()=="content-type"),A=u.FormData&&o instanceof u.FormData,!(0<=Array.prototype.indexOf.call(iw,l,void 0))||p||A||d.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(let[S,O]of d)this.g.setRequestHeader(S,O);this.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{vd(this),this.u=!0,this.g.send(o),this.u=!1}catch(S){gd(this,S)}};function gd(o,l){o.h=!1,o.g&&(o.j=!0,o.g.abort(),o.j=!1),o.l=l,o.m=5,yd(o),ki(o)}function yd(o){o.A||(o.A=!0,Pe(o,"complete"),Pe(o,"error"))}r.abort=function(o){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=o||7,Pe(this,"complete"),Pe(this,"abort"),ki(this))},r.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),ki(this,!0)),ae.aa.N.call(this)},r.Ea=function(){this.s||(this.B||this.u||this.j?_d(this):this.bb())},r.bb=function(){_d(this)};function _d(o){if(o.h&&typeof a!="undefined"&&(!o.v[1]||mt(o)!=4||o.Z()!=2)){if(o.u&&mt(o)==4)Uh(o.Ea,0,o);else if(Pe(o,"readystatechange"),mt(o)==4){o.h=!1;try{let O=o.Z();e:switch(O){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var l=!0;break e;default:l=!1}var d;if(!(d=l)){var p;if(p=O===0){var A=String(o.D).match(ud)[1]||null;!A&&u.self&&u.self.location&&(A=u.self.location.protocol.slice(0,-1)),p=!sw.test(A?A.toLowerCase():"")}d=p}if(d)Pe(o,"complete"),Pe(o,"success");else{o.m=6;try{var S=2<mt(o)?o.g.statusText:""}catch{S=""}o.l=S+" ["+o.Z()+"]",yd(o)}}finally{ki(o)}}}}function ki(o,l){if(o.g){vd(o);let d=o.g,p=o.v[0]?()=>{}:null;o.g=null,o.v=null,l||Pe(o,"ready");try{d.onreadystatechange=p}catch{}}}function vd(o){o.I&&(u.clearTimeout(o.I),o.I=null)}r.isActive=function(){return!!this.g};function mt(o){return o.g?o.g.readyState:0}r.Z=function(){try{return 2<mt(this)?this.g.status:-1}catch{return-1}},r.oa=function(){try{return this.g?this.g.responseText:""}catch{return""}},r.Oa=function(o){if(this.g){var l=this.g.responseText;return o&&l.indexOf(o)==0&&(l=l.substring(o.length)),Fv(l)}};function wd(o){try{if(!o.g)return null;if("response"in o.g)return o.g.response;switch(o.H){case"":case"text":return o.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in o.g)return o.g.mozResponseArrayBuffer}return null}catch{return null}}function ow(o){let l={};o=(o.g&&2<=mt(o)&&o.g.getAllResponseHeaders()||"").split(`\r
9
+ `);for(let p=0;p<o.length;p++){if(F(o[p]))continue;var d=I(o[p]);let A=d[0];if(d=d[1],typeof d!="string")continue;d=d.trim();let S=l[A]||[];l[A]=S,S.push(d)}E(l,function(p){return p.join(", ")})}r.Ba=function(){return this.m},r.Ka=function(){return typeof this.l=="string"?this.l:String(this.l)};function ms(o,l,d){return d&&d.internalChannelParams&&d.internalChannelParams[o]||l}function bd(o){this.Aa=0,this.i=[],this.j=new as,this.ia=this.qa=this.I=this.W=this.g=this.ya=this.D=this.H=this.m=this.S=this.o=null,this.Ya=this.U=0,this.Va=ms("failFast",!1,o),this.F=this.C=this.u=this.s=this.l=null,this.X=!0,this.za=this.T=-1,this.Y=this.v=this.B=0,this.Ta=ms("baseRetryDelayMs",5e3,o),this.cb=ms("retryDelaySeedMs",1e4,o),this.Wa=ms("forwardChannelMaxRetries",2,o),this.wa=ms("forwardChannelRequestTimeoutMs",2e4,o),this.pa=o&&o.xmlHttpFactory||void 0,this.Xa=o&&o.Tb||void 0,this.Ca=o&&o.useFetchStreams||!1,this.L=void 0,this.J=o&&o.supportsCrossDomainXhr||!1,this.K="",this.h=new rd(o&&o.concurrentRequestLimit),this.Da=new rw,this.P=o&&o.fastHandshake||!1,this.O=o&&o.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=o&&o.Rb||!1,o&&o.xa&&this.j.xa(),o&&o.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&o&&o.detectBufferingProxy||!1,this.ja=void 0,o&&o.longPollingTimeout&&0<o.longPollingTimeout&&(this.ja=o.longPollingTimeout),this.ca=void 0,this.R=0,this.M=!1,this.ka=this.A=null}r=bd.prototype,r.la=8,r.G=1,r.connect=function(o,l,d,p){Ce(0),this.W=o,this.H=l||{},d&&p!==void 0&&(this.H.OSID=d,this.H.OAID=p),this.F=this.X,this.I=Cd(this,null,this.W),Oi(this)};function au(o){if(Td(o),o.G==3){var l=o.U++,d=pt(o.I);if(se(d,"SID",o.K),se(d,"RID",l),se(d,"TYPE","terminate"),gs(o,d),l=new Nt(o,o.j,l),l.L=2,l.v=Pi(pt(d)),d=!1,u.navigator&&u.navigator.sendBeacon)try{d=u.navigator.sendBeacon(l.v.toString(),"")}catch{}!d&&u.Image&&(new Image().src=l.v,d=!0),d||(l.g=kd(l.j,null),l.g.ea(l.v)),l.F=Date.now(),xi(l)}Pd(o)}function Di(o){o.g&&(cu(o),o.g.cancel(),o.g=null)}function Td(o){Di(o),o.u&&(u.clearTimeout(o.u),o.u=null),Ni(o),o.h.cancel(),o.s&&(typeof o.s=="number"&&u.clearTimeout(o.s),o.s=null)}function Oi(o){if(!nd(o.h)&&!o.s){o.s=!0;var l=o.Ga;Zn||Nh(),es||(Zn(),es=!0),Ua.add(l,o),o.B=0}}function aw(o,l){return sd(o.h)>=o.h.j-(o.s?1:0)?!1:o.s?(o.i=l.D.concat(o.i),!0):o.G==1||o.G==2||o.B>=(o.Va?0:o.Wa)?!1:(o.s=os(g(o.Ga,o,l),Rd(o,o.B)),o.B++,!0)}r.Ga=function(o){if(this.s)if(this.s=null,this.G==1){if(!o){this.U=Math.floor(1e5*Math.random()),o=this.U++;let A=new Nt(this,this.j,o),S=this.o;if(this.S&&(S?(S=y(S),T(S,this.S)):S=this.S),this.m!==null||this.O||(A.H=S,S=null),this.P)e:{for(var l=0,d=0;d<this.i.length;d++){t:{var p=this.i[d];if("__data__"in p.map&&(p=p.map.__data__,typeof p=="string")){p=p.length;break t}p=void 0}if(p===void 0)break;if(l+=p,4096<l){l=d;break e}if(l===4096||d===this.i.length-1){l=d+1;break e}}l=1e3}else l=1e3;l=Id(this,A,l),d=pt(this.I),se(d,"RID",o),se(d,"CVER",22),this.D&&se(d,"X-HTTP-Session-Id",this.D),gs(this,d),S&&(this.O?l="headers="+encodeURIComponent(String(md(S)))+"&"+l:this.m&&ou(d,this.m,S)),iu(this.h,A),this.Ua&&se(d,"TYPE","init"),this.P?(se(d,"$req",l),se(d,"SID","null"),A.T=!0,tu(A,d,null)):tu(A,d,l),this.G=2}}else this.G==3&&(o?Ed(this,o):this.i.length==0||nd(this.h)||Ed(this))};function Ed(o,l){var d;l?d=l.l:d=o.U++;let p=pt(o.I);se(p,"SID",o.K),se(p,"RID",d),se(p,"AID",o.T),gs(o,p),o.m&&o.o&&ou(p,o.m,o.o),d=new Nt(o,o.j,d,o.B+1),o.m===null&&(d.H=o.o),l&&(o.i=l.D.concat(o.i)),l=Id(o,d,1e3),d.I=Math.round(.5*o.wa)+Math.round(.5*o.wa*Math.random()),iu(o.h,d),tu(d,p,l)}function gs(o,l){o.H&&B(o.H,function(d,p){se(l,p,d)}),o.l&&ad({},function(d,p){se(l,p,d)})}function Id(o,l,d){d=Math.min(o.i.length,d);var p=o.l?g(o.l.Na,o.l,o):null;e:{var A=o.i;let S=-1;for(;;){let O=["count="+d];S==-1?0<d?(S=A[0].g,O.push("ofs="+S)):S=0:O.push("ofs="+S);let te=!0;for(let ve=0;ve<d;ve++){let X=A[ve].g,Ie=A[ve].map;if(X-=S,0>X)S=Math.max(0,A[ve].g-100),te=!1;else try{nw(Ie,O,"req"+X+"_")}catch{p&&p(Ie)}}if(te){p=O.join("&");break e}}}return o=o.i.splice(0,d),l.D=o,p}function Ad(o){if(!o.g&&!o.u){o.Y=1;var l=o.Fa;Zn||Nh(),es||(Zn(),es=!0),Ua.add(l,o),o.v=0}}function uu(o){return o.g||o.u||3<=o.v?!1:(o.Y++,o.u=os(g(o.Fa,o),Rd(o,o.v)),o.v++,!0)}r.Fa=function(){if(this.u=null,xd(this),this.ba&&!(this.M||this.g==null||0>=this.R)){var o=2*this.R;this.j.info("BP detection timer enabled: "+o),this.A=os(g(this.ab,this),o)}},r.ab=function(){this.A&&(this.A=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.M=!0,Ce(10),Di(this),xd(this))};function cu(o){o.A!=null&&(u.clearTimeout(o.A),o.A=null)}function xd(o){o.g=new Nt(o,o.j,"rpc",o.Y),o.m===null&&(o.g.H=o.o),o.g.O=0;var l=pt(o.qa);se(l,"RID","rpc"),se(l,"SID",o.K),se(l,"AID",o.T),se(l,"CI",o.F?"0":"1"),!o.F&&o.ja&&se(l,"TO",o.ja),se(l,"TYPE","xmlhttp"),gs(o,l),o.m&&o.o&&ou(l,o.m,o.o),o.L&&(o.g.I=o.L);var d=o.g;o=o.ia,d.L=1,d.v=Pi(pt(l)),d.m=null,d.P=!0,Zh(d,o)}r.Za=function(){this.C!=null&&(this.C=null,Di(this),uu(this),Ce(19))};function Ni(o){o.C!=null&&(u.clearTimeout(o.C),o.C=null)}function Sd(o,l){var d=null;if(o.g==l){Ni(o),cu(o),o.g=null;var p=2}else if(su(o.h,l))d=l.D,id(o.h,l),p=1;else return;if(o.G!=0){if(l.o)if(p==1){d=l.m?l.m.length:0,l=Date.now()-l.F;var A=o.B;p=Ei(),Pe(p,new Qh(p,d)),Oi(o)}else Ad(o);else if(A=l.s,A==3||A==0&&0<l.X||!(p==1&&aw(o,l)||p==2&&uu(o)))switch(d&&0<d.length&&(l=o.h,l.i=l.i.concat(d)),A){case 1:lr(o,5);break;case 4:lr(o,10);break;case 3:lr(o,6);break;default:lr(o,2)}}}function Rd(o,l){let d=o.Ta+Math.floor(Math.random()*o.cb);return o.isActive()||(d*=2),d*l}function lr(o,l){if(o.j.info("Error code "+l),l==2){var d=g(o.fb,o),p=o.Xa;let A=!p;p=new cr(p||"//www.google.com/images/cleardot.gif"),u.location&&u.location.protocol=="http"||Si(p,"https"),Pi(p),A?ew(p.toString(),d):tw(p.toString(),d)}else Ce(2);o.G=0,o.l&&o.l.sa(l),Pd(o),Td(o)}r.fb=function(o){o?(this.j.info("Successfully pinged google.com"),Ce(2)):(this.j.info("Failed to ping google.com"),Ce(1))};function Pd(o){if(o.G=0,o.ka=[],o.l){let l=od(o.h);(l.length!=0||o.i.length!=0)&&(R(o.ka,l),R(o.ka,o.i),o.h.i.length=0,C(o.i),o.i.length=0),o.l.ra()}}function Cd(o,l,d){var p=d instanceof cr?pt(d):new cr(d);if(p.g!="")l&&(p.g=l+"."+p.g),Ri(p,p.s);else{var A=u.location;p=A.protocol,l=l?l+"."+A.hostname:A.hostname,A=+A.port;var S=new cr(null);p&&Si(S,p),l&&(S.g=l),A&&Ri(S,A),d&&(S.l=d),p=S}return d=o.D,l=o.ya,d&&l&&se(p,d,l),se(p,"VER",o.la),gs(o,p),p}function kd(o,l,d){if(l&&!o.J)throw Error("Can't create secondary domain capable XhrIo object.");return l=o.Ca&&!o.pa?new ae(new ds({eb:d})):new ae(o.pa),l.Ha(o.J),l}r.isActive=function(){return!!this.l&&this.l.isActive(this)};function Dd(){}r=Dd.prototype,r.ua=function(){},r.ta=function(){},r.sa=function(){},r.ra=function(){},r.isActive=function(){return!0},r.Na=function(){};function Vi(){}Vi.prototype.g=function(o,l){return new Fe(o,l)};function Fe(o,l){Ee.call(this),this.g=new bd(l),this.l=o,this.h=l&&l.messageUrlParams||null,o=l&&l.messageHeaders||null,l&&l.clientProtocolHeaderRequired&&(o?o["X-Client-Protocol"]="webchannel":o={"X-Client-Protocol":"webchannel"}),this.g.o=o,o=l&&l.initMessageHeaders||null,l&&l.messageContentType&&(o?o["X-WebChannel-Content-Type"]=l.messageContentType:o={"X-WebChannel-Content-Type":l.messageContentType}),l&&l.va&&(o?o["X-WebChannel-Client-Profile"]=l.va:o={"X-WebChannel-Client-Profile":l.va}),this.g.S=o,(o=l&&l.Sb)&&!F(o)&&(this.g.m=o),this.v=l&&l.supportsCrossDomainXhr||!1,this.u=l&&l.sendRawJson||!1,(l=l&&l.httpSessionIdParam)&&!F(l)&&(this.g.D=l,o=this.h,o!==null&&l in o&&(o=this.h,l in o&&delete o[l])),this.j=new $r(this)}P(Fe,Ee),Fe.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},Fe.prototype.close=function(){au(this.g)},Fe.prototype.o=function(o){var l=this.g;if(typeof o=="string"){var d={};d.__data__=o,o=d}else this.u&&(d={},d.__data__=Qa(o),o=d);l.i.push(new zv(l.Ya++,o)),l.G==3&&Oi(l)},Fe.prototype.N=function(){this.g.l=null,delete this.j,au(this.g),delete this.g,Fe.aa.N.call(this)};function Od(o){Ya.call(this),o.__headers__&&(this.headers=o.__headers__,this.statusCode=o.__status__,delete o.__headers__,delete o.__status__);var l=o.__sm__;if(l){e:{for(let d in l){o=d;break e}o=void 0}(this.i=o)&&(o=this.i,l=l!==null&&o in l?l[o]:void 0),this.data=l}else this.data=o}P(Od,Ya);function Nd(){Xa.call(this),this.status=1}P(Nd,Xa);function $r(o){this.g=o}P($r,Dd),$r.prototype.ua=function(){Pe(this.g,"a")},$r.prototype.ta=function(o){Pe(this.g,new Od(o))},$r.prototype.sa=function(o){Pe(this.g,new Nd)},$r.prototype.ra=function(){Pe(this.g,"b")},Vi.prototype.createWebChannel=Vi.prototype.g,Fe.prototype.send=Fe.prototype.o,Fe.prototype.open=Fe.prototype.m,Fe.prototype.close=Fe.prototype.close,Gu=It.createWebChannelTransport=function(){return new Vi},zu=It.getStatEventTarget=function(){return Ei()},qu=It.Event=ar,po=It.Stat={mb:0,pb:1,qb:2,Jb:3,Ob:4,Lb:5,Mb:6,Kb:7,Ib:8,Nb:9,PROXY:10,NOPROXY:11,Gb:12,Cb:13,Db:14,Bb:15,Eb:16,Fb:17,ib:18,hb:19,jb:20},Ii.NO_ERROR=0,Ii.TIMEOUT=8,Ii.HTTP_ERROR=6,xs=It.ErrorCode=Ii,Jh.COMPLETE="complete",$u=It.EventType=Jh,Gh.EventType=ss,ss.OPEN="a",ss.CLOSE="b",ss.ERROR="c",ss.MESSAGE="d",Ee.prototype.listen=Ee.prototype.K,hn=It.WebChannel=Gh,Jx=It.FetchXmlHttpFactory=ds,ae.prototype.listenOnce=ae.prototype.L,ae.prototype.getLastError=ae.prototype.Ka,ae.prototype.getLastErrorCode=ae.prototype.Ba,ae.prototype.getStatus=ae.prototype.Z,ae.prototype.getResponseJson=ae.prototype.Oa,ae.prototype.getResponseText=ae.prototype.oa,ae.prototype.send=ae.prototype.ea,ae.prototype.setWithCredentials=ae.prototype.Ha,Bu=It.XhrIo=ae}).apply(typeof fo!="undefined"?fo:typeof self!="undefined"?self:typeof window!="undefined"?window:{});var jm="@firebase/firestore",Um="4.7.10";var ye=class{constructor(e){this.uid=e}isAuthenticated(){return this.uid!=null}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}};ye.UNAUTHENTICATED=new ye(null),ye.GOOGLE_CREDENTIALS=new ye("google-credentials-uid"),ye.FIRST_PARTY=new ye("first-party-uid"),ye.MOCK_USER=new ye("mock-user");var Vn="11.5.0";var yr=new ln("@firebase/firestore");function dn(){return yr.logLevel}function V(r,...e){if(yr.logLevel<=Q.DEBUG){let t=e.map(Dl);yr.debug(`Firestore (${Vn}): ${r}`,...t)}}function At(r,...e){if(yr.logLevel<=Q.ERROR){let t=e.map(Dl);yr.error(`Firestore (${Vn}): ${r}`,...t)}}function vn(r,...e){if(yr.logLevel<=Q.WARN){let t=e.map(Dl);yr.warn(`Firestore (${Vn}): ${r}`,...t)}}function Dl(r){if(typeof r=="string")return r;try{return function(t){return JSON.stringify(t)}(r)}catch{return r}}function M(r="Unexpected state"){let e=`FIRESTORE (${Vn}) INTERNAL ASSERTION FAILED: `+r;throw At(e),new Error(e)}function ee(r,e){r||M()}function $(r,e){return r}var D={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"},L=class extends Qe{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}};var tt=class{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}};var bo=class{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}},Ju=class{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(ye.UNAUTHENTICATED))}shutdown(){}},Yu=class{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}},Xu=class{constructor(e){this.t=e,this.currentUser=ye.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){ee(this.o===void 0);let n=this.i,s=c=>this.i!==n?(n=this.i,t(c)):Promise.resolve(),i=new tt;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new tt,e.enqueueRetryable(()=>s(this.currentUser))};let a=()=>{let c=i;e.enqueueRetryable(async()=>{await c.promise,await s(this.currentUser)})},u=c=>{V("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=c,this.o&&(this.auth.addAuthTokenListener(this.o),a())};this.t.onInit(c=>u(c)),setTimeout(()=>{if(!this.auth){let c=this.t.getImmediate({optional:!0});c?u(c):(V("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new tt)}},0),a()}getToken(){let e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(n=>this.i!==e?(V("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):n?(ee(typeof n.accessToken=="string"),new bo(n.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){let e=this.auth&&this.auth.getUid();return ee(e===null||typeof e=="string"),new ye(e)}},Zu=class{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=ye.FIRST_PARTY,this.T=new Map}I(){return this.P?this.P():null}get headers(){this.T.set("X-Goog-AuthUser",this.l);let e=this.I();return e&&this.T.set("Authorization",e),this.h&&this.T.set("X-Goog-Iam-Authorization-Token",this.h),this.T}},ec=class{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new Zu(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(ye.FIRST_PARTY))}shutdown(){}invalidateToken(){}},To=class{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}},tc=class{constructor(e,t){this.A=t,this.forceRefresh=!1,this.appCheck=null,this.R=null,this.V=null,Dm(e)&&e.settings.appCheckToken&&(this.V=e.settings.appCheckToken)}start(e,t){ee(this.o===void 0);let n=i=>{i.error!=null&&V("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${i.error.message}`);let a=i.token!==this.R;return this.R=i.token,V("FirebaseAppCheckTokenProvider",`Received ${a?"new":"existing"} token.`),a?t(i.token):Promise.resolve()};this.o=i=>{e.enqueueRetryable(()=>n(i))};let s=i=>{V("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=i,this.o&&this.appCheck.addTokenListener(this.o)};this.A.onInit(i=>s(i)),setTimeout(()=>{if(!this.appCheck){let i=this.A.getImmediate({optional:!0});i?s(i):V("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.V)return Promise.resolve(new To(this.V));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(t=>t?(ee(typeof t.token=="string"),this.R=t.token,new To(t.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}};function Yx(r){let e=typeof self!="undefined"&&(self.crypto||self.msCrypto),t=new Uint8Array(r);if(e&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let n=0;n<r;n++)t[n]=Math.floor(256*Math.random());return t}function Sg(){return new TextEncoder}var Eo=class{static newId(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(4.129032258064516),n="";for(;n.length<20;){let s=Yx(40);for(let i=0;i<s.length;++i)n.length<20&&s[i]<t&&(n+=e.charAt(s[i]%62))}return n}};function K(r,e){return r<e?-1:r>e?1:0}function rc(r,e){let t=0;for(;t<r.length&&t<e.length;){let n=r.codePointAt(t),s=e.codePointAt(t);if(n!==s){if(n<128&&s<128)return K(n,s);{let i=Sg(),a=Xx(i.encode(Bm(r,t)),i.encode(Bm(e,t)));return a!==0?a:K(n,s)}}t+=n>65535?2:1}return K(r.length,e.length)}function Bm(r,e){return r.codePointAt(e)>65535?r.substring(e,e+2):r.substring(e,e+1)}function Xx(r,e){for(let t=0;t<r.length&&t<e.length;++t)if(r[t]!==e[t])return K(r[t],e[t]);return K(r.length,e.length)}function wn(r,e,t){return r.length===e.length&&r.every((n,s)=>t(n,e[s]))}var $m=-62135596800,qm=1e6,we=class r{static now(){return r.fromMillis(Date.now())}static fromDate(e){return r.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),n=Math.floor((e-1e3*t)*qm);return new r(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new L(D.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new L(D.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<$m)throw new L(D.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new L(D.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/qm}_compareTo(e){return this.seconds===e.seconds?K(this.nanoseconds,e.nanoseconds):K(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){let e=this.seconds-$m;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}};var q=class r{static fromTimestamp(e){return new r(e)}static min(){return new r(new we(0,0))}static max(){return new r(new we(253402300799,999999999))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}};var zm="__name__",Io=class r{constructor(e,t,n){t===void 0?t=0:t>e.length&&M(),n===void 0?n=e.length-t:n>e.length-t&&M(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return r.comparator(this,e)===0}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof r?e.forEach(n=>{t.push(n)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=e===void 0?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return this.length===0}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){let n=Math.min(e.length,t.length);for(let s=0;s<n;s++){let i=r.compareSegments(e.get(s),t.get(s));if(i!==0)return i}return K(e.length,t.length)}static compareSegments(e,t){let n=r.isNumericId(e),s=r.isNumericId(t);return n&&!s?-1:!n&&s?1:n&&s?r.extractNumericId(e).compare(r.extractNumericId(t)):rc(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return Et.fromString(e.substring(4,e.length-2))}},fe=class r extends Io{construct(e,t,n){return new r(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){let t=[];for(let n of e){if(n.indexOf("//")>=0)throw new L(D.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(s=>s.length>0))}return new r(t)}static emptyPath(){return new r([])}},Zx=/^[_a-zA-Z][_a-zA-Z0-9]*$/,Ue=class r extends Io{construct(e,t,n){return new r(e,t,n)}static isValidIdentifier(e){return Zx.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),r.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return this.length===1&&this.get(0)===zm}static keyField(){return new r([zm])}static fromServerFormat(e){let t=[],n="",s=0,i=()=>{if(n.length===0)throw new L(D.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""},a=!1;for(;s<e.length;){let u=e[s];if(u==="\\"){if(s+1===e.length)throw new L(D.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let c=e[s+1];if(c!=="\\"&&c!=="."&&c!=="`")throw new L(D.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=c,s+=2}else u==="`"?(a=!a,s++):u!=="."||a?(n+=u,s++):(i(),s++)}if(i(),a)throw new L(D.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new r(t)}static emptyPath(){return new r([])}};var j=class r{constructor(e){this.path=e}static fromPath(e){return new r(fe.fromString(e))}static fromName(e){return new r(fe.fromString(e).popFirst(5))}static empty(){return new r(fe.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return e!==null&&fe.comparator(this.path,e.path)===0}toString(){return this.path.toString()}static comparator(e,t){return fe.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new r(new fe(e.slice()))}};var Ds=-1,nc=class{constructor(e,t,n,s){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=s}};nc.UNKNOWN_ID=-1;function eS(r,e){let t=r.toTimestamp().seconds,n=r.toTimestamp().nanoseconds+1,s=q.fromTimestamp(n===1e9?new we(t+1,0):new we(t,n));return new _r(s,j.empty(),e)}function tS(r){return new _r(r.readTime,r.key,Ds)}var _r=class r{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new r(q.min(),j.empty(),Ds)}static max(){return new r(q.max(),j.empty(),Ds)}};function rS(r,e){let t=r.readTime.compareTo(e.readTime);return t!==0?t:(t=j.comparator(r.documentKey,e.documentKey),t!==0?t:K(r.largestBatchId,e.largestBatchId))}var nS="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",sc=class{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}};async function Ln(r){if(r.code!==D.FAILED_PRECONDITION||r.message!==nS)throw r;V("LocalStore","Unexpectedly lost primary lease")}var k=class r{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(t=>{this.isDone=!0,this.result=t,this.nextCallback&&this.nextCallback(t)},t=>{this.isDone=!0,this.error=t,this.catchCallback&&this.catchCallback(t)})}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&M(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new r((n,s)=>{this.nextCallback=i=>{this.wrapSuccess(e,i).next(n,s)},this.catchCallback=i=>{this.wrapFailure(t,i).next(n,s)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{let t=e();return t instanceof r?t:r.resolve(t)}catch(t){return r.reject(t)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):r.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):r.reject(t)}static resolve(e){return new r((t,n)=>{t(e)})}static reject(e){return new r((t,n)=>{n(e)})}static waitFor(e){return new r((t,n)=>{let s=0,i=0,a=!1;e.forEach(u=>{++s,u.next(()=>{++i,a&&i===s&&t()},c=>n(c))}),a=!0,i===s&&t()})}static or(e){let t=r.resolve(!1);for(let n of e)t=t.next(s=>s?r.resolve(s):n());return t}static forEach(e,t){let n=[];return e.forEach((s,i)=>{n.push(t.call(this,s,i))}),this.waitFor(n)}static mapArray(e,t){return new r((n,s)=>{let i=e.length,a=new Array(i),u=0;for(let c=0;c<i;c++){let h=c;t(e[h]).next(f=>{a[h]=f,++u,u===i&&n(a)},f=>s(f))}})}static doWhile(e,t){return new r((n,s)=>{let i=()=>{e()===!0?t().next(()=>{i()},s):n()};i()})}};function sS(r){let e=r.match(/Android ([\d.]+)/i),t=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(t)}function Fn(r){return r.name==="IndexedDbTransactionError"}var bn=class{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=n=>this.oe(n),this._e=n=>t.writeSequenceNumber(n))}oe(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this._e&&this._e(e),e}};bn.ae=-1;var Ol=-1;function ia(r){return r==null}function Os(r){return r===0&&1/r==-1/0}function iS(r){return typeof r=="number"&&Number.isInteger(r)&&!Os(r)&&r<=Number.MAX_SAFE_INTEGER&&r>=Number.MIN_SAFE_INTEGER}var Rg="";function oS(r){let e="";for(let t=0;t<r.length;t++)e.length>0&&(e=Gm(e)),e=aS(r.get(t),e);return Gm(e)}function aS(r,e){let t=e,n=r.length;for(let s=0;s<n;s++){let i=r.charAt(s);switch(i){case"\0":t+="";break;case Rg:t+="";break;default:t+=i}}return t}function Gm(r){return r+Rg+""}var uS="remoteDocuments",Pg="owner";var Cg="mutationQueues";var kg="mutations";var Dg="documentMutations",cS="remoteDocumentsV14";var Og="remoteDocumentGlobal";var Ng="targets";var Vg="targetDocuments";var Lg="targetGlobal",Fg="collectionParents";var Mg="clientMetadata";var jg="bundles";var Ug="namedQueries";var lS="indexConfiguration";var hS="indexState";var dS="indexEntries";var Bg="documentOverlays";var fS="globals";var pS=[Cg,kg,Dg,uS,Ng,Pg,Lg,Vg,Mg,Og,Fg,jg,Ug],KM=[...pS,Bg],mS=[Cg,kg,Dg,cS,Ng,Pg,Lg,Vg,Mg,Og,Fg,jg,Ug,Bg],gS=mS,yS=[...gS,lS,hS,dS];var HM=[...yS,fS];function Km(r){let e=0;for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e++;return e}function nr(r,e){for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e(t,r[t])}function $g(r){for(let e in r)if(Object.prototype.hasOwnProperty.call(r,e))return!1;return!0}var ce=class r{constructor(e,t){this.comparator=e,this.root=t||rt.EMPTY}insert(e,t){return new r(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,rt.BLACK,null,null))}remove(e){return new r(this.comparator,this.root.remove(e,this.comparator).copy(null,null,rt.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){let n=this.comparator(e,t.key);if(n===0)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){let s=this.comparator(e,n.key);if(s===0)return t+n.left.size;s<0?n=n.left:(t+=n.left.size+1,n=n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal((t,n)=>(e(t,n),!1))}toString(){let e=[];return this.inorderTraversal((t,n)=>(e.push(`${t}:${n}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new gn(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new gn(this.root,e,this.comparator,!1)}getReverseIterator(){return new gn(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new gn(this.root,e,this.comparator,!0)}},gn=class{constructor(e,t,n,s){this.isReverse=s,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&s&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(i===0){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop(),t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(this.nodeStack.length===0)return null;let e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}},rt=class r{constructor(e,t,n,s,i){this.key=e,this.value=t,this.color=n!=null?n:r.RED,this.left=s!=null?s:r.EMPTY,this.right=i!=null?i:r.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,s,i){return new r(e!=null?e:this.key,t!=null?t:this.value,n!=null?n:this.color,s!=null?s:this.left,i!=null?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let s=this,i=n(e,s.key);return s=i<0?s.copy(null,null,null,s.left.insert(e,t,n),null):i===0?s.copy(null,t,null,null,null):s.copy(null,null,null,null,s.right.insert(e,t,n)),s.fixUp()}removeMin(){if(this.left.isEmpty())return r.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,s=this;if(t(e,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(e,t),null);else{if(s.left.isRed()&&(s=s.rotateRight()),s.right.isEmpty()||s.right.isRed()||s.right.left.isRed()||(s=s.moveRedRight()),t(e,s.key)===0){if(s.right.isEmpty())return r.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(e,t))}return s.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){let e=this.copy(null,null,r.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,r.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){let e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed()||this.right.isRed())throw M();let e=this.left.check();if(e!==this.right.check())throw M();return e+(this.isRed()?0:1)}};rt.EMPTY=null,rt.RED=!0,rt.BLACK=!1;rt.EMPTY=new class{constructor(){this.size=0}get key(){throw M()}get value(){throw M()}get color(){throw M()}get left(){throw M()}get right(){throw M()}copy(e,t,n,s,i){return this}insert(e,t,n){return new rt(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};var _e=class r{constructor(e){this.comparator=e,this.data=new ce(this.comparator)}has(e){return this.data.get(e)!==null}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal((t,n)=>(e(t),!1))}forEachInRange(e,t){let n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){let s=n.getNext();if(this.comparator(s.key,e[1])>=0)return;t(s.key)}}forEachWhile(e,t){let n;for(n=t!==void 0?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){let t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new Ao(this.data.getIterator())}getIteratorFrom(e){return new Ao(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(n=>{t=t.add(n)}),t}isEqual(e){if(!(e instanceof r)||this.size!==e.size)return!1;let t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){let s=t.getNext().key,i=n.getNext().key;if(this.comparator(s,i)!==0)return!1}return!0}toArray(){let e=[];return this.forEach(t=>{e.push(t)}),e}toString(){let e=[];return this.forEach(t=>e.push(t)),"SortedSet("+e.toString()+")"}copy(e){let t=new r(this.comparator);return t.data=e,t}},Ao=class{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}};var qe=class r{constructor(e){this.fields=e,e.sort(Ue.comparator)}static empty(){return new r([])}unionWith(e){let t=new _e(Ue.comparator);for(let n of this.fields)t=t.add(n);for(let n of e)t=t.add(n);return new r(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return wn(this.fields,e.fields,(t,n)=>t.isEqual(n))}};var xo=class extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}};var Re=class r{constructor(e){this.binaryString=e}static fromBase64String(e){let t=function(s){try{return atob(s)}catch(i){throw typeof DOMException!="undefined"&&i instanceof DOMException?new xo("Invalid base64 string: "+i):i}}(e);return new r(t)}static fromUint8Array(e){let t=function(s){let i="";for(let a=0;a<s.length;++a)i+=String.fromCharCode(s[a]);return i}(e);return new r(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return function(t){return btoa(t)}(this.binaryString)}toUint8Array(){return function(t){let n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return K(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}};Re.EMPTY_BYTE_STRING=new Re("");var _S=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function xt(r){if(ee(!!r),typeof r=="string"){let e=0,t=_S.exec(r);if(ee(!!t),t[1]){let s=t[1];s=(s+"000000000").substr(0,9),e=Number(s)}let n=new Date(r);return{seconds:Math.floor(n.getTime()/1e3),nanos:e}}return{seconds:oe(r.seconds),nanos:oe(r.nanos)}}function oe(r){return typeof r=="number"?r:typeof r=="string"?Number(r):0}function St(r){return typeof r=="string"?Re.fromBase64String(r):Re.fromUint8Array(r)}var qg="server_timestamp",zg="__type__",Gg="__previous_value__",Kg="__local_write_time__";function Nl(r){var e,t;return((t=(((e=r==null?void 0:r.mapValue)===null||e===void 0?void 0:e.fields)||{})[zg])===null||t===void 0?void 0:t.stringValue)===qg}function oa(r){let e=r.mapValue.fields[Gg];return Nl(e)?oa(e):e}function Ns(r){let e=xt(r.mapValue.fields[Kg].timestampValue);return new we(e.seconds,e.nanos)}var ic=class{constructor(e,t,n,s,i,a,u,c,h){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=s,this.ssl=i,this.forceLongPolling=a,this.autoDetectLongPolling=u,this.longPollingOptions=c,this.useFetchStreams=h}},So="(default)",Ro=class r{constructor(e,t){this.projectId=e,this.database=t||So}static empty(){return new r("","")}get isDefaultDatabase(){return this.database===So}isEqual(e){return e instanceof r&&e.projectId===this.projectId&&e.database===this.database}};var Vl="__type__",Hg="__max__",mo={mapValue:{fields:{__type__:{stringValue:Hg}}}},Ll="__vector__",Tn="value";function Zt(r){return"nullValue"in r?0:"booleanValue"in r?1:"integerValue"in r||"doubleValue"in r?2:"timestampValue"in r?3:"stringValue"in r?5:"bytesValue"in r?6:"referenceValue"in r?7:"geoPointValue"in r?8:"arrayValue"in r?9:"mapValue"in r?Nl(r)?4:Qg(r)?9007199254740991:Wg(r)?10:11:M()}function ot(r,e){if(r===e)return!0;let t=Zt(r);if(t!==Zt(e))return!1;switch(t){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===e.booleanValue;case 4:return Ns(r).isEqual(Ns(e));case 3:return function(s,i){if(typeof s.timestampValue=="string"&&typeof i.timestampValue=="string"&&s.timestampValue.length===i.timestampValue.length)return s.timestampValue===i.timestampValue;let a=xt(s.timestampValue),u=xt(i.timestampValue);return a.seconds===u.seconds&&a.nanos===u.nanos}(r,e);case 5:return r.stringValue===e.stringValue;case 6:return function(s,i){return St(s.bytesValue).isEqual(St(i.bytesValue))}(r,e);case 7:return r.referenceValue===e.referenceValue;case 8:return function(s,i){return oe(s.geoPointValue.latitude)===oe(i.geoPointValue.latitude)&&oe(s.geoPointValue.longitude)===oe(i.geoPointValue.longitude)}(r,e);case 2:return function(s,i){if("integerValue"in s&&"integerValue"in i)return oe(s.integerValue)===oe(i.integerValue);if("doubleValue"in s&&"doubleValue"in i){let a=oe(s.doubleValue),u=oe(i.doubleValue);return a===u?Os(a)===Os(u):isNaN(a)&&isNaN(u)}return!1}(r,e);case 9:return wn(r.arrayValue.values||[],e.arrayValue.values||[],ot);case 10:case 11:return function(s,i){let a=s.mapValue.fields||{},u=i.mapValue.fields||{};if(Km(a)!==Km(u))return!1;for(let c in a)if(a.hasOwnProperty(c)&&(u[c]===void 0||!ot(a[c],u[c])))return!1;return!0}(r,e);default:return M()}}function Vs(r,e){return(r.values||[]).find(t=>ot(t,e))!==void 0}function En(r,e){if(r===e)return 0;let t=Zt(r),n=Zt(e);if(t!==n)return K(t,n);switch(t){case 0:case 9007199254740991:return 0;case 1:return K(r.booleanValue,e.booleanValue);case 2:return function(i,a){let u=oe(i.integerValue||i.doubleValue),c=oe(a.integerValue||a.doubleValue);return u<c?-1:u>c?1:u===c?0:isNaN(u)?isNaN(c)?0:-1:1}(r,e);case 3:return Hm(r.timestampValue,e.timestampValue);case 4:return Hm(Ns(r),Ns(e));case 5:return rc(r.stringValue,e.stringValue);case 6:return function(i,a){let u=St(i),c=St(a);return u.compareTo(c)}(r.bytesValue,e.bytesValue);case 7:return function(i,a){let u=i.split("/"),c=a.split("/");for(let h=0;h<u.length&&h<c.length;h++){let f=K(u[h],c[h]);if(f!==0)return f}return K(u.length,c.length)}(r.referenceValue,e.referenceValue);case 8:return function(i,a){let u=K(oe(i.latitude),oe(a.latitude));return u!==0?u:K(oe(i.longitude),oe(a.longitude))}(r.geoPointValue,e.geoPointValue);case 9:return Wm(r.arrayValue,e.arrayValue);case 10:return function(i,a){var u,c,h,f;let m=i.fields||{},g=a.fields||{},b=(u=m[Tn])===null||u===void 0?void 0:u.arrayValue,P=(c=g[Tn])===null||c===void 0?void 0:c.arrayValue,C=K(((h=b==null?void 0:b.values)===null||h===void 0?void 0:h.length)||0,((f=P==null?void 0:P.values)===null||f===void 0?void 0:f.length)||0);return C!==0?C:Wm(b,P)}(r.mapValue,e.mapValue);case 11:return function(i,a){if(i===mo.mapValue&&a===mo.mapValue)return 0;if(i===mo.mapValue)return 1;if(a===mo.mapValue)return-1;let u=i.fields||{},c=Object.keys(u),h=a.fields||{},f=Object.keys(h);c.sort(),f.sort();for(let m=0;m<c.length&&m<f.length;++m){let g=rc(c[m],f[m]);if(g!==0)return g;let b=En(u[c[m]],h[f[m]]);if(b!==0)return b}return K(c.length,f.length)}(r.mapValue,e.mapValue);default:throw M()}}function Hm(r,e){if(typeof r=="string"&&typeof e=="string"&&r.length===e.length)return K(r,e);let t=xt(r),n=xt(e),s=K(t.seconds,n.seconds);return s!==0?s:K(t.nanos,n.nanos)}function Wm(r,e){let t=r.values||[],n=e.values||[];for(let s=0;s<t.length&&s<n.length;++s){let i=En(t[s],n[s]);if(i)return i}return K(t.length,n.length)}function In(r){return oc(r)}function oc(r){return"nullValue"in r?"null":"booleanValue"in r?""+r.booleanValue:"integerValue"in r?""+r.integerValue:"doubleValue"in r?""+r.doubleValue:"timestampValue"in r?function(t){let n=xt(t);return`time(${n.seconds},${n.nanos})`}(r.timestampValue):"stringValue"in r?r.stringValue:"bytesValue"in r?function(t){return St(t).toBase64()}(r.bytesValue):"referenceValue"in r?function(t){return j.fromName(t).toString()}(r.referenceValue):"geoPointValue"in r?function(t){return`geo(${t.latitude},${t.longitude})`}(r.geoPointValue):"arrayValue"in r?function(t){let n="[",s=!0;for(let i of t.values||[])s?s=!1:n+=",",n+=oc(i);return n+"]"}(r.arrayValue):"mapValue"in r?function(t){let n=Object.keys(t.fields||{}).sort(),s="{",i=!0;for(let a of n)i?i=!1:s+=",",s+=`${a}:${oc(t.fields[a])}`;return s+"}"}(r.mapValue):M()}function _o(r){switch(Zt(r)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let e=oa(r);return e?16+_o(e):16;case 5:return 2*r.stringValue.length;case 6:return St(r.bytesValue).approximateByteSize();case 7:return r.referenceValue.length;case 9:return function(n){return(n.values||[]).reduce((s,i)=>s+_o(i),0)}(r.arrayValue);case 10:case 11:return function(n){let s=0;return nr(n.fields,(i,a)=>{s+=i.length+_o(a)}),s}(r.mapValue);default:throw M()}}function ac(r){return!!r&&"integerValue"in r}function Fl(r){return!!r&&"arrayValue"in r}function Qm(r){return!!r&&"nullValue"in r}function Jm(r){return!!r&&"doubleValue"in r&&isNaN(Number(r.doubleValue))}function vo(r){return!!r&&"mapValue"in r}function Wg(r){var e,t;return((t=(((e=r==null?void 0:r.mapValue)===null||e===void 0?void 0:e.fields)||{})[Vl])===null||t===void 0?void 0:t.stringValue)===Ll}function Rs(r){if(r.geoPointValue)return{geoPointValue:Object.assign({},r.geoPointValue)};if(r.timestampValue&&typeof r.timestampValue=="object")return{timestampValue:Object.assign({},r.timestampValue)};if(r.mapValue){let e={mapValue:{fields:{}}};return nr(r.mapValue.fields,(t,n)=>e.mapValue.fields[t]=Rs(n)),e}if(r.arrayValue){let e={arrayValue:{values:[]}};for(let t=0;t<(r.arrayValue.values||[]).length;++t)e.arrayValue.values[t]=Rs(r.arrayValue.values[t]);return e}return Object.assign({},r)}function Qg(r){return(((r.mapValue||{}).fields||{}).__type__||{}).stringValue===Hg}var QM={mapValue:{fields:{[Vl]:{stringValue:Ll},[Tn]:{arrayValue:{}}}}};var je=class r{constructor(e){this.value=e}static empty(){return new r({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(t=(t.mapValue.fields||{})[e.get(n)],!vo(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Rs(t)}setAll(e){let t=Ue.emptyPath(),n={},s=[];e.forEach((a,u)=>{if(!t.isImmediateParentOf(u)){let c=this.getFieldsMap(t);this.applyChanges(c,n,s),n={},s=[],t=u.popLast()}a?n[u.lastSegment()]=Rs(a):s.push(u.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,n,s)}delete(e){let t=this.field(e.popLast());vo(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return ot(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let s=t.mapValue.fields[e.get(n)];vo(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=s),t=s}return t.mapValue.fields}applyChanges(e,t,n){nr(t,(s,i)=>e[s]=i);for(let s of n)delete e[s]}clone(){return new r(Rs(this.value))}};function Jg(r){let e=[];return nr(r.fields,(t,n)=>{let s=new Ue([t]);if(vo(n)){let i=Jg(n.mapValue).fields;if(i.length===0)e.push(s);else for(let a of i)e.push(s.child(a))}else e.push(s)}),new qe(e)}var Je=class r{constructor(e,t,n,s,i,a,u){this.key=e,this.documentType=t,this.version=n,this.readTime=s,this.createTime=i,this.data=a,this.documentState=u}static newInvalidDocument(e){return new r(e,0,q.min(),q.min(),q.min(),je.empty(),0)}static newFoundDocument(e,t,n,s){return new r(e,1,t,q.min(),n,s,0)}static newNoDocument(e,t){return new r(e,2,t,q.min(),q.min(),je.empty(),0)}static newUnknownDocument(e,t){return new r(e,3,t,q.min(),q.min(),je.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(q.min())||this.documentType!==2&&this.documentType!==0||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=je.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=je.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=q.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return this.documentState===1}get hasCommittedMutations(){return this.documentState===2}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return this.documentType!==0}isFoundDocument(){return this.documentType===1}isNoDocument(){return this.documentType===2}isUnknownDocument(){return this.documentType===3}isEqual(e){return e instanceof r&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new r(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}};var An=class{constructor(e,t){this.position=e,this.inclusive=t}};function Ym(r,e,t){let n=0;for(let s=0;s<r.position.length;s++){let i=e[s],a=r.position[s];if(i.field.isKeyField()?n=j.comparator(j.fromName(a.referenceValue),t.key):n=En(a,t.data.field(i.field)),i.dir==="desc"&&(n*=-1),n!==0)break}return n}function Xm(r,e){if(r===null)return e===null;if(e===null||r.inclusive!==e.inclusive||r.position.length!==e.position.length)return!1;for(let t=0;t<r.position.length;t++)if(!ot(r.position[t],e.position[t]))return!1;return!0}var xn=class{constructor(e,t="asc"){this.field=e,this.dir=t}};function vS(r,e){return r.dir===e.dir&&r.field.isEqual(e.field)}var Po=class{},me=class r extends Po{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?t==="in"||t==="not-in"?this.createKeyFieldInFilter(e,t,n):new cc(e,t,n):t==="array-contains"?new dc(e,n):t==="in"?new fc(e,n):t==="not-in"?new pc(e,n):t==="array-contains-any"?new mc(e,n):new r(e,t,n)}static createKeyFieldInFilter(e,t,n){return t==="in"?new lc(e,n):new hc(e,n)}matches(e){let t=e.data.field(this.field);return this.op==="!="?t!==null&&this.matchesComparison(En(t,this.value)):t!==null&&Zt(this.value)===Zt(t)&&this.matchesComparison(En(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return e===0;case"!=":return e!==0;case">":return e>0;case">=":return e>=0;default:return M()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}},at=class r extends Po{constructor(e,t){super(),this.filters=e,this.op=t,this.ce=null}static create(e,t){return new r(e,t)}matches(e){return Yg(this)?this.filters.find(t=>!t.matches(e))===void 0:this.filters.find(t=>t.matches(e))!==void 0}getFlattenedFilters(){return this.ce!==null||(this.ce=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ce}getFilters(){return Object.assign([],this.filters)}};function Yg(r){return r.op==="and"}function Xg(r){return wS(r)&&Yg(r)}function wS(r){for(let e of r.filters)if(e instanceof at)return!1;return!0}function uc(r){if(r instanceof me)return r.field.canonicalString()+r.op.toString()+In(r.value);if(Xg(r))return r.filters.map(e=>uc(e)).join(",");{let e=r.filters.map(t=>uc(t)).join(",");return`${r.op}(${e})`}}function Zg(r,e){return r instanceof me?function(n,s){return s instanceof me&&n.op===s.op&&n.field.isEqual(s.field)&&ot(n.value,s.value)}(r,e):r instanceof at?function(n,s){return s instanceof at&&n.op===s.op&&n.filters.length===s.filters.length?n.filters.reduce((i,a,u)=>i&&Zg(a,s.filters[u]),!0):!1}(r,e):void M()}function ey(r){return r instanceof me?function(t){return`${t.field.canonicalString()} ${t.op} ${In(t.value)}`}(r):r instanceof at?function(t){return t.op.toString()+" {"+t.getFilters().map(ey).join(" ,")+"}"}(r):"Filter"}var cc=class extends me{constructor(e,t,n){super(e,t,n),this.key=j.fromName(n.referenceValue)}matches(e){let t=j.comparator(e.key,this.key);return this.matchesComparison(t)}},lc=class extends me{constructor(e,t){super(e,"in",t),this.keys=ty("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}},hc=class extends me{constructor(e,t){super(e,"not-in",t),this.keys=ty("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}};function ty(r,e){var t;return(((t=e.arrayValue)===null||t===void 0?void 0:t.values)||[]).map(n=>j.fromName(n.referenceValue))}var dc=class extends me{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return Fl(t)&&Vs(t.arrayValue,this.value)}},fc=class extends me{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return t!==null&&Vs(this.value.arrayValue,t)}},pc=class extends me{constructor(e,t){super(e,"not-in",t)}matches(e){if(Vs(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return t!==null&&!Vs(this.value.arrayValue,t)}},mc=class extends me{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!Fl(t)||!t.arrayValue.values)&&t.arrayValue.values.some(n=>Vs(this.value.arrayValue,n))}};var gc=class{constructor(e,t=null,n=[],s=[],i=null,a=null,u=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=s,this.limit=i,this.startAt=a,this.endAt=u,this.le=null}};function Zm(r,e=null,t=[],n=[],s=null,i=null,a=null){return new gc(r,e,t,n,s,i,a)}function Ml(r){let e=$(r);if(e.le===null){let t=e.path.canonicalString();e.collectionGroup!==null&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map(n=>uc(n)).join(","),t+="|ob:",t+=e.orderBy.map(n=>function(i){return i.field.canonicalString()+i.dir}(n)).join(","),ia(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(n=>In(n)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(n=>In(n)).join(",")),e.le=t}return e.le}function jl(r,e){if(r.limit!==e.limit||r.orderBy.length!==e.orderBy.length)return!1;for(let t=0;t<r.orderBy.length;t++)if(!vS(r.orderBy[t],e.orderBy[t]))return!1;if(r.filters.length!==e.filters.length)return!1;for(let t=0;t<r.filters.length;t++)if(!Zg(r.filters[t],e.filters[t]))return!1;return r.collectionGroup===e.collectionGroup&&!!r.path.isEqual(e.path)&&!!Xm(r.startAt,e.startAt)&&Xm(r.endAt,e.endAt)}function yc(r){return j.isDocumentKey(r.path)&&r.collectionGroup===null&&r.filters.length===0}var Sn=class{constructor(e,t=null,n=[],s=[],i=null,a="F",u=null,c=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=s,this.limit=i,this.limitType=a,this.startAt=u,this.endAt=c,this.he=null,this.Pe=null,this.Te=null,this.startAt,this.endAt}};function bS(r,e,t,n,s,i,a,u){return new Sn(r,e,t,n,s,i,a,u)}function aa(r){return new Sn(r)}function eg(r){return r.filters.length===0&&r.limit===null&&r.startAt==null&&r.endAt==null&&(r.explicitOrderBy.length===0||r.explicitOrderBy.length===1&&r.explicitOrderBy[0].field.isKeyField())}function TS(r){return r.collectionGroup!==null}function Ps(r){let e=$(r);if(e.he===null){e.he=[];let t=new Set;for(let i of e.explicitOrderBy)e.he.push(i),t.add(i.field.canonicalString());let n=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(function(a){let u=new _e(Ue.comparator);return a.filters.forEach(c=>{c.getFlattenedFilters().forEach(h=>{h.isInequality()&&(u=u.add(h.field))})}),u})(e).forEach(i=>{t.has(i.canonicalString())||i.isKeyField()||e.he.push(new xn(i,n))}),t.has(Ue.keyField().canonicalString())||e.he.push(new xn(Ue.keyField(),n))}return e.he}function nt(r){let e=$(r);return e.Pe||(e.Pe=ES(e,Ps(r))),e.Pe}function ES(r,e){if(r.limitType==="F")return Zm(r.path,r.collectionGroup,e,r.filters,r.limit,r.startAt,r.endAt);{e=e.map(s=>{let i=s.dir==="desc"?"asc":"desc";return new xn(s.field,i)});let t=r.endAt?new An(r.endAt.position,r.endAt.inclusive):null,n=r.startAt?new An(r.startAt.position,r.startAt.inclusive):null;return Zm(r.path,r.collectionGroup,e,r.filters,r.limit,t,n)}}function _c(r,e,t){return new Sn(r.path,r.collectionGroup,r.explicitOrderBy.slice(),r.filters.slice(),e,t,r.startAt,r.endAt)}function ua(r,e){return jl(nt(r),nt(e))&&r.limitType===e.limitType}function ry(r){return`${Ml(nt(r))}|lt:${r.limitType}`}function fn(r){return`Query(target=${function(t){let n=t.path.canonicalString();return t.collectionGroup!==null&&(n+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(n+=`, filters: [${t.filters.map(s=>ey(s)).join(", ")}]`),ia(t.limit)||(n+=", limit: "+t.limit),t.orderBy.length>0&&(n+=`, orderBy: [${t.orderBy.map(s=>function(a){return`${a.field.canonicalString()} (${a.dir})`}(s)).join(", ")}]`),t.startAt&&(n+=", startAt: ",n+=t.startAt.inclusive?"b:":"a:",n+=t.startAt.position.map(s=>In(s)).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(s=>In(s)).join(",")),`Target(${n})`}(nt(r))}; limitType=${r.limitType})`}function ca(r,e){return e.isFoundDocument()&&function(n,s){let i=s.key.path;return n.collectionGroup!==null?s.key.hasCollectionId(n.collectionGroup)&&n.path.isPrefixOf(i):j.isDocumentKey(n.path)?n.path.isEqual(i):n.path.isImmediateParentOf(i)}(r,e)&&function(n,s){for(let i of Ps(n))if(!i.field.isKeyField()&&s.data.field(i.field)===null)return!1;return!0}(r,e)&&function(n,s){for(let i of n.filters)if(!i.matches(s))return!1;return!0}(r,e)&&function(n,s){return!(n.startAt&&!function(a,u,c){let h=Ym(a,u,c);return a.inclusive?h<=0:h<0}(n.startAt,Ps(n),s)||n.endAt&&!function(a,u,c){let h=Ym(a,u,c);return a.inclusive?h>=0:h>0}(n.endAt,Ps(n),s))}(r,e)}function IS(r){return r.collectionGroup||(r.path.length%2==1?r.path.lastSegment():r.path.get(r.path.length-2))}function ny(r){return(e,t)=>{let n=!1;for(let s of Ps(r)){let i=AS(s,e,t);if(i!==0)return i;n=n||s.field.isKeyField()}return 0}}function AS(r,e,t){let n=r.field.isKeyField()?j.comparator(e.key,t.key):function(i,a,u){let c=a.data.field(i),h=u.data.field(i);return c!==null&&h!==null?En(c,h):M()}(r.field,e,t);switch(r.dir){case"asc":return n;case"desc":return-1*n;default:return M()}}var Rt=class{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){let t=this.mapKeyFn(e),n=this.inner[t];if(n!==void 0){for(let[s,i]of n)if(this.equalsFn(s,e))return i}}has(e){return this.get(e)!==void 0}set(e,t){let n=this.mapKeyFn(e),s=this.inner[n];if(s===void 0)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<s.length;i++)if(this.equalsFn(s[i][0],e))return void(s[i]=[e,t]);s.push([e,t]),this.innerSize++}delete(e){let t=this.mapKeyFn(e),n=this.inner[t];if(n===void 0)return!1;for(let s=0;s<n.length;s++)if(this.equalsFn(n[s][0],e))return n.length===1?delete this.inner[t]:n.splice(s,1),this.innerSize--,!0;return!1}forEach(e){nr(this.inner,(t,n)=>{for(let[s,i]of n)e(s,i)})}isEmpty(){return $g(this.inner)}size(){return this.innerSize}};var xS=new ce(j.comparator);function Pt(){return xS}var sy=new ce(j.comparator);function Ss(...r){let e=sy;for(let t of r)e=e.insert(t.key,t);return e}function iy(r){let e=sy;return r.forEach((t,n)=>e=e.insert(t,n.overlayedDocument)),e}function pr(){return Cs()}function oy(){return Cs()}function Cs(){return new Rt(r=>r.toString(),(r,e)=>r.isEqual(e))}var SS=new ce(j.comparator),RS=new _e(j.comparator);function W(...r){let e=RS;for(let t of r)e=e.add(t);return e}var PS=new _e(K);function CS(){return PS}function Ul(r,e){if(r.useProto3Json){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Os(e)?"-0":e}}function ay(r){return{integerValue:""+r}}function kS(r,e){return iS(e)?ay(e):Ul(r,e)}var Rn=class{constructor(){this._=void 0}};function DS(r,e,t){return r instanceof Pn?function(s,i){let a={fields:{[zg]:{stringValue:qg},[Kg]:{timestampValue:{seconds:s.seconds,nanos:s.nanoseconds}}}};return i&&Nl(i)&&(i=oa(i)),i&&(a.fields[Gg]=i),{mapValue:a}}(t,e):r instanceof vr?cy(r,e):r instanceof wr?ly(r,e):function(s,i){let a=uy(s,i),u=tg(a)+tg(s.Ie);return ac(a)&&ac(s.Ie)?ay(u):Ul(s.serializer,u)}(r,e)}function OS(r,e,t){return r instanceof vr?cy(r,e):r instanceof wr?ly(r,e):t}function uy(r,e){return r instanceof Cn?function(n){return ac(n)||function(i){return!!i&&"doubleValue"in i}(n)}(e)?e:{integerValue:0}:null}var Pn=class extends Rn{},vr=class extends Rn{constructor(e){super(),this.elements=e}};function cy(r,e){let t=hy(e);for(let n of r.elements)t.some(s=>ot(s,n))||t.push(n);return{arrayValue:{values:t}}}var wr=class extends Rn{constructor(e){super(),this.elements=e}};function ly(r,e){let t=hy(e);for(let n of r.elements)t=t.filter(s=>!ot(s,n));return{arrayValue:{values:t}}}var Cn=class extends Rn{constructor(e,t){super(),this.serializer=e,this.Ie=t}};function tg(r){return oe(r.integerValue||r.doubleValue)}function hy(r){return Fl(r)&&r.arrayValue.values?r.arrayValue.values.slice():[]}function NS(r,e){return r.field.isEqual(e.field)&&function(n,s){return n instanceof vr&&s instanceof vr||n instanceof wr&&s instanceof wr?wn(n.elements,s.elements,ot):n instanceof Cn&&s instanceof Cn?ot(n.Ie,s.Ie):n instanceof Pn&&s instanceof Pn}(r.transform,e.transform)}var vc=class{constructor(e,t){this.version=e,this.transformResults=t}},Xt=class r{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new r}static exists(e){return new r(void 0,e)}static updateTime(e){return new r(e)}get isNone(){return this.updateTime===void 0&&this.exists===void 0}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}};function wo(r,e){return r.updateTime!==void 0?e.isFoundDocument()&&e.version.isEqual(r.updateTime):r.exists===void 0||r.exists===e.isFoundDocument()}var kn=class{};function dy(r,e){if(!r.hasLocalMutations||e&&e.fields.length===0)return null;if(e===null)return r.isNoDocument()?new Co(r.key,Xt.none()):new br(r.key,r.data,Xt.none());{let t=r.data,n=je.empty(),s=new _e(Ue.comparator);for(let i of e.fields)if(!s.has(i)){let a=t.field(i);a===null&&i.length>1&&(i=i.popLast(),a=t.field(i)),a===null?n.delete(i):n.set(i,a),s=s.add(i)}return new ut(r.key,n,new qe(s.toArray()),Xt.none())}}function VS(r,e,t){r instanceof br?function(s,i,a){let u=s.value.clone(),c=ng(s.fieldTransforms,i,a.transformResults);u.setAll(c),i.convertToFoundDocument(a.version,u).setHasCommittedMutations()}(r,e,t):r instanceof ut?function(s,i,a){if(!wo(s.precondition,i))return void i.convertToUnknownDocument(a.version);let u=ng(s.fieldTransforms,i,a.transformResults),c=i.data;c.setAll(fy(s)),c.setAll(u),i.convertToFoundDocument(a.version,c).setHasCommittedMutations()}(r,e,t):function(s,i,a){i.convertToNoDocument(a.version).setHasCommittedMutations()}(0,e,t)}function ks(r,e,t,n){return r instanceof br?function(i,a,u,c){if(!wo(i.precondition,a))return u;let h=i.value.clone(),f=sg(i.fieldTransforms,c,a);return h.setAll(f),a.convertToFoundDocument(a.version,h).setHasLocalMutations(),null}(r,e,t,n):r instanceof ut?function(i,a,u,c){if(!wo(i.precondition,a))return u;let h=sg(i.fieldTransforms,c,a),f=a.data;return f.setAll(fy(i)),f.setAll(h),a.convertToFoundDocument(a.version,f).setHasLocalMutations(),u===null?null:u.unionWith(i.fieldMask.fields).unionWith(i.fieldTransforms.map(m=>m.field))}(r,e,t,n):function(i,a,u){return wo(i.precondition,a)?(a.convertToNoDocument(a.version).setHasLocalMutations(),null):u}(r,e,t)}function LS(r,e){let t=null;for(let n of r.fieldTransforms){let s=e.data.field(n.field),i=uy(n.transform,s||null);i!=null&&(t===null&&(t=je.empty()),t.set(n.field,i))}return t||null}function rg(r,e){return r.type===e.type&&!!r.key.isEqual(e.key)&&!!r.precondition.isEqual(e.precondition)&&!!function(n,s){return n===void 0&&s===void 0||!(!n||!s)&&wn(n,s,(i,a)=>NS(i,a))}(r.fieldTransforms,e.fieldTransforms)&&(r.type===0?r.value.isEqual(e.value):r.type!==1||r.data.isEqual(e.data)&&r.fieldMask.isEqual(e.fieldMask))}var br=class extends kn{constructor(e,t,n,s=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}},ut=class extends kn{constructor(e,t,n,s,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=s,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}};function fy(r){let e=new Map;return r.fieldMask.fields.forEach(t=>{if(!t.isEmpty()){let n=r.data.field(t);e.set(t,n)}}),e}function ng(r,e,t){let n=new Map;ee(r.length===t.length);for(let s=0;s<t.length;s++){let i=r[s],a=i.transform,u=e.data.field(i.field);n.set(i.field,OS(a,u,t[s]))}return n}function sg(r,e,t){let n=new Map;for(let s of r){let i=s.transform,a=t.data.field(s.field);n.set(s.field,DS(i,a,e))}return n}var Co=class extends kn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}},wc=class extends kn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}};var bc=class{constructor(e,t,n,s){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=s}applyToRemoteDocument(e,t){let n=t.mutationResults;for(let s=0;s<this.mutations.length;s++){let i=this.mutations[s];i.key.isEqual(e.key)&&VS(i,e,n[s])}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=ks(n,e,t,this.localWriteTime));for(let n of this.mutations)n.key.isEqual(e.key)&&(t=ks(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let n=oy();return this.mutations.forEach(s=>{let i=e.get(s.key),a=i.overlayedDocument,u=this.applyToLocalView(a,i.mutatedFields);u=t.has(s.key)?null:u;let c=dy(a,u);c!==null&&n.set(s.key,c),a.isValidDocument()||a.convertToNoDocument(q.min())}),n}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),W())}isEqual(e){return this.batchId===e.batchId&&wn(this.mutations,e.mutations,(t,n)=>rg(t,n))&&wn(this.baseMutations,e.baseMutations,(t,n)=>rg(t,n))}},Tc=class r{constructor(e,t,n,s){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=s}static from(e,t,n){ee(e.mutations.length===n.length);let s=function(){return SS}(),i=e.mutations;for(let a=0;a<i.length;a++)s=s.insert(i[a].key,n[a].version);return new r(e,t,n,s)}};var Ec=class{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return e!==null&&this.mutation===e.mutation}toString(){return`Overlay{
10
10
  largestBatchId: ${this.largestBatchId},
11
11
  mutation: ${this.mutation.toString()}
12
- }`}};var Ic=class{constructor(e,t){this.count=e,this.unchangedNames=t}};var he,J;function FS(r){switch(r){case D.OK:return M();case D.CANCELLED:case D.UNKNOWN:case D.DEADLINE_EXCEEDED:case D.RESOURCE_EXHAUSTED:case D.INTERNAL:case D.UNAVAILABLE:case D.UNAUTHENTICATED:return!1;case D.INVALID_ARGUMENT:case D.NOT_FOUND:case D.ALREADY_EXISTS:case D.PERMISSION_DENIED:case D.FAILED_PRECONDITION:case D.ABORTED:case D.OUT_OF_RANGE:case D.UNIMPLEMENTED:case D.DATA_LOSS:return!0;default:return M()}}function py(r){if(r===void 0)return At("GRPC error has no .code"),D.UNKNOWN;switch(r){case he.OK:return D.OK;case he.CANCELLED:return D.CANCELLED;case he.UNKNOWN:return D.UNKNOWN;case he.DEADLINE_EXCEEDED:return D.DEADLINE_EXCEEDED;case he.RESOURCE_EXHAUSTED:return D.RESOURCE_EXHAUSTED;case he.INTERNAL:return D.INTERNAL;case he.UNAVAILABLE:return D.UNAVAILABLE;case he.UNAUTHENTICATED:return D.UNAUTHENTICATED;case he.INVALID_ARGUMENT:return D.INVALID_ARGUMENT;case he.NOT_FOUND:return D.NOT_FOUND;case he.ALREADY_EXISTS:return D.ALREADY_EXISTS;case he.PERMISSION_DENIED:return D.PERMISSION_DENIED;case he.FAILED_PRECONDITION:return D.FAILED_PRECONDITION;case he.ABORTED:return D.ABORTED;case he.OUT_OF_RANGE:return D.OUT_OF_RANGE;case he.UNIMPLEMENTED:return D.UNIMPLEMENTED;case he.DATA_LOSS:return D.DATA_LOSS;default:return M()}}(J=he||(he={}))[J.OK=0]="OK",J[J.CANCELLED=1]="CANCELLED",J[J.UNKNOWN=2]="UNKNOWN",J[J.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",J[J.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",J[J.NOT_FOUND=5]="NOT_FOUND",J[J.ALREADY_EXISTS=6]="ALREADY_EXISTS",J[J.PERMISSION_DENIED=7]="PERMISSION_DENIED",J[J.UNAUTHENTICATED=16]="UNAUTHENTICATED",J[J.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",J[J.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",J[J.ABORTED=10]="ABORTED",J[J.OUT_OF_RANGE=11]="OUT_OF_RANGE",J[J.UNIMPLEMENTED=12]="UNIMPLEMENTED",J[J.INTERNAL=13]="INTERNAL",J[J.UNAVAILABLE=14]="UNAVAILABLE",J[J.DATA_LOSS=15]="DATA_LOSS";var ig=null;var MS=new Et([4294967295,4294967295],0);function og(r){let e=Sg().encode(r),t=new Uu;return t.update(e),new Uint8Array(t.digest())}function ag(r){let e=new DataView(r.buffer),t=e.getUint32(0,!0),n=e.getUint32(4,!0),s=e.getUint32(8,!0),i=e.getUint32(12,!0);return[new Et([t,n],0),new Et([s,i],0)]}var Ac=class r{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new mr(`Invalid padding: ${t}`);if(n<0)throw new mr(`Invalid hash count: ${n}`);if(e.length>0&&this.hashCount===0)throw new mr(`Invalid hash count: ${n}`);if(e.length===0&&t!==0)throw new mr(`Invalid padding when bitmap length is 0: ${t}`);this.Ee=8*e.length-t,this.de=Et.fromNumber(this.Ee)}Ae(e,t,n){let s=e.add(t.multiply(Et.fromNumber(n)));return s.compare(MS)===1&&(s=new Et([s.getBits(0),s.getBits(1)],0)),s.modulo(this.de).toNumber()}Re(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(this.Ee===0)return!1;let t=og(e),[n,s]=ag(t);for(let i=0;i<this.hashCount;i++){let a=this.Ae(n,s,i);if(!this.Re(a))return!1}return!0}static create(e,t,n){let s=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),a=new r(i,s,t);return n.forEach(u=>a.insert(u)),a}insert(e){if(this.Ee===0)return;let t=og(e),[n,s]=ag(t);for(let i=0;i<this.hashCount;i++){let a=this.Ae(n,s,i);this.Ve(a)}}Ve(e){let t=Math.floor(e/8),n=e%8;this.bitmap[t]|=1<<n}},mr=class extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}};var Do=class r{constructor(e,t,n,s,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=s,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){let s=new Map;return s.set(e,Ls.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new r(q.min(),s,new ce(K),Pt(),W())}},Ls=class r{constructor(e,t,n,s,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=s,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new r(n,t,W(),W(),W())}};var yn=class{constructor(e,t,n,s){this.me=e,this.removedTargetIds=t,this.key=n,this.fe=s}},Oo=class{constructor(e,t){this.targetId=e,this.ge=t}},No=class{constructor(e,t,n=Re.EMPTY_BYTE_STRING,s=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=s}},Vo=class{constructor(){this.pe=0,this.ye=ug(),this.we=Re.EMPTY_BYTE_STRING,this.Se=!1,this.be=!0}get current(){return this.Se}get resumeToken(){return this.we}get De(){return this.pe!==0}get ve(){return this.be}Ce(e){e.approximateByteSize()>0&&(this.be=!0,this.we=e)}Fe(){let e=W(),t=W(),n=W();return this.ye.forEach((s,i)=>{switch(i){case 0:e=e.add(s);break;case 2:t=t.add(s);break;case 1:n=n.add(s);break;default:M()}}),new Ls(this.we,this.Se,e,t,n)}Me(){this.be=!1,this.ye=ug()}xe(e,t){this.be=!0,this.ye=this.ye.insert(e,t)}Oe(e){this.be=!0,this.ye=this.ye.remove(e)}Ne(){this.pe+=1}Be(){this.pe-=1,ee(this.pe>=0)}Le(){this.be=!0,this.Se=!0}},xc=class{constructor(e){this.ke=e,this.qe=new Map,this.Qe=Pt(),this.$e=yo(),this.Ue=yo(),this.Ke=new ce(K)}We(e){for(let t of e.me)e.fe&&e.fe.isFoundDocument()?this.Ge(t,e.fe):this.ze(t,e.key,e.fe);for(let t of e.removedTargetIds)this.ze(t,e.key,e.fe)}je(e){this.forEachTarget(e,t=>{let n=this.He(t);switch(e.state){case 0:this.Je(t)&&n.Ce(e.resumeToken);break;case 1:n.Be(),n.De||n.Me(),n.Ce(e.resumeToken);break;case 2:n.Be(),n.De||this.removeTarget(t);break;case 3:this.Je(t)&&(n.Le(),n.Ce(e.resumeToken));break;case 4:this.Je(t)&&(this.Ye(t),n.Ce(e.resumeToken));break;default:M()}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.qe.forEach((n,s)=>{this.Je(s)&&t(s)})}Ze(e){let t=e.targetId,n=e.ge.count,s=this.Xe(t);if(s){let i=s.target;if(yc(i))if(n===0){let a=new j(i.path);this.ze(t,a,Je.newNoDocument(a,q.min()))}else ee(n===1);else{let a=this.et(t);if(a!==n){let u=this.tt(e),c=u?this.nt(u,e,a):1;if(c!==0){this.Ye(t);let h=c===2?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ke=this.Ke.insert(t,h)}ig==null||ig.rt(function(f,m,g,b,P){var C,R,N,F,U,G;let Y={localCacheCount:f,existenceFilterCount:m.count,databaseId:g.database,projectId:g.projectId},B=m.unchangedNames;return B&&(Y.bloomFilter={applied:P===0,hashCount:(C=B==null?void 0:B.hashCount)!==null&&C!==void 0?C:0,bitmapLength:(F=(N=(R=B==null?void 0:B.bits)===null||R===void 0?void 0:R.bitmap)===null||N===void 0?void 0:N.length)!==null&&F!==void 0?F:0,padding:(G=(U=B==null?void 0:B.bits)===null||U===void 0?void 0:U.padding)!==null&&G!==void 0?G:0,mightContain:E=>{var y;return(y=b==null?void 0:b.mightContain(E))!==null&&y!==void 0&&y}}),Y}(a,e.ge,this.ke.it(),u,c))}}}}tt(e){let t=e.ge.unchangedNames;if(!t||!t.bits)return null;let{bits:{bitmap:n="",padding:s=0},hashCount:i=0}=t,a,u;try{a=St(n).toUint8Array()}catch(c){if(c instanceof So)return vn("Decoding the base64 bloom filter in existence filter failed ("+c.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw c}try{u=new Ac(a,s,i)}catch(c){return vn(c instanceof mr?"BloomFilter error: ":"Applying bloom filter failed: ",c),null}return u.Ee===0?null:u}nt(e,t,n){return t.ge.count===n-this.st(e,t.targetId)?0:2}st(e,t){let n=this.ke.getRemoteKeysForTarget(t),s=0;return n.forEach(i=>{let a=this.ke.it(),u=`projects/${a.projectId}/databases/${a.database}/documents/${i.path.canonicalString()}`;e.mightContain(u)||(this.ze(t,i,null),s++)}),s}ot(e){let t=new Map;this.qe.forEach((i,a)=>{let u=this.Xe(a);if(u){if(i.current&&yc(u.target)){let c=new j(u.target.path);this._t(c).has(a)||this.ut(a,c)||this.ze(a,c,Je.newNoDocument(c,e))}i.ve&&(t.set(a,i.Fe()),i.Me())}});let n=W();this.Ue.forEach((i,a)=>{let u=!0;a.forEachWhile(c=>{let h=this.Xe(c);return!h||h.purpose==="TargetPurposeLimboResolution"||(u=!1,!1)}),u&&(n=n.add(i))}),this.Qe.forEach((i,a)=>a.setReadTime(e));let s=new Do(e,t,this.Ke,this.Qe,n);return this.Qe=Pt(),this.$e=yo(),this.Ue=yo(),this.Ke=new ce(K),s}Ge(e,t){if(!this.Je(e))return;let n=this.ut(e,t.key)?2:0;this.He(e).xe(t.key,n),this.Qe=this.Qe.insert(t.key,t),this.$e=this.$e.insert(t.key,this._t(t.key).add(e)),this.Ue=this.Ue.insert(t.key,this.ct(t.key).add(e))}ze(e,t,n){if(!this.Je(e))return;let s=this.He(e);this.ut(e,t)?s.xe(t,1):s.Oe(t),this.Ue=this.Ue.insert(t,this.ct(t).delete(e)),this.Ue=this.Ue.insert(t,this.ct(t).add(e)),n&&(this.Qe=this.Qe.insert(t,n))}removeTarget(e){this.qe.delete(e)}et(e){let t=this.He(e).Fe();return this.ke.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Ne(e){this.He(e).Ne()}He(e){let t=this.qe.get(e);return t||(t=new Vo,this.qe.set(e,t)),t}ct(e){let t=this.Ue.get(e);return t||(t=new _e(K),this.Ue=this.Ue.insert(e,t)),t}_t(e){let t=this.$e.get(e);return t||(t=new _e(K),this.$e=this.$e.insert(e,t)),t}Je(e){let t=this.Xe(e)!==null;return t||V("WatchChangeAggregator","Detected inactive target",e),t}Xe(e){let t=this.qe.get(e);return t&&t.De?null:this.ke.lt(e)}Ye(e){this.qe.set(e,new Vo),this.ke.getRemoteKeysForTarget(e).forEach(t=>{this.ze(e,t,null)})}ut(e,t){return this.ke.getRemoteKeysForTarget(e).has(t)}};function yo(){return new ce(j.comparator)}function ug(){return new ce(j.comparator)}var jS={asc:"ASCENDING",desc:"DESCENDING"},US={"<":"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"},BS={and:"AND",or:"OR"},Sc=class{constructor(e,t){this.databaseId=e,this.useProto3Json=t}};function Rc(r,e){return r.useProto3Json||oa(e)?e:{value:e}}function Lo(r,e){return r.useProto3Json?`${new Date(1e3*e.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+e.nanoseconds).slice(-9)}Z`:{seconds:""+e.seconds,nanos:e.nanoseconds}}function my(r,e){return r.useProto3Json?e.toBase64():e.toUint8Array()}function $S(r,e){return Lo(r,e.toTimestamp())}function st(r){return ee(!!r),q.fromTimestamp(function(t){let n=xt(t);return new we(n.seconds,n.nanos)}(r))}function Bl(r,e){return Pc(r,e).canonicalString()}function Pc(r,e){let t=function(s){return new fe(["projects",s.projectId,"databases",s.database])}(r).child("documents");return e===void 0?t:t.child(e)}function gy(r){let e=fe.fromString(r);return ee(by(e)),e}function Cc(r,e){return Bl(r.databaseId,e.path)}function Ku(r,e){let t=gy(e);if(t.get(1)!==r.databaseId.projectId)throw new L(D.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+t.get(1)+" vs "+r.databaseId.projectId);if(t.get(3)!==r.databaseId.database)throw new L(D.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+t.get(3)+" vs "+r.databaseId.database);return new j(_y(t))}function yy(r,e){return Bl(r.databaseId,e)}function qS(r){let e=gy(r);return e.length===4?fe.emptyPath():_y(e)}function kc(r){return new fe(["projects",r.databaseId.projectId,"databases",r.databaseId.database]).canonicalString()}function _y(r){return ee(r.length>4&&r.get(4)==="documents"),r.popFirst(5)}function cg(r,e,t){return{name:Cc(r,e),fields:t.value.mapValue.fields}}function zS(r,e){let t;if("targetChange"in e){e.targetChange;let n=function(h){return h==="NO_CHANGE"?0:h==="ADD"?1:h==="REMOVE"?2:h==="CURRENT"?3:h==="RESET"?4:M()}(e.targetChange.targetChangeType||"NO_CHANGE"),s=e.targetChange.targetIds||[],i=function(h,f){return h.useProto3Json?(ee(f===void 0||typeof f=="string"),Re.fromBase64String(f||"")):(ee(f===void 0||f instanceof Buffer||f instanceof Uint8Array),Re.fromUint8Array(f||new Uint8Array))}(r,e.targetChange.resumeToken),a=e.targetChange.cause,u=a&&function(h){let f=h.code===void 0?D.UNKNOWN:py(h.code);return new L(f,h.message||"")}(a);t=new No(n,s,i,u||null)}else if("documentChange"in e){e.documentChange;let n=e.documentChange;n.document,n.document.name,n.document.updateTime;let s=Ku(r,n.document.name),i=st(n.document.updateTime),a=n.document.createTime?st(n.document.createTime):q.min(),u=new je({mapValue:{fields:n.document.fields}}),c=Je.newFoundDocument(s,i,a,u),h=n.targetIds||[],f=n.removedTargetIds||[];t=new yn(h,f,c.key,c)}else if("documentDelete"in e){e.documentDelete;let n=e.documentDelete;n.document;let s=Ku(r,n.document),i=n.readTime?st(n.readTime):q.min(),a=Je.newNoDocument(s,i),u=n.removedTargetIds||[];t=new yn([],u,a.key,a)}else if("documentRemove"in e){e.documentRemove;let n=e.documentRemove;n.document;let s=Ku(r,n.document),i=n.removedTargetIds||[];t=new yn([],i,s,null)}else{if(!("filter"in e))return M();{e.filter;let n=e.filter;n.targetId;let{count:s=0,unchangedNames:i}=n,a=new Ic(s,i),u=n.targetId;t=new Oo(u,a)}}return t}function GS(r,e){let t;if(e instanceof br)t={update:cg(r,e.key,e.value)};else if(e instanceof ko)t={delete:Cc(r,e.key)};else if(e instanceof ut)t={update:cg(r,e.key,e.data),updateMask:eR(e.fieldMask)};else{if(!(e instanceof wc))return M();t={verify:Cc(r,e.key)}}return e.fieldTransforms.length>0&&(t.updateTransforms=e.fieldTransforms.map(n=>function(i,a){let u=a.transform;if(u instanceof Pn)return{fieldPath:a.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(u instanceof vr)return{fieldPath:a.field.canonicalString(),appendMissingElements:{values:u.elements}};if(u instanceof wr)return{fieldPath:a.field.canonicalString(),removeAllFromArray:{values:u.elements}};if(u instanceof Cn)return{fieldPath:a.field.canonicalString(),increment:u.Ie};throw M()}(0,n))),e.precondition.isNone||(t.currentDocument=function(s,i){return i.updateTime!==void 0?{updateTime:$S(s,i.updateTime)}:i.exists!==void 0?{exists:i.exists}:M()}(r,e.precondition)),t}function KS(r,e){return r&&r.length>0?(ee(e!==void 0),r.map(t=>function(s,i){let a=s.updateTime?st(s.updateTime):st(i);return a.isEqual(q.min())&&(a=st(i)),new vc(a,s.transformResults||[])}(t,e))):[]}function HS(r,e){return{documents:[yy(r,e.path)]}}function WS(r,e){let t={structuredQuery:{}},n=e.path,s;e.collectionGroup!==null?(s=n,t.structuredQuery.from=[{collectionId:e.collectionGroup,allDescendants:!0}]):(s=n.popLast(),t.structuredQuery.from=[{collectionId:n.lastSegment()}]),t.parent=yy(r,s);let i=function(h){if(h.length!==0)return wy(at.create(h,"and"))}(e.filters);i&&(t.structuredQuery.where=i);let a=function(h){if(h.length!==0)return h.map(f=>function(g){return{field:pn(g.field),direction:YS(g.dir)}}(f))}(e.orderBy);a&&(t.structuredQuery.orderBy=a);let u=Rc(r,e.limit);return u!==null&&(t.structuredQuery.limit=u),e.startAt&&(t.structuredQuery.startAt=function(h){return{before:h.inclusive,values:h.position}}(e.startAt)),e.endAt&&(t.structuredQuery.endAt=function(h){return{before:!h.inclusive,values:h.position}}(e.endAt)),{ht:t,parent:s}}function QS(r){let e=qS(r.parent),t=r.structuredQuery,n=t.from?t.from.length:0,s=null;if(n>0){ee(n===1);let f=t.from[0];f.allDescendants?s=f.collectionId:e=e.child(f.collectionId)}let i=[];t.where&&(i=function(m){let g=vy(m);return g instanceof at&&Xg(g)?g.getFilters():[g]}(t.where));let a=[];t.orderBy&&(a=function(m){return m.map(g=>function(P){return new xn(mn(P.field),function(R){switch(R){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(P.direction))}(g))}(t.orderBy));let u=null;t.limit&&(u=function(m){let g;return g=typeof m=="object"?m.value:m,oa(g)?null:g}(t.limit));let c=null;t.startAt&&(c=function(m){let g=!!m.before,b=m.values||[];return new An(b,g)}(t.startAt));let h=null;return t.endAt&&(h=function(m){let g=!m.before,b=m.values||[];return new An(b,g)}(t.endAt)),bS(e,s,a,i,u,"F",c,h)}function JS(r,e){let t=function(s){switch(s){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return M()}}(e.purpose);return t==null?null:{"goog-listen-tags":t}}function vy(r){return r.unaryFilter!==void 0?function(t){switch(t.unaryFilter.op){case"IS_NAN":let n=mn(t.unaryFilter.field);return me.create(n,"==",{doubleValue:NaN});case"IS_NULL":let s=mn(t.unaryFilter.field);return me.create(s,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let i=mn(t.unaryFilter.field);return me.create(i,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let a=mn(t.unaryFilter.field);return me.create(a,"!=",{nullValue:"NULL_VALUE"});default:return M()}}(r):r.fieldFilter!==void 0?function(t){return me.create(mn(t.fieldFilter.field),function(s){switch(s){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 M()}}(t.fieldFilter.op),t.fieldFilter.value)}(r):r.compositeFilter!==void 0?function(t){return at.create(t.compositeFilter.filters.map(n=>vy(n)),function(s){switch(s){case"AND":return"and";case"OR":return"or";default:return M()}}(t.compositeFilter.op))}(r):M()}function YS(r){return jS[r]}function XS(r){return US[r]}function ZS(r){return BS[r]}function pn(r){return{fieldPath:r.canonicalString()}}function mn(r){return Ue.fromServerFormat(r.fieldPath)}function wy(r){return r instanceof me?function(t){if(t.op==="=="){if(Jm(t.value))return{unaryFilter:{field:pn(t.field),op:"IS_NAN"}};if(Qm(t.value))return{unaryFilter:{field:pn(t.field),op:"IS_NULL"}}}else if(t.op==="!="){if(Jm(t.value))return{unaryFilter:{field:pn(t.field),op:"IS_NOT_NAN"}};if(Qm(t.value))return{unaryFilter:{field:pn(t.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:pn(t.field),op:XS(t.op),value:t.value}}}(r):r instanceof at?function(t){let n=t.getFilters().map(s=>wy(s));return n.length===1?n[0]:{compositeFilter:{op:ZS(t.op),filters:n}}}(r):M()}function eR(r){let e=[];return r.fields.forEach(t=>e.push(t.canonicalString())),{fieldPaths:e}}function by(r){return r.length>=4&&r.get(0)==="projects"&&r.get(2)==="databases"}var Fs=class r{constructor(e,t,n,s,i=q.min(),a=q.min(),u=Re.EMPTY_BYTE_STRING,c=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=s,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=a,this.resumeToken=u,this.expectedCount=c}withSequenceNumber(e){return new r(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new r(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new r(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new r(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}};var Dc=class{constructor(e){this.Tt=e}};function tR(r){let e=QS({parent:r.parent,structuredQuery:r.structuredQuery});return r.limitType==="LAST"?_c(e,e.limit,"L"):e}var Fo=class{constructor(){}At(e,t){this.Rt(e,t),t.Vt()}Rt(e,t){if("nullValue"in e)this.ft(t,5);else if("booleanValue"in e)this.ft(t,10),t.gt(e.booleanValue?1:0);else if("integerValue"in e)this.ft(t,15),t.gt(oe(e.integerValue));else if("doubleValue"in e){let n=oe(e.doubleValue);isNaN(n)?this.ft(t,13):(this.ft(t,15),Os(n)?t.gt(0):t.gt(n))}else if("timestampValue"in e){let n=e.timestampValue;this.ft(t,20),typeof n=="string"&&(n=xt(n)),t.yt(`${n.seconds||""}`),t.gt(n.nanos||0)}else if("stringValue"in e)this.wt(e.stringValue,t),this.St(t);else if("bytesValue"in e)this.ft(t,30),t.bt(St(e.bytesValue)),this.St(t);else if("referenceValue"in e)this.Dt(e.referenceValue,t);else if("geoPointValue"in e){let n=e.geoPointValue;this.ft(t,45),t.gt(n.latitude||0),t.gt(n.longitude||0)}else"mapValue"in e?Qg(e)?this.ft(t,Number.MAX_SAFE_INTEGER):Wg(e)?this.vt(e.mapValue,t):(this.Ct(e.mapValue,t),this.St(t)):"arrayValue"in e?(this.Ft(e.arrayValue,t),this.St(t)):M()}wt(e,t){this.ft(t,25),this.Mt(e,t)}Mt(e,t){t.yt(e)}Ct(e,t){let n=e.fields||{};this.ft(t,55);for(let s of Object.keys(n))this.wt(s,t),this.Rt(n[s],t)}vt(e,t){var n,s;let i=e.fields||{};this.ft(t,53);let a=Tn,u=((s=(n=i[a].arrayValue)===null||n===void 0?void 0:n.values)===null||s===void 0?void 0:s.length)||0;this.ft(t,15),t.gt(oe(u)),this.wt(a,t),this.Rt(i[a],t)}Ft(e,t){let n=e.values||[];this.ft(t,50);for(let s of n)this.Rt(s,t)}Dt(e,t){this.ft(t,37),j.fromName(e).path.forEach(n=>{this.ft(t,60),this.Mt(n,t)})}ft(e,t){e.gt(t)}St(e){e.gt(2)}};Fo.xt=new Fo;var Oc=class{constructor(){this.Tn=new Nc}addToCollectionParentIndex(e,t){return this.Tn.add(t),k.resolve()}getCollectionParents(e,t){return k.resolve(this.Tn.getEntries(t))}addFieldIndex(e,t){return k.resolve()}deleteFieldIndex(e,t){return k.resolve()}deleteAllFieldIndexes(e){return k.resolve()}createTargetIndexes(e,t){return k.resolve()}getDocumentsMatchingTarget(e,t){return k.resolve(null)}getIndexType(e,t){return k.resolve(0)}getFieldIndexes(e,t){return k.resolve([])}getNextCollectionGroupToUpdate(e){return k.resolve(null)}getMinOffset(e,t){return k.resolve(_r.min())}getMinOffsetFromCollectionGroup(e,t){return k.resolve(_r.min())}updateCollectionGroup(e,t,n){return k.resolve()}updateIndexEntries(e,t){return k.resolve()}},Nc=class{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),s=this.index[t]||new _e(fe.comparator),i=!s.has(n);return this.index[t]=s.add(n),i}has(e){let t=e.lastSegment(),n=e.popLast(),s=this.index[t];return s&&s.has(n)}getEntries(e){return(this.index[e]||new _e(fe.comparator)).toArray()}};var JM=new Uint8Array(0);var lg={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},Ty=41943040,$e=class r{static withCacheSize(e){return new r(e,r.DEFAULT_COLLECTION_PERCENTILE,r.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}};$e.DEFAULT_COLLECTION_PERCENTILE=10,$e.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,$e.DEFAULT=new $e(Ty,$e.DEFAULT_COLLECTION_PERCENTILE,$e.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),$e.DISABLED=new $e(-1,0,0);var Ms=class r{constructor(e){this.$n=e}next(){return this.$n+=2,this.$n}static Un(){return new r(0)}static Kn(){return new r(-1)}};var hg="LruGarbageCollector",rR=1048576;function dg([r,e],[t,n]){let s=K(r,t);return s===0?K(e,n):s}var Vc=class{constructor(e){this.Hn=e,this.buffer=new _e(dg),this.Jn=0}Yn(){return++this.Jn}Zn(e){let t=[e,this.Yn()];if(this.buffer.size<this.Hn)this.buffer=this.buffer.add(t);else{let n=this.buffer.last();dg(t,n)<0&&(this.buffer=this.buffer.delete(n).add(t))}}get maxValue(){return this.buffer.last()[0]}},Lc=class{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Xn=null}start(){this.garbageCollector.params.cacheSizeCollectionThreshold!==-1&&this.er(6e4)}stop(){this.Xn&&(this.Xn.cancel(),this.Xn=null)}get started(){return this.Xn!==null}er(e){V(hg,`Garbage collection scheduled in ${e}ms`),this.Xn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Xn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(t){Fn(t)?V(hg,"Ignoring IndexedDB error during garbage collection: ",t):await Ln(t)}await this.er(3e5)})}},Fc=class{constructor(e,t){this.tr=e,this.params=t}calculateTargetCount(e,t){return this.tr.nr(e).next(n=>Math.floor(t/100*n))}nthSequenceNumber(e,t){if(t===0)return k.resolve(bn.ae);let n=new Vc(t);return this.tr.forEachTarget(e,s=>n.Zn(s.sequenceNumber)).next(()=>this.tr.rr(e,s=>n.Zn(s))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.tr.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.tr.removeOrphanedDocuments(e,t)}collect(e,t){return this.params.cacheSizeCollectionThreshold===-1?(V("LruGarbageCollector","Garbage collection skipped; disabled"),k.resolve(lg)):this.getCacheSize(e).next(n=>n<this.params.cacheSizeCollectionThreshold?(V("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),lg):this.ir(e,t))}getCacheSize(e){return this.tr.getCacheSize(e)}ir(e,t){let n,s,i,a,u,c,h,f=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(m=>(m>this.params.maximumSequenceNumbersToCollect?(V("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${m}`),s=this.params.maximumSequenceNumbersToCollect):s=m,a=Date.now(),this.nthSequenceNumber(e,s))).next(m=>(n=m,u=Date.now(),this.removeTargets(e,n,t))).next(m=>(i=m,c=Date.now(),this.removeOrphanedDocuments(e,n))).next(m=>(h=Date.now(),dn()<=Q.DEBUG&&V("LruGarbageCollector",`LRU Garbage Collection
12
+ }`}};var Ic=class{constructor(e,t){this.count=e,this.unchangedNames=t}};var he,J;function FS(r){switch(r){case D.OK:return M();case D.CANCELLED:case D.UNKNOWN:case D.DEADLINE_EXCEEDED:case D.RESOURCE_EXHAUSTED:case D.INTERNAL:case D.UNAVAILABLE:case D.UNAUTHENTICATED:return!1;case D.INVALID_ARGUMENT:case D.NOT_FOUND:case D.ALREADY_EXISTS:case D.PERMISSION_DENIED:case D.FAILED_PRECONDITION:case D.ABORTED:case D.OUT_OF_RANGE:case D.UNIMPLEMENTED:case D.DATA_LOSS:return!0;default:return M()}}function py(r){if(r===void 0)return At("GRPC error has no .code"),D.UNKNOWN;switch(r){case he.OK:return D.OK;case he.CANCELLED:return D.CANCELLED;case he.UNKNOWN:return D.UNKNOWN;case he.DEADLINE_EXCEEDED:return D.DEADLINE_EXCEEDED;case he.RESOURCE_EXHAUSTED:return D.RESOURCE_EXHAUSTED;case he.INTERNAL:return D.INTERNAL;case he.UNAVAILABLE:return D.UNAVAILABLE;case he.UNAUTHENTICATED:return D.UNAUTHENTICATED;case he.INVALID_ARGUMENT:return D.INVALID_ARGUMENT;case he.NOT_FOUND:return D.NOT_FOUND;case he.ALREADY_EXISTS:return D.ALREADY_EXISTS;case he.PERMISSION_DENIED:return D.PERMISSION_DENIED;case he.FAILED_PRECONDITION:return D.FAILED_PRECONDITION;case he.ABORTED:return D.ABORTED;case he.OUT_OF_RANGE:return D.OUT_OF_RANGE;case he.UNIMPLEMENTED:return D.UNIMPLEMENTED;case he.DATA_LOSS:return D.DATA_LOSS;default:return M()}}(J=he||(he={}))[J.OK=0]="OK",J[J.CANCELLED=1]="CANCELLED",J[J.UNKNOWN=2]="UNKNOWN",J[J.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",J[J.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",J[J.NOT_FOUND=5]="NOT_FOUND",J[J.ALREADY_EXISTS=6]="ALREADY_EXISTS",J[J.PERMISSION_DENIED=7]="PERMISSION_DENIED",J[J.UNAUTHENTICATED=16]="UNAUTHENTICATED",J[J.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",J[J.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",J[J.ABORTED=10]="ABORTED",J[J.OUT_OF_RANGE=11]="OUT_OF_RANGE",J[J.UNIMPLEMENTED=12]="UNIMPLEMENTED",J[J.INTERNAL=13]="INTERNAL",J[J.UNAVAILABLE=14]="UNAVAILABLE",J[J.DATA_LOSS=15]="DATA_LOSS";var ig=null;var MS=new Et([4294967295,4294967295],0);function og(r){let e=Sg().encode(r),t=new Uu;return t.update(e),new Uint8Array(t.digest())}function ag(r){let e=new DataView(r.buffer),t=e.getUint32(0,!0),n=e.getUint32(4,!0),s=e.getUint32(8,!0),i=e.getUint32(12,!0);return[new Et([t,n],0),new Et([s,i],0)]}var Ac=class r{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new mr(`Invalid padding: ${t}`);if(n<0)throw new mr(`Invalid hash count: ${n}`);if(e.length>0&&this.hashCount===0)throw new mr(`Invalid hash count: ${n}`);if(e.length===0&&t!==0)throw new mr(`Invalid padding when bitmap length is 0: ${t}`);this.Ee=8*e.length-t,this.de=Et.fromNumber(this.Ee)}Ae(e,t,n){let s=e.add(t.multiply(Et.fromNumber(n)));return s.compare(MS)===1&&(s=new Et([s.getBits(0),s.getBits(1)],0)),s.modulo(this.de).toNumber()}Re(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(this.Ee===0)return!1;let t=og(e),[n,s]=ag(t);for(let i=0;i<this.hashCount;i++){let a=this.Ae(n,s,i);if(!this.Re(a))return!1}return!0}static create(e,t,n){let s=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),a=new r(i,s,t);return n.forEach(u=>a.insert(u)),a}insert(e){if(this.Ee===0)return;let t=og(e),[n,s]=ag(t);for(let i=0;i<this.hashCount;i++){let a=this.Ae(n,s,i);this.Ve(a)}}Ve(e){let t=Math.floor(e/8),n=e%8;this.bitmap[t]|=1<<n}},mr=class extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}};var ko=class r{constructor(e,t,n,s,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=s,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){let s=new Map;return s.set(e,Ls.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new r(q.min(),s,new ce(K),Pt(),W())}},Ls=class r{constructor(e,t,n,s,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=s,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new r(n,t,W(),W(),W())}};var yn=class{constructor(e,t,n,s){this.me=e,this.removedTargetIds=t,this.key=n,this.fe=s}},Do=class{constructor(e,t){this.targetId=e,this.ge=t}},Oo=class{constructor(e,t,n=Re.EMPTY_BYTE_STRING,s=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=s}},No=class{constructor(){this.pe=0,this.ye=ug(),this.we=Re.EMPTY_BYTE_STRING,this.Se=!1,this.be=!0}get current(){return this.Se}get resumeToken(){return this.we}get De(){return this.pe!==0}get ve(){return this.be}Ce(e){e.approximateByteSize()>0&&(this.be=!0,this.we=e)}Fe(){let e=W(),t=W(),n=W();return this.ye.forEach((s,i)=>{switch(i){case 0:e=e.add(s);break;case 2:t=t.add(s);break;case 1:n=n.add(s);break;default:M()}}),new Ls(this.we,this.Se,e,t,n)}Me(){this.be=!1,this.ye=ug()}xe(e,t){this.be=!0,this.ye=this.ye.insert(e,t)}Oe(e){this.be=!0,this.ye=this.ye.remove(e)}Ne(){this.pe+=1}Be(){this.pe-=1,ee(this.pe>=0)}Le(){this.be=!0,this.Se=!0}},xc=class{constructor(e){this.ke=e,this.qe=new Map,this.Qe=Pt(),this.$e=go(),this.Ue=go(),this.Ke=new ce(K)}We(e){for(let t of e.me)e.fe&&e.fe.isFoundDocument()?this.Ge(t,e.fe):this.ze(t,e.key,e.fe);for(let t of e.removedTargetIds)this.ze(t,e.key,e.fe)}je(e){this.forEachTarget(e,t=>{let n=this.He(t);switch(e.state){case 0:this.Je(t)&&n.Ce(e.resumeToken);break;case 1:n.Be(),n.De||n.Me(),n.Ce(e.resumeToken);break;case 2:n.Be(),n.De||this.removeTarget(t);break;case 3:this.Je(t)&&(n.Le(),n.Ce(e.resumeToken));break;case 4:this.Je(t)&&(this.Ye(t),n.Ce(e.resumeToken));break;default:M()}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.qe.forEach((n,s)=>{this.Je(s)&&t(s)})}Ze(e){let t=e.targetId,n=e.ge.count,s=this.Xe(t);if(s){let i=s.target;if(yc(i))if(n===0){let a=new j(i.path);this.ze(t,a,Je.newNoDocument(a,q.min()))}else ee(n===1);else{let a=this.et(t);if(a!==n){let u=this.tt(e),c=u?this.nt(u,e,a):1;if(c!==0){this.Ye(t);let h=c===2?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ke=this.Ke.insert(t,h)}ig==null||ig.rt(function(f,m,g,b,P){var C,R,N,F,U,G;let Y={localCacheCount:f,existenceFilterCount:m.count,databaseId:g.database,projectId:g.projectId},B=m.unchangedNames;return B&&(Y.bloomFilter={applied:P===0,hashCount:(C=B==null?void 0:B.hashCount)!==null&&C!==void 0?C:0,bitmapLength:(F=(N=(R=B==null?void 0:B.bits)===null||R===void 0?void 0:R.bitmap)===null||N===void 0?void 0:N.length)!==null&&F!==void 0?F:0,padding:(G=(U=B==null?void 0:B.bits)===null||U===void 0?void 0:U.padding)!==null&&G!==void 0?G:0,mightContain:E=>{var y;return(y=b==null?void 0:b.mightContain(E))!==null&&y!==void 0&&y}}),Y}(a,e.ge,this.ke.it(),u,c))}}}}tt(e){let t=e.ge.unchangedNames;if(!t||!t.bits)return null;let{bits:{bitmap:n="",padding:s=0},hashCount:i=0}=t,a,u;try{a=St(n).toUint8Array()}catch(c){if(c instanceof xo)return vn("Decoding the base64 bloom filter in existence filter failed ("+c.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw c}try{u=new Ac(a,s,i)}catch(c){return vn(c instanceof mr?"BloomFilter error: ":"Applying bloom filter failed: ",c),null}return u.Ee===0?null:u}nt(e,t,n){return t.ge.count===n-this.st(e,t.targetId)?0:2}st(e,t){let n=this.ke.getRemoteKeysForTarget(t),s=0;return n.forEach(i=>{let a=this.ke.it(),u=`projects/${a.projectId}/databases/${a.database}/documents/${i.path.canonicalString()}`;e.mightContain(u)||(this.ze(t,i,null),s++)}),s}ot(e){let t=new Map;this.qe.forEach((i,a)=>{let u=this.Xe(a);if(u){if(i.current&&yc(u.target)){let c=new j(u.target.path);this._t(c).has(a)||this.ut(a,c)||this.ze(a,c,Je.newNoDocument(c,e))}i.ve&&(t.set(a,i.Fe()),i.Me())}});let n=W();this.Ue.forEach((i,a)=>{let u=!0;a.forEachWhile(c=>{let h=this.Xe(c);return!h||h.purpose==="TargetPurposeLimboResolution"||(u=!1,!1)}),u&&(n=n.add(i))}),this.Qe.forEach((i,a)=>a.setReadTime(e));let s=new ko(e,t,this.Ke,this.Qe,n);return this.Qe=Pt(),this.$e=go(),this.Ue=go(),this.Ke=new ce(K),s}Ge(e,t){if(!this.Je(e))return;let n=this.ut(e,t.key)?2:0;this.He(e).xe(t.key,n),this.Qe=this.Qe.insert(t.key,t),this.$e=this.$e.insert(t.key,this._t(t.key).add(e)),this.Ue=this.Ue.insert(t.key,this.ct(t.key).add(e))}ze(e,t,n){if(!this.Je(e))return;let s=this.He(e);this.ut(e,t)?s.xe(t,1):s.Oe(t),this.Ue=this.Ue.insert(t,this.ct(t).delete(e)),this.Ue=this.Ue.insert(t,this.ct(t).add(e)),n&&(this.Qe=this.Qe.insert(t,n))}removeTarget(e){this.qe.delete(e)}et(e){let t=this.He(e).Fe();return this.ke.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Ne(e){this.He(e).Ne()}He(e){let t=this.qe.get(e);return t||(t=new No,this.qe.set(e,t)),t}ct(e){let t=this.Ue.get(e);return t||(t=new _e(K),this.Ue=this.Ue.insert(e,t)),t}_t(e){let t=this.$e.get(e);return t||(t=new _e(K),this.$e=this.$e.insert(e,t)),t}Je(e){let t=this.Xe(e)!==null;return t||V("WatchChangeAggregator","Detected inactive target",e),t}Xe(e){let t=this.qe.get(e);return t&&t.De?null:this.ke.lt(e)}Ye(e){this.qe.set(e,new No),this.ke.getRemoteKeysForTarget(e).forEach(t=>{this.ze(e,t,null)})}ut(e,t){return this.ke.getRemoteKeysForTarget(e).has(t)}};function go(){return new ce(j.comparator)}function ug(){return new ce(j.comparator)}var jS={asc:"ASCENDING",desc:"DESCENDING"},US={"<":"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"},BS={and:"AND",or:"OR"},Sc=class{constructor(e,t){this.databaseId=e,this.useProto3Json=t}};function Rc(r,e){return r.useProto3Json||ia(e)?e:{value:e}}function Vo(r,e){return r.useProto3Json?`${new Date(1e3*e.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+e.nanoseconds).slice(-9)}Z`:{seconds:""+e.seconds,nanos:e.nanoseconds}}function my(r,e){return r.useProto3Json?e.toBase64():e.toUint8Array()}function $S(r,e){return Vo(r,e.toTimestamp())}function st(r){return ee(!!r),q.fromTimestamp(function(t){let n=xt(t);return new we(n.seconds,n.nanos)}(r))}function Bl(r,e){return Pc(r,e).canonicalString()}function Pc(r,e){let t=function(s){return new fe(["projects",s.projectId,"databases",s.database])}(r).child("documents");return e===void 0?t:t.child(e)}function gy(r){let e=fe.fromString(r);return ee(by(e)),e}function Cc(r,e){return Bl(r.databaseId,e.path)}function Ku(r,e){let t=gy(e);if(t.get(1)!==r.databaseId.projectId)throw new L(D.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+t.get(1)+" vs "+r.databaseId.projectId);if(t.get(3)!==r.databaseId.database)throw new L(D.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+t.get(3)+" vs "+r.databaseId.database);return new j(_y(t))}function yy(r,e){return Bl(r.databaseId,e)}function qS(r){let e=gy(r);return e.length===4?fe.emptyPath():_y(e)}function kc(r){return new fe(["projects",r.databaseId.projectId,"databases",r.databaseId.database]).canonicalString()}function _y(r){return ee(r.length>4&&r.get(4)==="documents"),r.popFirst(5)}function cg(r,e,t){return{name:Cc(r,e),fields:t.value.mapValue.fields}}function zS(r,e){let t;if("targetChange"in e){e.targetChange;let n=function(h){return h==="NO_CHANGE"?0:h==="ADD"?1:h==="REMOVE"?2:h==="CURRENT"?3:h==="RESET"?4:M()}(e.targetChange.targetChangeType||"NO_CHANGE"),s=e.targetChange.targetIds||[],i=function(h,f){return h.useProto3Json?(ee(f===void 0||typeof f=="string"),Re.fromBase64String(f||"")):(ee(f===void 0||f instanceof Buffer||f instanceof Uint8Array),Re.fromUint8Array(f||new Uint8Array))}(r,e.targetChange.resumeToken),a=e.targetChange.cause,u=a&&function(h){let f=h.code===void 0?D.UNKNOWN:py(h.code);return new L(f,h.message||"")}(a);t=new Oo(n,s,i,u||null)}else if("documentChange"in e){e.documentChange;let n=e.documentChange;n.document,n.document.name,n.document.updateTime;let s=Ku(r,n.document.name),i=st(n.document.updateTime),a=n.document.createTime?st(n.document.createTime):q.min(),u=new je({mapValue:{fields:n.document.fields}}),c=Je.newFoundDocument(s,i,a,u),h=n.targetIds||[],f=n.removedTargetIds||[];t=new yn(h,f,c.key,c)}else if("documentDelete"in e){e.documentDelete;let n=e.documentDelete;n.document;let s=Ku(r,n.document),i=n.readTime?st(n.readTime):q.min(),a=Je.newNoDocument(s,i),u=n.removedTargetIds||[];t=new yn([],u,a.key,a)}else if("documentRemove"in e){e.documentRemove;let n=e.documentRemove;n.document;let s=Ku(r,n.document),i=n.removedTargetIds||[];t=new yn([],i,s,null)}else{if(!("filter"in e))return M();{e.filter;let n=e.filter;n.targetId;let{count:s=0,unchangedNames:i}=n,a=new Ic(s,i),u=n.targetId;t=new Do(u,a)}}return t}function GS(r,e){let t;if(e instanceof br)t={update:cg(r,e.key,e.value)};else if(e instanceof Co)t={delete:Cc(r,e.key)};else if(e instanceof ut)t={update:cg(r,e.key,e.data),updateMask:eR(e.fieldMask)};else{if(!(e instanceof wc))return M();t={verify:Cc(r,e.key)}}return e.fieldTransforms.length>0&&(t.updateTransforms=e.fieldTransforms.map(n=>function(i,a){let u=a.transform;if(u instanceof Pn)return{fieldPath:a.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(u instanceof vr)return{fieldPath:a.field.canonicalString(),appendMissingElements:{values:u.elements}};if(u instanceof wr)return{fieldPath:a.field.canonicalString(),removeAllFromArray:{values:u.elements}};if(u instanceof Cn)return{fieldPath:a.field.canonicalString(),increment:u.Ie};throw M()}(0,n))),e.precondition.isNone||(t.currentDocument=function(s,i){return i.updateTime!==void 0?{updateTime:$S(s,i.updateTime)}:i.exists!==void 0?{exists:i.exists}:M()}(r,e.precondition)),t}function KS(r,e){return r&&r.length>0?(ee(e!==void 0),r.map(t=>function(s,i){let a=s.updateTime?st(s.updateTime):st(i);return a.isEqual(q.min())&&(a=st(i)),new vc(a,s.transformResults||[])}(t,e))):[]}function HS(r,e){return{documents:[yy(r,e.path)]}}function WS(r,e){let t={structuredQuery:{}},n=e.path,s;e.collectionGroup!==null?(s=n,t.structuredQuery.from=[{collectionId:e.collectionGroup,allDescendants:!0}]):(s=n.popLast(),t.structuredQuery.from=[{collectionId:n.lastSegment()}]),t.parent=yy(r,s);let i=function(h){if(h.length!==0)return wy(at.create(h,"and"))}(e.filters);i&&(t.structuredQuery.where=i);let a=function(h){if(h.length!==0)return h.map(f=>function(g){return{field:pn(g.field),direction:YS(g.dir)}}(f))}(e.orderBy);a&&(t.structuredQuery.orderBy=a);let u=Rc(r,e.limit);return u!==null&&(t.structuredQuery.limit=u),e.startAt&&(t.structuredQuery.startAt=function(h){return{before:h.inclusive,values:h.position}}(e.startAt)),e.endAt&&(t.structuredQuery.endAt=function(h){return{before:!h.inclusive,values:h.position}}(e.endAt)),{ht:t,parent:s}}function QS(r){let e=qS(r.parent),t=r.structuredQuery,n=t.from?t.from.length:0,s=null;if(n>0){ee(n===1);let f=t.from[0];f.allDescendants?s=f.collectionId:e=e.child(f.collectionId)}let i=[];t.where&&(i=function(m){let g=vy(m);return g instanceof at&&Xg(g)?g.getFilters():[g]}(t.where));let a=[];t.orderBy&&(a=function(m){return m.map(g=>function(P){return new xn(mn(P.field),function(R){switch(R){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(P.direction))}(g))}(t.orderBy));let u=null;t.limit&&(u=function(m){let g;return g=typeof m=="object"?m.value:m,ia(g)?null:g}(t.limit));let c=null;t.startAt&&(c=function(m){let g=!!m.before,b=m.values||[];return new An(b,g)}(t.startAt));let h=null;return t.endAt&&(h=function(m){let g=!m.before,b=m.values||[];return new An(b,g)}(t.endAt)),bS(e,s,a,i,u,"F",c,h)}function JS(r,e){let t=function(s){switch(s){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return M()}}(e.purpose);return t==null?null:{"goog-listen-tags":t}}function vy(r){return r.unaryFilter!==void 0?function(t){switch(t.unaryFilter.op){case"IS_NAN":let n=mn(t.unaryFilter.field);return me.create(n,"==",{doubleValue:NaN});case"IS_NULL":let s=mn(t.unaryFilter.field);return me.create(s,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let i=mn(t.unaryFilter.field);return me.create(i,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let a=mn(t.unaryFilter.field);return me.create(a,"!=",{nullValue:"NULL_VALUE"});default:return M()}}(r):r.fieldFilter!==void 0?function(t){return me.create(mn(t.fieldFilter.field),function(s){switch(s){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 M()}}(t.fieldFilter.op),t.fieldFilter.value)}(r):r.compositeFilter!==void 0?function(t){return at.create(t.compositeFilter.filters.map(n=>vy(n)),function(s){switch(s){case"AND":return"and";case"OR":return"or";default:return M()}}(t.compositeFilter.op))}(r):M()}function YS(r){return jS[r]}function XS(r){return US[r]}function ZS(r){return BS[r]}function pn(r){return{fieldPath:r.canonicalString()}}function mn(r){return Ue.fromServerFormat(r.fieldPath)}function wy(r){return r instanceof me?function(t){if(t.op==="=="){if(Jm(t.value))return{unaryFilter:{field:pn(t.field),op:"IS_NAN"}};if(Qm(t.value))return{unaryFilter:{field:pn(t.field),op:"IS_NULL"}}}else if(t.op==="!="){if(Jm(t.value))return{unaryFilter:{field:pn(t.field),op:"IS_NOT_NAN"}};if(Qm(t.value))return{unaryFilter:{field:pn(t.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:pn(t.field),op:XS(t.op),value:t.value}}}(r):r instanceof at?function(t){let n=t.getFilters().map(s=>wy(s));return n.length===1?n[0]:{compositeFilter:{op:ZS(t.op),filters:n}}}(r):M()}function eR(r){let e=[];return r.fields.forEach(t=>e.push(t.canonicalString())),{fieldPaths:e}}function by(r){return r.length>=4&&r.get(0)==="projects"&&r.get(2)==="databases"}var Fs=class r{constructor(e,t,n,s,i=q.min(),a=q.min(),u=Re.EMPTY_BYTE_STRING,c=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=s,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=a,this.resumeToken=u,this.expectedCount=c}withSequenceNumber(e){return new r(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new r(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new r(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new r(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}};var Dc=class{constructor(e){this.Tt=e}};function tR(r){let e=QS({parent:r.parent,structuredQuery:r.structuredQuery});return r.limitType==="LAST"?_c(e,e.limit,"L"):e}var Lo=class{constructor(){}At(e,t){this.Rt(e,t),t.Vt()}Rt(e,t){if("nullValue"in e)this.ft(t,5);else if("booleanValue"in e)this.ft(t,10),t.gt(e.booleanValue?1:0);else if("integerValue"in e)this.ft(t,15),t.gt(oe(e.integerValue));else if("doubleValue"in e){let n=oe(e.doubleValue);isNaN(n)?this.ft(t,13):(this.ft(t,15),Os(n)?t.gt(0):t.gt(n))}else if("timestampValue"in e){let n=e.timestampValue;this.ft(t,20),typeof n=="string"&&(n=xt(n)),t.yt(`${n.seconds||""}`),t.gt(n.nanos||0)}else if("stringValue"in e)this.wt(e.stringValue,t),this.St(t);else if("bytesValue"in e)this.ft(t,30),t.bt(St(e.bytesValue)),this.St(t);else if("referenceValue"in e)this.Dt(e.referenceValue,t);else if("geoPointValue"in e){let n=e.geoPointValue;this.ft(t,45),t.gt(n.latitude||0),t.gt(n.longitude||0)}else"mapValue"in e?Qg(e)?this.ft(t,Number.MAX_SAFE_INTEGER):Wg(e)?this.vt(e.mapValue,t):(this.Ct(e.mapValue,t),this.St(t)):"arrayValue"in e?(this.Ft(e.arrayValue,t),this.St(t)):M()}wt(e,t){this.ft(t,25),this.Mt(e,t)}Mt(e,t){t.yt(e)}Ct(e,t){let n=e.fields||{};this.ft(t,55);for(let s of Object.keys(n))this.wt(s,t),this.Rt(n[s],t)}vt(e,t){var n,s;let i=e.fields||{};this.ft(t,53);let a=Tn,u=((s=(n=i[a].arrayValue)===null||n===void 0?void 0:n.values)===null||s===void 0?void 0:s.length)||0;this.ft(t,15),t.gt(oe(u)),this.wt(a,t),this.Rt(i[a],t)}Ft(e,t){let n=e.values||[];this.ft(t,50);for(let s of n)this.Rt(s,t)}Dt(e,t){this.ft(t,37),j.fromName(e).path.forEach(n=>{this.ft(t,60),this.Mt(n,t)})}ft(e,t){e.gt(t)}St(e){e.gt(2)}};Lo.xt=new Lo;var Oc=class{constructor(){this.Tn=new Nc}addToCollectionParentIndex(e,t){return this.Tn.add(t),k.resolve()}getCollectionParents(e,t){return k.resolve(this.Tn.getEntries(t))}addFieldIndex(e,t){return k.resolve()}deleteFieldIndex(e,t){return k.resolve()}deleteAllFieldIndexes(e){return k.resolve()}createTargetIndexes(e,t){return k.resolve()}getDocumentsMatchingTarget(e,t){return k.resolve(null)}getIndexType(e,t){return k.resolve(0)}getFieldIndexes(e,t){return k.resolve([])}getNextCollectionGroupToUpdate(e){return k.resolve(null)}getMinOffset(e,t){return k.resolve(_r.min())}getMinOffsetFromCollectionGroup(e,t){return k.resolve(_r.min())}updateCollectionGroup(e,t,n){return k.resolve()}updateIndexEntries(e,t){return k.resolve()}},Nc=class{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),s=this.index[t]||new _e(fe.comparator),i=!s.has(n);return this.index[t]=s.add(n),i}has(e){let t=e.lastSegment(),n=e.popLast(),s=this.index[t];return s&&s.has(n)}getEntries(e){return(this.index[e]||new _e(fe.comparator)).toArray()}};var JM=new Uint8Array(0);var lg={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},Ty=41943040,$e=class r{static withCacheSize(e){return new r(e,r.DEFAULT_COLLECTION_PERCENTILE,r.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}};$e.DEFAULT_COLLECTION_PERCENTILE=10,$e.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,$e.DEFAULT=new $e(Ty,$e.DEFAULT_COLLECTION_PERCENTILE,$e.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),$e.DISABLED=new $e(-1,0,0);var Ms=class r{constructor(e){this.$n=e}next(){return this.$n+=2,this.$n}static Un(){return new r(0)}static Kn(){return new r(-1)}};var hg="LruGarbageCollector",rR=1048576;function dg([r,e],[t,n]){let s=K(r,t);return s===0?K(e,n):s}var Vc=class{constructor(e){this.Hn=e,this.buffer=new _e(dg),this.Jn=0}Yn(){return++this.Jn}Zn(e){let t=[e,this.Yn()];if(this.buffer.size<this.Hn)this.buffer=this.buffer.add(t);else{let n=this.buffer.last();dg(t,n)<0&&(this.buffer=this.buffer.delete(n).add(t))}}get maxValue(){return this.buffer.last()[0]}},Lc=class{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Xn=null}start(){this.garbageCollector.params.cacheSizeCollectionThreshold!==-1&&this.er(6e4)}stop(){this.Xn&&(this.Xn.cancel(),this.Xn=null)}get started(){return this.Xn!==null}er(e){V(hg,`Garbage collection scheduled in ${e}ms`),this.Xn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Xn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(t){Fn(t)?V(hg,"Ignoring IndexedDB error during garbage collection: ",t):await Ln(t)}await this.er(3e5)})}},Fc=class{constructor(e,t){this.tr=e,this.params=t}calculateTargetCount(e,t){return this.tr.nr(e).next(n=>Math.floor(t/100*n))}nthSequenceNumber(e,t){if(t===0)return k.resolve(bn.ae);let n=new Vc(t);return this.tr.forEachTarget(e,s=>n.Zn(s.sequenceNumber)).next(()=>this.tr.rr(e,s=>n.Zn(s))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.tr.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.tr.removeOrphanedDocuments(e,t)}collect(e,t){return this.params.cacheSizeCollectionThreshold===-1?(V("LruGarbageCollector","Garbage collection skipped; disabled"),k.resolve(lg)):this.getCacheSize(e).next(n=>n<this.params.cacheSizeCollectionThreshold?(V("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),lg):this.ir(e,t))}getCacheSize(e){return this.tr.getCacheSize(e)}ir(e,t){let n,s,i,a,u,c,h,f=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(m=>(m>this.params.maximumSequenceNumbersToCollect?(V("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${m}`),s=this.params.maximumSequenceNumbersToCollect):s=m,a=Date.now(),this.nthSequenceNumber(e,s))).next(m=>(n=m,u=Date.now(),this.removeTargets(e,n,t))).next(m=>(i=m,c=Date.now(),this.removeOrphanedDocuments(e,n))).next(m=>(h=Date.now(),dn()<=Q.DEBUG&&V("LruGarbageCollector",`LRU Garbage Collection
13
13
  Counted targets in ${a-f}ms
14
14
  Determined least recently used ${s} in `+(u-a)+`ms
15
15
  Removed ${i} targets in `+(c-u)+`ms
16
16
  Removed ${m} documents in `+(h-c)+`ms
17
- Total Duration: ${h-f}ms`),k.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:m})))}};function nR(r,e){return new Fc(r,e)}var Mc=class{constructor(){this.changes=new Rt(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Je.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let n=this.changes.get(t);return n!==void 0?k.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}};var jc=class{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}};var Uc=class{constructor(e,t,n,s){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=s}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next(s=>(n=s,this.remoteDocumentCache.getEntry(e,t))).next(s=>(n!==null&&ks(n.mutation,s,qe.empty(),we.now()),s))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(n=>this.getLocalViewOfDocuments(e,n,W()).next(()=>n))}getLocalViewOfDocuments(e,t,n=W()){let s=pr();return this.populateOverlays(e,s,t).next(()=>this.computeViews(e,t,s,n).next(i=>{let a=Ss();return i.forEach((u,c)=>{a=a.insert(u,c.overlayedDocument)}),a}))}getOverlayedDocuments(e,t){let n=pr();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,W()))}populateOverlays(e,t,n){let s=[];return n.forEach(i=>{t.has(i)||s.push(i)}),this.documentOverlayCache.getOverlays(e,s).next(i=>{i.forEach((a,u)=>{t.set(a,u)})})}computeViews(e,t,n,s){let i=Pt(),a=Cs(),u=function(){return Cs()}();return t.forEach((c,h)=>{let f=n.get(h.key);s.has(h.key)&&(f===void 0||f.mutation instanceof ut)?i=i.insert(h.key,h):f!==void 0?(a.set(h.key,f.mutation.getFieldMask()),ks(f.mutation,h,f.mutation.getFieldMask(),we.now())):a.set(h.key,qe.empty())}),this.recalculateAndSaveOverlays(e,i).next(c=>(c.forEach((h,f)=>a.set(h,f)),t.forEach((h,f)=>{var m;return u.set(h,new jc(f,(m=a.get(h))!==null&&m!==void 0?m:null))}),u))}recalculateAndSaveOverlays(e,t){let n=Cs(),s=new ce((a,u)=>a-u),i=W();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(a=>{for(let u of a)u.keys().forEach(c=>{let h=t.get(c);if(h===null)return;let f=n.get(c)||qe.empty();f=u.applyToLocalView(h,f),n.set(c,f);let m=(s.get(u.batchId)||W()).add(c);s=s.insert(u.batchId,m)})}).next(()=>{let a=[],u=s.getReverseIterator();for(;u.hasNext();){let c=u.getNext(),h=c.key,f=c.value,m=oy();f.forEach(g=>{if(!i.has(g)){let b=dy(t.get(g),n.get(g));b!==null&&m.set(g,b),i=i.add(g)}}),a.push(this.documentOverlayCache.saveOverlays(e,h,m))}return k.waitFor(a)}).next(()=>n)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(n=>this.recalculateAndSaveOverlays(e,n))}getDocumentsMatchingQuery(e,t,n,s){return function(a){return j.isDocumentKey(a.path)&&a.collectionGroup===null&&a.filters.length===0}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):TS(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,s):this.getDocumentsMatchingCollectionQuery(e,t,n,s)}getNextDocuments(e,t,n,s){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,s).next(i=>{let a=s-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,s-i.size):k.resolve(pr()),u=Ds,c=i;return a.next(h=>k.forEach(h,(f,m)=>(u<m.largestBatchId&&(u=m.largestBatchId),i.get(f)?k.resolve():this.remoteDocumentCache.getEntry(e,f).next(g=>{c=c.insert(f,g)}))).next(()=>this.populateOverlays(e,h,i)).next(()=>this.computeViews(e,c,h,W())).next(f=>({batchId:u,changes:iy(f)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new j(t)).next(n=>{let s=Ss();return n.isFoundDocument()&&(s=s.insert(n.key,n)),s})}getDocumentsMatchingCollectionGroupQuery(e,t,n,s){let i=t.collectionGroup,a=Ss();return this.indexManager.getCollectionParents(e,i).next(u=>k.forEach(u,c=>{let h=function(m,g){return new Sn(g,null,m.explicitOrderBy.slice(),m.filters.slice(),m.limit,m.limitType,m.startAt,m.endAt)}(t,c.child(i));return this.getDocumentsMatchingCollectionQuery(e,h,n,s).next(f=>{f.forEach((m,g)=>{a=a.insert(m,g)})})}).next(()=>a))}getDocumentsMatchingCollectionQuery(e,t,n,s){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next(a=>(i=a,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,s))).next(a=>{i.forEach((c,h)=>{let f=h.getKey();a.get(f)===null&&(a=a.insert(f,Je.newInvalidDocument(f)))});let u=Ss();return a.forEach((c,h)=>{let f=i.get(c);f!==void 0&&ks(f.mutation,h,qe.empty(),we.now()),la(t,h)&&(u=u.insert(c,h))}),u})}};var Bc=class{constructor(e){this.serializer=e,this.dr=new Map,this.Ar=new Map}getBundleMetadata(e,t){return k.resolve(this.dr.get(t))}saveBundleMetadata(e,t){return this.dr.set(t.id,function(s){return{id:s.id,version:s.version,createTime:st(s.createTime)}}(t)),k.resolve()}getNamedQuery(e,t){return k.resolve(this.Ar.get(t))}saveNamedQuery(e,t){return this.Ar.set(t.name,function(s){return{name:s.name,query:tR(s.bundledQuery),readTime:st(s.readTime)}}(t)),k.resolve()}};var $c=class{constructor(){this.overlays=new ce(j.comparator),this.Rr=new Map}getOverlay(e,t){return k.resolve(this.overlays.get(t))}getOverlays(e,t){let n=pr();return k.forEach(t,s=>this.getOverlay(e,s).next(i=>{i!==null&&n.set(s,i)})).next(()=>n)}saveOverlays(e,t,n){return n.forEach((s,i)=>{this.Et(e,t,i)}),k.resolve()}removeOverlaysForBatchId(e,t,n){let s=this.Rr.get(n);return s!==void 0&&(s.forEach(i=>this.overlays=this.overlays.remove(i)),this.Rr.delete(n)),k.resolve()}getOverlaysForCollection(e,t,n){let s=pr(),i=t.length+1,a=new j(t.child("")),u=this.overlays.getIteratorFrom(a);for(;u.hasNext();){let c=u.getNext().value,h=c.getKey();if(!t.isPrefixOf(h.path))break;h.path.length===i&&c.largestBatchId>n&&s.set(c.getKey(),c)}return k.resolve(s)}getOverlaysForCollectionGroup(e,t,n,s){let i=new ce((h,f)=>h-f),a=this.overlays.getIterator();for(;a.hasNext();){let h=a.getNext().value;if(h.getKey().getCollectionGroup()===t&&h.largestBatchId>n){let f=i.get(h.largestBatchId);f===null&&(f=pr(),i=i.insert(h.largestBatchId,f)),f.set(h.getKey(),h)}}let u=pr(),c=i.getIterator();for(;c.hasNext()&&(c.getNext().value.forEach((h,f)=>u.set(h,f)),!(u.size()>=s)););return k.resolve(u)}Et(e,t,n){let s=this.overlays.get(n.key);if(s!==null){let a=this.Rr.get(s.largestBatchId).delete(n.key);this.Rr.set(s.largestBatchId,a)}this.overlays=this.overlays.insert(n.key,new Ec(t,n));let i=this.Rr.get(t);i===void 0&&(i=W(),this.Rr.set(t,i)),this.Rr.set(t,i.add(n.key))}};var qc=class{constructor(){this.sessionToken=Re.EMPTY_BYTE_STRING}getSessionToken(e){return k.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,k.resolve()}};var js=class{constructor(){this.Vr=new _e(de.mr),this.gr=new _e(de.pr)}isEmpty(){return this.Vr.isEmpty()}addReference(e,t){let n=new de(e,t);this.Vr=this.Vr.add(n),this.gr=this.gr.add(n)}yr(e,t){e.forEach(n=>this.addReference(n,t))}removeReference(e,t){this.wr(new de(e,t))}Sr(e,t){e.forEach(n=>this.removeReference(n,t))}br(e){let t=new j(new fe([])),n=new de(t,e),s=new de(t,e+1),i=[];return this.gr.forEachInRange([n,s],a=>{this.wr(a),i.push(a.key)}),i}Dr(){this.Vr.forEach(e=>this.wr(e))}wr(e){this.Vr=this.Vr.delete(e),this.gr=this.gr.delete(e)}vr(e){let t=new j(new fe([])),n=new de(t,e),s=new de(t,e+1),i=W();return this.gr.forEachInRange([n,s],a=>{i=i.add(a.key)}),i}containsKey(e){let t=new de(e,0),n=this.Vr.firstAfterOrEqual(t);return n!==null&&e.isEqual(n.key)}},de=class{constructor(e,t){this.key=e,this.Cr=t}static mr(e,t){return j.comparator(e.key,t.key)||K(e.Cr,t.Cr)}static pr(e,t){return K(e.Cr,t.Cr)||j.comparator(e.key,t.key)}};var zc=class{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Fr=1,this.Mr=new _e(de.mr)}checkEmpty(e){return k.resolve(this.mutationQueue.length===0)}addMutationBatch(e,t,n,s){let i=this.Fr;this.Fr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let a=new bc(i,t,n,s);this.mutationQueue.push(a);for(let u of s)this.Mr=this.Mr.add(new de(u.key,i)),this.indexManager.addToCollectionParentIndex(e,u.key.path.popLast());return k.resolve(a)}lookupMutationBatch(e,t){return k.resolve(this.Or(t))}getNextMutationBatchAfterBatchId(e,t){let n=t+1,s=this.Nr(n),i=s<0?0:s;return k.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return k.resolve(this.mutationQueue.length===0?Ol:this.Fr-1)}getAllMutationBatches(e){return k.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new de(t,0),s=new de(t,Number.POSITIVE_INFINITY),i=[];return this.Mr.forEachInRange([n,s],a=>{let u=this.Or(a.Cr);i.push(u)}),k.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new _e(K);return t.forEach(s=>{let i=new de(s,0),a=new de(s,Number.POSITIVE_INFINITY);this.Mr.forEachInRange([i,a],u=>{n=n.add(u.Cr)})}),k.resolve(this.Br(n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,s=n.length+1,i=n;j.isDocumentKey(i)||(i=i.child(""));let a=new de(new j(i),0),u=new _e(K);return this.Mr.forEachWhile(c=>{let h=c.key.path;return!!n.isPrefixOf(h)&&(h.length===s&&(u=u.add(c.Cr)),!0)},a),k.resolve(this.Br(u))}Br(e){let t=[];return e.forEach(n=>{let s=this.Or(n);s!==null&&t.push(s)}),t}removeMutationBatch(e,t){ee(this.Lr(t.batchId,"removed")===0),this.mutationQueue.shift();let n=this.Mr;return k.forEach(t.mutations,s=>{let i=new de(s.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,s.key)}).next(()=>{this.Mr=n})}qn(e){}containsKey(e,t){let n=new de(t,0),s=this.Mr.firstAfterOrEqual(n);return k.resolve(t.isEqual(s&&s.key))}performConsistencyCheck(e){return this.mutationQueue.length,k.resolve()}Lr(e,t){return this.Nr(e)}Nr(e){return this.mutationQueue.length===0?0:e-this.mutationQueue[0].batchId}Or(e){let t=this.Nr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}};var Gc=class{constructor(e){this.kr=e,this.docs=function(){return new ce(j.comparator)}(),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){let n=t.key,s=this.docs.get(n),i=s?s.size:0,a=this.kr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:a}),this.size+=a-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){let t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){let n=this.docs.get(t);return k.resolve(n?n.document.mutableCopy():Je.newInvalidDocument(t))}getEntries(e,t){let n=Pt();return t.forEach(s=>{let i=this.docs.get(s);n=n.insert(s,i?i.document.mutableCopy():Je.newInvalidDocument(s))}),k.resolve(n)}getDocumentsMatchingQuery(e,t,n,s){let i=Pt(),a=t.path,u=new j(a.child("__id-9223372036854775808__")),c=this.docs.getIteratorFrom(u);for(;c.hasNext();){let{key:h,value:{document:f}}=c.getNext();if(!a.isPrefixOf(h.path))break;h.path.length>a.length+1||rS(tS(f),n)<=0||(s.has(f.key)||la(t,f))&&(i=i.insert(f.key,f.mutableCopy()))}return k.resolve(i)}getAllFromCollectionGroup(e,t,n,s){M()}qr(e,t){return k.forEach(this.docs,n=>t(n))}newChangeBuffer(e){return new Kc(this)}getSize(e){return k.resolve(this.size)}},Kc=class extends Mc{constructor(e){super(),this.Ir=e}applyChanges(e){let t=[];return this.changes.forEach((n,s)=>{s.isValidDocument()?t.push(this.Ir.addEntry(e,s)):this.Ir.removeEntry(n)}),k.waitFor(t)}getFromCache(e,t){return this.Ir.getEntry(e,t)}getAllFromCache(e,t){return this.Ir.getEntries(e,t)}};var Hc=class{constructor(e){this.persistence=e,this.Qr=new Rt(t=>Ml(t),jl),this.lastRemoteSnapshotVersion=q.min(),this.highestTargetId=0,this.$r=0,this.Ur=new js,this.targetCount=0,this.Kr=Ms.Un()}forEachTarget(e,t){return this.Qr.forEach((n,s)=>t(s)),k.resolve()}getLastRemoteSnapshotVersion(e){return k.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return k.resolve(this.$r)}allocateTargetId(e){return this.highestTargetId=this.Kr.next(),k.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.$r&&(this.$r=t),k.resolve()}zn(e){this.Qr.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this.Kr=new Ms(t),this.highestTargetId=t),e.sequenceNumber>this.$r&&(this.$r=e.sequenceNumber)}addTargetData(e,t){return this.zn(t),this.targetCount+=1,k.resolve()}updateTargetData(e,t){return this.zn(t),k.resolve()}removeTargetData(e,t){return this.Qr.delete(t.target),this.Ur.br(t.targetId),this.targetCount-=1,k.resolve()}removeTargets(e,t,n){let s=0,i=[];return this.Qr.forEach((a,u)=>{u.sequenceNumber<=t&&n.get(u.targetId)===null&&(this.Qr.delete(a),i.push(this.removeMatchingKeysForTargetId(e,u.targetId)),s++)}),k.waitFor(i).next(()=>s)}getTargetCount(e){return k.resolve(this.targetCount)}getTargetData(e,t){let n=this.Qr.get(t)||null;return k.resolve(n)}addMatchingKeys(e,t,n){return this.Ur.yr(t,n),k.resolve()}removeMatchingKeys(e,t,n){this.Ur.Sr(t,n);let s=this.persistence.referenceDelegate,i=[];return s&&t.forEach(a=>{i.push(s.markPotentiallyOrphaned(e,a))}),k.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Ur.br(t),k.resolve()}getMatchingKeysForTargetId(e,t){let n=this.Ur.vr(t);return k.resolve(n)}containsKey(e,t){return k.resolve(this.Ur.containsKey(t))}};var Mo=class{constructor(e,t){this.Wr={},this.overlays={},this.Gr=new bn(0),this.zr=!1,this.zr=!0,this.jr=new qc,this.referenceDelegate=e(this),this.Hr=new Hc(this),this.indexManager=new Oc,this.remoteDocumentCache=function(s){return new Gc(s)}(n=>this.referenceDelegate.Jr(n)),this.serializer=new Dc(t),this.Yr=new Bc(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.zr=!1,Promise.resolve()}get started(){return this.zr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new $c,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Wr[e.toKey()];return n||(n=new zc(t,this.referenceDelegate),this.Wr[e.toKey()]=n),n}getGlobalsCache(){return this.jr}getTargetCache(){return this.Hr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Yr}runTransaction(e,t,n){V("MemoryPersistence","Starting transaction:",e);let s=new Wc(this.Gr.next());return this.referenceDelegate.Zr(),n(s).next(i=>this.referenceDelegate.Xr(s).next(()=>i)).toPromise().then(i=>(s.raiseOnCommittedEvent(),i))}ei(e,t){return k.or(Object.values(this.Wr).map(n=>()=>n.containsKey(e,t)))}},Wc=class extends sc{constructor(e){super(),this.currentSequenceNumber=e}},Qc=class r{constructor(e){this.persistence=e,this.ti=new js,this.ni=null}static ri(e){return new r(e)}get ii(){if(this.ni)return this.ni;throw M()}addReference(e,t,n){return this.ti.addReference(n,t),this.ii.delete(n.toString()),k.resolve()}removeReference(e,t,n){return this.ti.removeReference(n,t),this.ii.add(n.toString()),k.resolve()}markPotentiallyOrphaned(e,t){return this.ii.add(t.toString()),k.resolve()}removeTarget(e,t){this.ti.br(t.targetId).forEach(s=>this.ii.add(s.toString()));let n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(s=>{s.forEach(i=>this.ii.add(i.toString()))}).next(()=>n.removeTargetData(e,t))}Zr(){this.ni=new Set}Xr(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return k.forEach(this.ii,n=>{let s=j.fromPath(n);return this.si(e,s).next(i=>{i||t.removeEntry(s,q.min())})}).next(()=>(this.ni=null,t.apply(e)))}updateLimboDocument(e,t){return this.si(e,t).next(n=>{n?this.ii.delete(t.toString()):this.ii.add(t.toString())})}Jr(e){return 0}si(e,t){return k.or([()=>k.resolve(this.ti.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.ei(e,t)])}},jo=class r{constructor(e,t){this.persistence=e,this.oi=new Rt(n=>oS(n.path),(n,s)=>n.isEqual(s)),this.garbageCollector=nR(this,t)}static ri(e,t){return new r(e,t)}Zr(){}Xr(e){return k.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}nr(e){let t=this.sr(e);return this.persistence.getTargetCache().getTargetCount(e).next(n=>t.next(s=>n+s))}sr(e){let t=0;return this.rr(e,n=>{t++}).next(()=>t)}rr(e,t){return k.forEach(this.oi,(n,s)=>this.ar(e,n,s).next(i=>i?k.resolve():t(s)))}removeTargets(e,t,n){return this.persistence.getTargetCache().removeTargets(e,t,n)}removeOrphanedDocuments(e,t){let n=0,s=this.persistence.getRemoteDocumentCache(),i=s.newChangeBuffer();return s.qr(e,a=>this.ar(e,a,t).next(u=>{u||(n++,i.removeEntry(a,q.min()))})).next(()=>i.apply(e)).next(()=>n)}markPotentiallyOrphaned(e,t){return this.oi.set(t,e.currentSequenceNumber),k.resolve()}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,n)}addReference(e,t,n){return this.oi.set(n,e.currentSequenceNumber),k.resolve()}removeReference(e,t,n){return this.oi.set(n,e.currentSequenceNumber),k.resolve()}updateLimboDocument(e,t){return this.oi.set(t,e.currentSequenceNumber),k.resolve()}Jr(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=vo(e.data.value)),t}ar(e,t,n){return k.or([()=>this.persistence.ei(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let s=this.oi.get(t);return k.resolve(s!==void 0&&s>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}};var Jc=class r{constructor(e,t,n,s){this.targetId=e,this.fromCache=t,this.Hi=n,this.Ji=s}static Yi(e,t){let n=W(),s=W();for(let i of t.docChanges)switch(i.type){case 0:n=n.add(i.doc.key);break;case 1:s=s.add(i.doc.key)}return new r(e,t.fromCache,n,s)}};var Yc=class{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}};var Xc=class{constructor(){this.Zi=!1,this.Xi=!1,this.es=100,this.ts=function(){return ym()?8:sS(gm())>0?6:4}()}initialize(e,t){this.ns=e,this.indexManager=t,this.Zi=!0}getDocumentsMatchingQuery(e,t,n,s){let i={result:null};return this.rs(e,t).next(a=>{i.result=a}).next(()=>{if(!i.result)return this.ss(e,t,s,n).next(a=>{i.result=a})}).next(()=>{if(i.result)return;let a=new Yc;return this._s(e,t,a).next(u=>{if(i.result=u,this.Xi)return this.us(e,t,a,u.size)})}).next(()=>i.result)}us(e,t,n,s){return n.documentReadCount<this.es?(dn()<=Q.DEBUG&&V("QueryEngine","SDK will not create cache indexes for query:",fn(t),"since it only creates cache indexes for collection contains","more than or equal to",this.es,"documents"),k.resolve()):(dn()<=Q.DEBUG&&V("QueryEngine","Query:",fn(t),"scans",n.documentReadCount,"local documents and returns",s,"documents as results."),n.documentReadCount>this.ts*s?(dn()<=Q.DEBUG&&V("QueryEngine","The SDK decides to create cache indexes for query:",fn(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,nt(t))):k.resolve())}rs(e,t){if(eg(t))return k.resolve(null);let n=nt(t);return this.indexManager.getIndexType(e,n).next(s=>s===0?null:(t.limit!==null&&s===1&&(t=_c(t,null,"F"),n=nt(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next(i=>{let a=W(...i);return this.ns.getDocuments(e,a).next(u=>this.indexManager.getMinOffset(e,n).next(c=>{let h=this.cs(t,u);return this.ls(t,h,a,c.readTime)?this.rs(e,_c(t,null,"F")):this.hs(e,h,t,c)}))})))}ss(e,t,n,s){return eg(t)||s.isEqual(q.min())?k.resolve(null):this.ns.getDocuments(e,n).next(i=>{let a=this.cs(t,i);return this.ls(t,a,n,s)?k.resolve(null):(dn()<=Q.DEBUG&&V("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),fn(t)),this.hs(e,a,t,eS(s,Ds)).next(u=>u))})}cs(e,t){let n=new _e(ny(e));return t.forEach((s,i)=>{la(e,i)&&(n=n.add(i))}),n}ls(e,t,n,s){if(e.limit===null)return!1;if(n.size!==t.size)return!0;let i=e.limitType==="F"?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(s)>0)}_s(e,t,n){return dn()<=Q.DEBUG&&V("QueryEngine","Using full collection scan to execute query:",fn(t)),this.ns.getDocumentsMatchingQuery(e,t,_r.min(),n)}hs(e,t,n,s){return this.ns.getDocumentsMatchingQuery(e,n,s).next(i=>(t.forEach(a=>{i=i.insert(a.key,a)}),i))}};var $l="LocalStore",sR=3e8,Zc=class{constructor(e,t,n,s){this.persistence=e,this.Ps=t,this.serializer=s,this.Ts=new ce(K),this.Is=new Rt(i=>Ml(i),jl),this.Es=new Map,this.ds=e.getRemoteDocumentCache(),this.Hr=e.getTargetCache(),this.Yr=e.getBundleCache(),this.As(n)}As(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Uc(this.ds,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.ds.setIndexManager(this.indexManager),this.Ps.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.Ts))}};function iR(r,e,t,n){return new Zc(r,e,t,n)}async function Ey(r,e){let t=$(r);return await t.persistence.runTransaction("Handle user change","readonly",n=>{let s;return t.mutationQueue.getAllMutationBatches(n).next(i=>(s=i,t.As(e),t.mutationQueue.getAllMutationBatches(n))).next(i=>{let a=[],u=[],c=W();for(let h of s){a.push(h.batchId);for(let f of h.mutations)c=c.add(f.key)}for(let h of i){u.push(h.batchId);for(let f of h.mutations)c=c.add(f.key)}return t.localDocuments.getDocuments(n,c).next(h=>({Rs:h,removedBatchIds:a,addedBatchIds:u}))})})}function oR(r,e){let t=$(r);return t.persistence.runTransaction("Acknowledge batch","readwrite-primary",n=>{let s=e.batch.keys(),i=t.ds.newChangeBuffer({trackRemovals:!0});return function(u,c,h,f){let m=h.batch,g=m.keys(),b=k.resolve();return g.forEach(P=>{b=b.next(()=>f.getEntry(c,P)).next(C=>{let R=h.docVersions.get(P);ee(R!==null),C.version.compareTo(R)<0&&(m.applyToRemoteDocument(C,h),C.isValidDocument()&&(C.setReadTime(h.commitVersion),f.addEntry(C)))})}),b.next(()=>u.mutationQueue.removeMutationBatch(c,m))}(t,n,e,i).next(()=>i.apply(n)).next(()=>t.mutationQueue.performConsistencyCheck(n)).next(()=>t.documentOverlayCache.removeOverlaysForBatchId(n,s,e.batch.batchId)).next(()=>t.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(n,function(u){let c=W();for(let h=0;h<u.mutationResults.length;++h)u.mutationResults[h].transformResults.length>0&&(c=c.add(u.batch.mutations[h].key));return c}(e))).next(()=>t.localDocuments.getDocuments(n,s))})}function Iy(r){let e=$(r);return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.Hr.getLastRemoteSnapshotVersion(t))}function aR(r,e){let t=$(r),n=e.snapshotVersion,s=t.Ts;return t.persistence.runTransaction("Apply remote event","readwrite-primary",i=>{let a=t.ds.newChangeBuffer({trackRemovals:!0});s=t.Ts;let u=[];e.targetChanges.forEach((f,m)=>{let g=s.get(m);if(!g)return;u.push(t.Hr.removeMatchingKeys(i,f.removedDocuments,m).next(()=>t.Hr.addMatchingKeys(i,f.addedDocuments,m)));let b=g.withSequenceNumber(i.currentSequenceNumber);e.targetMismatches.get(m)!==null?b=b.withResumeToken(Re.EMPTY_BYTE_STRING,q.min()).withLastLimboFreeSnapshotVersion(q.min()):f.resumeToken.approximateByteSize()>0&&(b=b.withResumeToken(f.resumeToken,n)),s=s.insert(m,b),function(C,R,N){return C.resumeToken.approximateByteSize()===0||R.snapshotVersion.toMicroseconds()-C.snapshotVersion.toMicroseconds()>=sR?!0:N.addedDocuments.size+N.modifiedDocuments.size+N.removedDocuments.size>0}(g,b,f)&&u.push(t.Hr.updateTargetData(i,b))});let c=Pt(),h=W();if(e.documentUpdates.forEach(f=>{e.resolvedLimboDocuments.has(f)&&u.push(t.persistence.referenceDelegate.updateLimboDocument(i,f))}),u.push(uR(i,a,e.documentUpdates).next(f=>{c=f.Vs,h=f.fs})),!n.isEqual(q.min())){let f=t.Hr.getLastRemoteSnapshotVersion(i).next(m=>t.Hr.setTargetsMetadata(i,i.currentSequenceNumber,n));u.push(f)}return k.waitFor(u).next(()=>a.apply(i)).next(()=>t.localDocuments.getLocalViewOfDocuments(i,c,h)).next(()=>c)}).then(i=>(t.Ts=s,i))}function uR(r,e,t){let n=W(),s=W();return t.forEach(i=>n=n.add(i)),e.getEntries(r,n).next(i=>{let a=Pt();return t.forEach((u,c)=>{let h=i.get(u);c.isFoundDocument()!==h.isFoundDocument()&&(s=s.add(u)),c.isNoDocument()&&c.version.isEqual(q.min())?(e.removeEntry(u,c.readTime),a=a.insert(u,c)):!h.isValidDocument()||c.version.compareTo(h.version)>0||c.version.compareTo(h.version)===0&&h.hasPendingWrites?(e.addEntry(c),a=a.insert(u,c)):V($l,"Ignoring outdated watch update for ",u,". Current version:",h.version," Watch version:",c.version)}),{Vs:a,fs:s}})}function cR(r,e){let t=$(r);return t.persistence.runTransaction("Get next mutation batch","readonly",n=>(e===void 0&&(e=Ol),t.mutationQueue.getNextMutationBatchAfterBatchId(n,e)))}function lR(r,e){let t=$(r);return t.persistence.runTransaction("Allocate target","readwrite",n=>{let s;return t.Hr.getTargetData(n,e).next(i=>i?(s=i,k.resolve(s)):t.Hr.allocateTargetId(n).next(a=>(s=new Fs(e,a,"TargetPurposeListen",n.currentSequenceNumber),t.Hr.addTargetData(n,s).next(()=>s))))}).then(n=>{let s=t.Ts.get(n.targetId);return(s===null||n.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(t.Ts=t.Ts.insert(n.targetId,n),t.Is.set(e,n.targetId)),n})}async function el(r,e,t){let n=$(r),s=n.Ts.get(e),i=t?"readwrite":"readwrite-primary";try{t||await n.persistence.runTransaction("Release target",i,a=>n.persistence.referenceDelegate.removeTarget(a,s))}catch(a){if(!Fn(a))throw a;V($l,`Failed to update sequence numbers for target ${e}: ${a}`)}n.Ts=n.Ts.remove(e),n.Is.delete(s.target)}function fg(r,e,t){let n=$(r),s=q.min(),i=W();return n.persistence.runTransaction("Execute query","readwrite",a=>function(c,h,f){let m=$(c),g=m.Is.get(f);return g!==void 0?k.resolve(m.Ts.get(g)):m.Hr.getTargetData(h,f)}(n,a,nt(e)).next(u=>{if(u)return s=u.lastLimboFreeSnapshotVersion,n.Hr.getMatchingKeysForTargetId(a,u.targetId).next(c=>{i=c})}).next(()=>n.Ps.getDocumentsMatchingQuery(a,e,t?s:q.min(),t?i:W())).next(u=>(hR(n,IS(e),u),{documents:u,gs:i})))}function hR(r,e,t){let n=r.Es.get(e)||q.min();t.forEach((s,i)=>{i.readTime.compareTo(n)>0&&(n=i.readTime)}),r.Es.set(e,n)}var Uo=class{constructor(){this.activeTargetIds=CS()}Ds(e){this.activeTargetIds=this.activeTargetIds.add(e)}vs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}bs(){let e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}};var tl=class{constructor(){this.ho=new Uo,this.Po={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this.ho.Ds(e),this.Po[e]||"not-current"}updateQueryState(e,t,n){this.Po[e]=t}removeLocalQueryTarget(e){this.ho.vs(e)}isLocalQueryTarget(e){return this.ho.activeTargetIds.has(e)}clearQueryState(e){delete this.Po[e]}getAllActiveQueryTargets(){return this.ho.activeTargetIds}isActiveQueryTarget(e){return this.ho.activeTargetIds.has(e)}start(){return this.ho=new Uo,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}};var rl=class{To(e){}shutdown(){}};var pg="ConnectivityMonitor",Bo=class{constructor(){this.Io=()=>this.Eo(),this.Ao=()=>this.Ro(),this.Vo=[],this.mo()}To(e){this.Vo.push(e)}shutdown(){window.removeEventListener("online",this.Io),window.removeEventListener("offline",this.Ao)}mo(){window.addEventListener("online",this.Io),window.addEventListener("offline",this.Ao)}Eo(){V(pg,"Network connectivity changed: AVAILABLE");for(let e of this.Vo)e(0)}Ro(){V(pg,"Network connectivity changed: UNAVAILABLE");for(let e of this.Vo)e(1)}static D(){return typeof window!="undefined"&&window.addEventListener!==void 0&&window.removeEventListener!==void 0}};var _o=null;function nl(){return _o===null?_o=function(){return 268435456+Math.round(2147483648*Math.random())}():_o++,"0x"+_o.toString(16)}var Hu="RestConnection",dR={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"},sl=class{get fo(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;let t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),s=encodeURIComponent(this.databaseId.database);this.po=t+"://"+e.host,this.yo=`projects/${n}/databases/${s}`,this.wo=this.databaseId.database===Ro?`project_id=${n}`:`project_id=${n}&database_id=${s}`}So(e,t,n,s,i){let a=nl(),u=this.bo(e,t.toUriEncodedString());V(Hu,`Sending RPC '${e}' ${a}:`,u,n);let c={"google-cloud-resource-prefix":this.yo,"x-goog-request-params":this.wo};return this.Do(c,s,i),this.vo(e,u,c,n).then(h=>(V(Hu,`Received RPC '${e}' ${a}: `,h),h),h=>{throw vn(Hu,`RPC '${e}' ${a} failed with error: `,h,"url: ",u,"request:",n),h})}Co(e,t,n,s,i,a){return this.So(e,t,n,s,i)}Do(e,t,n){e["X-Goog-Api-Client"]=function(){return"gl-js/ fire/"+Vn}(),e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach((s,i)=>e[i]=s),n&&n.headers.forEach((s,i)=>e[i]=s)}bo(e,t){let n=dR[e];return`${this.po}/v1/${t}:${n}`}terminate(){}};var il=class{constructor(e){this.Fo=e.Fo,this.Mo=e.Mo}xo(e){this.Oo=e}No(e){this.Bo=e}Lo(e){this.ko=e}onMessage(e){this.qo=e}close(){this.Mo()}send(e){this.Fo(e)}Qo(){this.Oo()}$o(){this.Bo()}Uo(e){this.ko(e)}Ko(e){this.qo(e)}};var Se="WebChannelConnection",ol=class extends sl{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}vo(e,t,n,s){let i=nl();return new Promise((a,u)=>{let c=new Bu;c.setWithCredentials(!0),c.listenOnce($u.COMPLETE,()=>{try{switch(c.getLastErrorCode()){case xs.NO_ERROR:let f=c.getResponseJson();V(Se,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(f)),a(f);break;case xs.TIMEOUT:V(Se,`RPC '${e}' ${i} timed out`),u(new L(D.DEADLINE_EXCEEDED,"Request time out"));break;case xs.HTTP_ERROR:let m=c.getStatus();if(V(Se,`RPC '${e}' ${i} failed with status:`,m,"response text:",c.getResponseText()),m>0){let g=c.getResponseJson();Array.isArray(g)&&(g=g[0]);let b=g==null?void 0:g.error;if(b&&b.status&&b.message){let P=function(R){let N=R.toLowerCase().replace(/_/g,"-");return Object.values(D).indexOf(N)>=0?N:D.UNKNOWN}(b.status);u(new L(P,b.message))}else u(new L(D.UNKNOWN,"Server responded with status "+c.getStatus()))}else u(new L(D.UNAVAILABLE,"Connection failed."));break;default:M()}}finally{V(Se,`RPC '${e}' ${i} completed.`)}});let h=JSON.stringify(s);V(Se,`RPC '${e}' ${i} sending request:`,s),c.send(t,"POST",h,n,15)})}Wo(e,t,n){let s=nl(),i=[this.po,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=Gu(),u=zu(),c={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},h=this.longPollingOptions.timeoutSeconds;h!==void 0&&(c.longPollingTimeout=Math.round(1e3*h)),this.useFetchStreams&&(c.useFetchStreams=!0),this.Do(c.initMessageHeaders,t,n),c.encodeInitMessageHeaders=!0;let f=i.join("");V(Se,`Creating RPC '${e}' stream ${s}: ${f}`,c);let m=a.createWebChannel(f,c),g=!1,b=!1,P=new il({Fo:R=>{b?V(Se,`Not sending because RPC '${e}' stream ${s} is closed:`,R):(g||(V(Se,`Opening RPC '${e}' stream ${s} transport.`),m.open(),g=!0),V(Se,`RPC '${e}' stream ${s} sending:`,R),m.send(R))},Mo:()=>m.close()}),C=(R,N,F)=>{R.listen(N,U=>{try{F(U)}catch(G){setTimeout(()=>{throw G},0)}})};return C(m,hn.EventType.OPEN,()=>{b||(V(Se,`RPC '${e}' stream ${s} transport opened.`),P.Qo())}),C(m,hn.EventType.CLOSE,()=>{b||(b=!0,V(Se,`RPC '${e}' stream ${s} transport closed`),P.Uo())}),C(m,hn.EventType.ERROR,R=>{b||(b=!0,vn(Se,`RPC '${e}' stream ${s} transport errored:`,R),P.Uo(new L(D.UNAVAILABLE,"The operation could not be completed")))}),C(m,hn.EventType.MESSAGE,R=>{var N;if(!b){let F=R.data[0];ee(!!F);let U=F,G=(U==null?void 0:U.error)||((N=U[0])===null||N===void 0?void 0:N.error);if(G){V(Se,`RPC '${e}' stream ${s} received error:`,G);let Y=G.status,B=function(w){let T=he[w];if(T!==void 0)return py(T)}(Y),E=G.message;B===void 0&&(B=D.INTERNAL,E="Unknown error status: "+Y+" with message "+G.message),b=!0,P.Uo(new L(B,E)),m.close()}else V(Se,`RPC '${e}' stream ${s} received:`,F),P.Ko(F)}}),C(u,qu.STAT_EVENT,R=>{R.stat===mo.PROXY?V(Se,`RPC '${e}' stream ${s} detected buffering proxy`):R.stat===mo.NOPROXY&&V(Se,`RPC '${e}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{P.$o()},0),P}};function Wu(){return typeof document!="undefined"?document:null}function ha(r){return new Sc(r,!0)}var $o=class{constructor(e,t,n=1e3,s=1.5,i=6e4){this.Ti=e,this.timerId=t,this.Go=n,this.zo=s,this.jo=i,this.Ho=0,this.Jo=null,this.Yo=Date.now(),this.reset()}reset(){this.Ho=0}Zo(){this.Ho=this.jo}Xo(e){this.cancel();let t=Math.floor(this.Ho+this.e_()),n=Math.max(0,Date.now()-this.Yo),s=Math.max(0,t-n);s>0&&V("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.Ho} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Jo=this.Ti.enqueueAfterDelay(this.timerId,s,()=>(this.Yo=Date.now(),e())),this.Ho*=this.zo,this.Ho<this.Go&&(this.Ho=this.Go),this.Ho>this.jo&&(this.Ho=this.jo)}t_(){this.Jo!==null&&(this.Jo.skipDelay(),this.Jo=null)}cancel(){this.Jo!==null&&(this.Jo.cancel(),this.Jo=null)}e_(){return(Math.random()-.5)*this.Ho}};var mg="PersistentStream",qo=class{constructor(e,t,n,s,i,a,u,c){this.Ti=e,this.n_=n,this.r_=s,this.connection=i,this.authCredentialsProvider=a,this.appCheckCredentialsProvider=u,this.listener=c,this.state=0,this.i_=0,this.s_=null,this.o_=null,this.stream=null,this.__=0,this.a_=new $o(e,t)}u_(){return this.state===1||this.state===5||this.c_()}c_(){return this.state===2||this.state===3}start(){this.__=0,this.state!==4?this.auth():this.l_()}async stop(){this.u_()&&await this.close(0)}h_(){this.state=0,this.a_.reset()}P_(){this.c_()&&this.s_===null&&(this.s_=this.Ti.enqueueAfterDelay(this.n_,6e4,()=>this.T_()))}I_(e){this.E_(),this.stream.send(e)}async T_(){if(this.c_())return this.close(0)}E_(){this.s_&&(this.s_.cancel(),this.s_=null)}d_(){this.o_&&(this.o_.cancel(),this.o_=null)}async close(e,t){this.E_(),this.d_(),this.a_.cancel(),this.i_++,e!==4?this.a_.reset():t&&t.code===D.RESOURCE_EXHAUSTED?(At(t.toString()),At("Using maximum backoff delay to prevent overloading the backend."),this.a_.Zo()):t&&t.code===D.UNAUTHENTICATED&&this.state!==3&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),this.stream!==null&&(this.A_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Lo(t)}A_(){}auth(){this.state=1;let e=this.R_(this.i_),t=this.i_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([n,s])=>{this.i_===t&&this.V_(n,s)},n=>{e(()=>{let s=new L(D.UNKNOWN,"Fetching auth token failed: "+n.message);return this.m_(s)})})}V_(e,t){let n=this.R_(this.i_);this.stream=this.f_(e,t),this.stream.xo(()=>{n(()=>this.listener.xo())}),this.stream.No(()=>{n(()=>(this.state=2,this.o_=this.Ti.enqueueAfterDelay(this.r_,1e4,()=>(this.c_()&&(this.state=3),Promise.resolve())),this.listener.No()))}),this.stream.Lo(s=>{n(()=>this.m_(s))}),this.stream.onMessage(s=>{n(()=>++this.__==1?this.g_(s):this.onNext(s))})}l_(){this.state=5,this.a_.Xo(async()=>{this.state=0,this.start()})}m_(e){return V(mg,`close with error: ${e}`),this.stream=null,this.close(4,e)}R_(e){return t=>{this.Ti.enqueueAndForget(()=>this.i_===e?t():(V(mg,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}},al=class extends qo{constructor(e,t,n,s,i,a){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,s,a),this.serializer=i}f_(e,t){return this.connection.Wo("Listen",e,t)}g_(e){return this.onNext(e)}onNext(e){this.a_.reset();let t=zS(this.serializer,e),n=function(i){if(!("targetChange"in i))return q.min();let a=i.targetChange;return a.targetIds&&a.targetIds.length?q.min():a.readTime?st(a.readTime):q.min()}(e);return this.listener.p_(t,n)}y_(e){let t={};t.database=kc(this.serializer),t.addTarget=function(i,a){let u,c=a.target;if(u=yc(c)?{documents:HS(i,c)}:{query:WS(i,c).ht},u.targetId=a.targetId,a.resumeToken.approximateByteSize()>0){u.resumeToken=my(i,a.resumeToken);let h=Rc(i,a.expectedCount);h!==null&&(u.expectedCount=h)}else if(a.snapshotVersion.compareTo(q.min())>0){u.readTime=Lo(i,a.snapshotVersion.toTimestamp());let h=Rc(i,a.expectedCount);h!==null&&(u.expectedCount=h)}return u}(this.serializer,e);let n=JS(this.serializer,e);n&&(t.labels=n),this.I_(t)}w_(e){let t={};t.database=kc(this.serializer),t.removeTarget=e,this.I_(t)}},ul=class extends qo{constructor(e,t,n,s,i,a){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,s,a),this.serializer=i}get S_(){return this.__>0}start(){this.lastStreamToken=void 0,super.start()}A_(){this.S_&&this.b_([])}f_(e,t){return this.connection.Wo("Write",e,t)}g_(e){return ee(!!e.streamToken),this.lastStreamToken=e.streamToken,ee(!e.writeResults||e.writeResults.length===0),this.listener.D_()}onNext(e){ee(!!e.streamToken),this.lastStreamToken=e.streamToken,this.a_.reset();let t=KS(e.writeResults,e.commitTime),n=st(e.commitTime);return this.listener.v_(n,t)}C_(){let e={};e.database=kc(this.serializer),this.I_(e)}b_(e){let t={streamToken:this.lastStreamToken,writes:e.map(n=>GS(this.serializer,n))};this.I_(t)}};var cl=class{},ll=class extends cl{constructor(e,t,n,s){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=s,this.F_=!1}M_(){if(this.F_)throw new L(D.FAILED_PRECONDITION,"The client has already been terminated.")}So(e,t,n,s){return this.M_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,a])=>this.connection.So(e,Pc(t,n),s,i,a)).catch(i=>{throw i.name==="FirebaseError"?(i.code===D.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),i):new L(D.UNKNOWN,i.toString())})}Co(e,t,n,s,i){return this.M_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([a,u])=>this.connection.Co(e,Pc(t,n),s,a,u,i)).catch(a=>{throw a.name==="FirebaseError"?(a.code===D.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),a):new L(D.UNKNOWN,a.toString())})}terminate(){this.F_=!0,this.connection.terminate()}},hl=class{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.x_=0,this.O_=null,this.N_=!0}B_(){this.x_===0&&(this.L_("Unknown"),this.O_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.O_=null,this.k_("Backend didn't respond within 10 seconds."),this.L_("Offline"),Promise.resolve())))}q_(e){this.state==="Online"?this.L_("Unknown"):(this.x_++,this.x_>=1&&(this.Q_(),this.k_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.L_("Offline")))}set(e){this.Q_(),this.x_=0,e==="Online"&&(this.N_=!1),this.L_(e)}L_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}k_(e){let t=`Could not reach Cloud Firestore backend. ${e}
18
- This 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.N_?(At(t),this.N_=!1):V("OnlineStateTracker",t)}Q_(){this.O_!==null&&(this.O_.cancel(),this.O_=null)}};var Tr="RemoteStore",dl=class{constructor(e,t,n,s,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.U_=[],this.K_=new Map,this.W_=new Set,this.G_=[],this.z_=i,this.z_.To(a=>{n.enqueueAndForget(async()=>{Er(this)&&(V(Tr,"Restarting streams for network reachability change."),await async function(c){let h=$(c);h.W_.add(4),await Hs(h),h.j_.set("Unknown"),h.W_.delete(4),await da(h)}(this))})}),this.j_=new hl(n,s)}};async function da(r){if(Er(r))for(let e of r.G_)await e(!0)}async function Hs(r){for(let e of r.G_)await e(!1)}function Ay(r,e){let t=$(r);t.K_.has(e.targetId)||(t.K_.set(e.targetId,e),Kl(t)?Gl(t):Mn(t).c_()&&zl(t,e))}function ql(r,e){let t=$(r),n=Mn(t);t.K_.delete(e),n.c_()&&xy(t,e),t.K_.size===0&&(n.c_()?n.P_():Er(t)&&t.j_.set("Unknown"))}function zl(r,e){if(r.H_.Ne(e.targetId),e.resumeToken.approximateByteSize()>0||e.snapshotVersion.compareTo(q.min())>0){let t=r.remoteSyncer.getRemoteKeysForTarget(e.targetId).size;e=e.withExpectedCount(t)}Mn(r).y_(e)}function xy(r,e){r.H_.Ne(e),Mn(r).w_(e)}function Gl(r){r.H_=new xc({getRemoteKeysForTarget:e=>r.remoteSyncer.getRemoteKeysForTarget(e),lt:e=>r.K_.get(e)||null,it:()=>r.datastore.serializer.databaseId}),Mn(r).start(),r.j_.B_()}function Kl(r){return Er(r)&&!Mn(r).u_()&&r.K_.size>0}function Er(r){return $(r).W_.size===0}function Sy(r){r.H_=void 0}async function fR(r){r.j_.set("Online")}async function pR(r){r.K_.forEach((e,t)=>{zl(r,e)})}async function mR(r,e){Sy(r),Kl(r)?(r.j_.q_(e),Gl(r)):r.j_.set("Unknown")}async function gR(r,e,t){if(r.j_.set("Online"),e instanceof No&&e.state===2&&e.cause)try{await async function(s,i){let a=i.cause;for(let u of i.targetIds)s.K_.has(u)&&(await s.remoteSyncer.rejectListen(u,a),s.K_.delete(u),s.H_.removeTarget(u))}(r,e)}catch(n){V(Tr,"Failed to remove targets %s: %s ",e.targetIds.join(","),n),await zo(r,n)}else if(e instanceof yn?r.H_.We(e):e instanceof Oo?r.H_.Ze(e):r.H_.je(e),!t.isEqual(q.min()))try{let n=await Iy(r.localStore);t.compareTo(n)>=0&&await function(i,a){let u=i.H_.ot(a);return u.targetChanges.forEach((c,h)=>{if(c.resumeToken.approximateByteSize()>0){let f=i.K_.get(h);f&&i.K_.set(h,f.withResumeToken(c.resumeToken,a))}}),u.targetMismatches.forEach((c,h)=>{let f=i.K_.get(c);if(!f)return;i.K_.set(c,f.withResumeToken(Re.EMPTY_BYTE_STRING,f.snapshotVersion)),xy(i,c);let m=new Fs(f.target,c,h,f.sequenceNumber);zl(i,m)}),i.remoteSyncer.applyRemoteEvent(u)}(r,t)}catch(n){V(Tr,"Failed to raise snapshot:",n),await zo(r,n)}}async function zo(r,e,t){if(!Fn(e))throw e;r.W_.add(1),await Hs(r),r.j_.set("Offline"),t||(t=()=>Iy(r.localStore)),r.asyncQueue.enqueueRetryable(async()=>{V(Tr,"Retrying IndexedDB access"),await t(),r.W_.delete(1),await da(r)})}function Ry(r,e){return e().catch(t=>zo(r,t,e))}async function fa(r){let e=$(r),t=er(e),n=e.U_.length>0?e.U_[e.U_.length-1].batchId:Ol;for(;yR(e);)try{let s=await cR(e.localStore,n);if(s===null){e.U_.length===0&&t.P_();break}n=s.batchId,_R(e,s)}catch(s){await zo(e,s)}Py(e)&&Cy(e)}function yR(r){return Er(r)&&r.U_.length<10}function _R(r,e){r.U_.push(e);let t=er(r);t.c_()&&t.S_&&t.b_(e.mutations)}function Py(r){return Er(r)&&!er(r).u_()&&r.U_.length>0}function Cy(r){er(r).start()}async function vR(r){er(r).C_()}async function wR(r){let e=er(r);for(let t of r.U_)e.b_(t.mutations)}async function bR(r,e,t){let n=r.U_.shift(),s=Tc.from(n,e,t);await Ry(r,()=>r.remoteSyncer.applySuccessfulWrite(s)),await fa(r)}async function TR(r,e){e&&er(r).S_&&await async function(n,s){if(function(a){return FS(a)&&a!==D.ABORTED}(s.code)){let i=n.U_.shift();er(n).h_(),await Ry(n,()=>n.remoteSyncer.rejectFailedWrite(i.batchId,s)),await fa(n)}}(r,e),Py(r)&&Cy(r)}async function gg(r,e){let t=$(r);t.asyncQueue.verifyOperationInProgress(),V(Tr,"RemoteStore received new credentials");let n=Er(t);t.W_.add(3),await Hs(t),n&&t.j_.set("Unknown"),await t.remoteSyncer.handleCredentialChange(e),t.W_.delete(3),await da(t)}async function ER(r,e){let t=$(r);e?(t.W_.delete(2),await da(t)):e||(t.W_.add(2),await Hs(t),t.j_.set("Unknown"))}function Mn(r){return r.J_||(r.J_=function(t,n,s){let i=$(t);return i.M_(),new al(n,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)}(r.datastore,r.asyncQueue,{xo:fR.bind(null,r),No:pR.bind(null,r),Lo:mR.bind(null,r),p_:gR.bind(null,r)}),r.G_.push(async e=>{e?(r.J_.h_(),Kl(r)?Gl(r):r.j_.set("Unknown")):(await r.J_.stop(),Sy(r))})),r.J_}function er(r){return r.Y_||(r.Y_=function(t,n,s){let i=$(t);return i.M_(),new ul(n,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)}(r.datastore,r.asyncQueue,{xo:()=>Promise.resolve(),No:vR.bind(null,r),Lo:TR.bind(null,r),D_:wR.bind(null,r),v_:bR.bind(null,r)}),r.G_.push(async e=>{e?(r.Y_.h_(),await fa(r)):(await r.Y_.stop(),r.U_.length>0&&(V(Tr,`Stopping write stream with ${r.U_.length} pending writes`),r.U_=[]))})),r.Y_}var fl=class r{constructor(e,t,n,s,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=s,this.removalCallback=i,this.deferred=new tt,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(a=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,s,i){let a=Date.now()+n,u=new r(e,t,a,s,i);return u.start(n),u}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){this.timerHandle!==null&&(this.clearTimeout(),this.deferred.reject(new L(D.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>this.timerHandle!==null?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){this.timerHandle!==null&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}};function Hl(r,e){if(At("AsyncQueue",`${e}: ${r}`),Fn(r))return new L(D.UNAVAILABLE,`${e}: ${r}`);throw r}var Go=class r{static emptySet(e){return new r(e.comparator)}constructor(e){this.comparator=e?(t,n)=>e(t,n)||j.comparator(t.key,n.key):(t,n)=>j.comparator(t.key,n.key),this.keyedMap=Ss(),this.sortedSet=new ce(this.comparator)}has(e){return this.keyedMap.get(e)!=null}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){let t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal((t,n)=>(e(t),!1))}add(e){let t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){let t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof r)||this.size!==e.size)return!1;let t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){let s=t.getNext().key,i=n.getNext().key;if(!s.isEqual(i))return!1}return!0}toString(){let e=[];return this.forEach(t=>{e.push(t.toString())}),e.length===0?"DocumentSet ()":`DocumentSet (
17
+ Total Duration: ${h-f}ms`),k.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:m})))}};function nR(r,e){return new Fc(r,e)}var Mc=class{constructor(){this.changes=new Rt(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Je.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let n=this.changes.get(t);return n!==void 0?k.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}};var jc=class{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}};var Uc=class{constructor(e,t,n,s){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=s}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next(s=>(n=s,this.remoteDocumentCache.getEntry(e,t))).next(s=>(n!==null&&ks(n.mutation,s,qe.empty(),we.now()),s))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(n=>this.getLocalViewOfDocuments(e,n,W()).next(()=>n))}getLocalViewOfDocuments(e,t,n=W()){let s=pr();return this.populateOverlays(e,s,t).next(()=>this.computeViews(e,t,s,n).next(i=>{let a=Ss();return i.forEach((u,c)=>{a=a.insert(u,c.overlayedDocument)}),a}))}getOverlayedDocuments(e,t){let n=pr();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,W()))}populateOverlays(e,t,n){let s=[];return n.forEach(i=>{t.has(i)||s.push(i)}),this.documentOverlayCache.getOverlays(e,s).next(i=>{i.forEach((a,u)=>{t.set(a,u)})})}computeViews(e,t,n,s){let i=Pt(),a=Cs(),u=function(){return Cs()}();return t.forEach((c,h)=>{let f=n.get(h.key);s.has(h.key)&&(f===void 0||f.mutation instanceof ut)?i=i.insert(h.key,h):f!==void 0?(a.set(h.key,f.mutation.getFieldMask()),ks(f.mutation,h,f.mutation.getFieldMask(),we.now())):a.set(h.key,qe.empty())}),this.recalculateAndSaveOverlays(e,i).next(c=>(c.forEach((h,f)=>a.set(h,f)),t.forEach((h,f)=>{var m;return u.set(h,new jc(f,(m=a.get(h))!==null&&m!==void 0?m:null))}),u))}recalculateAndSaveOverlays(e,t){let n=Cs(),s=new ce((a,u)=>a-u),i=W();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(a=>{for(let u of a)u.keys().forEach(c=>{let h=t.get(c);if(h===null)return;let f=n.get(c)||qe.empty();f=u.applyToLocalView(h,f),n.set(c,f);let m=(s.get(u.batchId)||W()).add(c);s=s.insert(u.batchId,m)})}).next(()=>{let a=[],u=s.getReverseIterator();for(;u.hasNext();){let c=u.getNext(),h=c.key,f=c.value,m=oy();f.forEach(g=>{if(!i.has(g)){let b=dy(t.get(g),n.get(g));b!==null&&m.set(g,b),i=i.add(g)}}),a.push(this.documentOverlayCache.saveOverlays(e,h,m))}return k.waitFor(a)}).next(()=>n)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(n=>this.recalculateAndSaveOverlays(e,n))}getDocumentsMatchingQuery(e,t,n,s){return function(a){return j.isDocumentKey(a.path)&&a.collectionGroup===null&&a.filters.length===0}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):TS(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,s):this.getDocumentsMatchingCollectionQuery(e,t,n,s)}getNextDocuments(e,t,n,s){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,s).next(i=>{let a=s-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,s-i.size):k.resolve(pr()),u=Ds,c=i;return a.next(h=>k.forEach(h,(f,m)=>(u<m.largestBatchId&&(u=m.largestBatchId),i.get(f)?k.resolve():this.remoteDocumentCache.getEntry(e,f).next(g=>{c=c.insert(f,g)}))).next(()=>this.populateOverlays(e,h,i)).next(()=>this.computeViews(e,c,h,W())).next(f=>({batchId:u,changes:iy(f)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new j(t)).next(n=>{let s=Ss();return n.isFoundDocument()&&(s=s.insert(n.key,n)),s})}getDocumentsMatchingCollectionGroupQuery(e,t,n,s){let i=t.collectionGroup,a=Ss();return this.indexManager.getCollectionParents(e,i).next(u=>k.forEach(u,c=>{let h=function(m,g){return new Sn(g,null,m.explicitOrderBy.slice(),m.filters.slice(),m.limit,m.limitType,m.startAt,m.endAt)}(t,c.child(i));return this.getDocumentsMatchingCollectionQuery(e,h,n,s).next(f=>{f.forEach((m,g)=>{a=a.insert(m,g)})})}).next(()=>a))}getDocumentsMatchingCollectionQuery(e,t,n,s){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next(a=>(i=a,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,s))).next(a=>{i.forEach((c,h)=>{let f=h.getKey();a.get(f)===null&&(a=a.insert(f,Je.newInvalidDocument(f)))});let u=Ss();return a.forEach((c,h)=>{let f=i.get(c);f!==void 0&&ks(f.mutation,h,qe.empty(),we.now()),ca(t,h)&&(u=u.insert(c,h))}),u})}};var Bc=class{constructor(e){this.serializer=e,this.dr=new Map,this.Ar=new Map}getBundleMetadata(e,t){return k.resolve(this.dr.get(t))}saveBundleMetadata(e,t){return this.dr.set(t.id,function(s){return{id:s.id,version:s.version,createTime:st(s.createTime)}}(t)),k.resolve()}getNamedQuery(e,t){return k.resolve(this.Ar.get(t))}saveNamedQuery(e,t){return this.Ar.set(t.name,function(s){return{name:s.name,query:tR(s.bundledQuery),readTime:st(s.readTime)}}(t)),k.resolve()}};var $c=class{constructor(){this.overlays=new ce(j.comparator),this.Rr=new Map}getOverlay(e,t){return k.resolve(this.overlays.get(t))}getOverlays(e,t){let n=pr();return k.forEach(t,s=>this.getOverlay(e,s).next(i=>{i!==null&&n.set(s,i)})).next(()=>n)}saveOverlays(e,t,n){return n.forEach((s,i)=>{this.Et(e,t,i)}),k.resolve()}removeOverlaysForBatchId(e,t,n){let s=this.Rr.get(n);return s!==void 0&&(s.forEach(i=>this.overlays=this.overlays.remove(i)),this.Rr.delete(n)),k.resolve()}getOverlaysForCollection(e,t,n){let s=pr(),i=t.length+1,a=new j(t.child("")),u=this.overlays.getIteratorFrom(a);for(;u.hasNext();){let c=u.getNext().value,h=c.getKey();if(!t.isPrefixOf(h.path))break;h.path.length===i&&c.largestBatchId>n&&s.set(c.getKey(),c)}return k.resolve(s)}getOverlaysForCollectionGroup(e,t,n,s){let i=new ce((h,f)=>h-f),a=this.overlays.getIterator();for(;a.hasNext();){let h=a.getNext().value;if(h.getKey().getCollectionGroup()===t&&h.largestBatchId>n){let f=i.get(h.largestBatchId);f===null&&(f=pr(),i=i.insert(h.largestBatchId,f)),f.set(h.getKey(),h)}}let u=pr(),c=i.getIterator();for(;c.hasNext()&&(c.getNext().value.forEach((h,f)=>u.set(h,f)),!(u.size()>=s)););return k.resolve(u)}Et(e,t,n){let s=this.overlays.get(n.key);if(s!==null){let a=this.Rr.get(s.largestBatchId).delete(n.key);this.Rr.set(s.largestBatchId,a)}this.overlays=this.overlays.insert(n.key,new Ec(t,n));let i=this.Rr.get(t);i===void 0&&(i=W(),this.Rr.set(t,i)),this.Rr.set(t,i.add(n.key))}};var qc=class{constructor(){this.sessionToken=Re.EMPTY_BYTE_STRING}getSessionToken(e){return k.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,k.resolve()}};var js=class{constructor(){this.Vr=new _e(de.mr),this.gr=new _e(de.pr)}isEmpty(){return this.Vr.isEmpty()}addReference(e,t){let n=new de(e,t);this.Vr=this.Vr.add(n),this.gr=this.gr.add(n)}yr(e,t){e.forEach(n=>this.addReference(n,t))}removeReference(e,t){this.wr(new de(e,t))}Sr(e,t){e.forEach(n=>this.removeReference(n,t))}br(e){let t=new j(new fe([])),n=new de(t,e),s=new de(t,e+1),i=[];return this.gr.forEachInRange([n,s],a=>{this.wr(a),i.push(a.key)}),i}Dr(){this.Vr.forEach(e=>this.wr(e))}wr(e){this.Vr=this.Vr.delete(e),this.gr=this.gr.delete(e)}vr(e){let t=new j(new fe([])),n=new de(t,e),s=new de(t,e+1),i=W();return this.gr.forEachInRange([n,s],a=>{i=i.add(a.key)}),i}containsKey(e){let t=new de(e,0),n=this.Vr.firstAfterOrEqual(t);return n!==null&&e.isEqual(n.key)}},de=class{constructor(e,t){this.key=e,this.Cr=t}static mr(e,t){return j.comparator(e.key,t.key)||K(e.Cr,t.Cr)}static pr(e,t){return K(e.Cr,t.Cr)||j.comparator(e.key,t.key)}};var zc=class{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Fr=1,this.Mr=new _e(de.mr)}checkEmpty(e){return k.resolve(this.mutationQueue.length===0)}addMutationBatch(e,t,n,s){let i=this.Fr;this.Fr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let a=new bc(i,t,n,s);this.mutationQueue.push(a);for(let u of s)this.Mr=this.Mr.add(new de(u.key,i)),this.indexManager.addToCollectionParentIndex(e,u.key.path.popLast());return k.resolve(a)}lookupMutationBatch(e,t){return k.resolve(this.Or(t))}getNextMutationBatchAfterBatchId(e,t){let n=t+1,s=this.Nr(n),i=s<0?0:s;return k.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return k.resolve(this.mutationQueue.length===0?Ol:this.Fr-1)}getAllMutationBatches(e){return k.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new de(t,0),s=new de(t,Number.POSITIVE_INFINITY),i=[];return this.Mr.forEachInRange([n,s],a=>{let u=this.Or(a.Cr);i.push(u)}),k.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new _e(K);return t.forEach(s=>{let i=new de(s,0),a=new de(s,Number.POSITIVE_INFINITY);this.Mr.forEachInRange([i,a],u=>{n=n.add(u.Cr)})}),k.resolve(this.Br(n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,s=n.length+1,i=n;j.isDocumentKey(i)||(i=i.child(""));let a=new de(new j(i),0),u=new _e(K);return this.Mr.forEachWhile(c=>{let h=c.key.path;return!!n.isPrefixOf(h)&&(h.length===s&&(u=u.add(c.Cr)),!0)},a),k.resolve(this.Br(u))}Br(e){let t=[];return e.forEach(n=>{let s=this.Or(n);s!==null&&t.push(s)}),t}removeMutationBatch(e,t){ee(this.Lr(t.batchId,"removed")===0),this.mutationQueue.shift();let n=this.Mr;return k.forEach(t.mutations,s=>{let i=new de(s.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,s.key)}).next(()=>{this.Mr=n})}qn(e){}containsKey(e,t){let n=new de(t,0),s=this.Mr.firstAfterOrEqual(n);return k.resolve(t.isEqual(s&&s.key))}performConsistencyCheck(e){return this.mutationQueue.length,k.resolve()}Lr(e,t){return this.Nr(e)}Nr(e){return this.mutationQueue.length===0?0:e-this.mutationQueue[0].batchId}Or(e){let t=this.Nr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}};var Gc=class{constructor(e){this.kr=e,this.docs=function(){return new ce(j.comparator)}(),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){let n=t.key,s=this.docs.get(n),i=s?s.size:0,a=this.kr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:a}),this.size+=a-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){let t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){let n=this.docs.get(t);return k.resolve(n?n.document.mutableCopy():Je.newInvalidDocument(t))}getEntries(e,t){let n=Pt();return t.forEach(s=>{let i=this.docs.get(s);n=n.insert(s,i?i.document.mutableCopy():Je.newInvalidDocument(s))}),k.resolve(n)}getDocumentsMatchingQuery(e,t,n,s){let i=Pt(),a=t.path,u=new j(a.child("__id-9223372036854775808__")),c=this.docs.getIteratorFrom(u);for(;c.hasNext();){let{key:h,value:{document:f}}=c.getNext();if(!a.isPrefixOf(h.path))break;h.path.length>a.length+1||rS(tS(f),n)<=0||(s.has(f.key)||ca(t,f))&&(i=i.insert(f.key,f.mutableCopy()))}return k.resolve(i)}getAllFromCollectionGroup(e,t,n,s){M()}qr(e,t){return k.forEach(this.docs,n=>t(n))}newChangeBuffer(e){return new Kc(this)}getSize(e){return k.resolve(this.size)}},Kc=class extends Mc{constructor(e){super(),this.Ir=e}applyChanges(e){let t=[];return this.changes.forEach((n,s)=>{s.isValidDocument()?t.push(this.Ir.addEntry(e,s)):this.Ir.removeEntry(n)}),k.waitFor(t)}getFromCache(e,t){return this.Ir.getEntry(e,t)}getAllFromCache(e,t){return this.Ir.getEntries(e,t)}};var Hc=class{constructor(e){this.persistence=e,this.Qr=new Rt(t=>Ml(t),jl),this.lastRemoteSnapshotVersion=q.min(),this.highestTargetId=0,this.$r=0,this.Ur=new js,this.targetCount=0,this.Kr=Ms.Un()}forEachTarget(e,t){return this.Qr.forEach((n,s)=>t(s)),k.resolve()}getLastRemoteSnapshotVersion(e){return k.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return k.resolve(this.$r)}allocateTargetId(e){return this.highestTargetId=this.Kr.next(),k.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.$r&&(this.$r=t),k.resolve()}zn(e){this.Qr.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this.Kr=new Ms(t),this.highestTargetId=t),e.sequenceNumber>this.$r&&(this.$r=e.sequenceNumber)}addTargetData(e,t){return this.zn(t),this.targetCount+=1,k.resolve()}updateTargetData(e,t){return this.zn(t),k.resolve()}removeTargetData(e,t){return this.Qr.delete(t.target),this.Ur.br(t.targetId),this.targetCount-=1,k.resolve()}removeTargets(e,t,n){let s=0,i=[];return this.Qr.forEach((a,u)=>{u.sequenceNumber<=t&&n.get(u.targetId)===null&&(this.Qr.delete(a),i.push(this.removeMatchingKeysForTargetId(e,u.targetId)),s++)}),k.waitFor(i).next(()=>s)}getTargetCount(e){return k.resolve(this.targetCount)}getTargetData(e,t){let n=this.Qr.get(t)||null;return k.resolve(n)}addMatchingKeys(e,t,n){return this.Ur.yr(t,n),k.resolve()}removeMatchingKeys(e,t,n){this.Ur.Sr(t,n);let s=this.persistence.referenceDelegate,i=[];return s&&t.forEach(a=>{i.push(s.markPotentiallyOrphaned(e,a))}),k.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Ur.br(t),k.resolve()}getMatchingKeysForTargetId(e,t){let n=this.Ur.vr(t);return k.resolve(n)}containsKey(e,t){return k.resolve(this.Ur.containsKey(t))}};var Fo=class{constructor(e,t){this.Wr={},this.overlays={},this.Gr=new bn(0),this.zr=!1,this.zr=!0,this.jr=new qc,this.referenceDelegate=e(this),this.Hr=new Hc(this),this.indexManager=new Oc,this.remoteDocumentCache=function(s){return new Gc(s)}(n=>this.referenceDelegate.Jr(n)),this.serializer=new Dc(t),this.Yr=new Bc(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.zr=!1,Promise.resolve()}get started(){return this.zr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new $c,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Wr[e.toKey()];return n||(n=new zc(t,this.referenceDelegate),this.Wr[e.toKey()]=n),n}getGlobalsCache(){return this.jr}getTargetCache(){return this.Hr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Yr}runTransaction(e,t,n){V("MemoryPersistence","Starting transaction:",e);let s=new Wc(this.Gr.next());return this.referenceDelegate.Zr(),n(s).next(i=>this.referenceDelegate.Xr(s).next(()=>i)).toPromise().then(i=>(s.raiseOnCommittedEvent(),i))}ei(e,t){return k.or(Object.values(this.Wr).map(n=>()=>n.containsKey(e,t)))}},Wc=class extends sc{constructor(e){super(),this.currentSequenceNumber=e}},Qc=class r{constructor(e){this.persistence=e,this.ti=new js,this.ni=null}static ri(e){return new r(e)}get ii(){if(this.ni)return this.ni;throw M()}addReference(e,t,n){return this.ti.addReference(n,t),this.ii.delete(n.toString()),k.resolve()}removeReference(e,t,n){return this.ti.removeReference(n,t),this.ii.add(n.toString()),k.resolve()}markPotentiallyOrphaned(e,t){return this.ii.add(t.toString()),k.resolve()}removeTarget(e,t){this.ti.br(t.targetId).forEach(s=>this.ii.add(s.toString()));let n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(s=>{s.forEach(i=>this.ii.add(i.toString()))}).next(()=>n.removeTargetData(e,t))}Zr(){this.ni=new Set}Xr(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return k.forEach(this.ii,n=>{let s=j.fromPath(n);return this.si(e,s).next(i=>{i||t.removeEntry(s,q.min())})}).next(()=>(this.ni=null,t.apply(e)))}updateLimboDocument(e,t){return this.si(e,t).next(n=>{n?this.ii.delete(t.toString()):this.ii.add(t.toString())})}Jr(e){return 0}si(e,t){return k.or([()=>k.resolve(this.ti.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.ei(e,t)])}},Mo=class r{constructor(e,t){this.persistence=e,this.oi=new Rt(n=>oS(n.path),(n,s)=>n.isEqual(s)),this.garbageCollector=nR(this,t)}static ri(e,t){return new r(e,t)}Zr(){}Xr(e){return k.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}nr(e){let t=this.sr(e);return this.persistence.getTargetCache().getTargetCount(e).next(n=>t.next(s=>n+s))}sr(e){let t=0;return this.rr(e,n=>{t++}).next(()=>t)}rr(e,t){return k.forEach(this.oi,(n,s)=>this.ar(e,n,s).next(i=>i?k.resolve():t(s)))}removeTargets(e,t,n){return this.persistence.getTargetCache().removeTargets(e,t,n)}removeOrphanedDocuments(e,t){let n=0,s=this.persistence.getRemoteDocumentCache(),i=s.newChangeBuffer();return s.qr(e,a=>this.ar(e,a,t).next(u=>{u||(n++,i.removeEntry(a,q.min()))})).next(()=>i.apply(e)).next(()=>n)}markPotentiallyOrphaned(e,t){return this.oi.set(t,e.currentSequenceNumber),k.resolve()}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,n)}addReference(e,t,n){return this.oi.set(n,e.currentSequenceNumber),k.resolve()}removeReference(e,t,n){return this.oi.set(n,e.currentSequenceNumber),k.resolve()}updateLimboDocument(e,t){return this.oi.set(t,e.currentSequenceNumber),k.resolve()}Jr(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=_o(e.data.value)),t}ar(e,t,n){return k.or([()=>this.persistence.ei(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let s=this.oi.get(t);return k.resolve(s!==void 0&&s>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}};var Jc=class r{constructor(e,t,n,s){this.targetId=e,this.fromCache=t,this.Hi=n,this.Ji=s}static Yi(e,t){let n=W(),s=W();for(let i of t.docChanges)switch(i.type){case 0:n=n.add(i.doc.key);break;case 1:s=s.add(i.doc.key)}return new r(e,t.fromCache,n,s)}};var Yc=class{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}};var Xc=class{constructor(){this.Zi=!1,this.Xi=!1,this.es=100,this.ts=function(){return ym()?8:sS(gm())>0?6:4}()}initialize(e,t){this.ns=e,this.indexManager=t,this.Zi=!0}getDocumentsMatchingQuery(e,t,n,s){let i={result:null};return this.rs(e,t).next(a=>{i.result=a}).next(()=>{if(!i.result)return this.ss(e,t,s,n).next(a=>{i.result=a})}).next(()=>{if(i.result)return;let a=new Yc;return this._s(e,t,a).next(u=>{if(i.result=u,this.Xi)return this.us(e,t,a,u.size)})}).next(()=>i.result)}us(e,t,n,s){return n.documentReadCount<this.es?(dn()<=Q.DEBUG&&V("QueryEngine","SDK will not create cache indexes for query:",fn(t),"since it only creates cache indexes for collection contains","more than or equal to",this.es,"documents"),k.resolve()):(dn()<=Q.DEBUG&&V("QueryEngine","Query:",fn(t),"scans",n.documentReadCount,"local documents and returns",s,"documents as results."),n.documentReadCount>this.ts*s?(dn()<=Q.DEBUG&&V("QueryEngine","The SDK decides to create cache indexes for query:",fn(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,nt(t))):k.resolve())}rs(e,t){if(eg(t))return k.resolve(null);let n=nt(t);return this.indexManager.getIndexType(e,n).next(s=>s===0?null:(t.limit!==null&&s===1&&(t=_c(t,null,"F"),n=nt(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next(i=>{let a=W(...i);return this.ns.getDocuments(e,a).next(u=>this.indexManager.getMinOffset(e,n).next(c=>{let h=this.cs(t,u);return this.ls(t,h,a,c.readTime)?this.rs(e,_c(t,null,"F")):this.hs(e,h,t,c)}))})))}ss(e,t,n,s){return eg(t)||s.isEqual(q.min())?k.resolve(null):this.ns.getDocuments(e,n).next(i=>{let a=this.cs(t,i);return this.ls(t,a,n,s)?k.resolve(null):(dn()<=Q.DEBUG&&V("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),fn(t)),this.hs(e,a,t,eS(s,Ds)).next(u=>u))})}cs(e,t){let n=new _e(ny(e));return t.forEach((s,i)=>{ca(e,i)&&(n=n.add(i))}),n}ls(e,t,n,s){if(e.limit===null)return!1;if(n.size!==t.size)return!0;let i=e.limitType==="F"?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(s)>0)}_s(e,t,n){return dn()<=Q.DEBUG&&V("QueryEngine","Using full collection scan to execute query:",fn(t)),this.ns.getDocumentsMatchingQuery(e,t,_r.min(),n)}hs(e,t,n,s){return this.ns.getDocumentsMatchingQuery(e,n,s).next(i=>(t.forEach(a=>{i=i.insert(a.key,a)}),i))}};var $l="LocalStore",sR=3e8,Zc=class{constructor(e,t,n,s){this.persistence=e,this.Ps=t,this.serializer=s,this.Ts=new ce(K),this.Is=new Rt(i=>Ml(i),jl),this.Es=new Map,this.ds=e.getRemoteDocumentCache(),this.Hr=e.getTargetCache(),this.Yr=e.getBundleCache(),this.As(n)}As(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Uc(this.ds,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.ds.setIndexManager(this.indexManager),this.Ps.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.Ts))}};function iR(r,e,t,n){return new Zc(r,e,t,n)}async function Ey(r,e){let t=$(r);return await t.persistence.runTransaction("Handle user change","readonly",n=>{let s;return t.mutationQueue.getAllMutationBatches(n).next(i=>(s=i,t.As(e),t.mutationQueue.getAllMutationBatches(n))).next(i=>{let a=[],u=[],c=W();for(let h of s){a.push(h.batchId);for(let f of h.mutations)c=c.add(f.key)}for(let h of i){u.push(h.batchId);for(let f of h.mutations)c=c.add(f.key)}return t.localDocuments.getDocuments(n,c).next(h=>({Rs:h,removedBatchIds:a,addedBatchIds:u}))})})}function oR(r,e){let t=$(r);return t.persistence.runTransaction("Acknowledge batch","readwrite-primary",n=>{let s=e.batch.keys(),i=t.ds.newChangeBuffer({trackRemovals:!0});return function(u,c,h,f){let m=h.batch,g=m.keys(),b=k.resolve();return g.forEach(P=>{b=b.next(()=>f.getEntry(c,P)).next(C=>{let R=h.docVersions.get(P);ee(R!==null),C.version.compareTo(R)<0&&(m.applyToRemoteDocument(C,h),C.isValidDocument()&&(C.setReadTime(h.commitVersion),f.addEntry(C)))})}),b.next(()=>u.mutationQueue.removeMutationBatch(c,m))}(t,n,e,i).next(()=>i.apply(n)).next(()=>t.mutationQueue.performConsistencyCheck(n)).next(()=>t.documentOverlayCache.removeOverlaysForBatchId(n,s,e.batch.batchId)).next(()=>t.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(n,function(u){let c=W();for(let h=0;h<u.mutationResults.length;++h)u.mutationResults[h].transformResults.length>0&&(c=c.add(u.batch.mutations[h].key));return c}(e))).next(()=>t.localDocuments.getDocuments(n,s))})}function Iy(r){let e=$(r);return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.Hr.getLastRemoteSnapshotVersion(t))}function aR(r,e){let t=$(r),n=e.snapshotVersion,s=t.Ts;return t.persistence.runTransaction("Apply remote event","readwrite-primary",i=>{let a=t.ds.newChangeBuffer({trackRemovals:!0});s=t.Ts;let u=[];e.targetChanges.forEach((f,m)=>{let g=s.get(m);if(!g)return;u.push(t.Hr.removeMatchingKeys(i,f.removedDocuments,m).next(()=>t.Hr.addMatchingKeys(i,f.addedDocuments,m)));let b=g.withSequenceNumber(i.currentSequenceNumber);e.targetMismatches.get(m)!==null?b=b.withResumeToken(Re.EMPTY_BYTE_STRING,q.min()).withLastLimboFreeSnapshotVersion(q.min()):f.resumeToken.approximateByteSize()>0&&(b=b.withResumeToken(f.resumeToken,n)),s=s.insert(m,b),function(C,R,N){return C.resumeToken.approximateByteSize()===0||R.snapshotVersion.toMicroseconds()-C.snapshotVersion.toMicroseconds()>=sR?!0:N.addedDocuments.size+N.modifiedDocuments.size+N.removedDocuments.size>0}(g,b,f)&&u.push(t.Hr.updateTargetData(i,b))});let c=Pt(),h=W();if(e.documentUpdates.forEach(f=>{e.resolvedLimboDocuments.has(f)&&u.push(t.persistence.referenceDelegate.updateLimboDocument(i,f))}),u.push(uR(i,a,e.documentUpdates).next(f=>{c=f.Vs,h=f.fs})),!n.isEqual(q.min())){let f=t.Hr.getLastRemoteSnapshotVersion(i).next(m=>t.Hr.setTargetsMetadata(i,i.currentSequenceNumber,n));u.push(f)}return k.waitFor(u).next(()=>a.apply(i)).next(()=>t.localDocuments.getLocalViewOfDocuments(i,c,h)).next(()=>c)}).then(i=>(t.Ts=s,i))}function uR(r,e,t){let n=W(),s=W();return t.forEach(i=>n=n.add(i)),e.getEntries(r,n).next(i=>{let a=Pt();return t.forEach((u,c)=>{let h=i.get(u);c.isFoundDocument()!==h.isFoundDocument()&&(s=s.add(u)),c.isNoDocument()&&c.version.isEqual(q.min())?(e.removeEntry(u,c.readTime),a=a.insert(u,c)):!h.isValidDocument()||c.version.compareTo(h.version)>0||c.version.compareTo(h.version)===0&&h.hasPendingWrites?(e.addEntry(c),a=a.insert(u,c)):V($l,"Ignoring outdated watch update for ",u,". Current version:",h.version," Watch version:",c.version)}),{Vs:a,fs:s}})}function cR(r,e){let t=$(r);return t.persistence.runTransaction("Get next mutation batch","readonly",n=>(e===void 0&&(e=Ol),t.mutationQueue.getNextMutationBatchAfterBatchId(n,e)))}function lR(r,e){let t=$(r);return t.persistence.runTransaction("Allocate target","readwrite",n=>{let s;return t.Hr.getTargetData(n,e).next(i=>i?(s=i,k.resolve(s)):t.Hr.allocateTargetId(n).next(a=>(s=new Fs(e,a,"TargetPurposeListen",n.currentSequenceNumber),t.Hr.addTargetData(n,s).next(()=>s))))}).then(n=>{let s=t.Ts.get(n.targetId);return(s===null||n.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(t.Ts=t.Ts.insert(n.targetId,n),t.Is.set(e,n.targetId)),n})}async function el(r,e,t){let n=$(r),s=n.Ts.get(e),i=t?"readwrite":"readwrite-primary";try{t||await n.persistence.runTransaction("Release target",i,a=>n.persistence.referenceDelegate.removeTarget(a,s))}catch(a){if(!Fn(a))throw a;V($l,`Failed to update sequence numbers for target ${e}: ${a}`)}n.Ts=n.Ts.remove(e),n.Is.delete(s.target)}function fg(r,e,t){let n=$(r),s=q.min(),i=W();return n.persistence.runTransaction("Execute query","readwrite",a=>function(c,h,f){let m=$(c),g=m.Is.get(f);return g!==void 0?k.resolve(m.Ts.get(g)):m.Hr.getTargetData(h,f)}(n,a,nt(e)).next(u=>{if(u)return s=u.lastLimboFreeSnapshotVersion,n.Hr.getMatchingKeysForTargetId(a,u.targetId).next(c=>{i=c})}).next(()=>n.Ps.getDocumentsMatchingQuery(a,e,t?s:q.min(),t?i:W())).next(u=>(hR(n,IS(e),u),{documents:u,gs:i})))}function hR(r,e,t){let n=r.Es.get(e)||q.min();t.forEach((s,i)=>{i.readTime.compareTo(n)>0&&(n=i.readTime)}),r.Es.set(e,n)}var jo=class{constructor(){this.activeTargetIds=CS()}Ds(e){this.activeTargetIds=this.activeTargetIds.add(e)}vs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}bs(){let e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}};var tl=class{constructor(){this.ho=new jo,this.Po={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this.ho.Ds(e),this.Po[e]||"not-current"}updateQueryState(e,t,n){this.Po[e]=t}removeLocalQueryTarget(e){this.ho.vs(e)}isLocalQueryTarget(e){return this.ho.activeTargetIds.has(e)}clearQueryState(e){delete this.Po[e]}getAllActiveQueryTargets(){return this.ho.activeTargetIds}isActiveQueryTarget(e){return this.ho.activeTargetIds.has(e)}start(){return this.ho=new jo,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}};var rl=class{To(e){}shutdown(){}};var pg="ConnectivityMonitor",Uo=class{constructor(){this.Io=()=>this.Eo(),this.Ao=()=>this.Ro(),this.Vo=[],this.mo()}To(e){this.Vo.push(e)}shutdown(){window.removeEventListener("online",this.Io),window.removeEventListener("offline",this.Ao)}mo(){window.addEventListener("online",this.Io),window.addEventListener("offline",this.Ao)}Eo(){V(pg,"Network connectivity changed: AVAILABLE");for(let e of this.Vo)e(0)}Ro(){V(pg,"Network connectivity changed: UNAVAILABLE");for(let e of this.Vo)e(1)}static D(){return typeof window!="undefined"&&window.addEventListener!==void 0&&window.removeEventListener!==void 0}};var yo=null;function nl(){return yo===null?yo=function(){return 268435456+Math.round(2147483648*Math.random())}():yo++,"0x"+yo.toString(16)}var Hu="RestConnection",dR={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"},sl=class{get fo(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;let t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),s=encodeURIComponent(this.databaseId.database);this.po=t+"://"+e.host,this.yo=`projects/${n}/databases/${s}`,this.wo=this.databaseId.database===So?`project_id=${n}`:`project_id=${n}&database_id=${s}`}So(e,t,n,s,i){let a=nl(),u=this.bo(e,t.toUriEncodedString());V(Hu,`Sending RPC '${e}' ${a}:`,u,n);let c={"google-cloud-resource-prefix":this.yo,"x-goog-request-params":this.wo};return this.Do(c,s,i),this.vo(e,u,c,n).then(h=>(V(Hu,`Received RPC '${e}' ${a}: `,h),h),h=>{throw vn(Hu,`RPC '${e}' ${a} failed with error: `,h,"url: ",u,"request:",n),h})}Co(e,t,n,s,i,a){return this.So(e,t,n,s,i)}Do(e,t,n){e["X-Goog-Api-Client"]=function(){return"gl-js/ fire/"+Vn}(),e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach((s,i)=>e[i]=s),n&&n.headers.forEach((s,i)=>e[i]=s)}bo(e,t){let n=dR[e];return`${this.po}/v1/${t}:${n}`}terminate(){}};var il=class{constructor(e){this.Fo=e.Fo,this.Mo=e.Mo}xo(e){this.Oo=e}No(e){this.Bo=e}Lo(e){this.ko=e}onMessage(e){this.qo=e}close(){this.Mo()}send(e){this.Fo(e)}Qo(){this.Oo()}$o(){this.Bo()}Uo(e){this.ko(e)}Ko(e){this.qo(e)}};var Se="WebChannelConnection",ol=class extends sl{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}vo(e,t,n,s){let i=nl();return new Promise((a,u)=>{let c=new Bu;c.setWithCredentials(!0),c.listenOnce($u.COMPLETE,()=>{try{switch(c.getLastErrorCode()){case xs.NO_ERROR:let f=c.getResponseJson();V(Se,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(f)),a(f);break;case xs.TIMEOUT:V(Se,`RPC '${e}' ${i} timed out`),u(new L(D.DEADLINE_EXCEEDED,"Request time out"));break;case xs.HTTP_ERROR:let m=c.getStatus();if(V(Se,`RPC '${e}' ${i} failed with status:`,m,"response text:",c.getResponseText()),m>0){let g=c.getResponseJson();Array.isArray(g)&&(g=g[0]);let b=g==null?void 0:g.error;if(b&&b.status&&b.message){let P=function(R){let N=R.toLowerCase().replace(/_/g,"-");return Object.values(D).indexOf(N)>=0?N:D.UNKNOWN}(b.status);u(new L(P,b.message))}else u(new L(D.UNKNOWN,"Server responded with status "+c.getStatus()))}else u(new L(D.UNAVAILABLE,"Connection failed."));break;default:M()}}finally{V(Se,`RPC '${e}' ${i} completed.`)}});let h=JSON.stringify(s);V(Se,`RPC '${e}' ${i} sending request:`,s),c.send(t,"POST",h,n,15)})}Wo(e,t,n){let s=nl(),i=[this.po,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=Gu(),u=zu(),c={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},h=this.longPollingOptions.timeoutSeconds;h!==void 0&&(c.longPollingTimeout=Math.round(1e3*h)),this.useFetchStreams&&(c.useFetchStreams=!0),this.Do(c.initMessageHeaders,t,n),c.encodeInitMessageHeaders=!0;let f=i.join("");V(Se,`Creating RPC '${e}' stream ${s}: ${f}`,c);let m=a.createWebChannel(f,c),g=!1,b=!1,P=new il({Fo:R=>{b?V(Se,`Not sending because RPC '${e}' stream ${s} is closed:`,R):(g||(V(Se,`Opening RPC '${e}' stream ${s} transport.`),m.open(),g=!0),V(Se,`RPC '${e}' stream ${s} sending:`,R),m.send(R))},Mo:()=>m.close()}),C=(R,N,F)=>{R.listen(N,U=>{try{F(U)}catch(G){setTimeout(()=>{throw G},0)}})};return C(m,hn.EventType.OPEN,()=>{b||(V(Se,`RPC '${e}' stream ${s} transport opened.`),P.Qo())}),C(m,hn.EventType.CLOSE,()=>{b||(b=!0,V(Se,`RPC '${e}' stream ${s} transport closed`),P.Uo())}),C(m,hn.EventType.ERROR,R=>{b||(b=!0,vn(Se,`RPC '${e}' stream ${s} transport errored:`,R),P.Uo(new L(D.UNAVAILABLE,"The operation could not be completed")))}),C(m,hn.EventType.MESSAGE,R=>{var N;if(!b){let F=R.data[0];ee(!!F);let U=F,G=(U==null?void 0:U.error)||((N=U[0])===null||N===void 0?void 0:N.error);if(G){V(Se,`RPC '${e}' stream ${s} received error:`,G);let Y=G.status,B=function(w){let T=he[w];if(T!==void 0)return py(T)}(Y),E=G.message;B===void 0&&(B=D.INTERNAL,E="Unknown error status: "+Y+" with message "+G.message),b=!0,P.Uo(new L(B,E)),m.close()}else V(Se,`RPC '${e}' stream ${s} received:`,F),P.Ko(F)}}),C(u,qu.STAT_EVENT,R=>{R.stat===po.PROXY?V(Se,`RPC '${e}' stream ${s} detected buffering proxy`):R.stat===po.NOPROXY&&V(Se,`RPC '${e}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{P.$o()},0),P}};function Wu(){return typeof document!="undefined"?document:null}function la(r){return new Sc(r,!0)}var Bo=class{constructor(e,t,n=1e3,s=1.5,i=6e4){this.Ti=e,this.timerId=t,this.Go=n,this.zo=s,this.jo=i,this.Ho=0,this.Jo=null,this.Yo=Date.now(),this.reset()}reset(){this.Ho=0}Zo(){this.Ho=this.jo}Xo(e){this.cancel();let t=Math.floor(this.Ho+this.e_()),n=Math.max(0,Date.now()-this.Yo),s=Math.max(0,t-n);s>0&&V("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.Ho} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Jo=this.Ti.enqueueAfterDelay(this.timerId,s,()=>(this.Yo=Date.now(),e())),this.Ho*=this.zo,this.Ho<this.Go&&(this.Ho=this.Go),this.Ho>this.jo&&(this.Ho=this.jo)}t_(){this.Jo!==null&&(this.Jo.skipDelay(),this.Jo=null)}cancel(){this.Jo!==null&&(this.Jo.cancel(),this.Jo=null)}e_(){return(Math.random()-.5)*this.Ho}};var mg="PersistentStream",$o=class{constructor(e,t,n,s,i,a,u,c){this.Ti=e,this.n_=n,this.r_=s,this.connection=i,this.authCredentialsProvider=a,this.appCheckCredentialsProvider=u,this.listener=c,this.state=0,this.i_=0,this.s_=null,this.o_=null,this.stream=null,this.__=0,this.a_=new Bo(e,t)}u_(){return this.state===1||this.state===5||this.c_()}c_(){return this.state===2||this.state===3}start(){this.__=0,this.state!==4?this.auth():this.l_()}async stop(){this.u_()&&await this.close(0)}h_(){this.state=0,this.a_.reset()}P_(){this.c_()&&this.s_===null&&(this.s_=this.Ti.enqueueAfterDelay(this.n_,6e4,()=>this.T_()))}I_(e){this.E_(),this.stream.send(e)}async T_(){if(this.c_())return this.close(0)}E_(){this.s_&&(this.s_.cancel(),this.s_=null)}d_(){this.o_&&(this.o_.cancel(),this.o_=null)}async close(e,t){this.E_(),this.d_(),this.a_.cancel(),this.i_++,e!==4?this.a_.reset():t&&t.code===D.RESOURCE_EXHAUSTED?(At(t.toString()),At("Using maximum backoff delay to prevent overloading the backend."),this.a_.Zo()):t&&t.code===D.UNAUTHENTICATED&&this.state!==3&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),this.stream!==null&&(this.A_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Lo(t)}A_(){}auth(){this.state=1;let e=this.R_(this.i_),t=this.i_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([n,s])=>{this.i_===t&&this.V_(n,s)},n=>{e(()=>{let s=new L(D.UNKNOWN,"Fetching auth token failed: "+n.message);return this.m_(s)})})}V_(e,t){let n=this.R_(this.i_);this.stream=this.f_(e,t),this.stream.xo(()=>{n(()=>this.listener.xo())}),this.stream.No(()=>{n(()=>(this.state=2,this.o_=this.Ti.enqueueAfterDelay(this.r_,1e4,()=>(this.c_()&&(this.state=3),Promise.resolve())),this.listener.No()))}),this.stream.Lo(s=>{n(()=>this.m_(s))}),this.stream.onMessage(s=>{n(()=>++this.__==1?this.g_(s):this.onNext(s))})}l_(){this.state=5,this.a_.Xo(async()=>{this.state=0,this.start()})}m_(e){return V(mg,`close with error: ${e}`),this.stream=null,this.close(4,e)}R_(e){return t=>{this.Ti.enqueueAndForget(()=>this.i_===e?t():(V(mg,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}},al=class extends $o{constructor(e,t,n,s,i,a){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,s,a),this.serializer=i}f_(e,t){return this.connection.Wo("Listen",e,t)}g_(e){return this.onNext(e)}onNext(e){this.a_.reset();let t=zS(this.serializer,e),n=function(i){if(!("targetChange"in i))return q.min();let a=i.targetChange;return a.targetIds&&a.targetIds.length?q.min():a.readTime?st(a.readTime):q.min()}(e);return this.listener.p_(t,n)}y_(e){let t={};t.database=kc(this.serializer),t.addTarget=function(i,a){let u,c=a.target;if(u=yc(c)?{documents:HS(i,c)}:{query:WS(i,c).ht},u.targetId=a.targetId,a.resumeToken.approximateByteSize()>0){u.resumeToken=my(i,a.resumeToken);let h=Rc(i,a.expectedCount);h!==null&&(u.expectedCount=h)}else if(a.snapshotVersion.compareTo(q.min())>0){u.readTime=Vo(i,a.snapshotVersion.toTimestamp());let h=Rc(i,a.expectedCount);h!==null&&(u.expectedCount=h)}return u}(this.serializer,e);let n=JS(this.serializer,e);n&&(t.labels=n),this.I_(t)}w_(e){let t={};t.database=kc(this.serializer),t.removeTarget=e,this.I_(t)}},ul=class extends $o{constructor(e,t,n,s,i,a){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,s,a),this.serializer=i}get S_(){return this.__>0}start(){this.lastStreamToken=void 0,super.start()}A_(){this.S_&&this.b_([])}f_(e,t){return this.connection.Wo("Write",e,t)}g_(e){return ee(!!e.streamToken),this.lastStreamToken=e.streamToken,ee(!e.writeResults||e.writeResults.length===0),this.listener.D_()}onNext(e){ee(!!e.streamToken),this.lastStreamToken=e.streamToken,this.a_.reset();let t=KS(e.writeResults,e.commitTime),n=st(e.commitTime);return this.listener.v_(n,t)}C_(){let e={};e.database=kc(this.serializer),this.I_(e)}b_(e){let t={streamToken:this.lastStreamToken,writes:e.map(n=>GS(this.serializer,n))};this.I_(t)}};var cl=class{},ll=class extends cl{constructor(e,t,n,s){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=s,this.F_=!1}M_(){if(this.F_)throw new L(D.FAILED_PRECONDITION,"The client has already been terminated.")}So(e,t,n,s){return this.M_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,a])=>this.connection.So(e,Pc(t,n),s,i,a)).catch(i=>{throw i.name==="FirebaseError"?(i.code===D.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),i):new L(D.UNKNOWN,i.toString())})}Co(e,t,n,s,i){return this.M_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([a,u])=>this.connection.Co(e,Pc(t,n),s,a,u,i)).catch(a=>{throw a.name==="FirebaseError"?(a.code===D.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),a):new L(D.UNKNOWN,a.toString())})}terminate(){this.F_=!0,this.connection.terminate()}},hl=class{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.x_=0,this.O_=null,this.N_=!0}B_(){this.x_===0&&(this.L_("Unknown"),this.O_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.O_=null,this.k_("Backend didn't respond within 10 seconds."),this.L_("Offline"),Promise.resolve())))}q_(e){this.state==="Online"?this.L_("Unknown"):(this.x_++,this.x_>=1&&(this.Q_(),this.k_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.L_("Offline")))}set(e){this.Q_(),this.x_=0,e==="Online"&&(this.N_=!1),this.L_(e)}L_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}k_(e){let t=`Could not reach Cloud Firestore backend. ${e}
18
+ This 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.N_?(At(t),this.N_=!1):V("OnlineStateTracker",t)}Q_(){this.O_!==null&&(this.O_.cancel(),this.O_=null)}};var Tr="RemoteStore",dl=class{constructor(e,t,n,s,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.U_=[],this.K_=new Map,this.W_=new Set,this.G_=[],this.z_=i,this.z_.To(a=>{n.enqueueAndForget(async()=>{Er(this)&&(V(Tr,"Restarting streams for network reachability change."),await async function(c){let h=$(c);h.W_.add(4),await Hs(h),h.j_.set("Unknown"),h.W_.delete(4),await ha(h)}(this))})}),this.j_=new hl(n,s)}};async function ha(r){if(Er(r))for(let e of r.G_)await e(!0)}async function Hs(r){for(let e of r.G_)await e(!1)}function Ay(r,e){let t=$(r);t.K_.has(e.targetId)||(t.K_.set(e.targetId,e),Kl(t)?Gl(t):Mn(t).c_()&&zl(t,e))}function ql(r,e){let t=$(r),n=Mn(t);t.K_.delete(e),n.c_()&&xy(t,e),t.K_.size===0&&(n.c_()?n.P_():Er(t)&&t.j_.set("Unknown"))}function zl(r,e){if(r.H_.Ne(e.targetId),e.resumeToken.approximateByteSize()>0||e.snapshotVersion.compareTo(q.min())>0){let t=r.remoteSyncer.getRemoteKeysForTarget(e.targetId).size;e=e.withExpectedCount(t)}Mn(r).y_(e)}function xy(r,e){r.H_.Ne(e),Mn(r).w_(e)}function Gl(r){r.H_=new xc({getRemoteKeysForTarget:e=>r.remoteSyncer.getRemoteKeysForTarget(e),lt:e=>r.K_.get(e)||null,it:()=>r.datastore.serializer.databaseId}),Mn(r).start(),r.j_.B_()}function Kl(r){return Er(r)&&!Mn(r).u_()&&r.K_.size>0}function Er(r){return $(r).W_.size===0}function Sy(r){r.H_=void 0}async function fR(r){r.j_.set("Online")}async function pR(r){r.K_.forEach((e,t)=>{zl(r,e)})}async function mR(r,e){Sy(r),Kl(r)?(r.j_.q_(e),Gl(r)):r.j_.set("Unknown")}async function gR(r,e,t){if(r.j_.set("Online"),e instanceof Oo&&e.state===2&&e.cause)try{await async function(s,i){let a=i.cause;for(let u of i.targetIds)s.K_.has(u)&&(await s.remoteSyncer.rejectListen(u,a),s.K_.delete(u),s.H_.removeTarget(u))}(r,e)}catch(n){V(Tr,"Failed to remove targets %s: %s ",e.targetIds.join(","),n),await qo(r,n)}else if(e instanceof yn?r.H_.We(e):e instanceof Do?r.H_.Ze(e):r.H_.je(e),!t.isEqual(q.min()))try{let n=await Iy(r.localStore);t.compareTo(n)>=0&&await function(i,a){let u=i.H_.ot(a);return u.targetChanges.forEach((c,h)=>{if(c.resumeToken.approximateByteSize()>0){let f=i.K_.get(h);f&&i.K_.set(h,f.withResumeToken(c.resumeToken,a))}}),u.targetMismatches.forEach((c,h)=>{let f=i.K_.get(c);if(!f)return;i.K_.set(c,f.withResumeToken(Re.EMPTY_BYTE_STRING,f.snapshotVersion)),xy(i,c);let m=new Fs(f.target,c,h,f.sequenceNumber);zl(i,m)}),i.remoteSyncer.applyRemoteEvent(u)}(r,t)}catch(n){V(Tr,"Failed to raise snapshot:",n),await qo(r,n)}}async function qo(r,e,t){if(!Fn(e))throw e;r.W_.add(1),await Hs(r),r.j_.set("Offline"),t||(t=()=>Iy(r.localStore)),r.asyncQueue.enqueueRetryable(async()=>{V(Tr,"Retrying IndexedDB access"),await t(),r.W_.delete(1),await ha(r)})}function Ry(r,e){return e().catch(t=>qo(r,t,e))}async function da(r){let e=$(r),t=er(e),n=e.U_.length>0?e.U_[e.U_.length-1].batchId:Ol;for(;yR(e);)try{let s=await cR(e.localStore,n);if(s===null){e.U_.length===0&&t.P_();break}n=s.batchId,_R(e,s)}catch(s){await qo(e,s)}Py(e)&&Cy(e)}function yR(r){return Er(r)&&r.U_.length<10}function _R(r,e){r.U_.push(e);let t=er(r);t.c_()&&t.S_&&t.b_(e.mutations)}function Py(r){return Er(r)&&!er(r).u_()&&r.U_.length>0}function Cy(r){er(r).start()}async function vR(r){er(r).C_()}async function wR(r){let e=er(r);for(let t of r.U_)e.b_(t.mutations)}async function bR(r,e,t){let n=r.U_.shift(),s=Tc.from(n,e,t);await Ry(r,()=>r.remoteSyncer.applySuccessfulWrite(s)),await da(r)}async function TR(r,e){e&&er(r).S_&&await async function(n,s){if(function(a){return FS(a)&&a!==D.ABORTED}(s.code)){let i=n.U_.shift();er(n).h_(),await Ry(n,()=>n.remoteSyncer.rejectFailedWrite(i.batchId,s)),await da(n)}}(r,e),Py(r)&&Cy(r)}async function gg(r,e){let t=$(r);t.asyncQueue.verifyOperationInProgress(),V(Tr,"RemoteStore received new credentials");let n=Er(t);t.W_.add(3),await Hs(t),n&&t.j_.set("Unknown"),await t.remoteSyncer.handleCredentialChange(e),t.W_.delete(3),await ha(t)}async function ER(r,e){let t=$(r);e?(t.W_.delete(2),await ha(t)):e||(t.W_.add(2),await Hs(t),t.j_.set("Unknown"))}function Mn(r){return r.J_||(r.J_=function(t,n,s){let i=$(t);return i.M_(),new al(n,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)}(r.datastore,r.asyncQueue,{xo:fR.bind(null,r),No:pR.bind(null,r),Lo:mR.bind(null,r),p_:gR.bind(null,r)}),r.G_.push(async e=>{e?(r.J_.h_(),Kl(r)?Gl(r):r.j_.set("Unknown")):(await r.J_.stop(),Sy(r))})),r.J_}function er(r){return r.Y_||(r.Y_=function(t,n,s){let i=$(t);return i.M_(),new ul(n,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)}(r.datastore,r.asyncQueue,{xo:()=>Promise.resolve(),No:vR.bind(null,r),Lo:TR.bind(null,r),D_:wR.bind(null,r),v_:bR.bind(null,r)}),r.G_.push(async e=>{e?(r.Y_.h_(),await da(r)):(await r.Y_.stop(),r.U_.length>0&&(V(Tr,`Stopping write stream with ${r.U_.length} pending writes`),r.U_=[]))})),r.Y_}var fl=class r{constructor(e,t,n,s,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=s,this.removalCallback=i,this.deferred=new tt,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(a=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,s,i){let a=Date.now()+n,u=new r(e,t,a,s,i);return u.start(n),u}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){this.timerHandle!==null&&(this.clearTimeout(),this.deferred.reject(new L(D.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>this.timerHandle!==null?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){this.timerHandle!==null&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}};function Hl(r,e){if(At("AsyncQueue",`${e}: ${r}`),Fn(r))return new L(D.UNAVAILABLE,`${e}: ${r}`);throw r}var zo=class r{static emptySet(e){return new r(e.comparator)}constructor(e){this.comparator=e?(t,n)=>e(t,n)||j.comparator(t.key,n.key):(t,n)=>j.comparator(t.key,n.key),this.keyedMap=Ss(),this.sortedSet=new ce(this.comparator)}has(e){return this.keyedMap.get(e)!=null}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){let t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal((t,n)=>(e(t),!1))}add(e){let t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){let t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof r)||this.size!==e.size)return!1;let t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){let s=t.getNext().key,i=n.getNext().key;if(!s.isEqual(i))return!1}return!0}toString(){let e=[];return this.forEach(t=>{e.push(t.toString())}),e.length===0?"DocumentSet ()":`DocumentSet (
19
19
  `+e.join(`
20
20
  `)+`
21
- )`}copy(e,t){let n=new r;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}};var Ko=class{constructor(){this.Z_=new ce(j.comparator)}track(e){let t=e.doc.key,n=this.Z_.get(t);n?e.type!==0&&n.type===3?this.Z_=this.Z_.insert(t,e):e.type===3&&n.type!==1?this.Z_=this.Z_.insert(t,{type:n.type,doc:e.doc}):e.type===2&&n.type===2?this.Z_=this.Z_.insert(t,{type:2,doc:e.doc}):e.type===2&&n.type===0?this.Z_=this.Z_.insert(t,{type:0,doc:e.doc}):e.type===1&&n.type===0?this.Z_=this.Z_.remove(t):e.type===1&&n.type===2?this.Z_=this.Z_.insert(t,{type:1,doc:n.doc}):e.type===0&&n.type===1?this.Z_=this.Z_.insert(t,{type:2,doc:e.doc}):M():this.Z_=this.Z_.insert(t,e)}X_(){let e=[];return this.Z_.inorderTraversal((t,n)=>{e.push(n)}),e}},Dn=class r{constructor(e,t,n,s,i,a,u,c,h){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=s,this.mutatedKeys=i,this.fromCache=a,this.syncStateChanged=u,this.excludesMetadataChanges=c,this.hasCachedResults=h}static fromInitialDocuments(e,t,n,s,i){let a=[];return t.forEach(u=>{a.push({type:0,doc:u})}),new r(e,t,Go.emptySet(t),a,n,s,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&ca(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let s=0;s<t.length;s++)if(t[s].type!==n[s].type||!t[s].doc.isEqual(n[s].doc))return!1;return!0}};var pl=class{constructor(){this.ea=void 0,this.ta=[]}na(){return this.ta.some(e=>e.ra())}},ml=class{constructor(){this.queries=yg(),this.onlineState="Unknown",this.ia=new Set}terminate(){(function(t,n){let s=$(t),i=s.queries;s.queries=yg(),i.forEach((a,u)=>{for(let c of u.ta)c.onError(n)})})(this,new L(D.ABORTED,"Firestore shutting down"))}};function yg(){return new Rt(r=>ry(r),ca)}async function ky(r,e){let t=$(r),n=3,s=e.query,i=t.queries.get(s);i?!i.na()&&e.ra()&&(n=2):(i=new pl,n=e.ra()?0:1);try{switch(n){case 0:i.ea=await t.onListen(s,!0);break;case 1:i.ea=await t.onListen(s,!1);break;case 2:await t.onFirstRemoteStoreListen(s)}}catch(a){let u=Hl(a,`Initialization of query '${fn(e.query)}' failed`);return void e.onError(u)}t.queries.set(s,i),i.ta.push(e),e.sa(t.onlineState),i.ea&&e.oa(i.ea)&&Wl(t)}async function Dy(r,e){let t=$(r),n=e.query,s=3,i=t.queries.get(n);if(i){let a=i.ta.indexOf(e);a>=0&&(i.ta.splice(a,1),i.ta.length===0?s=e.ra()?0:1:!i.na()&&e.ra()&&(s=2))}switch(s){case 0:return t.queries.delete(n),t.onUnlisten(n,!0);case 1:return t.queries.delete(n),t.onUnlisten(n,!1);case 2:return t.onLastRemoteStoreUnlisten(n);default:return}}function IR(r,e){let t=$(r),n=!1;for(let s of e){let i=s.query,a=t.queries.get(i);if(a){for(let u of a.ta)u.oa(s)&&(n=!0);a.ea=s}}n&&Wl(t)}function AR(r,e,t){let n=$(r),s=n.queries.get(e);if(s)for(let i of s.ta)i.onError(t);n.queries.delete(e)}function Wl(r){r.ia.forEach(e=>{e.next()})}var gl,_g;(_g=gl||(gl={}))._a="default",_g.Cache="cache";var Ho=class{constructor(e,t,n){this.query=e,this.aa=t,this.ua=!1,this.ca=null,this.onlineState="Unknown",this.options=n||{}}oa(e){if(!this.options.includeMetadataChanges){let n=[];for(let s of e.docChanges)s.type!==3&&n.push(s);e=new Dn(e.query,e.docs,e.oldDocs,n,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.ua?this.la(e)&&(this.aa.next(e),t=!0):this.ha(e,this.onlineState)&&(this.Pa(e),t=!0),this.ca=e,t}onError(e){this.aa.error(e)}sa(e){this.onlineState=e;let t=!1;return this.ca&&!this.ua&&this.ha(this.ca,e)&&(this.Pa(this.ca),t=!0),t}ha(e,t){if(!e.fromCache||!this.ra())return!0;let n=t!=="Offline";return(!this.options.Ta||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||t==="Offline")}la(e){if(e.docChanges.length>0)return!0;let t=this.ca&&this.ca.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&this.options.includeMetadataChanges===!0}Pa(e){e=Dn.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.ua=!0,this.aa.next(e)}ra(){return this.options.source!==gl.Cache}};var Wo=class{constructor(e){this.key=e}},Qo=class{constructor(e){this.key=e}},yl=class{constructor(e,t){this.query=e,this.fa=t,this.ga=null,this.hasCachedResults=!1,this.current=!1,this.pa=W(),this.mutatedKeys=W(),this.ya=ny(e),this.wa=new Go(this.ya)}get Sa(){return this.fa}ba(e,t){let n=t?t.Da:new Ko,s=t?t.wa:this.wa,i=t?t.mutatedKeys:this.mutatedKeys,a=s,u=!1,c=this.query.limitType==="F"&&s.size===this.query.limit?s.last():null,h=this.query.limitType==="L"&&s.size===this.query.limit?s.first():null;if(e.inorderTraversal((f,m)=>{let g=s.get(f),b=la(this.query,m)?m:null,P=!!g&&this.mutatedKeys.has(g.key),C=!!b&&(b.hasLocalMutations||this.mutatedKeys.has(b.key)&&b.hasCommittedMutations),R=!1;g&&b?g.data.isEqual(b.data)?P!==C&&(n.track({type:3,doc:b}),R=!0):this.va(g,b)||(n.track({type:2,doc:b}),R=!0,(c&&this.ya(b,c)>0||h&&this.ya(b,h)<0)&&(u=!0)):!g&&b?(n.track({type:0,doc:b}),R=!0):g&&!b&&(n.track({type:1,doc:g}),R=!0,(c||h)&&(u=!0)),R&&(b?(a=a.add(b),i=C?i.add(f):i.delete(f)):(a=a.delete(f),i=i.delete(f)))}),this.query.limit!==null)for(;a.size>this.query.limit;){let f=this.query.limitType==="F"?a.last():a.first();a=a.delete(f.key),i=i.delete(f.key),n.track({type:1,doc:f})}return{wa:a,Da:n,ls:u,mutatedKeys:i}}va(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,s){let i=this.wa;this.wa=e.wa,this.mutatedKeys=e.mutatedKeys;let a=e.Da.X_();a.sort((f,m)=>function(b,P){let C=R=>{switch(R){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return M()}};return C(b)-C(P)}(f.type,m.type)||this.ya(f.doc,m.doc)),this.Ca(n),s=s!=null&&s;let u=t&&!s?this.Fa():[],c=this.pa.size===0&&this.current&&!s?1:0,h=c!==this.ga;return this.ga=c,a.length!==0||h?{snapshot:new Dn(this.query,e.wa,i,a,e.mutatedKeys,c===0,h,!1,!!n&&n.resumeToken.approximateByteSize()>0),Ma:u}:{Ma:u}}sa(e){return this.current&&e==="Offline"?(this.current=!1,this.applyChanges({wa:this.wa,Da:new Ko,mutatedKeys:this.mutatedKeys,ls:!1},!1)):{Ma:[]}}xa(e){return!this.fa.has(e)&&!!this.wa.has(e)&&!this.wa.get(e).hasLocalMutations}Ca(e){e&&(e.addedDocuments.forEach(t=>this.fa=this.fa.add(t)),e.modifiedDocuments.forEach(t=>{}),e.removedDocuments.forEach(t=>this.fa=this.fa.delete(t)),this.current=e.current)}Fa(){if(!this.current)return[];let e=this.pa;this.pa=W(),this.wa.forEach(n=>{this.xa(n.key)&&(this.pa=this.pa.add(n.key))});let t=[];return e.forEach(n=>{this.pa.has(n)||t.push(new Qo(n))}),this.pa.forEach(n=>{e.has(n)||t.push(new Wo(n))}),t}Oa(e){this.fa=e.gs,this.pa=W();let t=this.ba(e.documents);return this.applyChanges(t,!0)}Na(){return Dn.fromInitialDocuments(this.query,this.wa,this.mutatedKeys,this.ga===0,this.hasCachedResults)}},Ql="SyncEngine",_l=class{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}},vl=class{constructor(e){this.key=e,this.Ba=!1}},wl=class{constructor(e,t,n,s,i,a){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=s,this.currentUser=i,this.maxConcurrentLimboResolutions=a,this.La={},this.ka=new Rt(u=>ry(u),ca),this.qa=new Map,this.Qa=new Set,this.$a=new ce(j.comparator),this.Ua=new Map,this.Ka=new js,this.Wa={},this.Ga=new Map,this.za=Ms.Kn(),this.onlineState="Unknown",this.ja=void 0}get isPrimaryClient(){return this.ja===!0}};async function xR(r,e,t=!0){let n=My(r),s,i=n.ka.get(e);return i?(n.sharedClientState.addLocalQueryTarget(i.targetId),s=i.view.Na()):s=await Oy(n,e,t,!0),s}async function SR(r,e){let t=My(r);await Oy(t,e,!0,!1)}async function Oy(r,e,t,n){let s=await lR(r.localStore,nt(e)),i=s.targetId,a=r.sharedClientState.addLocalQueryTarget(i,t),u;return n&&(u=await RR(r,e,i,a==="current",s.resumeToken)),r.isPrimaryClient&&t&&Ay(r.remoteStore,s),u}async function RR(r,e,t,n,s){r.Ha=(m,g,b)=>async function(C,R,N,F){let U=R.view.ba(N);U.ls&&(U=await fg(C.localStore,R.query,!1).then(({documents:E})=>R.view.ba(E,U)));let G=F&&F.targetChanges.get(R.targetId),Y=F&&F.targetMismatches.get(R.targetId)!=null,B=R.view.applyChanges(U,C.isPrimaryClient,G,Y);return wg(C,R.targetId,B.Ma),B.snapshot}(r,m,g,b);let i=await fg(r.localStore,e,!0),a=new yl(e,i.gs),u=a.ba(i.documents),c=Ls.createSynthesizedTargetChangeForCurrentChange(t,n&&r.onlineState!=="Offline",s),h=a.applyChanges(u,r.isPrimaryClient,c);wg(r,t,h.Ma);let f=new _l(e,t,a);return r.ka.set(e,f),r.qa.has(t)?r.qa.get(t).push(e):r.qa.set(t,[e]),h.snapshot}async function PR(r,e,t){let n=$(r),s=n.ka.get(e),i=n.qa.get(s.targetId);if(i.length>1)return n.qa.set(s.targetId,i.filter(a=>!ca(a,e))),void n.ka.delete(e);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(s.targetId),n.sharedClientState.isActiveQueryTarget(s.targetId)||await el(n.localStore,s.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(s.targetId),t&&ql(n.remoteStore,s.targetId),bl(n,s.targetId)}).catch(Ln)):(bl(n,s.targetId),await el(n.localStore,s.targetId,!0))}async function CR(r,e){let t=$(r),n=t.ka.get(e),s=t.qa.get(n.targetId);t.isPrimaryClient&&s.length===1&&(t.sharedClientState.removeLocalQueryTarget(n.targetId),ql(t.remoteStore,n.targetId))}async function kR(r,e,t){let n=MR(r);try{let s=await function(a,u){let c=$(a),h=we.now(),f=u.reduce((b,P)=>b.add(P.key),W()),m,g;return c.persistence.runTransaction("Locally write mutations","readwrite",b=>{let P=Pt(),C=W();return c.ds.getEntries(b,f).next(R=>{P=R,P.forEach((N,F)=>{F.isValidDocument()||(C=C.add(N))})}).next(()=>c.localDocuments.getOverlayedDocuments(b,P)).next(R=>{m=R;let N=[];for(let F of u){let U=LS(F,m.get(F.key).overlayedDocument);U!=null&&N.push(new ut(F.key,U,Jg(U.value.mapValue),Xt.exists(!0)))}return c.mutationQueue.addMutationBatch(b,h,N,u)}).next(R=>{g=R;let N=R.applyToLocalDocumentSet(m,C);return c.documentOverlayCache.saveOverlays(b,R.batchId,N)})}).then(()=>({batchId:g.batchId,changes:iy(m)}))}(n.localStore,e);n.sharedClientState.addPendingMutation(s.batchId),function(a,u,c){let h=a.Wa[a.currentUser.toKey()];h||(h=new ce(K)),h=h.insert(u,c),a.Wa[a.currentUser.toKey()]=h}(n,s.batchId,t),await Ws(n,s.changes),await fa(n.remoteStore)}catch(s){let i=Hl(s,"Failed to persist write");t.reject(i)}}async function Ny(r,e){let t=$(r);try{let n=await aR(t.localStore,e);e.targetChanges.forEach((s,i)=>{let a=t.Ua.get(i);a&&(ee(s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size<=1),s.addedDocuments.size>0?a.Ba=!0:s.modifiedDocuments.size>0?ee(a.Ba):s.removedDocuments.size>0&&(ee(a.Ba),a.Ba=!1))}),await Ws(t,n,e)}catch(n){await Ln(n)}}function vg(r,e,t){let n=$(r);if(n.isPrimaryClient&&t===0||!n.isPrimaryClient&&t===1){let s=[];n.ka.forEach((i,a)=>{let u=a.view.sa(e);u.snapshot&&s.push(u.snapshot)}),function(a,u){let c=$(a);c.onlineState=u;let h=!1;c.queries.forEach((f,m)=>{for(let g of m.ta)g.sa(u)&&(h=!0)}),h&&Wl(c)}(n.eventManager,e),s.length&&n.La.p_(s),n.onlineState=e,n.isPrimaryClient&&n.sharedClientState.setOnlineState(e)}}async function DR(r,e,t){let n=$(r);n.sharedClientState.updateQueryState(e,"rejected",t);let s=n.Ua.get(e),i=s&&s.key;if(i){let a=new ce(j.comparator);a=a.insert(i,Je.newNoDocument(i,q.min()));let u=W().add(i),c=new Do(q.min(),new Map,new ce(K),a,u);await Ny(n,c),n.$a=n.$a.remove(i),n.Ua.delete(e),Jl(n)}else await el(n.localStore,e,!1).then(()=>bl(n,e,t)).catch(Ln)}async function OR(r,e){let t=$(r),n=e.batch.batchId;try{let s=await oR(t.localStore,e);Ly(t,n,null),Vy(t,n),t.sharedClientState.updateMutationState(n,"acknowledged"),await Ws(t,s)}catch(s){await Ln(s)}}async function NR(r,e,t){let n=$(r);try{let s=await function(a,u){let c=$(a);return c.persistence.runTransaction("Reject batch","readwrite-primary",h=>{let f;return c.mutationQueue.lookupMutationBatch(h,u).next(m=>(ee(m!==null),f=m.keys(),c.mutationQueue.removeMutationBatch(h,m))).next(()=>c.mutationQueue.performConsistencyCheck(h)).next(()=>c.documentOverlayCache.removeOverlaysForBatchId(h,f,u)).next(()=>c.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(h,f)).next(()=>c.localDocuments.getDocuments(h,f))})}(n.localStore,e);Ly(n,e,t),Vy(n,e),n.sharedClientState.updateMutationState(e,"rejected",t),await Ws(n,s)}catch(s){await Ln(s)}}function Vy(r,e){(r.Ga.get(e)||[]).forEach(t=>{t.resolve()}),r.Ga.delete(e)}function Ly(r,e,t){let n=$(r),s=n.Wa[n.currentUser.toKey()];if(s){let i=s.get(e);i&&(t?i.reject(t):i.resolve(),s=s.remove(e)),n.Wa[n.currentUser.toKey()]=s}}function bl(r,e,t=null){r.sharedClientState.removeLocalQueryTarget(e);for(let n of r.qa.get(e))r.ka.delete(n),t&&r.La.Ja(n,t);r.qa.delete(e),r.isPrimaryClient&&r.Ka.br(e).forEach(n=>{r.Ka.containsKey(n)||Fy(r,n)})}function Fy(r,e){r.Qa.delete(e.path.canonicalString());let t=r.$a.get(e);t!==null&&(ql(r.remoteStore,t),r.$a=r.$a.remove(e),r.Ua.delete(t),Jl(r))}function wg(r,e,t){for(let n of t)n instanceof Wo?(r.Ka.addReference(n.key,e),VR(r,n)):n instanceof Qo?(V(Ql,"Document no longer in limbo: "+n.key),r.Ka.removeReference(n.key,e),r.Ka.containsKey(n.key)||Fy(r,n.key)):M()}function VR(r,e){let t=e.key,n=t.path.canonicalString();r.$a.get(t)||r.Qa.has(n)||(V(Ql,"New document in limbo: "+t),r.Qa.add(n),Jl(r))}function Jl(r){for(;r.Qa.size>0&&r.$a.size<r.maxConcurrentLimboResolutions;){let e=r.Qa.values().next().value;r.Qa.delete(e);let t=new j(fe.fromString(e)),n=r.za.next();r.Ua.set(n,new vl(t)),r.$a=r.$a.insert(t,n),Ay(r.remoteStore,new Fs(nt(ua(t.path)),n,"TargetPurposeLimboResolution",bn.ae))}}async function Ws(r,e,t){let n=$(r),s=[],i=[],a=[];n.ka.isEmpty()||(n.ka.forEach((u,c)=>{a.push(n.Ha(c,e,t).then(h=>{var f;if((h||t)&&n.isPrimaryClient){let m=h?!h.fromCache:(f=t==null?void 0:t.targetChanges.get(c.targetId))===null||f===void 0?void 0:f.current;n.sharedClientState.updateQueryState(c.targetId,m?"current":"not-current")}if(h){s.push(h);let m=Jc.Yi(c.targetId,h);i.push(m)}}))}),await Promise.all(a),n.La.p_(s),await async function(c,h){let f=$(c);try{await f.persistence.runTransaction("notifyLocalViewChanges","readwrite",m=>k.forEach(h,g=>k.forEach(g.Hi,b=>f.persistence.referenceDelegate.addReference(m,g.targetId,b)).next(()=>k.forEach(g.Ji,b=>f.persistence.referenceDelegate.removeReference(m,g.targetId,b)))))}catch(m){if(!Fn(m))throw m;V($l,"Failed to update sequence numbers: "+m)}for(let m of h){let g=m.targetId;if(!m.fromCache){let b=f.Ts.get(g),P=b.snapshotVersion,C=b.withLastLimboFreeSnapshotVersion(P);f.Ts=f.Ts.insert(g,C)}}}(n.localStore,i))}async function LR(r,e){let t=$(r);if(!t.currentUser.isEqual(e)){V(Ql,"User change. New user:",e.toKey());let n=await Ey(t.localStore,e);t.currentUser=e,function(i,a){i.Ga.forEach(u=>{u.forEach(c=>{c.reject(new L(D.CANCELLED,a))})}),i.Ga.clear()}(t,"'waitForPendingWrites' promise is rejected due to a user change."),t.sharedClientState.handleUserChange(e,n.removedBatchIds,n.addedBatchIds),await Ws(t,n.Rs)}}function FR(r,e){let t=$(r),n=t.Ua.get(e);if(n&&n.Ba)return W().add(n.key);{let s=W(),i=t.qa.get(e);if(!i)return s;for(let a of i){let u=t.ka.get(a);s=s.unionWith(u.view.Sa)}return s}}function My(r){let e=$(r);return e.remoteStore.remoteSyncer.applyRemoteEvent=Ny.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=FR.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=DR.bind(null,e),e.La.p_=IR.bind(null,e.eventManager),e.La.Ja=AR.bind(null,e.eventManager),e}function MR(r){let e=$(r);return e.remoteStore.remoteSyncer.applySuccessfulWrite=OR.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=NR.bind(null,e),e}var On=class{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=ha(e.databaseInfo.databaseId),this.sharedClientState=this.Za(e),this.persistence=this.Xa(e),await this.persistence.start(),this.localStore=this.eu(e),this.gcScheduler=this.tu(e,this.localStore),this.indexBackfillerScheduler=this.nu(e,this.localStore)}tu(e,t){return null}nu(e,t){return null}eu(e){return iR(this.persistence,new Xc,e.initialUser,this.serializer)}Xa(e){return new Mo(Qc.ri,this.serializer)}Za(e){return new tl}async terminate(){var e,t;(e=this.gcScheduler)===null||e===void 0||e.stop(),(t=this.indexBackfillerScheduler)===null||t===void 0||t.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}};On.provider={build:()=>new On};var Tl=class extends On{constructor(e){super(),this.cacheSizeBytes=e}tu(e,t){ee(this.persistence.referenceDelegate instanceof jo);let n=this.persistence.referenceDelegate.garbageCollector;return new Lc(n,e.asyncQueue,t)}Xa(e){let t=this.cacheSizeBytes!==void 0?$e.withCacheSize(this.cacheSizeBytes):$e.DEFAULT;return new Mo(n=>jo.ri(n,t),this.serializer)}};var Us=class{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=n=>vg(this.syncEngine,n,1),this.remoteStore.remoteSyncer.handleCredentialChange=LR.bind(null,this.syncEngine),await ER(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return function(){return new ml}()}createDatastore(e){let t=ha(e.databaseInfo.databaseId),n=function(i){return new ol(i)}(e.databaseInfo);return function(i,a,u,c){return new ll(i,a,u,c)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return function(n,s,i,a,u){return new dl(n,s,i,a,u)}(this.localStore,this.datastore,e.asyncQueue,t=>vg(this.syncEngine,t,0),function(){return Bo.D()?new Bo:new rl}())}createSyncEngine(e,t){return function(s,i,a,u,c,h,f){let m=new wl(s,i,a,u,c,h);return f&&(m.ja=!0),m}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e,t;await async function(s){let i=$(s);V(Tr,"RemoteStore shutting down."),i.W_.add(5),await Hs(i),i.z_.shutdown(),i.j_.set("Unknown")}(this.remoteStore),(e=this.datastore)===null||e===void 0||e.terminate(),(t=this.eventManager)===null||t===void 0||t.terminate()}};Us.provider={build:()=>new Us};var Jo=class{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.iu(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.iu(this.observer.error,e):At("Uncaught Error in snapshot listener:",e.toString()))}su(){this.muted=!0}iu(e,t){setTimeout(()=>{this.muted||e(t)},0)}};var tr="FirestoreClient",El=class{constructor(e,t,n,s,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=s,this.user=ye.UNAUTHENTICATED,this.clientId=Io.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,async a=>{V(tr,"Received user=",a.uid),await this.authCredentialListener(a),this.user=a}),this.appCheckCredentials.start(n,a=>(V(tr,"Received new app check token=",a),this.appCheckCredentialListener(a,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let e=new tt;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){let n=Hl(t,"Failed to shutdown persistence");e.reject(n)}}),e.promise}};async function Qu(r,e){r.asyncQueue.verifyOperationInProgress(),V(tr,"Initializing OfflineComponentProvider");let t=r.configuration;await e.initialize(t);let n=t.initialUser;r.setCredentialChangeListener(async s=>{n.isEqual(s)||(await Ey(e.localStore,s),n=s)}),e.persistence.setDatabaseDeletedListener(()=>r.terminate()),r._offlineComponents=e}async function bg(r,e){r.asyncQueue.verifyOperationInProgress();let t=await jR(r);V(tr,"Initializing OnlineComponentProvider"),await e.initialize(t,r.configuration),r.setCredentialChangeListener(n=>gg(e.remoteStore,n)),r.setAppCheckTokenChangeListener((n,s)=>gg(e.remoteStore,s)),r._onlineComponents=e}async function jR(r){if(!r._offlineComponents)if(r._uninitializedComponentsProvider){V(tr,"Using user provided OfflineComponentProvider");try{await Qu(r,r._uninitializedComponentsProvider._offline)}catch(e){let t=e;if(!function(s){return s.name==="FirebaseError"?s.code===D.FAILED_PRECONDITION||s.code===D.UNIMPLEMENTED:!(typeof DOMException!="undefined"&&s instanceof DOMException)||s.code===22||s.code===20||s.code===11}(t))throw t;vn("Error using user provided cache. Falling back to memory cache: "+t),await Qu(r,new On)}}else V(tr,"Using default OfflineComponentProvider"),await Qu(r,new Tl(void 0));return r._offlineComponents}async function jy(r){return r._onlineComponents||(r._uninitializedComponentsProvider?(V(tr,"Using user provided OnlineComponentProvider"),await bg(r,r._uninitializedComponentsProvider._online)):(V(tr,"Using default OnlineComponentProvider"),await bg(r,new Us))),r._onlineComponents}function UR(r){return jy(r).then(e=>e.syncEngine)}async function Il(r){let e=await jy(r),t=e.eventManager;return t.onListen=xR.bind(null,e.syncEngine),t.onUnlisten=PR.bind(null,e.syncEngine),t.onFirstRemoteStoreListen=SR.bind(null,e.syncEngine),t.onLastRemoteStoreUnlisten=CR.bind(null,e.syncEngine),t}function BR(r,e,t={}){let n=new tt;return r.asyncQueue.enqueueAndForget(async()=>function(i,a,u,c,h){let f=new Jo({next:g=>{f.su(),a.enqueueAndForget(()=>Dy(i,m));let b=g.docs.has(u);!b&&g.fromCache?h.reject(new L(D.UNAVAILABLE,"Failed to get document because the client is offline.")):b&&g.fromCache&&c&&c.source==="server"?h.reject(new L(D.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.)')):h.resolve(g)},error:g=>h.reject(g)}),m=new Ho(ua(u.path),f,{includeMetadataChanges:!0,Ta:!0});return ky(i,m)}(await Il(r),r.asyncQueue,e,t,n)),n.promise}function Uy(r){let e={};return r.timeoutSeconds!==void 0&&(e.timeoutSeconds=r.timeoutSeconds),e}var Tg=new Map;function $R(r,e,t){if(!t)throw new L(D.INVALID_ARGUMENT,`Function ${r}() cannot be called with an empty ${e}.`)}function qR(r,e,t,n){if(e===!0&&n===!0)throw new L(D.INVALID_ARGUMENT,`${r} and ${t} cannot be used together.`)}function Eg(r){if(!j.isDocumentKey(r))throw new L(D.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${r} has ${r.length}.`)}function Yl(r){if(r===void 0)return"undefined";if(r===null)return"null";if(typeof r=="string")return r.length>20&&(r=`${r.substring(0,20)}...`),JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean")return""+r;if(typeof r=="object"){if(r instanceof Array)return"an array";{let e=function(n){return n.constructor?n.constructor.name:null}(r);return e?`a custom ${e} object`:"an object"}}return typeof r=="function"?"a function":M()}function it(r,e){if("_delegate"in r&&(r=r._delegate),!(r instanceof e)){if(e.name===r.constructor.name)throw new L(D.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let t=Yl(r);throw new L(D.INVALID_ARGUMENT,`Expected type '${e.name}', but it was: ${t}`)}}return r}var By="firestore.googleapis.com",Ig=!0,Yo=class{constructor(e){var t,n;if(e.host===void 0){if(e.ssl!==void 0)throw new L(D.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=By,this.ssl=Ig}else this.host=e.host,this.ssl=(t=e.ssl)!==null&&t!==void 0?t:Ig;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e.cacheSizeBytes===void 0)this.cacheSizeBytes=Ty;else{if(e.cacheSizeBytes!==-1&&e.cacheSizeBytes<rR)throw new L(D.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}qR("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:e.experimentalAutoDetectLongPolling===void 0?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Uy((n=e.experimentalLongPollingOptions)!==null&&n!==void 0?n:{}),function(i){if(i.timeoutSeconds!==void 0){if(isNaN(i.timeoutSeconds))throw new L(D.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (must not be NaN)`);if(i.timeoutSeconds<5)throw new L(D.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (minimum allowed value is 5)`);if(i.timeoutSeconds>30)throw new L(D.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&function(n,s){return n.timeoutSeconds===s.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}},Bs=class{constructor(e,t,n,s){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=s,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Yo({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new L(D.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 this._terminateTask!=="notTerminated"}_setSettings(e){if(this._settingsFrozen)throw new L(D.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 Yo(e),this._emulatorOptions=e.emulatorOptions||{},e.credentials!==void 0&&(this._authCredentials=function(n){if(!n)return new Ju;switch(n.type){case"firstParty":return new ec(n.sessionIndex||"0",n.iamToken||null,n.authTokenFactory||null);case"provider":return n.client;default:throw new L(D.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask==="notTerminated"&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){this._terminateTask==="notTerminated"?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(t){let n=Tg.get(t);n&&(V("ComponentProvider","Removing Datastore"),Tg.delete(t),n.terminate())}(this),Promise.resolve()}};function zR(r,e,t,n={}){var s;let i=(r=it(r,Bs))._getSettings(),a=Object.assign(Object.assign({},i),{emulatorOptions:r._getEmulatorOptions()}),u=`${e}:${t}`;i.host!==By&&i.host!==u&&vn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let c=Object.assign(Object.assign({},i),{host:u,ssl:!1,emulatorOptions:n});if(!cn(c,a)&&(r._setSettings(c),n.mockUserToken)){let h,f;if(typeof n.mockUserToken=="string")h=n.mockUserToken,f=ye.MOCK_USER;else{h=mm(n.mockUserToken,(s=r._app)===null||s===void 0?void 0:s.options.projectId);let m=n.mockUserToken.sub||n.mockUserToken.user_id;if(!m)throw new L(D.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");f=new ye(m)}r._authCredentials=new Yu(new To(h,f))}}var Xo=class r{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new r(this.firestore,e,this._query)}},Ne=class r{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new $s(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new r(this.firestore,e,this._key)}},$s=class r extends Xo{constructor(e,t,n){super(e,t,ua(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new Ne(this.firestore,null,new j(e))}withConverter(e){return new r(this.firestore,e,this._path)}};function pa(r,e,...t){if(r=wt(r),arguments.length===1&&(e=Io.newId()),$R("doc","path",e),r instanceof Bs){let n=fe.fromString(e,...t);return Eg(n),new Ne(r,null,new j(n))}{if(!(r instanceof Ne||r instanceof $s))throw new L(D.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let n=r._path.child(fe.fromString(e,...t));return Eg(n),new Ne(r.firestore,r instanceof $s?r.converter:null,new j(n))}}var Ag="AsyncQueue",Zo=class{constructor(e=Promise.resolve()){this.Vu=[],this.mu=!1,this.fu=[],this.gu=null,this.pu=!1,this.yu=!1,this.wu=[],this.a_=new $o(this,"async_queue_retry"),this.Su=()=>{let n=Wu();n&&V(Ag,"Visibility state changed to "+n.visibilityState),this.a_.t_()},this.bu=e;let t=Wu();t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",this.Su)}get isShuttingDown(){return this.mu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Du(),this.vu(e)}enterRestrictedMode(e){if(!this.mu){this.mu=!0,this.yu=e||!1;let t=Wu();t&&typeof t.removeEventListener=="function"&&t.removeEventListener("visibilitychange",this.Su)}}enqueue(e){if(this.Du(),this.mu)return new Promise(()=>{});let t=new tt;return this.vu(()=>this.mu&&this.yu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Vu.push(e),this.Cu()))}async Cu(){if(this.Vu.length!==0){try{await this.Vu[0](),this.Vu.shift(),this.a_.reset()}catch(e){if(!Fn(e))throw e;V(Ag,"Operation failed with retryable error: "+e)}this.Vu.length>0&&this.a_.Xo(()=>this.Cu())}}vu(e){let t=this.bu.then(()=>(this.pu=!0,e().catch(n=>{this.gu=n,this.pu=!1;let s=function(a){let u=a.message||"";return a.stack&&(u=a.stack.includes(a.message)?a.stack:a.message+`
22
- `+a.stack),u}(n);throw At("INTERNAL UNHANDLED ERROR: ",s),n}).then(n=>(this.pu=!1,n))));return this.bu=t,t}enqueueAfterDelay(e,t,n){this.Du(),this.wu.indexOf(e)>-1&&(t=0);let s=fl.createAndSchedule(this,e,t,n,i=>this.Fu(i));return this.fu.push(s),s}Du(){this.gu&&M()}verifyOperationInProgress(){}async Mu(){let e;do e=this.bu,await e;while(e!==this.bu)}xu(e){for(let t of this.fu)if(t.timerId===e)return!0;return!1}Ou(e){return this.Mu().then(()=>{this.fu.sort((t,n)=>t.targetTimeMs-n.targetTimeMs);for(let t of this.fu)if(t.skipDelay(),e!=="all"&&t.timerId===e)break;return this.Mu()})}Nu(e){this.wu.push(e)}Fu(e){let t=this.fu.indexOf(e);this.fu.splice(t,1)}};function xg(r){return function(t,n){if(typeof t!="object"||t===null)return!1;let s=t;for(let i of n)if(i in s&&typeof s[i]=="function")return!0;return!1}(r,["next","error","complete"])}var rr=class extends Bs{constructor(e,t,n,s){super(e,t,n,s),this.type="firestore",this._queue=new Zo,this._persistenceKey=(s==null?void 0:s.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new Zo(e),this._firestoreClient=void 0,await e}}};function $y(r,e){let t=typeof r=="object"?r:Nm(),n=typeof r=="string"?r:e||Ro,s=km(t,"firestore").getImmediate({identifier:n});if(!s._initialized){let i=pm("firestore");i&&zR(s,...i)}return s}function Xl(r){if(r._terminated)throw new L(D.FAILED_PRECONDITION,"The client has already been terminated.");return r._firestoreClient||GR(r),r._firestoreClient}function GR(r){var e,t,n;let s=r._freezeSettings(),i=function(u,c,h,f){return new ic(u,c,h,f.host,f.ssl,f.experimentalForceLongPolling,f.experimentalAutoDetectLongPolling,Uy(f.experimentalLongPollingOptions),f.useFetchStreams)}(r._databaseId,((e=r._app)===null||e===void 0?void 0:e.options.appId)||"",r._persistenceKey,s);r._componentsProvider||!((t=s.localCache)===null||t===void 0)&&t._offlineComponentProvider&&(!((n=s.localCache)===null||n===void 0)&&n._onlineComponentProvider)&&(r._componentsProvider={_offline:s.localCache._offlineComponentProvider,_online:s.localCache._onlineComponentProvider}),r._firestoreClient=new El(r._authCredentials,r._appCheckCredentials,r._queue,i,r._componentsProvider&&function(u){let c=u==null?void 0:u._online.build();return{_offline:u==null?void 0:u._offline.build(c),_online:c}}(r._componentsProvider))}var qs=class r{constructor(e){this._byteString=e}static fromBase64String(e){try{return new r(Re.fromBase64String(e))}catch(t){throw new L(D.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+t)}}static fromUint8Array(e){return new r(Re.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}};var Nn=class{constructor(...e){for(let t=0;t<e.length;++t)if(e[t].length===0)throw new L(D.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Ue(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}};var zs=class{constructor(e){this._methodName=e}};var Gs=class{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new L(D.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new L(D.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return K(this._lat,e._lat)||K(this._long,e._long)}};var Ks=class{constructor(e){this._values=(e||[]).map(t=>t)}toArray(){return this._values.map(e=>e)}isEqual(e){return function(n,s){if(n.length!==s.length)return!1;for(let i=0;i<n.length;++i)if(n[i]!==s[i])return!1;return!0}(this._values,e._values)}};var KR=/^__.*__$/,Al=class{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return this.fieldMask!==null?new ut(e,this.data,this.fieldMask,t,this.fieldTransforms):new br(e,this.data,t,this.fieldTransforms)}},ea=class{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new ut(e,this.data,this.fieldMask,t,this.fieldTransforms)}};function qy(r){switch(r){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw M()}}var xl=class r{constructor(e,t,n,s,i,a){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=s,i===void 0&&this.Bu(),this.fieldTransforms=i||[],this.fieldMask=a||[]}get path(){return this.settings.path}get Lu(){return this.settings.Lu}ku(e){return new r(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}qu(e){var t;let n=(t=this.path)===null||t===void 0?void 0:t.child(e),s=this.ku({path:n,Qu:!1});return s.$u(e),s}Uu(e){var t;let n=(t=this.path)===null||t===void 0?void 0:t.child(e),s=this.ku({path:n,Qu:!1});return s.Bu(),s}Ku(e){return this.ku({path:void 0,Qu:!0})}Wu(e){return ra(e,this.settings.methodName,this.settings.Gu||!1,this.path,this.settings.zu)}contains(e){return this.fieldMask.find(t=>e.isPrefixOf(t))!==void 0||this.fieldTransforms.find(t=>e.isPrefixOf(t.field))!==void 0}Bu(){if(this.path)for(let e=0;e<this.path.length;e++)this.$u(this.path.get(e))}$u(e){if(e.length===0)throw this.Wu("Document fields must not be empty");if(qy(this.Lu)&&KR.test(e))throw this.Wu('Document fields cannot begin and end with "__"')}},Sl=class{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||ha(e)}ju(e,t,n,s=!1){return new xl({Lu:e,methodName:t,zu:n,path:Ue.emptyPath(),Qu:!1,Gu:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function zy(r){let e=r._freezeSettings(),t=ha(r._databaseId);return new Sl(r._databaseId,!!e.ignoreUndefinedProperties,t)}function HR(r,e,t,n,s,i={}){let a=r.ju(i.merge||i.mergeFields?2:0,e,t,s);Zl("Data must be an object, but it was:",a,n);let u=Gy(n,a),c,h;if(i.merge)c=new qe(a.fieldMask),h=a.fieldTransforms;else if(i.mergeFields){let f=[];for(let m of i.mergeFields){let g=Rl(e,m,t);if(!a.contains(g))throw new L(D.INVALID_ARGUMENT,`Field '${g}' is specified in your field mask but missing from your input data.`);Hy(f,g)||f.push(g)}c=new qe(f),h=a.fieldTransforms.filter(m=>c.covers(m.field))}else c=null,h=a.fieldTransforms;return new Al(new je(u),c,h)}var ta=class r extends zs{_toFieldTransform(e){if(e.Lu!==2)throw e.Lu===1?e.Wu(`${this._methodName}() can only appear at the top level of your update data`):e.Wu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof r}};function WR(r,e,t,n){let s=r.ju(1,e,t);Zl("Data must be an object, but it was:",s,n);let i=[],a=je.empty();nr(n,(c,h)=>{let f=eh(e,c,t);h=wt(h);let m=s.Uu(f);if(h instanceof ta)i.push(f);else{let g=ma(h,m);g!=null&&(i.push(f),a.set(f,g))}});let u=new qe(i);return new ea(a,u,s.fieldTransforms)}function QR(r,e,t,n,s,i){let a=r.ju(1,e,t),u=[Rl(e,n,t)],c=[s];if(i.length%2!=0)throw new L(D.INVALID_ARGUMENT,`Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let g=0;g<i.length;g+=2)u.push(Rl(e,i[g])),c.push(i[g+1]);let h=[],f=je.empty();for(let g=u.length-1;g>=0;--g)if(!Hy(h,u[g])){let b=u[g],P=c[g];P=wt(P);let C=a.Uu(b);if(P instanceof ta)h.push(b);else{let R=ma(P,C);R!=null&&(h.push(b),f.set(b,R))}}let m=new qe(h);return new ea(f,m,a.fieldTransforms)}function ma(r,e){if(Ky(r=wt(r)))return Zl("Unsupported field value:",e,r),Gy(r,e);if(r instanceof zs)return function(n,s){if(!qy(s.Lu))throw s.Wu(`${n._methodName}() can only be used with update() and set()`);if(!s.path)throw s.Wu(`${n._methodName}() is not currently supported inside arrays`);let i=n._toFieldTransform(s);i&&s.fieldTransforms.push(i)}(r,e),null;if(r===void 0&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),r instanceof Array){if(e.settings.Qu&&e.Lu!==4)throw e.Wu("Nested arrays are not supported");return function(n,s){let i=[],a=0;for(let u of n){let c=ma(u,s.Ku(a));c==null&&(c={nullValue:"NULL_VALUE"}),i.push(c),a++}return{arrayValue:{values:i}}}(r,e)}return function(n,s){if((n=wt(n))===null)return{nullValue:"NULL_VALUE"};if(typeof n=="number")return kS(s.serializer,n);if(typeof n=="boolean")return{booleanValue:n};if(typeof n=="string")return{stringValue:n};if(n instanceof Date){let i=we.fromDate(n);return{timestampValue:Lo(s.serializer,i)}}if(n instanceof we){let i=new we(n.seconds,1e3*Math.floor(n.nanoseconds/1e3));return{timestampValue:Lo(s.serializer,i)}}if(n instanceof Gs)return{geoPointValue:{latitude:n.latitude,longitude:n.longitude}};if(n instanceof qs)return{bytesValue:my(s.serializer,n._byteString)};if(n instanceof Ne){let i=s.databaseId,a=n.firestore._databaseId;if(!a.isEqual(i))throw s.Wu(`Document reference is for database ${a.projectId}/${a.database} but should be for database ${i.projectId}/${i.database}`);return{referenceValue:Bl(n.firestore._databaseId||s.databaseId,n._key.path)}}if(n instanceof Ks)return function(a,u){return{mapValue:{fields:{[Vl]:{stringValue:Ll},[Tn]:{arrayValue:{values:a.toArray().map(h=>{if(typeof h!="number")throw u.Wu("VectorValues must only contain numeric values.");return Ul(u.serializer,h)})}}}}}}(n,s);throw s.Wu(`Unsupported field value: ${Yl(n)}`)}(r,e)}function Gy(r,e){let t={};return $g(r)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):nr(r,(n,s)=>{let i=ma(s,e.qu(n));i!=null&&(t[n]=i)}),{mapValue:{fields:t}}}function Ky(r){return!(typeof r!="object"||r===null||r instanceof Array||r instanceof Date||r instanceof we||r instanceof Gs||r instanceof qs||r instanceof Ne||r instanceof zs||r instanceof Ks)}function Zl(r,e,t){if(!Ky(t)||!function(s){return typeof s=="object"&&s!==null&&(Object.getPrototypeOf(s)===Object.prototype||Object.getPrototypeOf(s)===null)}(t)){let n=Yl(t);throw n==="an object"?e.Wu(r+" a custom object"):e.Wu(r+" "+n)}}function Rl(r,e,t){if((e=wt(e))instanceof Nn)return e._internalPath;if(typeof e=="string")return eh(r,e);throw ra("Field path arguments must be of type string or ",r,!1,void 0,t)}var JR=new RegExp("[~\\*/\\[\\]]");function eh(r,e,t){if(e.search(JR)>=0)throw ra(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,r,!1,void 0,t);try{return new Nn(...e.split("."))._internalPath}catch{throw ra(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,r,!1,void 0,t)}}function ra(r,e,t,n,s){let i=n&&!n.isEmpty(),a=s!==void 0,u=`Function ${e}() called with invalid data`;t&&(u+=" (via `toFirestore()`)"),u+=". ";let c="";return(i||a)&&(c+=" (found",i&&(c+=` in field ${n}`),a&&(c+=` in document ${s}`),c+=")"),new L(D.INVALID_ARGUMENT,u+r+c)}function Hy(r,e){return r.some(t=>t.isEqual(e))}var na=class{constructor(e,t,n,s,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=s,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new Ne(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new Pl(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){let t=this._document.data.field(Wy("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t)}}},Pl=class extends na{data(){return super.data()}};function Wy(r,e){return typeof e=="string"?eh(r,e):e instanceof Nn?e._internalPath:e._delegate._internalPath}function YR(r){if(r.limitType==="L"&&r.explicitOrderBy.length===0)throw new L(D.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var Cl=class{convertValue(e,t="none"){switch(Zt(e)){case 0:return null;case 1:return e.booleanValue;case 2:return oe(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(St(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw M()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let n={};return nr(e,(s,i)=>{n[s]=this.convertValue(i,t)}),n}convertVectorValue(e){var t,n,s;let i=(s=(n=(t=e.fields)===null||t===void 0?void 0:t[Tn].arrayValue)===null||n===void 0?void 0:n.values)===null||s===void 0?void 0:s.map(a=>oe(a.doubleValue));return new Ks(i)}convertGeoPoint(e){return new Gs(oe(e.latitude),oe(e.longitude))}convertArray(e,t){return(e.values||[]).map(n=>this.convertValue(n,t))}convertServerTimestamp(e,t){switch(t){case"previous":let n=aa(e);return n==null?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Ns(e));default:return null}}convertTimestamp(e){let t=xt(e);return new we(t.seconds,t.nanos)}convertDocumentKey(e,t){let n=fe.fromString(e);ee(by(n));let s=new Po(n.get(1),n.get(3)),i=new j(n.popFirst(5));return s.isEqual(t)||At(`Document ${i} 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 (${t.projectId}/${t.database}) instead.`),i}};function XR(r,e,t){let n;return n=r?t&&(t.merge||t.mergeFields)?r.toFirestore(e,t):r.toFirestore(e):e,n}var gr=class{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}},sa=class extends na{constructor(e,t,n,s,i,a){super(e,t,n,s,a),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let t=new _n(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){let n=this._document.data.field(Wy("DocumentSnapshot.get",e));if(n!==null)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}},_n=class extends sa{data(e={}){return super.data(e)}},kl=class{constructor(e,t,n,s){this._firestore=e,this._userDataWriter=t,this._snapshot=s,this.metadata=new gr(s.hasPendingWrites,s.fromCache),this.query=n}get docs(){let e=[];return this.forEach(t=>e.push(t)),e}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(e,t){this._snapshot.docs.forEach(n=>{e.call(t,new _n(this._firestore,this._userDataWriter,n.key,n,new gr(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new L(D.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(s,i){if(s._snapshot.oldDocs.isEmpty()){let a=0;return s._snapshot.docChanges.map(u=>{let c=new _n(s._firestore,s._userDataWriter,u.doc.key,u.doc,new gr(s._snapshot.mutatedKeys.has(u.doc.key),s._snapshot.fromCache),s.query.converter);return u.doc,{type:"added",doc:c,oldIndex:-1,newIndex:a++}})}{let a=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(u=>i||u.type!==3).map(u=>{let c=new _n(s._firestore,s._userDataWriter,u.doc.key,u.doc,new gr(s._snapshot.mutatedKeys.has(u.doc.key),s._snapshot.fromCache),s.query.converter),h=-1,f=-1;return u.type!==0&&(h=a.indexOf(u.doc.key),a=a.delete(u.doc.key)),u.type!==1&&(a=a.add(u.doc),f=a.indexOf(u.doc.key)),{type:ZR(u.type),doc:c,oldIndex:h,newIndex:f}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}};function ZR(r){switch(r){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return M()}}function th(r){r=it(r,Ne);let e=it(r.firestore,rr);return BR(Xl(e),r._key).then(t=>Yy(e,r,t))}var ia=class extends Cl{constructor(e){super(),this.firestore=e}convertBytes(e){return new qs(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new Ne(this.firestore,null,t)}};function rh(r,e,t){r=it(r,Ne);let n=it(r.firestore,rr),s=XR(r.converter,e,t);return Jy(n,[HR(zy(n),"setDoc",r._key,s,r.converter!==null,t).toMutation(r._key,Xt.none())])}function nh(r,e,t,...n){r=it(r,Ne);let s=it(r.firestore,rr),i=zy(s),a;return a=typeof(e=wt(e))=="string"||e instanceof Nn?QR(i,"updateDoc",r._key,e,t,n):WR(i,"updateDoc",r._key,e),Jy(s,[a.toMutation(r._key,Xt.exists(!0))])}function Qy(r,...e){var t,n,s;r=wt(r);let i={includeMetadataChanges:!1,source:"default"},a=0;typeof e[a]!="object"||xg(e[a])||(i=e[a],a++);let u={includeMetadataChanges:i.includeMetadataChanges,source:i.source};if(xg(e[a])){let m=e[a];e[a]=(t=m.next)===null||t===void 0?void 0:t.bind(m),e[a+1]=(n=m.error)===null||n===void 0?void 0:n.bind(m),e[a+2]=(s=m.complete)===null||s===void 0?void 0:s.bind(m)}let c,h,f;if(r instanceof Ne)h=it(r.firestore,rr),f=ua(r._key.path),c={next:m=>{e[a]&&e[a](Yy(h,r,m))},error:e[a+1],complete:e[a+2]};else{let m=it(r,Xo);h=it(m.firestore,rr),f=m._query;let g=new ia(h);c={next:b=>{e[a]&&e[a](new kl(h,g,m,b))},error:e[a+1],complete:e[a+2]},YR(r._query)}return function(g,b,P,C){let R=new Jo(C),N=new Ho(b,R,P);return g.asyncQueue.enqueueAndForget(async()=>ky(await Il(g),N)),()=>{R.su(),g.asyncQueue.enqueueAndForget(async()=>Dy(await Il(g),N))}}(Xl(h),f,u,c)}function Jy(r,e){return function(n,s){let i=new tt;return n.asyncQueue.enqueueAndForget(async()=>kR(await UR(n),s,i)),i.promise}(Xl(r),e)}function Yy(r,e,t){let n=t.docs.get(e._key),s=new ia(r);return new sa(r,s,e._key,n,new gr(t.hasPendingWrites,t.fromCache),e.converter)}(function(e,t=!0){(function(s){Vn=s})(Om),Is(new bt("firestore",(n,{instanceIdentifier:s,options:i})=>{let a=n.getProvider("app").getImmediate(),u=new rr(new Xu(n.getProvider("auth-internal")),new tc(a,n.getProvider("app-check-internal")),function(h,f){if(!Object.prototype.hasOwnProperty.apply(h.options,["projectId"]))throw new L(D.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Po(h.options.projectId,f)}(a,s),a);return i=Object.assign({useFetchStreams:t},i),u._setSettings(i),u},"PUBLIC").setMultipleInstances(!0)),Yt(jm,Um,e),Yt(jm,Um,"esm2017")})();var Xy=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(sr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)};var Qs=class extends Error{constructor(e,t="FunctionsError",n){super(e),this.name=t,this.context=n}},ga=class extends Qs{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},ya=class extends Qs{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},_a=class extends Qs{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},va;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(va||(va={}));var sP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},Js=class{constructor(e,{headers:t={},customFetch:n,region:s=va.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=Xy(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var n;return sP(this,void 0,void 0,function*(){try{let{headers:s,method:i,body:a}=t,u={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(u["x-region"]=c);let h;a&&(s&&!Object.prototype.hasOwnProperty.call(s,"Content-Type")||!s)&&(typeof Blob!="undefined"&&a instanceof Blob||a instanceof ArrayBuffer?(u["Content-Type"]="application/octet-stream",h=a):typeof a=="string"?(u["Content-Type"]="text/plain",h=a):typeof FormData!="undefined"&&a instanceof FormData?h=a:(u["Content-Type"]="application/json",h=JSON.stringify(a)));let f=yield this.fetch(`${this.url}/${e}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},u),this.headers),s),body:h}).catch(P=>{throw new ga(P)}),m=f.headers.get("x-relay-error");if(m&&m==="true")throw new ya(f);if(!f.ok)throw new _a(f);let g=((n=f.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),b;return g==="application/json"?b=yield f.json():g==="application/octet-stream"?b=yield f.blob():g==="text/event-stream"?b=f:g==="multipart/form-data"?b=yield f.formData():b=yield f.text(),{data:b,error:null}}catch(s){return{data:null,error:s}}})}};var h_=hu(l_(),1),{PostgrestClient:d_,PostgrestQueryBuilder:g2,PostgrestFilterBuilder:y2,PostgrestTransformBuilder:_2,PostgrestBuilder:v2,PostgrestError:gP}=h_.default;var f_="2.11.2";var p_={"X-Client-Info":`realtime-js/${f_}`},m_="1.0.0",Ia=1e4,g_=1e3,Ar;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(Ar||(Ar={}));var Ve;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(Ve||(Ve={}));var Be;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(Be||(Be={}));var Ea;(function(r){r.websocket="websocket"})(Ea||(Ea={}));var ir;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(ir||(ir={}));var ni=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),n=new TextDecoder;return this._decodeBroadcast(e,t,n)}_decodeBroadcast(e,t,n){let s=t.getUint8(1),i=t.getUint8(2),a=this.HEADER_LENGTH+2,u=n.decode(e.slice(a,a+s));a=a+s;let c=n.decode(e.slice(a,a+i));a=a+i;let h=JSON.parse(n.decode(e.slice(a,e.byteLength)));return{ref:null,topic:u,event:c,payload:h}}};var xr=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var ne;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(ne||(ne={}));var _h=(r,e,t={})=>{var n;let s=(n=t.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((i,a)=>(i[a]=yP(a,r,e,s),i),{})},yP=(r,e,t,n)=>{let s=e.find(u=>u.name===r),i=s==null?void 0:s.type,a=t[r];return i&&!n.includes(i)?y_(i,a):yh(a)},y_=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return bP(e,t)}switch(r){case ne.bool:return _P(e);case ne.float4:case ne.float8:case ne.int2:case ne.int4:case ne.int8:case ne.numeric:case ne.oid:return vP(e);case ne.json:case ne.jsonb:return wP(e);case ne.timestamp:return TP(e);case ne.abstime:case ne.date:case ne.daterange:case ne.int4range:case ne.int8range:case ne.money:case ne.reltime:case ne.text:case ne.time:case ne.timestamptz:case ne.timetz:case ne.tsrange:case ne.tstzrange:return yh(e);default:return yh(e)}},yh=r=>r,_P=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},vP=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},wP=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},bP=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,n=r[t];if(r[0]==="{"&&n==="}"){let i,a=r.slice(1,t);try{i=JSON.parse("["+a+"]")}catch{i=a?a.split(","):[]}return i.map(u=>y_(e,u))}return r},TP=r=>typeof r=="string"?r.replace(" ","T"):r,Aa=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var Sr=class{constructor(e,t,n={},s=Ia){this.channel=e,this.event=t,this.payload=n,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var n;return this._hasReceived(e)&&t((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(n=>n.status===e).forEach(n=>n.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var vh;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(vh||(vh={}));var Bn=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let n=(t==null?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},s=>{let{onJoin:i,onLeave:a,onSync:u}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,s,i,a),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,i,a)}),this.pendingDiffs=[],u()}),this.channel._on(n.diff,{},s=>{let{onJoin:i,onLeave:a,onSync:u}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=r.syncDiff(this.state,s,i,a),u())}),this.onJoin((s,i,a)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:a})}),this.onLeave((s,i,a)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:a})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,n,s){let i=this.cloneDeep(e),a=this.transformState(t),u={},c={};return this.map(i,(h,f)=>{a[h]||(c[h]=f)}),this.map(a,(h,f)=>{let m=i[h];if(m){let g=f.map(R=>R.presence_ref),b=m.map(R=>R.presence_ref),P=f.filter(R=>b.indexOf(R.presence_ref)<0),C=m.filter(R=>g.indexOf(R.presence_ref)<0);P.length>0&&(u[h]=P),C.length>0&&(c[h]=C)}else u[h]=f}),this.syncDiff(i,{joins:u,leaves:c},n,s)}static syncDiff(e,t,n,s){let{joins:i,leaves:a}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return n||(n=()=>{}),s||(s=()=>{}),this.map(i,(u,c)=>{var h;let f=(h=e[u])!==null&&h!==void 0?h:[];if(e[u]=this.cloneDeep(c),f.length>0){let m=e[u].map(b=>b.presence_ref),g=f.filter(b=>m.indexOf(b.presence_ref)<0);e[u].unshift(...g)}n(u,f,c)}),this.map(a,(u,c)=>{let h=e[u];if(!h)return;let f=c.map(m=>m.presence_ref);h=h.filter(m=>f.indexOf(m.presence_ref)<0),e[u]=h,s(u,h,c),h.length===0&&delete e[u]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(n=>t(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,n)=>{let s=e[n];return"metas"in s?t[n]=s.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):t[n]=s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var wh;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(wh||(wh={}));var bh;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(bh||(bh={}));var ct;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(ct||(ct={}));var $n=class r{constructor(e,t={config:{}},n){this.topic=e,this.params=t,this.socket=n,this.bindings={},this.state=Ve.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new Sr(this,Be.join,this.params,this.timeout),this.rejoinTimer=new xr(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Ve.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=Ve.closed,this.socket._remove(this)}),this._onError(s=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,s),this.state=Ve.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Ve.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Be.reply,{},(s,i)=>{this._trigger(this._replyEventName(i),s)}),this.presence=new Bn(this),this.broadcastEndpointURL=Aa(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var n,s;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:i,presence:a,private:u}}=this.params;this._onError(f=>e==null?void 0:e(ct.CHANNEL_ERROR,f)),this._onClose(()=>e==null?void 0:e(ct.CLOSED));let c={},h={broadcast:i,presence:a,postgres_changes:(s=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(f=>f.filter))!==null&&s!==void 0?s:[],private:u};this.socket.accessTokenValue&&(c.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:h},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:f})=>{var m;if(this.socket.setAuth(),f===void 0){e==null||e(ct.SUBSCRIBED);return}else{let g=this.bindings.postgres_changes,b=(m=g==null?void 0:g.length)!==null&&m!==void 0?m:0,P=[];for(let C=0;C<b;C++){let R=g[C],{filter:{event:N,schema:F,table:U,filter:G}}=R,Y=f&&f[C];if(Y&&Y.event===N&&Y.schema===F&&Y.table===U&&Y.filter===G)P.push(Object.assign(Object.assign({},R),{id:Y.id}));else{this.unsubscribe(),e==null||e(ct.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=P,e&&e(ct.SUBSCRIBED);return}}).receive("error",f=>{e==null||e(ct.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(ct.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,n){return this._on(e,t,n)}async send(e,t={}){var n,s;if(!this._canPush()&&e.type==="broadcast"){let{event:i,payload:a}=e,c={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:a,private:this.private}]})};try{let h=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(n=t.timeout)!==null&&n!==void 0?n:this.timeout);return await((s=h.body)===null||s===void 0?void 0:s.cancel()),h.ok?"ok":"error"}catch(h){return h.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,u,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(u=(a=this.params)===null||a===void 0?void 0:a.config)===null||u===void 0?void 0:u.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),h.receive("ok",()=>i("ok")),h.receive("error",()=>i("error")),h.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=Ve.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Be.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(n=>{let s=new Sr(this,Be.leave,{},e);s.receive("ok",()=>{t(),n("ok")}).receive("timeout",()=>{t(),n("timed out")}).receive("error",()=>{n("error")}),s.send(),this._canPush()||s.trigger("ok",{})})}async _fetchWithTimeout(e,t,n){let s=new AbortController,i=setTimeout(()=>s.abort(),n),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(i),a}_push(e,t,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new Sr(this,e,t,n);return this._canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}_onMessage(e,t,n){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,n){var s,i;let a=e.toLocaleLowerCase(),{close:u,error:c,leave:h,join:f}=Be;if(n&&[u,c,h,f].indexOf(a)>=0&&n!==this._joinRef())return;let g=this._onMessage(a,t,n);if(t&&!g)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(a)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(b=>{var P,C,R;return((P=b.filter)===null||P===void 0?void 0:P.event)==="*"||((R=(C=b.filter)===null||C===void 0?void 0:C.event)===null||R===void 0?void 0:R.toLocaleLowerCase())===a}).map(b=>b.callback(g,n)):(i=this.bindings[a])===null||i===void 0||i.filter(b=>{var P,C,R,N,F,U;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in b){let G=b.id,Y=(P=b.filter)===null||P===void 0?void 0:P.event;return G&&((C=t.ids)===null||C===void 0?void 0:C.includes(G))&&(Y==="*"||(Y==null?void 0:Y.toLocaleLowerCase())===((R=t.data)===null||R===void 0?void 0:R.type.toLocaleLowerCase()))}else{let G=(F=(N=b==null?void 0:b.filter)===null||N===void 0?void 0:N.event)===null||F===void 0?void 0:F.toLocaleLowerCase();return G==="*"||G===((U=t==null?void 0:t.event)===null||U===void 0?void 0:U.toLocaleLowerCase())}else return b.type.toLocaleLowerCase()===a}).map(b=>{if(typeof g=="object"&&"ids"in g){let P=g.data,{schema:C,table:R,commit_timestamp:N,type:F,errors:U}=P;g=Object.assign(Object.assign({},{schema:C,table:R,commit_timestamp:N,eventType:F,new:{},old:{},errors:U}),this._getPayloadRecords(P))}b.callback(g,n)})}_isClosed(){return this.state===Ve.closed}_isJoined(){return this.state===Ve.joined}_isJoining(){return this.state===Ve.joining}_isLeaving(){return this.state===Ve.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,n){let s=e.toLocaleLowerCase(),i={type:s,filter:t,callback:n};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,t){let n=e.toLocaleLowerCase();return this.bindings[n]=this.bindings[n].filter(s=>{var i;return!(((i=s.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===n&&r.isEqual(s.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Be.close,{},e)}_onError(e){this._on(Be.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Ve.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=_h(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=_h(e.columns,e.old_record)),t}};var IP=()=>{},AP=typeof WebSocket!="undefined",xP=`
21
+ )`}copy(e,t){let n=new r;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}};var Go=class{constructor(){this.Z_=new ce(j.comparator)}track(e){let t=e.doc.key,n=this.Z_.get(t);n?e.type!==0&&n.type===3?this.Z_=this.Z_.insert(t,e):e.type===3&&n.type!==1?this.Z_=this.Z_.insert(t,{type:n.type,doc:e.doc}):e.type===2&&n.type===2?this.Z_=this.Z_.insert(t,{type:2,doc:e.doc}):e.type===2&&n.type===0?this.Z_=this.Z_.insert(t,{type:0,doc:e.doc}):e.type===1&&n.type===0?this.Z_=this.Z_.remove(t):e.type===1&&n.type===2?this.Z_=this.Z_.insert(t,{type:1,doc:n.doc}):e.type===0&&n.type===1?this.Z_=this.Z_.insert(t,{type:2,doc:e.doc}):M():this.Z_=this.Z_.insert(t,e)}X_(){let e=[];return this.Z_.inorderTraversal((t,n)=>{e.push(n)}),e}},Dn=class r{constructor(e,t,n,s,i,a,u,c,h){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=s,this.mutatedKeys=i,this.fromCache=a,this.syncStateChanged=u,this.excludesMetadataChanges=c,this.hasCachedResults=h}static fromInitialDocuments(e,t,n,s,i){let a=[];return t.forEach(u=>{a.push({type:0,doc:u})}),new r(e,t,zo.emptySet(t),a,n,s,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&ua(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let s=0;s<t.length;s++)if(t[s].type!==n[s].type||!t[s].doc.isEqual(n[s].doc))return!1;return!0}};var pl=class{constructor(){this.ea=void 0,this.ta=[]}na(){return this.ta.some(e=>e.ra())}},ml=class{constructor(){this.queries=yg(),this.onlineState="Unknown",this.ia=new Set}terminate(){(function(t,n){let s=$(t),i=s.queries;s.queries=yg(),i.forEach((a,u)=>{for(let c of u.ta)c.onError(n)})})(this,new L(D.ABORTED,"Firestore shutting down"))}};function yg(){return new Rt(r=>ry(r),ua)}async function ky(r,e){let t=$(r),n=3,s=e.query,i=t.queries.get(s);i?!i.na()&&e.ra()&&(n=2):(i=new pl,n=e.ra()?0:1);try{switch(n){case 0:i.ea=await t.onListen(s,!0);break;case 1:i.ea=await t.onListen(s,!1);break;case 2:await t.onFirstRemoteStoreListen(s)}}catch(a){let u=Hl(a,`Initialization of query '${fn(e.query)}' failed`);return void e.onError(u)}t.queries.set(s,i),i.ta.push(e),e.sa(t.onlineState),i.ea&&e.oa(i.ea)&&Wl(t)}async function Dy(r,e){let t=$(r),n=e.query,s=3,i=t.queries.get(n);if(i){let a=i.ta.indexOf(e);a>=0&&(i.ta.splice(a,1),i.ta.length===0?s=e.ra()?0:1:!i.na()&&e.ra()&&(s=2))}switch(s){case 0:return t.queries.delete(n),t.onUnlisten(n,!0);case 1:return t.queries.delete(n),t.onUnlisten(n,!1);case 2:return t.onLastRemoteStoreUnlisten(n);default:return}}function IR(r,e){let t=$(r),n=!1;for(let s of e){let i=s.query,a=t.queries.get(i);if(a){for(let u of a.ta)u.oa(s)&&(n=!0);a.ea=s}}n&&Wl(t)}function AR(r,e,t){let n=$(r),s=n.queries.get(e);if(s)for(let i of s.ta)i.onError(t);n.queries.delete(e)}function Wl(r){r.ia.forEach(e=>{e.next()})}var gl,_g;(_g=gl||(gl={}))._a="default",_g.Cache="cache";var Ko=class{constructor(e,t,n){this.query=e,this.aa=t,this.ua=!1,this.ca=null,this.onlineState="Unknown",this.options=n||{}}oa(e){if(!this.options.includeMetadataChanges){let n=[];for(let s of e.docChanges)s.type!==3&&n.push(s);e=new Dn(e.query,e.docs,e.oldDocs,n,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.ua?this.la(e)&&(this.aa.next(e),t=!0):this.ha(e,this.onlineState)&&(this.Pa(e),t=!0),this.ca=e,t}onError(e){this.aa.error(e)}sa(e){this.onlineState=e;let t=!1;return this.ca&&!this.ua&&this.ha(this.ca,e)&&(this.Pa(this.ca),t=!0),t}ha(e,t){if(!e.fromCache||!this.ra())return!0;let n=t!=="Offline";return(!this.options.Ta||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||t==="Offline")}la(e){if(e.docChanges.length>0)return!0;let t=this.ca&&this.ca.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&this.options.includeMetadataChanges===!0}Pa(e){e=Dn.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.ua=!0,this.aa.next(e)}ra(){return this.options.source!==gl.Cache}};var Ho=class{constructor(e){this.key=e}},Wo=class{constructor(e){this.key=e}},yl=class{constructor(e,t){this.query=e,this.fa=t,this.ga=null,this.hasCachedResults=!1,this.current=!1,this.pa=W(),this.mutatedKeys=W(),this.ya=ny(e),this.wa=new zo(this.ya)}get Sa(){return this.fa}ba(e,t){let n=t?t.Da:new Go,s=t?t.wa:this.wa,i=t?t.mutatedKeys:this.mutatedKeys,a=s,u=!1,c=this.query.limitType==="F"&&s.size===this.query.limit?s.last():null,h=this.query.limitType==="L"&&s.size===this.query.limit?s.first():null;if(e.inorderTraversal((f,m)=>{let g=s.get(f),b=ca(this.query,m)?m:null,P=!!g&&this.mutatedKeys.has(g.key),C=!!b&&(b.hasLocalMutations||this.mutatedKeys.has(b.key)&&b.hasCommittedMutations),R=!1;g&&b?g.data.isEqual(b.data)?P!==C&&(n.track({type:3,doc:b}),R=!0):this.va(g,b)||(n.track({type:2,doc:b}),R=!0,(c&&this.ya(b,c)>0||h&&this.ya(b,h)<0)&&(u=!0)):!g&&b?(n.track({type:0,doc:b}),R=!0):g&&!b&&(n.track({type:1,doc:g}),R=!0,(c||h)&&(u=!0)),R&&(b?(a=a.add(b),i=C?i.add(f):i.delete(f)):(a=a.delete(f),i=i.delete(f)))}),this.query.limit!==null)for(;a.size>this.query.limit;){let f=this.query.limitType==="F"?a.last():a.first();a=a.delete(f.key),i=i.delete(f.key),n.track({type:1,doc:f})}return{wa:a,Da:n,ls:u,mutatedKeys:i}}va(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,s){let i=this.wa;this.wa=e.wa,this.mutatedKeys=e.mutatedKeys;let a=e.Da.X_();a.sort((f,m)=>function(b,P){let C=R=>{switch(R){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return M()}};return C(b)-C(P)}(f.type,m.type)||this.ya(f.doc,m.doc)),this.Ca(n),s=s!=null&&s;let u=t&&!s?this.Fa():[],c=this.pa.size===0&&this.current&&!s?1:0,h=c!==this.ga;return this.ga=c,a.length!==0||h?{snapshot:new Dn(this.query,e.wa,i,a,e.mutatedKeys,c===0,h,!1,!!n&&n.resumeToken.approximateByteSize()>0),Ma:u}:{Ma:u}}sa(e){return this.current&&e==="Offline"?(this.current=!1,this.applyChanges({wa:this.wa,Da:new Go,mutatedKeys:this.mutatedKeys,ls:!1},!1)):{Ma:[]}}xa(e){return!this.fa.has(e)&&!!this.wa.has(e)&&!this.wa.get(e).hasLocalMutations}Ca(e){e&&(e.addedDocuments.forEach(t=>this.fa=this.fa.add(t)),e.modifiedDocuments.forEach(t=>{}),e.removedDocuments.forEach(t=>this.fa=this.fa.delete(t)),this.current=e.current)}Fa(){if(!this.current)return[];let e=this.pa;this.pa=W(),this.wa.forEach(n=>{this.xa(n.key)&&(this.pa=this.pa.add(n.key))});let t=[];return e.forEach(n=>{this.pa.has(n)||t.push(new Wo(n))}),this.pa.forEach(n=>{e.has(n)||t.push(new Ho(n))}),t}Oa(e){this.fa=e.gs,this.pa=W();let t=this.ba(e.documents);return this.applyChanges(t,!0)}Na(){return Dn.fromInitialDocuments(this.query,this.wa,this.mutatedKeys,this.ga===0,this.hasCachedResults)}},Ql="SyncEngine",_l=class{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}},vl=class{constructor(e){this.key=e,this.Ba=!1}},wl=class{constructor(e,t,n,s,i,a){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=s,this.currentUser=i,this.maxConcurrentLimboResolutions=a,this.La={},this.ka=new Rt(u=>ry(u),ua),this.qa=new Map,this.Qa=new Set,this.$a=new ce(j.comparator),this.Ua=new Map,this.Ka=new js,this.Wa={},this.Ga=new Map,this.za=Ms.Kn(),this.onlineState="Unknown",this.ja=void 0}get isPrimaryClient(){return this.ja===!0}};async function xR(r,e,t=!0){let n=My(r),s,i=n.ka.get(e);return i?(n.sharedClientState.addLocalQueryTarget(i.targetId),s=i.view.Na()):s=await Oy(n,e,t,!0),s}async function SR(r,e){let t=My(r);await Oy(t,e,!0,!1)}async function Oy(r,e,t,n){let s=await lR(r.localStore,nt(e)),i=s.targetId,a=r.sharedClientState.addLocalQueryTarget(i,t),u;return n&&(u=await RR(r,e,i,a==="current",s.resumeToken)),r.isPrimaryClient&&t&&Ay(r.remoteStore,s),u}async function RR(r,e,t,n,s){r.Ha=(m,g,b)=>async function(C,R,N,F){let U=R.view.ba(N);U.ls&&(U=await fg(C.localStore,R.query,!1).then(({documents:E})=>R.view.ba(E,U)));let G=F&&F.targetChanges.get(R.targetId),Y=F&&F.targetMismatches.get(R.targetId)!=null,B=R.view.applyChanges(U,C.isPrimaryClient,G,Y);return wg(C,R.targetId,B.Ma),B.snapshot}(r,m,g,b);let i=await fg(r.localStore,e,!0),a=new yl(e,i.gs),u=a.ba(i.documents),c=Ls.createSynthesizedTargetChangeForCurrentChange(t,n&&r.onlineState!=="Offline",s),h=a.applyChanges(u,r.isPrimaryClient,c);wg(r,t,h.Ma);let f=new _l(e,t,a);return r.ka.set(e,f),r.qa.has(t)?r.qa.get(t).push(e):r.qa.set(t,[e]),h.snapshot}async function PR(r,e,t){let n=$(r),s=n.ka.get(e),i=n.qa.get(s.targetId);if(i.length>1)return n.qa.set(s.targetId,i.filter(a=>!ua(a,e))),void n.ka.delete(e);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(s.targetId),n.sharedClientState.isActiveQueryTarget(s.targetId)||await el(n.localStore,s.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(s.targetId),t&&ql(n.remoteStore,s.targetId),bl(n,s.targetId)}).catch(Ln)):(bl(n,s.targetId),await el(n.localStore,s.targetId,!0))}async function CR(r,e){let t=$(r),n=t.ka.get(e),s=t.qa.get(n.targetId);t.isPrimaryClient&&s.length===1&&(t.sharedClientState.removeLocalQueryTarget(n.targetId),ql(t.remoteStore,n.targetId))}async function kR(r,e,t){let n=MR(r);try{let s=await function(a,u){let c=$(a),h=we.now(),f=u.reduce((b,P)=>b.add(P.key),W()),m,g;return c.persistence.runTransaction("Locally write mutations","readwrite",b=>{let P=Pt(),C=W();return c.ds.getEntries(b,f).next(R=>{P=R,P.forEach((N,F)=>{F.isValidDocument()||(C=C.add(N))})}).next(()=>c.localDocuments.getOverlayedDocuments(b,P)).next(R=>{m=R;let N=[];for(let F of u){let U=LS(F,m.get(F.key).overlayedDocument);U!=null&&N.push(new ut(F.key,U,Jg(U.value.mapValue),Xt.exists(!0)))}return c.mutationQueue.addMutationBatch(b,h,N,u)}).next(R=>{g=R;let N=R.applyToLocalDocumentSet(m,C);return c.documentOverlayCache.saveOverlays(b,R.batchId,N)})}).then(()=>({batchId:g.batchId,changes:iy(m)}))}(n.localStore,e);n.sharedClientState.addPendingMutation(s.batchId),function(a,u,c){let h=a.Wa[a.currentUser.toKey()];h||(h=new ce(K)),h=h.insert(u,c),a.Wa[a.currentUser.toKey()]=h}(n,s.batchId,t),await Ws(n,s.changes),await da(n.remoteStore)}catch(s){let i=Hl(s,"Failed to persist write");t.reject(i)}}async function Ny(r,e){let t=$(r);try{let n=await aR(t.localStore,e);e.targetChanges.forEach((s,i)=>{let a=t.Ua.get(i);a&&(ee(s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size<=1),s.addedDocuments.size>0?a.Ba=!0:s.modifiedDocuments.size>0?ee(a.Ba):s.removedDocuments.size>0&&(ee(a.Ba),a.Ba=!1))}),await Ws(t,n,e)}catch(n){await Ln(n)}}function vg(r,e,t){let n=$(r);if(n.isPrimaryClient&&t===0||!n.isPrimaryClient&&t===1){let s=[];n.ka.forEach((i,a)=>{let u=a.view.sa(e);u.snapshot&&s.push(u.snapshot)}),function(a,u){let c=$(a);c.onlineState=u;let h=!1;c.queries.forEach((f,m)=>{for(let g of m.ta)g.sa(u)&&(h=!0)}),h&&Wl(c)}(n.eventManager,e),s.length&&n.La.p_(s),n.onlineState=e,n.isPrimaryClient&&n.sharedClientState.setOnlineState(e)}}async function DR(r,e,t){let n=$(r);n.sharedClientState.updateQueryState(e,"rejected",t);let s=n.Ua.get(e),i=s&&s.key;if(i){let a=new ce(j.comparator);a=a.insert(i,Je.newNoDocument(i,q.min()));let u=W().add(i),c=new ko(q.min(),new Map,new ce(K),a,u);await Ny(n,c),n.$a=n.$a.remove(i),n.Ua.delete(e),Jl(n)}else await el(n.localStore,e,!1).then(()=>bl(n,e,t)).catch(Ln)}async function OR(r,e){let t=$(r),n=e.batch.batchId;try{let s=await oR(t.localStore,e);Ly(t,n,null),Vy(t,n),t.sharedClientState.updateMutationState(n,"acknowledged"),await Ws(t,s)}catch(s){await Ln(s)}}async function NR(r,e,t){let n=$(r);try{let s=await function(a,u){let c=$(a);return c.persistence.runTransaction("Reject batch","readwrite-primary",h=>{let f;return c.mutationQueue.lookupMutationBatch(h,u).next(m=>(ee(m!==null),f=m.keys(),c.mutationQueue.removeMutationBatch(h,m))).next(()=>c.mutationQueue.performConsistencyCheck(h)).next(()=>c.documentOverlayCache.removeOverlaysForBatchId(h,f,u)).next(()=>c.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(h,f)).next(()=>c.localDocuments.getDocuments(h,f))})}(n.localStore,e);Ly(n,e,t),Vy(n,e),n.sharedClientState.updateMutationState(e,"rejected",t),await Ws(n,s)}catch(s){await Ln(s)}}function Vy(r,e){(r.Ga.get(e)||[]).forEach(t=>{t.resolve()}),r.Ga.delete(e)}function Ly(r,e,t){let n=$(r),s=n.Wa[n.currentUser.toKey()];if(s){let i=s.get(e);i&&(t?i.reject(t):i.resolve(),s=s.remove(e)),n.Wa[n.currentUser.toKey()]=s}}function bl(r,e,t=null){r.sharedClientState.removeLocalQueryTarget(e);for(let n of r.qa.get(e))r.ka.delete(n),t&&r.La.Ja(n,t);r.qa.delete(e),r.isPrimaryClient&&r.Ka.br(e).forEach(n=>{r.Ka.containsKey(n)||Fy(r,n)})}function Fy(r,e){r.Qa.delete(e.path.canonicalString());let t=r.$a.get(e);t!==null&&(ql(r.remoteStore,t),r.$a=r.$a.remove(e),r.Ua.delete(t),Jl(r))}function wg(r,e,t){for(let n of t)n instanceof Ho?(r.Ka.addReference(n.key,e),VR(r,n)):n instanceof Wo?(V(Ql,"Document no longer in limbo: "+n.key),r.Ka.removeReference(n.key,e),r.Ka.containsKey(n.key)||Fy(r,n.key)):M()}function VR(r,e){let t=e.key,n=t.path.canonicalString();r.$a.get(t)||r.Qa.has(n)||(V(Ql,"New document in limbo: "+t),r.Qa.add(n),Jl(r))}function Jl(r){for(;r.Qa.size>0&&r.$a.size<r.maxConcurrentLimboResolutions;){let e=r.Qa.values().next().value;r.Qa.delete(e);let t=new j(fe.fromString(e)),n=r.za.next();r.Ua.set(n,new vl(t)),r.$a=r.$a.insert(t,n),Ay(r.remoteStore,new Fs(nt(aa(t.path)),n,"TargetPurposeLimboResolution",bn.ae))}}async function Ws(r,e,t){let n=$(r),s=[],i=[],a=[];n.ka.isEmpty()||(n.ka.forEach((u,c)=>{a.push(n.Ha(c,e,t).then(h=>{var f;if((h||t)&&n.isPrimaryClient){let m=h?!h.fromCache:(f=t==null?void 0:t.targetChanges.get(c.targetId))===null||f===void 0?void 0:f.current;n.sharedClientState.updateQueryState(c.targetId,m?"current":"not-current")}if(h){s.push(h);let m=Jc.Yi(c.targetId,h);i.push(m)}}))}),await Promise.all(a),n.La.p_(s),await async function(c,h){let f=$(c);try{await f.persistence.runTransaction("notifyLocalViewChanges","readwrite",m=>k.forEach(h,g=>k.forEach(g.Hi,b=>f.persistence.referenceDelegate.addReference(m,g.targetId,b)).next(()=>k.forEach(g.Ji,b=>f.persistence.referenceDelegate.removeReference(m,g.targetId,b)))))}catch(m){if(!Fn(m))throw m;V($l,"Failed to update sequence numbers: "+m)}for(let m of h){let g=m.targetId;if(!m.fromCache){let b=f.Ts.get(g),P=b.snapshotVersion,C=b.withLastLimboFreeSnapshotVersion(P);f.Ts=f.Ts.insert(g,C)}}}(n.localStore,i))}async function LR(r,e){let t=$(r);if(!t.currentUser.isEqual(e)){V(Ql,"User change. New user:",e.toKey());let n=await Ey(t.localStore,e);t.currentUser=e,function(i,a){i.Ga.forEach(u=>{u.forEach(c=>{c.reject(new L(D.CANCELLED,a))})}),i.Ga.clear()}(t,"'waitForPendingWrites' promise is rejected due to a user change."),t.sharedClientState.handleUserChange(e,n.removedBatchIds,n.addedBatchIds),await Ws(t,n.Rs)}}function FR(r,e){let t=$(r),n=t.Ua.get(e);if(n&&n.Ba)return W().add(n.key);{let s=W(),i=t.qa.get(e);if(!i)return s;for(let a of i){let u=t.ka.get(a);s=s.unionWith(u.view.Sa)}return s}}function My(r){let e=$(r);return e.remoteStore.remoteSyncer.applyRemoteEvent=Ny.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=FR.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=DR.bind(null,e),e.La.p_=IR.bind(null,e.eventManager),e.La.Ja=AR.bind(null,e.eventManager),e}function MR(r){let e=$(r);return e.remoteStore.remoteSyncer.applySuccessfulWrite=OR.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=NR.bind(null,e),e}var On=class{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=la(e.databaseInfo.databaseId),this.sharedClientState=this.Za(e),this.persistence=this.Xa(e),await this.persistence.start(),this.localStore=this.eu(e),this.gcScheduler=this.tu(e,this.localStore),this.indexBackfillerScheduler=this.nu(e,this.localStore)}tu(e,t){return null}nu(e,t){return null}eu(e){return iR(this.persistence,new Xc,e.initialUser,this.serializer)}Xa(e){return new Fo(Qc.ri,this.serializer)}Za(e){return new tl}async terminate(){var e,t;(e=this.gcScheduler)===null||e===void 0||e.stop(),(t=this.indexBackfillerScheduler)===null||t===void 0||t.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}};On.provider={build:()=>new On};var Tl=class extends On{constructor(e){super(),this.cacheSizeBytes=e}tu(e,t){ee(this.persistence.referenceDelegate instanceof Mo);let n=this.persistence.referenceDelegate.garbageCollector;return new Lc(n,e.asyncQueue,t)}Xa(e){let t=this.cacheSizeBytes!==void 0?$e.withCacheSize(this.cacheSizeBytes):$e.DEFAULT;return new Fo(n=>Mo.ri(n,t),this.serializer)}};var Us=class{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=n=>vg(this.syncEngine,n,1),this.remoteStore.remoteSyncer.handleCredentialChange=LR.bind(null,this.syncEngine),await ER(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return function(){return new ml}()}createDatastore(e){let t=la(e.databaseInfo.databaseId),n=function(i){return new ol(i)}(e.databaseInfo);return function(i,a,u,c){return new ll(i,a,u,c)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return function(n,s,i,a,u){return new dl(n,s,i,a,u)}(this.localStore,this.datastore,e.asyncQueue,t=>vg(this.syncEngine,t,0),function(){return Uo.D()?new Uo:new rl}())}createSyncEngine(e,t){return function(s,i,a,u,c,h,f){let m=new wl(s,i,a,u,c,h);return f&&(m.ja=!0),m}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e,t;await async function(s){let i=$(s);V(Tr,"RemoteStore shutting down."),i.W_.add(5),await Hs(i),i.z_.shutdown(),i.j_.set("Unknown")}(this.remoteStore),(e=this.datastore)===null||e===void 0||e.terminate(),(t=this.eventManager)===null||t===void 0||t.terminate()}};Us.provider={build:()=>new Us};var Qo=class{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.iu(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.iu(this.observer.error,e):At("Uncaught Error in snapshot listener:",e.toString()))}su(){this.muted=!0}iu(e,t){setTimeout(()=>{this.muted||e(t)},0)}};var tr="FirestoreClient",El=class{constructor(e,t,n,s,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=s,this.user=ye.UNAUTHENTICATED,this.clientId=Eo.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,async a=>{V(tr,"Received user=",a.uid),await this.authCredentialListener(a),this.user=a}),this.appCheckCredentials.start(n,a=>(V(tr,"Received new app check token=",a),this.appCheckCredentialListener(a,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let e=new tt;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){let n=Hl(t,"Failed to shutdown persistence");e.reject(n)}}),e.promise}};async function Qu(r,e){r.asyncQueue.verifyOperationInProgress(),V(tr,"Initializing OfflineComponentProvider");let t=r.configuration;await e.initialize(t);let n=t.initialUser;r.setCredentialChangeListener(async s=>{n.isEqual(s)||(await Ey(e.localStore,s),n=s)}),e.persistence.setDatabaseDeletedListener(()=>r.terminate()),r._offlineComponents=e}async function bg(r,e){r.asyncQueue.verifyOperationInProgress();let t=await jR(r);V(tr,"Initializing OnlineComponentProvider"),await e.initialize(t,r.configuration),r.setCredentialChangeListener(n=>gg(e.remoteStore,n)),r.setAppCheckTokenChangeListener((n,s)=>gg(e.remoteStore,s)),r._onlineComponents=e}async function jR(r){if(!r._offlineComponents)if(r._uninitializedComponentsProvider){V(tr,"Using user provided OfflineComponentProvider");try{await Qu(r,r._uninitializedComponentsProvider._offline)}catch(e){let t=e;if(!function(s){return s.name==="FirebaseError"?s.code===D.FAILED_PRECONDITION||s.code===D.UNIMPLEMENTED:!(typeof DOMException!="undefined"&&s instanceof DOMException)||s.code===22||s.code===20||s.code===11}(t))throw t;vn("Error using user provided cache. Falling back to memory cache: "+t),await Qu(r,new On)}}else V(tr,"Using default OfflineComponentProvider"),await Qu(r,new Tl(void 0));return r._offlineComponents}async function jy(r){return r._onlineComponents||(r._uninitializedComponentsProvider?(V(tr,"Using user provided OnlineComponentProvider"),await bg(r,r._uninitializedComponentsProvider._online)):(V(tr,"Using default OnlineComponentProvider"),await bg(r,new Us))),r._onlineComponents}function UR(r){return jy(r).then(e=>e.syncEngine)}async function Il(r){let e=await jy(r),t=e.eventManager;return t.onListen=xR.bind(null,e.syncEngine),t.onUnlisten=PR.bind(null,e.syncEngine),t.onFirstRemoteStoreListen=SR.bind(null,e.syncEngine),t.onLastRemoteStoreUnlisten=CR.bind(null,e.syncEngine),t}function BR(r,e,t={}){let n=new tt;return r.asyncQueue.enqueueAndForget(async()=>function(i,a,u,c,h){let f=new Qo({next:g=>{f.su(),a.enqueueAndForget(()=>Dy(i,m));let b=g.docs.has(u);!b&&g.fromCache?h.reject(new L(D.UNAVAILABLE,"Failed to get document because the client is offline.")):b&&g.fromCache&&c&&c.source==="server"?h.reject(new L(D.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.)')):h.resolve(g)},error:g=>h.reject(g)}),m=new Ko(aa(u.path),f,{includeMetadataChanges:!0,Ta:!0});return ky(i,m)}(await Il(r),r.asyncQueue,e,t,n)),n.promise}function Uy(r){let e={};return r.timeoutSeconds!==void 0&&(e.timeoutSeconds=r.timeoutSeconds),e}var Tg=new Map;function $R(r,e,t){if(!t)throw new L(D.INVALID_ARGUMENT,`Function ${r}() cannot be called with an empty ${e}.`)}function qR(r,e,t,n){if(e===!0&&n===!0)throw new L(D.INVALID_ARGUMENT,`${r} and ${t} cannot be used together.`)}function Eg(r){if(!j.isDocumentKey(r))throw new L(D.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${r} has ${r.length}.`)}function Yl(r){if(r===void 0)return"undefined";if(r===null)return"null";if(typeof r=="string")return r.length>20&&(r=`${r.substring(0,20)}...`),JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean")return""+r;if(typeof r=="object"){if(r instanceof Array)return"an array";{let e=function(n){return n.constructor?n.constructor.name:null}(r);return e?`a custom ${e} object`:"an object"}}return typeof r=="function"?"a function":M()}function it(r,e){if("_delegate"in r&&(r=r._delegate),!(r instanceof e)){if(e.name===r.constructor.name)throw new L(D.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let t=Yl(r);throw new L(D.INVALID_ARGUMENT,`Expected type '${e.name}', but it was: ${t}`)}}return r}var By="firestore.googleapis.com",Ig=!0,Jo=class{constructor(e){var t,n;if(e.host===void 0){if(e.ssl!==void 0)throw new L(D.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=By,this.ssl=Ig}else this.host=e.host,this.ssl=(t=e.ssl)!==null&&t!==void 0?t:Ig;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e.cacheSizeBytes===void 0)this.cacheSizeBytes=Ty;else{if(e.cacheSizeBytes!==-1&&e.cacheSizeBytes<rR)throw new L(D.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}qR("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:e.experimentalAutoDetectLongPolling===void 0?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Uy((n=e.experimentalLongPollingOptions)!==null&&n!==void 0?n:{}),function(i){if(i.timeoutSeconds!==void 0){if(isNaN(i.timeoutSeconds))throw new L(D.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (must not be NaN)`);if(i.timeoutSeconds<5)throw new L(D.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (minimum allowed value is 5)`);if(i.timeoutSeconds>30)throw new L(D.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&function(n,s){return n.timeoutSeconds===s.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}},Bs=class{constructor(e,t,n,s){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=s,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Jo({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new L(D.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 this._terminateTask!=="notTerminated"}_setSettings(e){if(this._settingsFrozen)throw new L(D.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 Jo(e),this._emulatorOptions=e.emulatorOptions||{},e.credentials!==void 0&&(this._authCredentials=function(n){if(!n)return new Ju;switch(n.type){case"firstParty":return new ec(n.sessionIndex||"0",n.iamToken||null,n.authTokenFactory||null);case"provider":return n.client;default:throw new L(D.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask==="notTerminated"&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){this._terminateTask==="notTerminated"?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(t){let n=Tg.get(t);n&&(V("ComponentProvider","Removing Datastore"),Tg.delete(t),n.terminate())}(this),Promise.resolve()}};function zR(r,e,t,n={}){var s;let i=(r=it(r,Bs))._getSettings(),a=Object.assign(Object.assign({},i),{emulatorOptions:r._getEmulatorOptions()}),u=`${e}:${t}`;i.host!==By&&i.host!==u&&vn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let c=Object.assign(Object.assign({},i),{host:u,ssl:!1,emulatorOptions:n});if(!cn(c,a)&&(r._setSettings(c),n.mockUserToken)){let h,f;if(typeof n.mockUserToken=="string")h=n.mockUserToken,f=ye.MOCK_USER;else{h=mm(n.mockUserToken,(s=r._app)===null||s===void 0?void 0:s.options.projectId);let m=n.mockUserToken.sub||n.mockUserToken.user_id;if(!m)throw new L(D.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");f=new ye(m)}r._authCredentials=new Yu(new bo(h,f))}}var Yo=class r{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new r(this.firestore,e,this._query)}},Ne=class r{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new $s(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new r(this.firestore,e,this._key)}},$s=class r extends Yo{constructor(e,t,n){super(e,t,aa(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new Ne(this.firestore,null,new j(e))}withConverter(e){return new r(this.firestore,e,this._path)}};function fa(r,e,...t){if(r=wt(r),arguments.length===1&&(e=Eo.newId()),$R("doc","path",e),r instanceof Bs){let n=fe.fromString(e,...t);return Eg(n),new Ne(r,null,new j(n))}{if(!(r instanceof Ne||r instanceof $s))throw new L(D.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let n=r._path.child(fe.fromString(e,...t));return Eg(n),new Ne(r.firestore,r instanceof $s?r.converter:null,new j(n))}}var Ag="AsyncQueue",Xo=class{constructor(e=Promise.resolve()){this.Vu=[],this.mu=!1,this.fu=[],this.gu=null,this.pu=!1,this.yu=!1,this.wu=[],this.a_=new Bo(this,"async_queue_retry"),this.Su=()=>{let n=Wu();n&&V(Ag,"Visibility state changed to "+n.visibilityState),this.a_.t_()},this.bu=e;let t=Wu();t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",this.Su)}get isShuttingDown(){return this.mu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Du(),this.vu(e)}enterRestrictedMode(e){if(!this.mu){this.mu=!0,this.yu=e||!1;let t=Wu();t&&typeof t.removeEventListener=="function"&&t.removeEventListener("visibilitychange",this.Su)}}enqueue(e){if(this.Du(),this.mu)return new Promise(()=>{});let t=new tt;return this.vu(()=>this.mu&&this.yu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Vu.push(e),this.Cu()))}async Cu(){if(this.Vu.length!==0){try{await this.Vu[0](),this.Vu.shift(),this.a_.reset()}catch(e){if(!Fn(e))throw e;V(Ag,"Operation failed with retryable error: "+e)}this.Vu.length>0&&this.a_.Xo(()=>this.Cu())}}vu(e){let t=this.bu.then(()=>(this.pu=!0,e().catch(n=>{this.gu=n,this.pu=!1;let s=function(a){let u=a.message||"";return a.stack&&(u=a.stack.includes(a.message)?a.stack:a.message+`
22
+ `+a.stack),u}(n);throw At("INTERNAL UNHANDLED ERROR: ",s),n}).then(n=>(this.pu=!1,n))));return this.bu=t,t}enqueueAfterDelay(e,t,n){this.Du(),this.wu.indexOf(e)>-1&&(t=0);let s=fl.createAndSchedule(this,e,t,n,i=>this.Fu(i));return this.fu.push(s),s}Du(){this.gu&&M()}verifyOperationInProgress(){}async Mu(){let e;do e=this.bu,await e;while(e!==this.bu)}xu(e){for(let t of this.fu)if(t.timerId===e)return!0;return!1}Ou(e){return this.Mu().then(()=>{this.fu.sort((t,n)=>t.targetTimeMs-n.targetTimeMs);for(let t of this.fu)if(t.skipDelay(),e!=="all"&&t.timerId===e)break;return this.Mu()})}Nu(e){this.wu.push(e)}Fu(e){let t=this.fu.indexOf(e);this.fu.splice(t,1)}};function xg(r){return function(t,n){if(typeof t!="object"||t===null)return!1;let s=t;for(let i of n)if(i in s&&typeof s[i]=="function")return!0;return!1}(r,["next","error","complete"])}var rr=class extends Bs{constructor(e,t,n,s){super(e,t,n,s),this.type="firestore",this._queue=new Xo,this._persistenceKey=(s==null?void 0:s.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new Xo(e),this._firestoreClient=void 0,await e}}};function $y(r,e){let t=typeof r=="object"?r:Nm(),n=typeof r=="string"?r:e||So,s=km(t,"firestore").getImmediate({identifier:n});if(!s._initialized){let i=pm("firestore");i&&zR(s,...i)}return s}function Xl(r){if(r._terminated)throw new L(D.FAILED_PRECONDITION,"The client has already been terminated.");return r._firestoreClient||GR(r),r._firestoreClient}function GR(r){var e,t,n;let s=r._freezeSettings(),i=function(u,c,h,f){return new ic(u,c,h,f.host,f.ssl,f.experimentalForceLongPolling,f.experimentalAutoDetectLongPolling,Uy(f.experimentalLongPollingOptions),f.useFetchStreams)}(r._databaseId,((e=r._app)===null||e===void 0?void 0:e.options.appId)||"",r._persistenceKey,s);r._componentsProvider||!((t=s.localCache)===null||t===void 0)&&t._offlineComponentProvider&&(!((n=s.localCache)===null||n===void 0)&&n._onlineComponentProvider)&&(r._componentsProvider={_offline:s.localCache._offlineComponentProvider,_online:s.localCache._onlineComponentProvider}),r._firestoreClient=new El(r._authCredentials,r._appCheckCredentials,r._queue,i,r._componentsProvider&&function(u){let c=u==null?void 0:u._online.build();return{_offline:u==null?void 0:u._offline.build(c),_online:c}}(r._componentsProvider))}var qs=class r{constructor(e){this._byteString=e}static fromBase64String(e){try{return new r(Re.fromBase64String(e))}catch(t){throw new L(D.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+t)}}static fromUint8Array(e){return new r(Re.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}};var Nn=class{constructor(...e){for(let t=0;t<e.length;++t)if(e[t].length===0)throw new L(D.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Ue(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}};var zs=class{constructor(e){this._methodName=e}};var Gs=class{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new L(D.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new L(D.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return K(this._lat,e._lat)||K(this._long,e._long)}};var Ks=class{constructor(e){this._values=(e||[]).map(t=>t)}toArray(){return this._values.map(e=>e)}isEqual(e){return function(n,s){if(n.length!==s.length)return!1;for(let i=0;i<n.length;++i)if(n[i]!==s[i])return!1;return!0}(this._values,e._values)}};var KR=/^__.*__$/,Al=class{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return this.fieldMask!==null?new ut(e,this.data,this.fieldMask,t,this.fieldTransforms):new br(e,this.data,t,this.fieldTransforms)}},Zo=class{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new ut(e,this.data,this.fieldMask,t,this.fieldTransforms)}};function qy(r){switch(r){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw M()}}var xl=class r{constructor(e,t,n,s,i,a){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=s,i===void 0&&this.Bu(),this.fieldTransforms=i||[],this.fieldMask=a||[]}get path(){return this.settings.path}get Lu(){return this.settings.Lu}ku(e){return new r(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}qu(e){var t;let n=(t=this.path)===null||t===void 0?void 0:t.child(e),s=this.ku({path:n,Qu:!1});return s.$u(e),s}Uu(e){var t;let n=(t=this.path)===null||t===void 0?void 0:t.child(e),s=this.ku({path:n,Qu:!1});return s.Bu(),s}Ku(e){return this.ku({path:void 0,Qu:!0})}Wu(e){return ta(e,this.settings.methodName,this.settings.Gu||!1,this.path,this.settings.zu)}contains(e){return this.fieldMask.find(t=>e.isPrefixOf(t))!==void 0||this.fieldTransforms.find(t=>e.isPrefixOf(t.field))!==void 0}Bu(){if(this.path)for(let e=0;e<this.path.length;e++)this.$u(this.path.get(e))}$u(e){if(e.length===0)throw this.Wu("Document fields must not be empty");if(qy(this.Lu)&&KR.test(e))throw this.Wu('Document fields cannot begin and end with "__"')}},Sl=class{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||la(e)}ju(e,t,n,s=!1){return new xl({Lu:e,methodName:t,zu:n,path:Ue.emptyPath(),Qu:!1,Gu:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function zy(r){let e=r._freezeSettings(),t=la(r._databaseId);return new Sl(r._databaseId,!!e.ignoreUndefinedProperties,t)}function HR(r,e,t,n,s,i={}){let a=r.ju(i.merge||i.mergeFields?2:0,e,t,s);Zl("Data must be an object, but it was:",a,n);let u=Gy(n,a),c,h;if(i.merge)c=new qe(a.fieldMask),h=a.fieldTransforms;else if(i.mergeFields){let f=[];for(let m of i.mergeFields){let g=Rl(e,m,t);if(!a.contains(g))throw new L(D.INVALID_ARGUMENT,`Field '${g}' is specified in your field mask but missing from your input data.`);Hy(f,g)||f.push(g)}c=new qe(f),h=a.fieldTransforms.filter(m=>c.covers(m.field))}else c=null,h=a.fieldTransforms;return new Al(new je(u),c,h)}var ea=class r extends zs{_toFieldTransform(e){if(e.Lu!==2)throw e.Lu===1?e.Wu(`${this._methodName}() can only appear at the top level of your update data`):e.Wu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof r}};function WR(r,e,t,n){let s=r.ju(1,e,t);Zl("Data must be an object, but it was:",s,n);let i=[],a=je.empty();nr(n,(c,h)=>{let f=eh(e,c,t);h=wt(h);let m=s.Uu(f);if(h instanceof ea)i.push(f);else{let g=pa(h,m);g!=null&&(i.push(f),a.set(f,g))}});let u=new qe(i);return new Zo(a,u,s.fieldTransforms)}function QR(r,e,t,n,s,i){let a=r.ju(1,e,t),u=[Rl(e,n,t)],c=[s];if(i.length%2!=0)throw new L(D.INVALID_ARGUMENT,`Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let g=0;g<i.length;g+=2)u.push(Rl(e,i[g])),c.push(i[g+1]);let h=[],f=je.empty();for(let g=u.length-1;g>=0;--g)if(!Hy(h,u[g])){let b=u[g],P=c[g];P=wt(P);let C=a.Uu(b);if(P instanceof ea)h.push(b);else{let R=pa(P,C);R!=null&&(h.push(b),f.set(b,R))}}let m=new qe(h);return new Zo(f,m,a.fieldTransforms)}function pa(r,e){if(Ky(r=wt(r)))return Zl("Unsupported field value:",e,r),Gy(r,e);if(r instanceof zs)return function(n,s){if(!qy(s.Lu))throw s.Wu(`${n._methodName}() can only be used with update() and set()`);if(!s.path)throw s.Wu(`${n._methodName}() is not currently supported inside arrays`);let i=n._toFieldTransform(s);i&&s.fieldTransforms.push(i)}(r,e),null;if(r===void 0&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),r instanceof Array){if(e.settings.Qu&&e.Lu!==4)throw e.Wu("Nested arrays are not supported");return function(n,s){let i=[],a=0;for(let u of n){let c=pa(u,s.Ku(a));c==null&&(c={nullValue:"NULL_VALUE"}),i.push(c),a++}return{arrayValue:{values:i}}}(r,e)}return function(n,s){if((n=wt(n))===null)return{nullValue:"NULL_VALUE"};if(typeof n=="number")return kS(s.serializer,n);if(typeof n=="boolean")return{booleanValue:n};if(typeof n=="string")return{stringValue:n};if(n instanceof Date){let i=we.fromDate(n);return{timestampValue:Vo(s.serializer,i)}}if(n instanceof we){let i=new we(n.seconds,1e3*Math.floor(n.nanoseconds/1e3));return{timestampValue:Vo(s.serializer,i)}}if(n instanceof Gs)return{geoPointValue:{latitude:n.latitude,longitude:n.longitude}};if(n instanceof qs)return{bytesValue:my(s.serializer,n._byteString)};if(n instanceof Ne){let i=s.databaseId,a=n.firestore._databaseId;if(!a.isEqual(i))throw s.Wu(`Document reference is for database ${a.projectId}/${a.database} but should be for database ${i.projectId}/${i.database}`);return{referenceValue:Bl(n.firestore._databaseId||s.databaseId,n._key.path)}}if(n instanceof Ks)return function(a,u){return{mapValue:{fields:{[Vl]:{stringValue:Ll},[Tn]:{arrayValue:{values:a.toArray().map(h=>{if(typeof h!="number")throw u.Wu("VectorValues must only contain numeric values.");return Ul(u.serializer,h)})}}}}}}(n,s);throw s.Wu(`Unsupported field value: ${Yl(n)}`)}(r,e)}function Gy(r,e){let t={};return $g(r)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):nr(r,(n,s)=>{let i=pa(s,e.qu(n));i!=null&&(t[n]=i)}),{mapValue:{fields:t}}}function Ky(r){return!(typeof r!="object"||r===null||r instanceof Array||r instanceof Date||r instanceof we||r instanceof Gs||r instanceof qs||r instanceof Ne||r instanceof zs||r instanceof Ks)}function Zl(r,e,t){if(!Ky(t)||!function(s){return typeof s=="object"&&s!==null&&(Object.getPrototypeOf(s)===Object.prototype||Object.getPrototypeOf(s)===null)}(t)){let n=Yl(t);throw n==="an object"?e.Wu(r+" a custom object"):e.Wu(r+" "+n)}}function Rl(r,e,t){if((e=wt(e))instanceof Nn)return e._internalPath;if(typeof e=="string")return eh(r,e);throw ta("Field path arguments must be of type string or ",r,!1,void 0,t)}var JR=new RegExp("[~\\*/\\[\\]]");function eh(r,e,t){if(e.search(JR)>=0)throw ta(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,r,!1,void 0,t);try{return new Nn(...e.split("."))._internalPath}catch{throw ta(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,r,!1,void 0,t)}}function ta(r,e,t,n,s){let i=n&&!n.isEmpty(),a=s!==void 0,u=`Function ${e}() called with invalid data`;t&&(u+=" (via `toFirestore()`)"),u+=". ";let c="";return(i||a)&&(c+=" (found",i&&(c+=` in field ${n}`),a&&(c+=` in document ${s}`),c+=")"),new L(D.INVALID_ARGUMENT,u+r+c)}function Hy(r,e){return r.some(t=>t.isEqual(e))}var ra=class{constructor(e,t,n,s,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=s,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new Ne(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new Pl(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){let t=this._document.data.field(Wy("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t)}}},Pl=class extends ra{data(){return super.data()}};function Wy(r,e){return typeof e=="string"?eh(r,e):e instanceof Nn?e._internalPath:e._delegate._internalPath}function YR(r){if(r.limitType==="L"&&r.explicitOrderBy.length===0)throw new L(D.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var Cl=class{convertValue(e,t="none"){switch(Zt(e)){case 0:return null;case 1:return e.booleanValue;case 2:return oe(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(St(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw M()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let n={};return nr(e,(s,i)=>{n[s]=this.convertValue(i,t)}),n}convertVectorValue(e){var t,n,s;let i=(s=(n=(t=e.fields)===null||t===void 0?void 0:t[Tn].arrayValue)===null||n===void 0?void 0:n.values)===null||s===void 0?void 0:s.map(a=>oe(a.doubleValue));return new Ks(i)}convertGeoPoint(e){return new Gs(oe(e.latitude),oe(e.longitude))}convertArray(e,t){return(e.values||[]).map(n=>this.convertValue(n,t))}convertServerTimestamp(e,t){switch(t){case"previous":let n=oa(e);return n==null?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Ns(e));default:return null}}convertTimestamp(e){let t=xt(e);return new we(t.seconds,t.nanos)}convertDocumentKey(e,t){let n=fe.fromString(e);ee(by(n));let s=new Ro(n.get(1),n.get(3)),i=new j(n.popFirst(5));return s.isEqual(t)||At(`Document ${i} 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 (${t.projectId}/${t.database}) instead.`),i}};function XR(r,e,t){let n;return n=r?t&&(t.merge||t.mergeFields)?r.toFirestore(e,t):r.toFirestore(e):e,n}var gr=class{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}},na=class extends ra{constructor(e,t,n,s,i,a){super(e,t,n,s,a),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let t=new _n(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){let n=this._document.data.field(Wy("DocumentSnapshot.get",e));if(n!==null)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}},_n=class extends na{data(e={}){return super.data(e)}},kl=class{constructor(e,t,n,s){this._firestore=e,this._userDataWriter=t,this._snapshot=s,this.metadata=new gr(s.hasPendingWrites,s.fromCache),this.query=n}get docs(){let e=[];return this.forEach(t=>e.push(t)),e}get size(){return this._snapshot.docs.size}get empty(){return this.size===0}forEach(e,t){this._snapshot.docs.forEach(n=>{e.call(t,new _n(this._firestore,this._userDataWriter,n.key,n,new gr(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new L(D.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(s,i){if(s._snapshot.oldDocs.isEmpty()){let a=0;return s._snapshot.docChanges.map(u=>{let c=new _n(s._firestore,s._userDataWriter,u.doc.key,u.doc,new gr(s._snapshot.mutatedKeys.has(u.doc.key),s._snapshot.fromCache),s.query.converter);return u.doc,{type:"added",doc:c,oldIndex:-1,newIndex:a++}})}{let a=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(u=>i||u.type!==3).map(u=>{let c=new _n(s._firestore,s._userDataWriter,u.doc.key,u.doc,new gr(s._snapshot.mutatedKeys.has(u.doc.key),s._snapshot.fromCache),s.query.converter),h=-1,f=-1;return u.type!==0&&(h=a.indexOf(u.doc.key),a=a.delete(u.doc.key)),u.type!==1&&(a=a.add(u.doc),f=a.indexOf(u.doc.key)),{type:ZR(u.type),doc:c,oldIndex:h,newIndex:f}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}};function ZR(r){switch(r){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return M()}}function th(r){r=it(r,Ne);let e=it(r.firestore,rr);return BR(Xl(e),r._key).then(t=>Yy(e,r,t))}var sa=class extends Cl{constructor(e){super(),this.firestore=e}convertBytes(e){return new qs(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new Ne(this.firestore,null,t)}};function rh(r,e,t){r=it(r,Ne);let n=it(r.firestore,rr),s=XR(r.converter,e,t);return Jy(n,[HR(zy(n),"setDoc",r._key,s,r.converter!==null,t).toMutation(r._key,Xt.none())])}function nh(r,e,t,...n){r=it(r,Ne);let s=it(r.firestore,rr),i=zy(s),a;return a=typeof(e=wt(e))=="string"||e instanceof Nn?QR(i,"updateDoc",r._key,e,t,n):WR(i,"updateDoc",r._key,e),Jy(s,[a.toMutation(r._key,Xt.exists(!0))])}function Qy(r,...e){var t,n,s;r=wt(r);let i={includeMetadataChanges:!1,source:"default"},a=0;typeof e[a]!="object"||xg(e[a])||(i=e[a],a++);let u={includeMetadataChanges:i.includeMetadataChanges,source:i.source};if(xg(e[a])){let m=e[a];e[a]=(t=m.next)===null||t===void 0?void 0:t.bind(m),e[a+1]=(n=m.error)===null||n===void 0?void 0:n.bind(m),e[a+2]=(s=m.complete)===null||s===void 0?void 0:s.bind(m)}let c,h,f;if(r instanceof Ne)h=it(r.firestore,rr),f=aa(r._key.path),c={next:m=>{e[a]&&e[a](Yy(h,r,m))},error:e[a+1],complete:e[a+2]};else{let m=it(r,Yo);h=it(m.firestore,rr),f=m._query;let g=new sa(h);c={next:b=>{e[a]&&e[a](new kl(h,g,m,b))},error:e[a+1],complete:e[a+2]},YR(r._query)}return function(g,b,P,C){let R=new Qo(C),N=new Ko(b,R,P);return g.asyncQueue.enqueueAndForget(async()=>ky(await Il(g),N)),()=>{R.su(),g.asyncQueue.enqueueAndForget(async()=>Dy(await Il(g),N))}}(Xl(h),f,u,c)}function Jy(r,e){return function(n,s){let i=new tt;return n.asyncQueue.enqueueAndForget(async()=>kR(await UR(n),s,i)),i.promise}(Xl(r),e)}function Yy(r,e,t){let n=t.docs.get(e._key),s=new sa(r);return new na(r,s,e._key,n,new gr(t.hasPendingWrites,t.fromCache),e.converter)}(function(e,t=!0){(function(s){Vn=s})(Om),Is(new bt("firestore",(n,{instanceIdentifier:s,options:i})=>{let a=n.getProvider("app").getImmediate(),u=new rr(new Xu(n.getProvider("auth-internal")),new tc(a,n.getProvider("app-check-internal")),function(h,f){if(!Object.prototype.hasOwnProperty.apply(h.options,["projectId"]))throw new L(D.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Ro(h.options.projectId,f)}(a,s),a);return i=Object.assign({useFetchStreams:t},i),u._setSettings(i),u},"PUBLIC").setMultipleInstances(!0)),Yt(jm,Um,e),Yt(jm,Um,"esm2017")})();var Xy=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(sr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)};var Qs=class extends Error{constructor(e,t="FunctionsError",n){super(e),this.name=t,this.context=n}},ma=class extends Qs{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},ga=class extends Qs{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},ya=class extends Qs{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},_a;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(_a||(_a={}));var sP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},Js=class{constructor(e,{headers:t={},customFetch:n,region:s=_a.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=Xy(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var n;return sP(this,void 0,void 0,function*(){try{let{headers:s,method:i,body:a}=t,u={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(u["x-region"]=c);let h;a&&(s&&!Object.prototype.hasOwnProperty.call(s,"Content-Type")||!s)&&(typeof Blob!="undefined"&&a instanceof Blob||a instanceof ArrayBuffer?(u["Content-Type"]="application/octet-stream",h=a):typeof a=="string"?(u["Content-Type"]="text/plain",h=a):typeof FormData!="undefined"&&a instanceof FormData?h=a:(u["Content-Type"]="application/json",h=JSON.stringify(a)));let f=yield this.fetch(`${this.url}/${e}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},u),this.headers),s),body:h}).catch(P=>{throw new ma(P)}),m=f.headers.get("x-relay-error");if(m&&m==="true")throw new ga(f);if(!f.ok)throw new ya(f);let g=((n=f.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),b;return g==="application/json"?b=yield f.json():g==="application/octet-stream"?b=yield f.blob():g==="text/event-stream"?b=f:g==="multipart/form-data"?b=yield f.formData():b=yield f.text(),{data:b,error:null}}catch(s){return{data:null,error:s}}})}};var h_=hu(l_(),1),{PostgrestClient:d_,PostgrestQueryBuilder:g2,PostgrestFilterBuilder:y2,PostgrestTransformBuilder:_2,PostgrestBuilder:v2,PostgrestError:gP}=h_.default;var f_="2.11.2";var p_={"X-Client-Info":`realtime-js/${f_}`},m_="1.0.0",Ea=1e4,g_=1e3,Ar;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(Ar||(Ar={}));var Ve;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(Ve||(Ve={}));var Be;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(Be||(Be={}));var Ta;(function(r){r.websocket="websocket"})(Ta||(Ta={}));var ir;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(ir||(ir={}));var ni=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),n=new TextDecoder;return this._decodeBroadcast(e,t,n)}_decodeBroadcast(e,t,n){let s=t.getUint8(1),i=t.getUint8(2),a=this.HEADER_LENGTH+2,u=n.decode(e.slice(a,a+s));a=a+s;let c=n.decode(e.slice(a,a+i));a=a+i;let h=JSON.parse(n.decode(e.slice(a,e.byteLength)));return{ref:null,topic:u,event:c,payload:h}}};var xr=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var ne;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(ne||(ne={}));var _h=(r,e,t={})=>{var n;let s=(n=t.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((i,a)=>(i[a]=yP(a,r,e,s),i),{})},yP=(r,e,t,n)=>{let s=e.find(u=>u.name===r),i=s==null?void 0:s.type,a=t[r];return i&&!n.includes(i)?y_(i,a):yh(a)},y_=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return bP(e,t)}switch(r){case ne.bool:return _P(e);case ne.float4:case ne.float8:case ne.int2:case ne.int4:case ne.int8:case ne.numeric:case ne.oid:return vP(e);case ne.json:case ne.jsonb:return wP(e);case ne.timestamp:return TP(e);case ne.abstime:case ne.date:case ne.daterange:case ne.int4range:case ne.int8range:case ne.money:case ne.reltime:case ne.text:case ne.time:case ne.timestamptz:case ne.timetz:case ne.tsrange:case ne.tstzrange:return yh(e);default:return yh(e)}},yh=r=>r,_P=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},vP=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},wP=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},bP=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,n=r[t];if(r[0]==="{"&&n==="}"){let i,a=r.slice(1,t);try{i=JSON.parse("["+a+"]")}catch{i=a?a.split(","):[]}return i.map(u=>y_(e,u))}return r},TP=r=>typeof r=="string"?r.replace(" ","T"):r,Ia=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var Sr=class{constructor(e,t,n={},s=Ea){this.channel=e,this.event=t,this.payload=n,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var n;return this._hasReceived(e)&&t((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(n=>n.status===e).forEach(n=>n.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var vh;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(vh||(vh={}));var Bn=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let n=(t==null?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},s=>{let{onJoin:i,onLeave:a,onSync:u}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,s,i,a),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,i,a)}),this.pendingDiffs=[],u()}),this.channel._on(n.diff,{},s=>{let{onJoin:i,onLeave:a,onSync:u}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=r.syncDiff(this.state,s,i,a),u())}),this.onJoin((s,i,a)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:a})}),this.onLeave((s,i,a)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:a})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,n,s){let i=this.cloneDeep(e),a=this.transformState(t),u={},c={};return this.map(i,(h,f)=>{a[h]||(c[h]=f)}),this.map(a,(h,f)=>{let m=i[h];if(m){let g=f.map(R=>R.presence_ref),b=m.map(R=>R.presence_ref),P=f.filter(R=>b.indexOf(R.presence_ref)<0),C=m.filter(R=>g.indexOf(R.presence_ref)<0);P.length>0&&(u[h]=P),C.length>0&&(c[h]=C)}else u[h]=f}),this.syncDiff(i,{joins:u,leaves:c},n,s)}static syncDiff(e,t,n,s){let{joins:i,leaves:a}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return n||(n=()=>{}),s||(s=()=>{}),this.map(i,(u,c)=>{var h;let f=(h=e[u])!==null&&h!==void 0?h:[];if(e[u]=this.cloneDeep(c),f.length>0){let m=e[u].map(b=>b.presence_ref),g=f.filter(b=>m.indexOf(b.presence_ref)<0);e[u].unshift(...g)}n(u,f,c)}),this.map(a,(u,c)=>{let h=e[u];if(!h)return;let f=c.map(m=>m.presence_ref);h=h.filter(m=>f.indexOf(m.presence_ref)<0),e[u]=h,s(u,h,c),h.length===0&&delete e[u]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(n=>t(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,n)=>{let s=e[n];return"metas"in s?t[n]=s.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):t[n]=s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var wh;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(wh||(wh={}));var bh;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(bh||(bh={}));var ct;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(ct||(ct={}));var $n=class r{constructor(e,t={config:{}},n){this.topic=e,this.params=t,this.socket=n,this.bindings={},this.state=Ve.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new Sr(this,Be.join,this.params,this.timeout),this.rejoinTimer=new xr(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Ve.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=Ve.closed,this.socket._remove(this)}),this._onError(s=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,s),this.state=Ve.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Ve.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Be.reply,{},(s,i)=>{this._trigger(this._replyEventName(i),s)}),this.presence=new Bn(this),this.broadcastEndpointURL=Ia(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var n,s;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:i,presence:a,private:u}}=this.params;this._onError(f=>e==null?void 0:e(ct.CHANNEL_ERROR,f)),this._onClose(()=>e==null?void 0:e(ct.CLOSED));let c={},h={broadcast:i,presence:a,postgres_changes:(s=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(f=>f.filter))!==null&&s!==void 0?s:[],private:u};this.socket.accessTokenValue&&(c.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:h},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:f})=>{var m;if(this.socket.setAuth(),f===void 0){e==null||e(ct.SUBSCRIBED);return}else{let g=this.bindings.postgres_changes,b=(m=g==null?void 0:g.length)!==null&&m!==void 0?m:0,P=[];for(let C=0;C<b;C++){let R=g[C],{filter:{event:N,schema:F,table:U,filter:G}}=R,Y=f&&f[C];if(Y&&Y.event===N&&Y.schema===F&&Y.table===U&&Y.filter===G)P.push(Object.assign(Object.assign({},R),{id:Y.id}));else{this.unsubscribe(),e==null||e(ct.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=P,e&&e(ct.SUBSCRIBED);return}}).receive("error",f=>{e==null||e(ct.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(ct.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,n){return this._on(e,t,n)}async send(e,t={}){var n,s;if(!this._canPush()&&e.type==="broadcast"){let{event:i,payload:a}=e,c={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:a,private:this.private}]})};try{let h=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(n=t.timeout)!==null&&n!==void 0?n:this.timeout);return await((s=h.body)===null||s===void 0?void 0:s.cancel()),h.ok?"ok":"error"}catch(h){return h.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var a,u,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(u=(a=this.params)===null||a===void 0?void 0:a.config)===null||u===void 0?void 0:u.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),h.receive("ok",()=>i("ok")),h.receive("error",()=>i("error")),h.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=Ve.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Be.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(n=>{let s=new Sr(this,Be.leave,{},e);s.receive("ok",()=>{t(),n("ok")}).receive("timeout",()=>{t(),n("timed out")}).receive("error",()=>{n("error")}),s.send(),this._canPush()||s.trigger("ok",{})})}async _fetchWithTimeout(e,t,n){let s=new AbortController,i=setTimeout(()=>s.abort(),n),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(i),a}_push(e,t,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new Sr(this,e,t,n);return this._canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}_onMessage(e,t,n){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,n){var s,i;let a=e.toLocaleLowerCase(),{close:u,error:c,leave:h,join:f}=Be;if(n&&[u,c,h,f].indexOf(a)>=0&&n!==this._joinRef())return;let g=this._onMessage(a,t,n);if(t&&!g)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(a)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(b=>{var P,C,R;return((P=b.filter)===null||P===void 0?void 0:P.event)==="*"||((R=(C=b.filter)===null||C===void 0?void 0:C.event)===null||R===void 0?void 0:R.toLocaleLowerCase())===a}).map(b=>b.callback(g,n)):(i=this.bindings[a])===null||i===void 0||i.filter(b=>{var P,C,R,N,F,U;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in b){let G=b.id,Y=(P=b.filter)===null||P===void 0?void 0:P.event;return G&&((C=t.ids)===null||C===void 0?void 0:C.includes(G))&&(Y==="*"||(Y==null?void 0:Y.toLocaleLowerCase())===((R=t.data)===null||R===void 0?void 0:R.type.toLocaleLowerCase()))}else{let G=(F=(N=b==null?void 0:b.filter)===null||N===void 0?void 0:N.event)===null||F===void 0?void 0:F.toLocaleLowerCase();return G==="*"||G===((U=t==null?void 0:t.event)===null||U===void 0?void 0:U.toLocaleLowerCase())}else return b.type.toLocaleLowerCase()===a}).map(b=>{if(typeof g=="object"&&"ids"in g){let P=g.data,{schema:C,table:R,commit_timestamp:N,type:F,errors:U}=P;g=Object.assign(Object.assign({},{schema:C,table:R,commit_timestamp:N,eventType:F,new:{},old:{},errors:U}),this._getPayloadRecords(P))}b.callback(g,n)})}_isClosed(){return this.state===Ve.closed}_isJoined(){return this.state===Ve.joined}_isJoining(){return this.state===Ve.joining}_isLeaving(){return this.state===Ve.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,n){let s=e.toLocaleLowerCase(),i={type:s,filter:t,callback:n};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,t){let n=e.toLocaleLowerCase();return this.bindings[n]=this.bindings[n].filter(s=>{var i;return!(((i=s.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===n&&r.isEqual(s.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Be.close,{},e)}_onError(e){this._on(Be.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Ve.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=_h(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=_h(e.columns,e.old_record)),t}};var IP=()=>{},AP=typeof WebSocket!="undefined",xP=`
23
23
  addEventListener("message", (e) => {
24
24
  if (e.data.event === "start") {
25
25
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
26
26
  }
27
- });`,qn=class{constructor(e,t){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=p_,this.params={},this.timeout=Ia,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=IP,this.conn=null,this.sendBuffer=[],this.serializer=new ni,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let a;return i?a=i:typeof fetch=="undefined"?a=(...u)=>Promise.resolve().then(()=>(sr(),Ir)).then(({default:c})=>c(...u)):a=fetch,(...u)=>a(...u)},this.endPoint=`${e}/${Ea.websocket}`,this.httpEndpoint=Aa(e),t!=null&&t.transport?this.transport=t.transport:this.transport=null,t!=null&&t.params&&(this.params=t.params),t!=null&&t.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t!=null&&t.timeout&&(this.timeout=t.timeout),t!=null&&t.logger&&(this.logger=t.logger),t!=null&&t.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let s=(n=t==null?void 0:t.params)===null||n===void 0?void 0:n.apikey;if(s&&(this.accessTokenValue=s,this.apiKey=s),this.reconnectAfterMs=t!=null&&t.reconnectAfterMs?t.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=t!=null&&t.encode?t.encode:(i,a)=>a(JSON.stringify(i)),this.decode=t!=null&&t.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new xr(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t==null?void 0:t.fetch),t!=null&&t.worker){if(typeof window!="undefined"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(t==null?void 0:t.worker)||!1,this.workerUrl=t==null?void 0:t.workerUrl}this.accessToken=(t==null?void 0:t.accessToken)||null}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers});return}if(AP){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new Th(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>hu(v_())).then(({default:e})=>{this.conn=new e(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:m_}))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t!=null?t:""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,n){this.logger(e,t,n)}connectionState(){switch(this.conn&&this.conn.readyState){case Ar.connecting:return ir.Connecting;case Ar.open:return ir.Open;case Ar.closing:return ir.Closing;default:return ir.Closed}}isConnected(){return this.connectionState()===ir.Open}channel(e,t={config:{}}){let n=new $n(`realtime:${e}`,t,this);return this.channels.push(n),n}push(e){let{topic:t,event:n,payload:s,ref:i}=e,a=()=>{this.encode(e,u=>{var c;(c=this.conn)===null||c===void 0||c.send(u)})};this.log("push",`${t} ${n} (${i})`,s),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){let t=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;if(t){let n=null;try{n=JSON.parse(atob(t.split(".")[1]))}catch{}if(n&&n.exp&&!(Math.floor(Date.now()/1e3)-n.exp<0))return this.log("auth",`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${n.exp}`),Promise.reject(`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${n.exp}`);this.accessTokenValue=t,this.channels.forEach(s=>{t&&s.updateJoinPayload({access_token:t}),s.joinedOnce&&s._isJoined()&&s._push(Be.access_token,{access_token:t})})}}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(g_,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth()}}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:n,event:s,payload:i,ref:a}=t;a&&a===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${n} ${s} ${a&&"("+a+")"||""}`,i),this.channels.filter(u=>u._isMember(n)).forEach(u=>u._trigger(s,i,a)),this.stateChangeCallbacks.message.forEach(u=>u(t))})}async _onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);else{this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(Be.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let n=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${n}${s}`}_workerObjectUrl(e){let t;if(e)t=e;else{let n=new Blob([xP],{type:"application/javascript"});t=URL.createObjectURL(n)}return t}},Th=class{constructor(e,t,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Ar.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}};var zn=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function pe(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var xa=class extends zn{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Rr=class extends zn{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var SP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},Ra=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(sr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},w_=()=>SP(void 0,void 0,void 0,function*(){return typeof Response=="undefined"?(yield Promise.resolve().then(()=>(sr(),Ir))).Response:Response}),Sa=r=>{if(Array.isArray(r))return r.map(t=>Sa(t));if(typeof r=="function"||r!==Object(r))return r;let e={};return Object.entries(r).forEach(([t,n])=>{let s=t.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[s]=Sa(n)}),e};var Pr=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},Eh=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),RP=(r,e,t)=>Pr(void 0,void 0,void 0,function*(){let n=yield w_();r instanceof n&&!(t!=null&&t.noResolveJson)?r.json().then(s=>{e(new xa(Eh(s),r.status||500))}).catch(s=>{e(new Rr(Eh(s),s))}):e(new Rr(Eh(r),r))}),PP=(r,e,t,n)=>{let s={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),n&&(s.body=JSON.stringify(n)),Object.assign(Object.assign({},s),t))};function si(r,e,t,n,s,i){return Pr(this,void 0,void 0,function*(){return new Promise((a,u)=>{r(t,PP(e,n,s,i)).then(c=>{if(!c.ok)throw c;return n!=null&&n.noResolveJson?c:c.json()}).then(c=>a(c)).catch(c=>RP(c,u,n))})})}function Gn(r,e,t,n){return Pr(this,void 0,void 0,function*(){return si(r,"GET",e,t,n)})}function lt(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return si(r,"POST",e,n,s,t)})}function b_(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return si(r,"PUT",e,n,s,t)})}function T_(r,e,t,n){return Pr(this,void 0,void 0,function*(){return si(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),n)})}function Pa(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return si(r,"DELETE",e,n,s,t)})}var Le=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},CP={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},E_={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ii=class{constructor(e,t={},n,s){this.url=e,this.headers=t,this.bucketId=n,this.fetch=Ra(s)}uploadOrUpdate(e,t,n,s){return Le(this,void 0,void 0,function*(){try{let i,a=Object.assign(Object.assign({},E_),s),u=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(a.upsert)}),c=a.metadata;typeof Blob!="undefined"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",n)):typeof FormData!="undefined"&&n instanceof FormData?(i=n,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=n,u["cache-control"]=`max-age=${a.cacheControl}`,u["content-type"]=a.contentType,c&&(u["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),s!=null&&s.headers&&(u=Object.assign(Object.assign({},u),s.headers));let h=this._removeEmptyFolders(t),f=this._getFinalPath(h),m=yield this.fetch(`${this.url}/object/${f}`,Object.assign({method:e,body:i,headers:u},a!=null&&a.duplex?{duplex:a.duplex}:{})),g=yield m.json();return m.ok?{data:{path:h,id:g.Id,fullPath:g.Key},error:null}:{data:null,error:g}}catch(i){if(pe(i))return{data:null,error:i};throw i}})}upload(e,t,n){return Le(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,n)})}uploadToSignedUrl(e,t,n,s){return Le(this,void 0,void 0,function*(){let i=this._removeEmptyFolders(e),a=this._getFinalPath(i),u=new URL(this.url+`/object/upload/sign/${a}`);u.searchParams.set("token",t);try{let c,h=Object.assign({upsert:E_.upsert},s),f=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob!="undefined"&&n instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",n)):typeof FormData!="undefined"&&n instanceof FormData?(c=n,c.append("cacheControl",h.cacheControl)):(c=n,f["cache-control"]=`max-age=${h.cacheControl}`,f["content-type"]=h.contentType);let m=yield this.fetch(u.toString(),{method:"PUT",body:c,headers:f}),g=yield m.json();return m.ok?{data:{path:i,fullPath:g.Key},error:null}:{data:null,error:g}}catch(c){if(pe(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return Le(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e),s=Object.assign({},this.headers);t!=null&&t.upsert&&(s["x-upsert"]="true");let i=yield lt(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:s}),a=new URL(this.url+i.url),u=a.searchParams.get("token");if(!u)throw new zn("No token returned by API");return{data:{signedUrl:a.toString(),path:e,token:u},error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}update(e,t,n){return Le(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,n)})}move(e,t,n){return Le(this,void 0,void 0,function*(){try{return{data:yield lt(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(pe(s))return{data:null,error:s};throw s}})}copy(e,t,n){return Le(this,void 0,void 0,function*(){try{return{data:{path:(yield lt(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(s){if(pe(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,n){return Le(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=yield lt(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers}),a=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${a}`)},{data:i,error:null}}catch(s){if(pe(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,n){return Le(this,void 0,void 0,function*(){try{let s=yield lt(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:s.map(a=>Object.assign(Object.assign({},a),{signedUrl:a.signedURL?encodeURI(`${this.url}${a.signedURL}${i}`):null})),error:null}}catch(s){if(pe(s))return{data:null,error:s};throw s}})}download(e,t){return Le(this,void 0,void 0,function*(){let s=typeof(t==null?void 0:t.transform)!="undefined"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),a=i?`?${i}`:"";try{let u=this._getFinalPath(e);return{data:yield(yield Gn(this.fetch,`${this.url}/${s}/${u}${a}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(u){if(pe(u))return{data:null,error:u};throw u}})}info(e){return Le(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{let n=yield Gn(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:Sa(n),error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}exists(e){return Le(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{return yield T_(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(pe(n)&&n instanceof Rr){let s=n.originalError;if([400,404].includes(s==null?void 0:s.status))return{data:!1,error:n}}throw n}})}getPublicUrl(e,t){let n=this._getFinalPath(e),s=[],i=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&s.push(i);let u=typeof(t==null?void 0:t.transform)!="undefined"?"render/image":"object",c=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});c!==""&&s.push(c);let h=s.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${u}/public/${n}${h}`)}}}remove(e){return Le(this,void 0,void 0,function*(){try{return{data:yield Pa(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(pe(t))return{data:null,error:t};throw t}})}list(e,t,n){return Le(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},CP),t),{prefix:e||""});return{data:yield lt(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},n),error:null}}catch(s){if(pe(s))return{data:null,error:s};throw s}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer!="undefined"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var I_="2.7.1";var A_={"X-Client-Info":`storage-js/${I_}`};var Kn=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},oi=class{constructor(e,t={},n){this.url=e,this.headers=Object.assign(Object.assign({},A_),t),this.fetch=Ra(n)}listBuckets(){return Kn(this,void 0,void 0,function*(){try{return{data:yield Gn(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(pe(e))return{data:null,error:e};throw e}})}getBucket(e){return Kn(this,void 0,void 0,function*(){try{return{data:yield Gn(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(pe(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Kn(this,void 0,void 0,function*(){try{return{data:yield lt(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}updateBucket(e,t){return Kn(this,void 0,void 0,function*(){try{return{data:yield b_(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}emptyBucket(e){return Kn(this,void 0,void 0,function*(){try{return{data:yield lt(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(pe(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Kn(this,void 0,void 0,function*(){try{return{data:yield Pa(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(pe(t))return{data:null,error:t};throw t}})}};var ai=class extends oi{constructor(e,t={},n){super(e,t,n)}from(e){return new ii(this.url,this.headers,e,this.fetch)}};var x_="2.49.4";var ui="";typeof Deno!="undefined"?ui="deno":typeof document!="undefined"?ui="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?ui="react-native":ui="node";var kP={"X-Client-Info":`supabase-js-${ui}/${x_}`},S_={headers:kP},R_={schema:"public"},P_={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},C_={};sr();var DP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},OP=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=sh:e=fetch,(...t)=>e(...t)},NP=()=>typeof Headers=="undefined"?ih:Headers,k_=(r,e,t)=>{let n=OP(t),s=NP();return(i,a)=>DP(void 0,void 0,void 0,function*(){var u;let c=(u=yield e())!==null&&u!==void 0?u:r,h=new s(a==null?void 0:a.headers);return h.has("apikey")||h.set("apikey",r),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),n(i,Object.assign(Object.assign({},a),{headers:h}))})};var VP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})};function D_(r){return r.replace(/\/$/,"")}function O_(r,e){let{db:t,auth:n,realtime:s,global:i}=r,{db:a,auth:u,realtime:c,global:h}=e,f={db:Object.assign(Object.assign({},a),t),auth:Object.assign(Object.assign({},u),n),realtime:Object.assign(Object.assign({},c),s),global:Object.assign(Object.assign({},h),i),accessToken:()=>VP(this,void 0,void 0,function*(){return""})};return r.accessToken?f.accessToken=r.accessToken:delete f.accessToken,f}var Ca="2.69.1";var Cr=30*1e3,ka=3,Da=ka*Cr,N_="http://localhost:9999",V_="supabase.auth.token";var L_={"X-Client-Info":`gotrue-js/${Ca}`};var ci="X-Supabase-Api-Version",Ih={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},F_=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,M_=6e5;var li=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=n}};function z(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Oa=class extends li{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}};function j_(r){return z(r)&&r.name==="AuthApiError"}var Hn=class extends li{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ht=class extends li{constructor(e,t,n,s){super(e,n,s),this.name=t,this.status=n}},ze=class extends ht{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function U_(r){return z(r)&&r.name==="AuthSessionMissingError"}var Wn=class extends ht{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},kr=class extends ht{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Dr=class extends ht{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function B_(r){return z(r)&&r.name==="AuthImplicitGrantRedirectError"}var hi=class extends ht{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},Qn=class extends ht{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Na(r){return z(r)&&r.name==="AuthRetryableFetchError"}var di=class extends ht{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}};var Ct=class extends ht{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var $_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),q_=`
28
- \r=`.split(""),LP=(()=>{let r=new Array(128);for(let e=0;e<r.length;e+=1)r[e]=-1;for(let e=0;e<q_.length;e+=1)r[q_[e].charCodeAt(0)]=-2;for(let e=0;e<$_.length;e+=1)r[$_[e].charCodeAt(0)]=e;return r})();function z_(r,e,t){let n=LP[r];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(r)}"`)}}function Ah(r){let e=[],t=a=>{e.push(String.fromCodePoint(a))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=a=>{jP(a,n,t)};for(let a=0;a<r.length;a+=1)z_(r.charCodeAt(a),s,i);return e.join("")}function FP(r,e){if(r<=127){e(r);return}else if(r<=2047){e(192|r>>6),e(128|r&63);return}else if(r<=65535){e(224|r>>12),e(128|r>>6&63),e(128|r&63);return}else if(r<=1114111){e(240|r>>18),e(128|r>>12&63),e(128|r>>6&63),e(128|r&63);return}throw new Error(`Unrecognized Unicode codepoint: ${r.toString(16)}`)}function MP(r,e){for(let t=0;t<r.length;t+=1){let n=r.charCodeAt(t);if(n>55295&&n<=56319){let s=(n-55296)*1024&65535;n=(r.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}FP(n,e)}}function jP(r,e,t){if(e.utf8seq===0){if(r<=127){t(r);return}for(let n=1;n<6;n+=1)if((r>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=r&31;else if(e.utf8seq===3)e.codepoint=r&15;else if(e.utf8seq===4)e.codepoint=r&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(r<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|r&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function G_(r){let e=[],t={queue:0,queuedBits:0},n=s=>{e.push(s)};for(let s=0;s<r.length;s+=1)z_(r.charCodeAt(s),t,n);return new Uint8Array(e)}function K_(r){let e=[];return MP(r,t=>e.push(t)),new Uint8Array(e)}function H_(r){return Math.round(Date.now()/1e3)+r}function W_(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}var Ye=()=>typeof window!="undefined"&&typeof document!="undefined",Or={tested:!1,writable:!1},or=()=>{if(!Ye())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Or.tested)return Or.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Or.tested=!0,Or.writable=!0}catch{Or.tested=!0,Or.writable=!1}return Or.writable};function Q_(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return t.searchParams.forEach((n,s)=>{e[s]=n}),e}var Va=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(sr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},J_=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",xh=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},pi=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},mi=async(r,e)=>{await r.removeItem(e)},fi=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};fi.promiseConstructor=Promise;function La(r){let e=r.split(".");if(e.length!==3)throw new Ct("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!F_.test(e[n]))throw new Ct("JWT not in base64url format");return{header:JSON.parse(Ah(e[0])),payload:JSON.parse(Ah(e[1])),signature:G_(e[2]),raw:{header:e[0],payload:e[1]}}}async function Y_(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function X_(r,e){return new Promise((n,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let a=await r(i);if(!e(i,null,a)){n(a);return}}catch(a){if(!e(i,a)){s(a);return}}})()})}function UP(r){return("0"+r.toString(16)).substr(-2)}function BP(){let e=new Uint32Array(56);if(typeof crypto=="undefined"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=t.length,s="";for(let i=0;i<56;i++)s+=t.charAt(Math.floor(Math.random()*n));return s}return crypto.getRandomValues(e),Array.from(e,UP).join("")}async function $P(r){let t=new TextEncoder().encode(r),n=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(n);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function qP(r){if(!(typeof crypto!="undefined"&&typeof crypto.subtle!="undefined"&&typeof TextEncoder!="undefined"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),r;let t=await $P(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Nr(r,e,t=!1){let n=BP(),s=n;t&&(s+="/PASSWORD_RECOVERY"),await xh(r,`${e}-code-verifier`,s);let i=await qP(n);return[i,n===i?"plain":"s256"]}var zP=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Z_(r){let e=r.headers.get(ci);if(!e||!e.match(zP))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function ev(r){if(!r)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(r<=e)throw new Error("JWT has expired")}function tv(r){switch(r){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var GP=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(r);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(r,n[s])&&(t[n[s]]=r[n[s]]);return t},Vr=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),KP=[502,503,504];async function rv(r){var e;if(!J_(r))throw new Qn(Vr(r),0);if(KP.includes(r.status))throw new Qn(Vr(r),r.status);let t;try{t=await r.json()}catch(i){throw new Hn(Vr(i),i)}let n,s=Z_(r);if(s&&s.getTime()>=Ih["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?n=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(n=t.error_code),n){if(n==="weak_password")throw new di(Vr(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new ze}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,a)=>i&&typeof a=="string",!0))throw new di(Vr(t),r.status,t.weak_password.reasons);throw new Oa(Vr(t),r.status||500,n)}var HP=(r,e,t,n)=>{let s={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),t))};async function H(r,e,t,n){var s;let i=Object.assign({},n==null?void 0:n.headers);i[ci]||(i[ci]=Ih["2024-01-01"].name),n!=null&&n.jwt&&(i.Authorization=`Bearer ${n.jwt}`);let a=(s=n==null?void 0:n.query)!==null&&s!==void 0?s:{};n!=null&&n.redirectTo&&(a.redirect_to=n.redirectTo);let u=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await WP(r,e,t+u,{headers:i,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(c):{data:Object.assign({},c),error:null}}async function WP(r,e,t,n,s,i){let a=HP(e,n,s,i),u;try{u=await r(t,Object.assign({},a))}catch(c){throw console.error(c),new Qn(Vr(c),0)}if(u.ok||await rv(u),n!=null&&n.noResolveJson)return u;try{return await u.json()}catch(c){await rv(c)}}function kt(r){var e;let t=null;QP(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=H_(r.expires_in)));let n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:n},error:null}}function Sh(r){let e=kt(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,n)=>t&&typeof n=="string",!0)&&(e.data.weak_password=r.weak_password),e}function dt(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function nv(r){return{data:r,error:null}}function sv(r){let{action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i}=r,a=GP(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),u={action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i},c=Object.assign({},a);return{data:{properties:u,user:c},error:null}}function iv(r){return r}function QP(r){return r.access_token&&r.refresh_token&&r.expires_in}var JP=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(r);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(r,n[s])&&(t[n[s]]=r[n[s]]);return t},Lr=class{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=Va(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await H(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(z(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,t={}){try{return await H(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:dt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:t}=e,n=JP(e,["options"]),s=Object.assign(Object.assign({},n),t);return"newEmail"in n&&(s.new_email=n==null?void 0:n.newEmail,delete s.newEmail),await H(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:sv,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(z(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await H(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:dt})}catch(t){if(z(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,n,s,i,a,u,c;try{let h={nextPage:null,lastPage:0,total:0},f=await H(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=e==null?void 0:e.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:iv});if(f.error)throw f.error;let m=await f.json(),g=(a=f.headers.get("x-total-count"))!==null&&a!==void 0?a:0,b=(c=(u=f.headers.get("link"))===null||u===void 0?void 0:u.split(","))!==null&&c!==void 0?c:[];return b.length>0&&(b.forEach(P=>{let C=parseInt(P.split(";")[0].split("=")[1].substring(0,1)),R=JSON.parse(P.split(";")[1].split("=")[1]);h[`${R}Page`]=C}),h.total=parseInt(g)),{data:Object.assign(Object.assign({},m),h),error:null}}catch(h){if(z(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await H(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:dt})}catch(t){if(z(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await H(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:dt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,t=!1){try{return await H(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:dt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{let{data:t,error:n}=await H(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:n}}catch(t){if(z(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await H(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(z(t))return{data:null,error:t};throw t}}};var ov={getItem:r=>or()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{or()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{or()&&globalThis.localStorage.removeItem(r)}};function Rh(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function av(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self!="undefined"&&(self.globalThis=self)}}var Fr={debug:!!(globalThis&&or()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},gi=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Fa=class extends gi{};async function Ph(r,e,t){Fr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),Fr.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){Fr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,s.name);try{return await t()}finally{Fr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,s.name)}}else{if(e===0)throw Fr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Fa(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Fr.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}av();var YP={url:N_,storageKey:V_,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:L_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function uv(r,e,t){return await t()}var Mr=class r{constructor(e){var t,n;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=r.nextInstanceID,r.nextInstanceID+=1,this.instanceID>0&&Ye()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let s=Object.assign(Object.assign({},YP),e);if(this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.persistSession=s.persistSession,this.storageKey=s.storageKey,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Lr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Va(s.fetch),this.lock=s.lock||uv,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:Ye()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=Ph:this.lock=uv,this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?s.storage?this.storage=s.storage:or()?this.storage=ov:(this.memoryStorage={},this.storage=Rh(this.memoryStorage)):(this.memoryStorage={},this.storage=Rh(this.memoryStorage)),Ye()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Ca}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let t=Q_(window.location.href),n="none";if(this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce"),Ye()&&this.detectSessionInUrl&&n!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),B_(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}let{session:a,redirectType:u}=s;return this._debug("#_initialize()","detected session in URL",a,"redirect type",u),await this._saveSession(a),setTimeout(async()=>{u==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return z(t)?{error:t}:{error:new Hn("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,s;try{let i=await H(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(t=e==null?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.captchaToken}},xform:kt}),{data:a,error:u}=i;if(u||!a)return{data:{user:null,session:null},error:u};let c=a.session,h=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(z(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var t,n,s;try{let i;if("email"in e){let{email:f,password:m,options:g}=e,b=null,P=null;this.flowType==="pkce"&&([b,P]=await Nr(this.storage,this.storageKey)),i=await H(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:f,password:m,data:(t=g==null?void 0:g.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken},code_challenge:b,code_challenge_method:P},xform:kt})}else if("phone"in e){let{phone:f,password:m,options:g}=e;i=await H(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:m,data:(n=g==null?void 0:g.data)!==null&&n!==void 0?n:{},channel:(s=g==null?void 0:g.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken}},xform:kt})}else throw new kr("You must provide either an email or phone number and a password");let{data:a,error:u}=i;if(u||!a)return{data:{user:null,session:null},error:u};let c=a.session,h=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(z(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:a,options:u}=e;t=await H(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Sh})}else if("phone"in e){let{phone:i,password:a,options:u}=e;t=await H(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Sh})}else throw new kr("You must provide either an email or phone number and a password");let{data:n,error:s}=t;return s?{data:{user:null,session:null},error:s}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new Wn}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:s})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,n,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await pi(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{let{data:i,error:a}=await H(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:kt});if(await mi(this.storage,`${this.storageKey}-code-verifier`),a)throw a;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Wn}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:s!=null?s:null}),error:a})}catch(i){if(z(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(e){try{let{options:t,provider:n,token:s,access_token:i,nonce:a}=e,u=await H(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:kt}),{data:c,error:h}=u;return h?{data:{user:null,session:null},error:h}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Wn}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,n,s,i,a;try{if("email"in e){let{email:u,options:c}=e,h=null,f=null;this.flowType==="pkce"&&([h,f]=await Nr(this.storage,this.storageKey));let{error:m}=await H(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:u,data:(t=c==null?void 0:c.data)!==null&&t!==void 0?t:{},create_user:(n=c==null?void 0:c.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:m}}if("phone"in e){let{phone:u,options:c}=e,{data:h,error:f}=await H(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:u,data:(s=c==null?void 0:c.data)!==null&&s!==void 0?s:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(a=c==null?void 0:c.channel)!==null&&a!==void 0?a:"sms"}});return{data:{user:null,session:null,messageId:h==null?void 0:h.message_id},error:f}}throw new kr("You must provide either an email or phone number.")}catch(u){if(z(u))return{data:{user:null,session:null},error:u};throw u}}async verifyOtp(e){var t,n;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:a,error:u}=await H(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:kt});if(u)throw u;if(!a)throw new Error("An error occurred on token verification.");let c=a.session,h=a.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(s){if(z(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithSSO(e){var t,n,s;try{let i=null,a=null;return this.flowType==="pkce"&&([i,a]=await Nr(this.storage,this.storageKey)),await H(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&n!==void 0?n:void 0}),!((s=e==null?void 0:e.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:a}),headers:this.headers,xform:nv})}catch(i){if(z(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)throw n;if(!t)throw new ze;let{error:s}=await H(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(z(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:n,type:s,options:i}=e,{error:a}=await H(this.fetch,"POST",t,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:a}}else if("phone"in e){let{phone:n,type:s,options:i}=e,{data:a,error:u}=await H(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:u}}throw new kr("You must provide either an email or phone number and a type")}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await n,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=t();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await pi(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<Da:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.storage.isServer){let a=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,h,f)=>(!a&&h==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),a=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,h,f))})}return{data:{session:e},error:null}}let{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:s},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await H(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:dt}):await this._useSession(async t=>{var n,s,i;let{data:a,error:u}=t;if(u)throw u;return!(!((n=a.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ze}:await H(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:dt})})}catch(t){if(z(t))return U_(t)&&(await this._removeSession(),await mi(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async n=>{let{data:s,error:i}=n;if(i)throw i;if(!s.session)throw new ze;let a=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await Nr(this.storage,this.storageKey));let{data:h,error:f}=await H(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:u,code_challenge_method:c}),jwt:a.access_token,xform:dt});if(f)throw f;return a.user=h.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),{data:{user:a.user},error:null}})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ze;let t=Date.now()/1e3,n=t,s=!0,i=null,{payload:a}=La(e.access_token);if(a.exp&&(n=a.exp,s=n<=t),s){let{session:u,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!u)return{data:{user:null,session:null},error:null};i=u}else{let{data:u,error:c}=await this._getUser(e.access_token);if(c)throw c;i={access_token:e.access_token,refresh_token:e.refresh_token,user:u.user,token_type:"bearer",expires_in:n-t,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(t){if(z(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var n;if(!e){let{data:a,error:u}=t;if(u)throw u;e=(n=a.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new ze;let{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!Ye())throw new Dr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Dr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new hi("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Dr("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new hi("No code detected.");let{data:F,error:U}=await this._exchangeCodeForSession(e.code);if(U)throw U;let G=new URL(window.location.href);return G.searchParams.delete("code"),window.history.replaceState(window.history.state,"",G.toString()),{data:{session:F.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:a,expires_in:u,expires_at:c,token_type:h}=e;if(!i||!u||!a||!h)throw new Dr("No session defined in URL");let f=Math.round(Date.now()/1e3),m=parseInt(u),g=f+m;c&&(g=parseInt(c));let b=g-f;b*1e3<=Cr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${b}s, should have been closer to ${m}s`);let P=g-m;f-P>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",P,g,f):f-P<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",P,g,f);let{data:C,error:R}=await this._getUser(i);if(R)throw R;let N={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:m,expires_at:g,refresh_token:a,token_type:h,user:C.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:N,redirectType:e.type},error:null}}catch(n){if(z(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await pi(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var n;let{data:s,error:i}=t;if(i)return{error:i};let a=(n=s.session)===null||n===void 0?void 0:n.access_token;if(a){let{error:u}=await this.admin.signOut(a,e);if(u&&!(j_(u)&&(u.status===404||u.status===401||u.status===403)))return{error:u}}return e!=="others"&&(await this._removeSession(),await mi(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t=W_(),n={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,n),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async t=>{var n,s;try{let{data:{session:i},error:a}=t;if(a)throw a;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await Nr(this.storage,this.storageKey,!0));try{return await H(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(z(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{let{data:t,error:n}=await this.getUser();if(n)throw n;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(z(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:n,error:s}=await this._useSession(async i=>{var a,u,c,h,f;let{data:m,error:g}=i;if(g)throw g;let b=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(u=e.options)===null||u===void 0?void 0:u.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await H(this.fetch,"GET",b,{headers:this.headers,jwt:(f=(h=m.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(s)throw s;return Ye()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),{data:{provider:e.provider,url:n==null?void 0:n.url},error:null}}catch(n){if(z(n))return{data:{provider:e.provider,url:null},error:n};throw n}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:a}=t;if(a)throw a;return await H(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let n=Date.now();return await X_(async s=>(s>0&&await Y_(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await H(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:kt})),(s,i)=>{let a=200*Math.pow(2,s);return i&&Na(i)&&Date.now()+a-n<Cr})}catch(n){if(this._debug(t,"error",n),z(n))return{data:{session:null,user:null},error:n};throw n}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",n),Ye()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let n=await pi(this.storage,this.storageKey);if(this._debug(t,"session from storage",n),!this._isValidSession(n)){this._debug(t,"session is not valid"),n!==null&&await this._removeSession();return}let s=((e=n.expires_at)!==null&&e!==void 0?e:1/0)*1e3-Date.now()<Da;if(this._debug(t,`session has${s?"":" not"} expired with margin of ${Da}s`),s){if(this.autoRefreshToken&&n.refresh_token){let{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),Na(i)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(t,"error",n),console.error(n);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,n;if(!e)throw new ze;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new fi;let{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new ze;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let u={session:i.session,error:null};return this.refreshingDeferred.resolve(u),u}catch(i){if(this._debug(s,"error",i),z(i)){let a={session:null,error:i};return Na(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(a),a}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,n=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],a=Array.from(this.stateChangeEmitters.values()).map(async u=>{try{await u.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(a),i.length>0){for(let u=0;u<i.length;u+=1)console.error(i[u]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await xh(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await mi(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ye()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Cr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:n}}=t;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((n.expires_at*1e3-e)/Cr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Cr}ms, refresh threshold is ${ka} ticks`),s<=ka&&await this._callRefreshToken(n.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof gi)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ye()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){let s=[`provider=${encodeURIComponent(t)}`];if(n!=null&&n.redirectTo&&s.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[i,a]=await Nr(this.storage,this.storageKey),u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});s.push(u.toString())}if(n!=null&&n.queryParams){let i=new URLSearchParams(n.queryParams);s.push(i.toString())}return n!=null&&n.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;return i?{data:null,error:i}:await H(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:a}=t;if(a)return{data:null,error:a};let u=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:c,error:h}=await H(this.fetch,"POST",`${this.url}/factors`,{body:u,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return h?{data:null,error:h}:(e.factorType==="totp"&&(!((s=c==null?void 0:c.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),{data:c,error:null})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;if(i)return{data:null,error:i};let{data:a,error:u}=await H(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});return u?{data:null,error:u}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),{data:a,error:u})})}catch(t){if(z(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;return i?{data:null,error:i}:await H(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token})})}catch(t){if(z(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?{data:null,error:n}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let n=(e==null?void 0:e.factors)||[],s=n.filter(a=>a.factor_type==="totp"&&a.status==="verified"),i=n.filter(a=>a.factor_type==="phone"&&a.status==="verified");return{data:{all:n,totp:s,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,n;let{data:{session:s},error:i}=e;if(i)return{data:null,error:i};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:a}=La(s.access_token),u=null;a.aal&&(u=a.aal);let c=u;((n=(t=s.user.factors)===null||t===void 0?void 0:t.filter(m=>m.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(c="aal2");let f=a.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:f},error:null}}))}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(a=>a.kid===e);if(n||(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+M_>Date.now()))return n;let{data:s,error:i}=await H(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;if(!s.keys||s.keys.length===0)throw new Ct("JWKS is empty");if(this.jwks=s,this.jwks_cached_at=Date.now(),n=s.keys.find(a=>a.kid===e),!n)throw new Ct("No matching signing key found in JWKS");return n}async getClaims(e,t={keys:[]}){try{let n=e;if(!n){let{data:b,error:P}=await this.getSession();if(P||!b.session)return{data:null,error:P};n=b.session.access_token}let{header:s,payload:i,signature:a,raw:{header:u,payload:c}}=La(n);if(ev(i.exp),!s.kid||s.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){let{error:b}=await this.getUser(n);if(b)throw b;return{data:{claims:i,header:s,signature:a},error:null}}let h=tv(s.alg),f=await this.fetchJwk(s.kid,t),m=await crypto.subtle.importKey("jwk",f,h,!0,["verify"]);if(!await crypto.subtle.verify(h,m,a,K_(`${u}.${c}`)))throw new Ct("Invalid JWT signature");return{data:{claims:i,header:s,signature:a},error:null}}catch(n){if(z(n))return{data:null,error:n};throw n}}};Mr.nextInstanceID=0;var XP=Mr,Ch=XP;var Ma=class extends Ch{constructor(e){super(e)}};var ZP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},Jn=class{constructor(e,t,n){var s,i,a;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let u=D_(e);this.realtimeUrl=`${u}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${u}/auth/v1`,this.storageUrl=`${u}/storage/v1`,this.functionsUrl=`${u}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:R_,realtime:C_,auth:Object.assign(Object.assign({},P_),{storageKey:c}),global:S_},f=O_(n!=null?n:{},h);this.storageKey=(s=f.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(i=f.global.headers)!==null&&i!==void 0?i:{},f.accessToken?(this.accessToken=f.accessToken,this.auth=new Proxy({},{get:(m,g)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(g)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((a=f.auth)!==null&&a!==void 0?a:{},this.headers,f.global.fetch),this.fetch=k_(t,this._getAccessToken.bind(this),f.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},f.realtime)),this.rest=new d_(`${u}/rest/v1`,{headers:this.headers,schema:f.db.schema,fetch:this.fetch}),f.accessToken||this._listenForAuthEvents()}get functions(){return new Js(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ai(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},n={}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return ZP(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();let{data:n}=yield this.auth.getSession();return(t=(e=n.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:s,storageKey:i,flowType:a,lock:u,debug:c},h,f){let m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ma({url:this.authUrl,headers:Object.assign(Object.assign({},m),h),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:s,flowType:a,lock:u,debug:c,fetch:f,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new qn(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,n)=>{this._handleTokenChanged(t,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(e,t,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?this.changedAccessToken=n:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var cv=(r,e,t)=>new Jn(r,e,t);var gv=hu(pv(),1);var tC=Object.prototype.toString,rC=r=>tC.call(r)==="[object Error]",nC=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function kh(r){return r&&rC(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:nC.has(r.message):!1}var Dh=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},mv=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function yi(r,e){return new Promise((t,n)=>{var u,c,h;e={...e},(u=e.onFailedAttempt)!=null||(e.onFailedAttempt=()=>{}),(c=e.shouldRetry)!=null||(e.shouldRetry=()=>!0),(h=e.retries)!=null||(e.retries=10);let s=gv.default.operation(e),i=()=>{var f;s.stop(),n((f=e.signal)==null?void 0:f.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",i,{once:!0});let a=()=>{var f;(f=e.signal)==null||f.removeEventListener("abort",i),s.stop()};s.attempt(async f=>{try{let m=await r(f);a(),t(m)}catch(m){try{if(!(m instanceof Error))throw new TypeError(`Non-error was thrown: "${m}". You should only throw errors.`);if(m instanceof Dh)throw m.originalError;if(m instanceof TypeError&&!kh(m))throw m;if(mv(m,f,e),await e.shouldRetry(m)||(s.stop(),n(m)),await e.onFailedAttempt(m),!s.retry(m))throw s.mainError()}catch(g){mv(g,f,e),a(),n(g)}}})})}var sC=function(e,t){if(typeof e!="function")throw new Error("First argument to supabasey() must be a callback function");let n={session:null,retries:3,retry:{minTimeout:100,factor:2,randomize:!0,onFailedAttempt:i=>console.info(`[Attempt ${i.attemptNumber}/${i.attemptNumber+i.retriesLeft-1}] failed to run Supabase query`),shouldRetry:i=>(console.log("QUERY SHOULD-RETRY",i),!0)},...t},s=n.session?typeof n.session=="string"?ge.sessions[n.session]:typeof n.session=="object"?n.session:(()=>{throw new Error(`Unknown session type for supabasey(cb, {session}) - expected Object|String got ${typeof n.session}`)})():(()=>{throw new Error("supabasey(cb, {session}) cannot be empty - specify a session or use bindSession() first")})();return Promise.resolve().then(()=>yi(()=>e.call(s,s),{...n.retries&&{retries:n.retries},...t.retry})).then(i=>{if(i!=null&&i.error)ge.throw(i.error);else if(i.data)return i.data}).catch(i=>{throw console.log("Supabasey error:",i),i})},ge=sC;ge.bindSession=function(e){if(typeof e=="string"&&!ge.sessions[e])throw new Error(`Unable to bind to non-existant session "${e}"`);let t=(n,s)=>ge(n,{session:e,...s});return t.rpc=(n,s,i)=>ge.rpc(n,s,{session:e,...i}),t};ge.init=function(e){let t={env:{},init:!0,login:!1,session:"auto",...e},n=t.env,s=t.session=="auto"&&n.SUPABASE_URL?n.SUPABASE_URL:t.session?t.session:(()=>{throw new Error("Sesison should be truthy if using @iebh/supabasey.middleware({session:String})")})(),i=ge.sessions[s];return Promise.resolve().then(()=>{if(!i)if(t.init){if(!n.SUPABASE_URL||!n.SUPABASE_KEY)throw new Error("Both env.SUPABASE_URL + env.SUPABASE_KEY should be specified to use @iebh/supabasey.middleware(), otherwise disable with {init:false}");i=ge.sessions[s]=cv(n.SUPABASE_URL,n.SUPABASE_KEY)}else throw new Error("No Supabase session for middleware to work with!")}).then(()=>{if(t.login){if(i.supabaseyIsLoggedIn)return;if(!n.SUPABASE_USER||!n.SUPABASE_PASS)throw new Error("User credentials missing when using @iebh/supabasey.middleware(), provide in env.SUPABASE_USER + ..._PASS");return ge(a=>a.auth.signInWithPassword({email:n.SUPABASE_USER,password:n.SUPABASE_PASS}),{session:i}).then(()=>i.supabaseyIsLoggedIn=!0)}else return}).then(()=>ge.bindSession(i))};ge.middleware=function(e){let t={env:{},injectEnv:!0,...e};return async(n,s,i,a)=>ge.init({...e,env:i}).then(u=>{t.injectEnv&&(i.supabasey=u)}).catch(u=>ge.throw(u))};ge.throw=function(r){throw typeof r=="string"?new Error(r):r instanceof Error?r:/JSON object requested, multiple \(or no\) rows returned$/.test(r.message)?(console.warn("Supabase query resulted in NOT-FOUND:",r.message),console.warn("Supabase raw error",r),new Error("NOT-FOUND")):(console.warn("Supabase query threw",r.message||r||"Unknown error"),new Error(`${(r==null?void 0:r.code)||"UnknownError"}: ${(r==null?void 0:r.message)||"Unknown Supabase error"}`))};ge.rpc=function(r,e,t){return ge(async n=>await n.rpc(r,e),t)};ge.sessions={};var yv=ge;function iC(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function ja(r,e){return Array.isArray(r)?r.map(t=>ja(t,e)):typeof r=="object"?Object.fromEntries(Object.entries(iC(r,e)).map(([t,n])=>[t,ja(n,e)])):r}var _v={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var vv={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var wv={id:"~infinity",test:r=>r===1/0||r===-1/0,serialize:r=>({_:"~infinity",v:r===1/0?1:0}),deserialize:r=>r.v==1?1/0:-1/0};var bv={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var Tv={id:"~regexp",test:r=>r instanceof RegExp,serialize:r=>({_:"~regexp",v:r.source,f:r.flags}),deserialize:r=>new RegExp(r.v,r.f)};var Ev={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var Iv={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var Yn={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[_v,vv,wv,bv,Tv,Ev,Iv],circular:!0,symetric:!1},loadedModules:{},loadModules(r){return r.map(e=>{if(Z(e)){if(!e.id)throw new Error("Provided custom module does not expose an `id` property");return Yn.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=uo(e,Yn.settings),n=Yn.loadModules(t.modules),s=t.symetric?ja(r):t.clone?Wt(r):r,i=new Map,a=(u,c)=>{let h=Z(u);if(h&&t.circular){let g=i.get(u);if(g)return Qt(s,c,{_:"~circular",p:g.join(".")});i.set(u,c)}let f=n.find(g=>g.test(u)),m=(!t.depth||c.length<t.depth)&&h;if(f){let g=f.serialize(u);if(f.recursive&&m){let b=xe(u);t.symetric&&b.sort(),Qt(s,c,g),b.forEach(P=>a(u[P],c.concat(P)))}else c.length?Qt(s,c,g):s=g}else if(m){let g=xe(u);t.symetric&&g.sort(),g.forEach(b=>a(u[b],c.concat(b)))}};return a(s,[]),t.stringify?JSON.stringify(s):s},deserialize(r,e){let t=uo(e,Yn.settings),n=Yn.loadModules(t.modules),s=vu(n,"id"),i=t.destringify?JSON.parse(r):t.clone?Wt(r):r,a=(u,c)=>{if(Z(u)&&u._&&typeof u._=="string"&&u._.startsWith("~")&&s[u._]){let h=s[u._].deserialize(u);c.length?s[u._].recursive&&Z(h)?(Qt(i,c,h),xe(h).forEach(f=>a(u[f],[...c,f]))):Qt(i,c,h):i=h}else t.circular&&Z(u)&&u._&&u._=="~circular"?Qt(i,c,vs(i,u.p)):(!t.depth||c.length<t.depth)&&Z(u)&&xe(u).forEach(h=>a(u[h],c.concat(h)))};return a(i,[]),i}},_i=Yn;var Av="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var xv=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Av[t[r]&63];return e};var Dt=class r{constructor(e,t){this.throttle=250;this.config={heartbeatInterval:5e4,syncroRegistryUrl:"https://tera-tools.com/api/sync",context:{}};this.isDirty=!1;this._destroyActions=[];this.path=e,Object.assign(this,{...t,config:{...this.config,...t==null?void 0:t.config}}),r.session||(r.session=`syncro_${xv()}`)}debug(...e){}debugError(...e){console.log(`[Syncro ${this.path}]`,...e)}destroy(){return this.debug("Destroy!"),Promise.all(this._destroyActions.map(e=>e())).then(()=>this._destroyActions=[])}getReactive(e){console.warn("Syncro.getReactive has not been subclassed, assuming a POJO response");let t={...e};return{doc:t,setState(n){Object.entries(n||{}).forEach(([s,i])=>t[s]=i)},getState(){return Wt(t)},watch(n){}}}static pathSplit(e,t){var a;let n={allowAsterisk:!1,...t},i={...(a=new RegExp("^(?<entity>\\w+?)::(?<id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:::(?<relation>[\\w\\-"+(n.allowAsterisk?"\\*":"")+"]+?))?$").exec(e))==null?void 0:a.groups};if(!i||!i.entity||!i.id)throw new Error(`Invalid session path syntax "${e}"`);if(r.SyncroEntities&&!(i.entity in r.SyncroEntities))throw new Error(`Unsupported entity "${e}" -> Entity="${i.entity}"`);return{entity:i.entity,id:i.id,relation:i.relation,fsCollection:i.entity,fsId:i.relation?`${i.id}::${i.relation}`:i.id}}static toFirestore(e={}){return _i.serialize(e,{circular:!1,clone:!0,modules:[Sv,..._i.settings.modules],stringify:!1})}static fromFirestore(e={}){return _i.deserialize(e,{circular:!1,clone:!0,modules:[Sv,..._i.settings.modules],destringify:!1})}static toFirestoreFields(e){let t={};for(let[n,s]of Object.entries(e)){let i=typeof s;i==="string"?t[n]={stringValue:s}:i==="number"?t[n]={doubleValue:s}:i==="boolean"?t[n]={booleanValue:s}:s===null?t[n]={nullValue:null}:Array.isArray(s)?t[n]={arrayValue:{values:s.map(a=>r.toFirestoreFields({item:a}).item)}}:i==="object"&&(t[n]={mapValue:{fields:r.toFirestoreFields(s)}})}return t}static fromFirestoreFields(e={}){let t={};for(let n in e){let s=e[n],i=["stringValue","booleanValue","doubleValue","integerValue","timestampValue","mapValue","arrayValue","nullValue"].find(a=>a===Object.keys(s)[0]);if(i)if(i==="mapValue")t[n]=r.fromFirestoreFields(s.mapValue.fields||{});else if(i==="arrayValue"){let a=s.arrayValue.values;t[n]=a?a.map(u=>r.fromFirestoreFields(u)):[]}else i==="nullValue"?t[n]=null:t[n]=s[i];else t[n]=r.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=r.pathSplit(e);return Promise.resolve().then(async()=>th(pa(r.firestore,t,n))).then(s=>s.exists()?r.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:i,fsId:a}=r.pathSplit(e),u=pa(r.firestore,i,a),c=r.toFirestore(t);return Promise.resolve().then(()=>s.method==="merge"?nh(u,c):rh(u,c)).then(()=>t)}mount(e){let t={initialState:null,retries:5,retryMinTime:250,...e},{fsCollection:n,fsId:s,entity:i}=r.pathSplit(this.path),a,u;return yi(async()=>{await this.setHeartbeat(!1),this.docRef=pa(r.firestore,n,s);let c=await this.getFirestoreState();if(a=this.getReactive(c),!a.doc||!a.setState||!a.getState||!a.watch)throw new Error("Syncro.getReactive() requires a returned `doc`, `setState()`, `getState()` + `watch()`");this.value=u=a.doc,this.debug("Initial state",{doc:u});let h=Qy(this.docRef,f=>{let m=r.fromFirestore(f.data());this.debug("Incoming snapshot",{snapshotData:m}),a.setState(m)});if(this._destroyActions.push(h),_u(u))if(t.initialState)this.debug("Populate initial Syncro state (from provided initialState)"),await this.setFirestoreState(t.initialState,{method:"set"});else{this.debug(`Populate initial Syncro state (from "${i}" Syncro worker)`);let f=await fetch(`${this.config.syncroRegistryUrl}/${this.path}`);if(!f.ok)throw new Error(`Failed to check Syncro "${n}::${s}" status - ${f.statusText}`)}return a.watch(wu(f=>{this.debug("Local change",{newState:f}),this.markDirty(),this.setFirestoreState(f,{method:"merge"})},this.throttle)),await this.setHeartbeat(!0,{immediate:!0}),this},{retries:t.retries,minTimeout:t.retryMinTime,randomize:!0,factor:3,onFailedAttempt:async c=>{this.debugError(`[Attempt ${c.attemptNumber}/${c.attemptNumber+c.retriesLeft-1}] to mount syncro`,c),await this.destroy()}})}async set(e,t,n){let s;if(typeof e=="string")s[e]=t;else if(typeof e=="object")[s,n]=[e,t];else throw new Error("Unknown call signature for set() - call with string+value or object");let i={delta:!0,flush:!0,forceFlush:!1,flushDestroy:!1,...n},a=!1;return i.delta?Object.entries(s).filter(([u,c])=>!bs(this.value[u],c)).forEach(([u,c])=>{a=!0,this.value[u]=c}):(a=!0,Object.assign(this.value,s)),(i.forceFlush||a)&&i.flush&&await this.flush({destroy:i.flushDestroy}),this}setHeartbeat(e=!0,t){let n={immediate:!0,...t};if(clearTimeout(this._heartbeatTimer),e){let s=async()=>{await this.heartbeat(),e&&this.setHeartbeat(!0)};if(this._heartbeatTimer=setTimeout(s,this.config.heartbeatInterval),n.immediate)return this.heartbeat()}}async heartbeat(){this.debug("heartbeat!");try{let e=await fetch(`${this.config.syncroRegistryUrl}/${this.path}/heartbeat`,{method:"post",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:r.session,...this.isDirty&&{dirty:!0}})});e.ok||console.warn(this.path,`Heartbeat failed - ${e.statusText}`,{response:e}),this.isDirty=!1}catch(e){console.warn(this.path,"Heartbeat fetch error",e)}}async setFirestoreState(e,t,n=0){let s={method:"merge",...t};if(!this.docRef)throw new Error("mount() must be called before setting Firestore state");let i=r.toFirestore(e);try{return s.method==="merge"?await nh(this.docRef,i):await rh(this.docRef,i)}catch(a){if(a instanceof Qe&&a.code==="not-found"){if(n<3)return console.warn("Firebase syncro document does not exist during document update, reinitializing..."),(await fetch(`${this.config.syncroRegistryUrl}/${this.path}?force=1`)).ok||console.error("Failed to reinitialize Syncro"),await this.setFirestoreState(e,t,n+1);console.warn("Max retries exceeded while trying to recover firestore syncro document, throwing error")}throw console.error(`Error during Firestore operation (${s.method}) on doc: ${this.docRef.path}`,a),a}}getFirestoreState(){if(!this.docRef)throw new Error("mount() must be called before getting Firestore state");return th(this.docRef).then(e=>{var t;return r.fromFirestore((t=e.data())!=null?t:{})})}markDirty(){return this.isDirty=!0,this}flush(e){let t={destroy:!1,...e};return fetch(`${this.config.syncroRegistryUrl}/${this.path}/flush`+(t.destroy?"?destroy=1":"")).then(n=>n.ok?null:Promise.reject(n.statusText||"An error occured"))}};var Sv={id:"~array",recursive:!0,test:r=>Array.isArray(r),serialize:r=>({_:"~array",...r}),deserialize:r=>{let e=Array.from({length:Object.keys(r).length-1});return Object.entries(r).filter(([t])=>t!=="_").forEach(([t,n])=>e[+t]=n),e}};var vi=class{init(){}constructor(e,t){}};var wi=class extends vi{constructor(){super(...arguments);this.syncros={};this.namespaces={}}async init(t){let n={firebaseApiKey:null,firebaseAuthDomain:null,firebaseProjectId:null,firebaseAppId:null,supabaseUrl:null,supabaseKey:null,...await this.getCredentials(),...t},s=Object.keys(n).filter(i=>i===null);if(s.length>0)throw new Error("Firebase plugin requires mandatory options: "+s.join(", "));Dt.firebase=ju({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),Dt.firestore=$y(Dt.firebase),Dt.supabasey=await yv.init({env:{SUPABASE_URL:n.supabaseUrl,SUPABASE_KEY:n.supabaseKey}})}_mountNamespace(t){let n;return Promise.resolve().then(()=>this.requireProject()).then(s=>{let i=t=="_PROJECT"?`projects::${s.id}`:`project_namespaces::${s.id}::${t}`;return n=this.syncros[t]=new Dt(i,{debug:(...a)=>this.debug(`SYNCRO://${i}`,...a),getReactive:this.getReactive}),n.mount()}).then(()=>{this.namespaces[t]=n.value})}_unmountNamespace(t){let n=this.syncros[t];return delete this.namespaces[t],delete this.syncros[t],n?n.destroy():Promise.resolve()}};var Oh=class extends wi{constructor(){super(...arguments);this.project=null;this.reactiveId=1001}async init(t){let n={app:null,Vue:null,globalName:"$tera",...t};if(!n.Vue)throw new Error("Vue instance to use must be specified in init options as `Vue`");if(this.Vue=n.Vue,!n.app)throw new Error("Vue Root / App instance to use must be specified in init options as `app`");this.app=n.app,n.globalName&&(this.Vue.prototype[n.globalName]=this),await super.init(n),this.project=await this.mountNamespace("_PROJECT")}getReactive(t){let n=this.Vue.observable(t),s=`_teraFy_${this.reactiveId++}`;return this.app[s]=n,{doc:n,setState:i=>{Object.entries(i||{}).filter(([a])=>!bs(n[a],i[a])).forEach(([a,u])=>n[a]=u)},getState:()=>Wt(n),watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Oh as default};
27
+ });`,qn=class{constructor(e,t){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=p_,this.params={},this.timeout=Ea,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=IP,this.conn=null,this.sendBuffer=[],this.serializer=new ni,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let a;return i?a=i:typeof fetch=="undefined"?a=(...u)=>Promise.resolve().then(()=>(sr(),Ir)).then(({default:c})=>c(...u)):a=fetch,(...u)=>a(...u)},this.endPoint=`${e}/${Ta.websocket}`,this.httpEndpoint=Ia(e),t!=null&&t.transport?this.transport=t.transport:this.transport=null,t!=null&&t.params&&(this.params=t.params),t!=null&&t.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t!=null&&t.timeout&&(this.timeout=t.timeout),t!=null&&t.logger&&(this.logger=t.logger),t!=null&&t.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let s=(n=t==null?void 0:t.params)===null||n===void 0?void 0:n.apikey;if(s&&(this.accessTokenValue=s,this.apiKey=s),this.reconnectAfterMs=t!=null&&t.reconnectAfterMs?t.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=t!=null&&t.encode?t.encode:(i,a)=>a(JSON.stringify(i)),this.decode=t!=null&&t.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new xr(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t==null?void 0:t.fetch),t!=null&&t.worker){if(typeof window!="undefined"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(t==null?void 0:t.worker)||!1,this.workerUrl=t==null?void 0:t.workerUrl}this.accessToken=(t==null?void 0:t.accessToken)||null}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers});return}if(AP){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new Th(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>hu(v_())).then(({default:e})=>{this.conn=new e(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:m_}))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t!=null?t:""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,n){this.logger(e,t,n)}connectionState(){switch(this.conn&&this.conn.readyState){case Ar.connecting:return ir.Connecting;case Ar.open:return ir.Open;case Ar.closing:return ir.Closing;default:return ir.Closed}}isConnected(){return this.connectionState()===ir.Open}channel(e,t={config:{}}){let n=new $n(`realtime:${e}`,t,this);return this.channels.push(n),n}push(e){let{topic:t,event:n,payload:s,ref:i}=e,a=()=>{this.encode(e,u=>{var c;(c=this.conn)===null||c===void 0||c.send(u)})};this.log("push",`${t} ${n} (${i})`,s),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){let t=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;if(t){let n=null;try{n=JSON.parse(atob(t.split(".")[1]))}catch{}if(n&&n.exp&&!(Math.floor(Date.now()/1e3)-n.exp<0))return this.log("auth",`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${n.exp}`),Promise.reject(`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${n.exp}`);this.accessTokenValue=t,this.channels.forEach(s=>{t&&s.updateJoinPayload({access_token:t}),s.joinedOnce&&s._isJoined()&&s._push(Be.access_token,{access_token:t})})}}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(g_,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth()}}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:n,event:s,payload:i,ref:a}=t;a&&a===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${n} ${s} ${a&&"("+a+")"||""}`,i),this.channels.filter(u=>u._isMember(n)).forEach(u=>u._trigger(s,i,a)),this.stateChangeCallbacks.message.forEach(u=>u(t))})}async _onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);else{this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(Be.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let n=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${n}${s}`}_workerObjectUrl(e){let t;if(e)t=e;else{let n=new Blob([xP],{type:"application/javascript"});t=URL.createObjectURL(n)}return t}},Th=class{constructor(e,t,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Ar.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}};var zn=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function pe(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Aa=class extends zn{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Rr=class extends zn{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var SP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},Sa=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(sr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},w_=()=>SP(void 0,void 0,void 0,function*(){return typeof Response=="undefined"?(yield Promise.resolve().then(()=>(sr(),Ir))).Response:Response}),xa=r=>{if(Array.isArray(r))return r.map(t=>xa(t));if(typeof r=="function"||r!==Object(r))return r;let e={};return Object.entries(r).forEach(([t,n])=>{let s=t.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[s]=xa(n)}),e};var Pr=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},Eh=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),RP=(r,e,t)=>Pr(void 0,void 0,void 0,function*(){let n=yield w_();r instanceof n&&!(t!=null&&t.noResolveJson)?r.json().then(s=>{e(new Aa(Eh(s),r.status||500))}).catch(s=>{e(new Rr(Eh(s),s))}):e(new Rr(Eh(r),r))}),PP=(r,e,t,n)=>{let s={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),n&&(s.body=JSON.stringify(n)),Object.assign(Object.assign({},s),t))};function si(r,e,t,n,s,i){return Pr(this,void 0,void 0,function*(){return new Promise((a,u)=>{r(t,PP(e,n,s,i)).then(c=>{if(!c.ok)throw c;return n!=null&&n.noResolveJson?c:c.json()}).then(c=>a(c)).catch(c=>RP(c,u,n))})})}function Gn(r,e,t,n){return Pr(this,void 0,void 0,function*(){return si(r,"GET",e,t,n)})}function lt(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return si(r,"POST",e,n,s,t)})}function b_(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return si(r,"PUT",e,n,s,t)})}function T_(r,e,t,n){return Pr(this,void 0,void 0,function*(){return si(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),n)})}function Ra(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return si(r,"DELETE",e,n,s,t)})}var Le=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},CP={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},E_={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ii=class{constructor(e,t={},n,s){this.url=e,this.headers=t,this.bucketId=n,this.fetch=Sa(s)}uploadOrUpdate(e,t,n,s){return Le(this,void 0,void 0,function*(){try{let i,a=Object.assign(Object.assign({},E_),s),u=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(a.upsert)}),c=a.metadata;typeof Blob!="undefined"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",n)):typeof FormData!="undefined"&&n instanceof FormData?(i=n,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=n,u["cache-control"]=`max-age=${a.cacheControl}`,u["content-type"]=a.contentType,c&&(u["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),s!=null&&s.headers&&(u=Object.assign(Object.assign({},u),s.headers));let h=this._removeEmptyFolders(t),f=this._getFinalPath(h),m=yield this.fetch(`${this.url}/object/${f}`,Object.assign({method:e,body:i,headers:u},a!=null&&a.duplex?{duplex:a.duplex}:{})),g=yield m.json();return m.ok?{data:{path:h,id:g.Id,fullPath:g.Key},error:null}:{data:null,error:g}}catch(i){if(pe(i))return{data:null,error:i};throw i}})}upload(e,t,n){return Le(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,n)})}uploadToSignedUrl(e,t,n,s){return Le(this,void 0,void 0,function*(){let i=this._removeEmptyFolders(e),a=this._getFinalPath(i),u=new URL(this.url+`/object/upload/sign/${a}`);u.searchParams.set("token",t);try{let c,h=Object.assign({upsert:E_.upsert},s),f=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob!="undefined"&&n instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",n)):typeof FormData!="undefined"&&n instanceof FormData?(c=n,c.append("cacheControl",h.cacheControl)):(c=n,f["cache-control"]=`max-age=${h.cacheControl}`,f["content-type"]=h.contentType);let m=yield this.fetch(u.toString(),{method:"PUT",body:c,headers:f}),g=yield m.json();return m.ok?{data:{path:i,fullPath:g.Key},error:null}:{data:null,error:g}}catch(c){if(pe(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return Le(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e),s=Object.assign({},this.headers);t!=null&&t.upsert&&(s["x-upsert"]="true");let i=yield lt(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:s}),a=new URL(this.url+i.url),u=a.searchParams.get("token");if(!u)throw new zn("No token returned by API");return{data:{signedUrl:a.toString(),path:e,token:u},error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}update(e,t,n){return Le(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,n)})}move(e,t,n){return Le(this,void 0,void 0,function*(){try{return{data:yield lt(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(pe(s))return{data:null,error:s};throw s}})}copy(e,t,n){return Le(this,void 0,void 0,function*(){try{return{data:{path:(yield lt(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(s){if(pe(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,n){return Le(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=yield lt(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers}),a=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${a}`)},{data:i,error:null}}catch(s){if(pe(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,n){return Le(this,void 0,void 0,function*(){try{let s=yield lt(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:s.map(a=>Object.assign(Object.assign({},a),{signedUrl:a.signedURL?encodeURI(`${this.url}${a.signedURL}${i}`):null})),error:null}}catch(s){if(pe(s))return{data:null,error:s};throw s}})}download(e,t){return Le(this,void 0,void 0,function*(){let s=typeof(t==null?void 0:t.transform)!="undefined"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),a=i?`?${i}`:"";try{let u=this._getFinalPath(e);return{data:yield(yield Gn(this.fetch,`${this.url}/${s}/${u}${a}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(u){if(pe(u))return{data:null,error:u};throw u}})}info(e){return Le(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{let n=yield Gn(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:xa(n),error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}exists(e){return Le(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{return yield T_(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(pe(n)&&n instanceof Rr){let s=n.originalError;if([400,404].includes(s==null?void 0:s.status))return{data:!1,error:n}}throw n}})}getPublicUrl(e,t){let n=this._getFinalPath(e),s=[],i=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&s.push(i);let u=typeof(t==null?void 0:t.transform)!="undefined"?"render/image":"object",c=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});c!==""&&s.push(c);let h=s.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${u}/public/${n}${h}`)}}}remove(e){return Le(this,void 0,void 0,function*(){try{return{data:yield Ra(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(pe(t))return{data:null,error:t};throw t}})}list(e,t,n){return Le(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},CP),t),{prefix:e||""});return{data:yield lt(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},n),error:null}}catch(s){if(pe(s))return{data:null,error:s};throw s}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer!="undefined"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var I_="2.7.1";var A_={"X-Client-Info":`storage-js/${I_}`};var Kn=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},oi=class{constructor(e,t={},n){this.url=e,this.headers=Object.assign(Object.assign({},A_),t),this.fetch=Sa(n)}listBuckets(){return Kn(this,void 0,void 0,function*(){try{return{data:yield Gn(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(pe(e))return{data:null,error:e};throw e}})}getBucket(e){return Kn(this,void 0,void 0,function*(){try{return{data:yield Gn(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(pe(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Kn(this,void 0,void 0,function*(){try{return{data:yield lt(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}updateBucket(e,t){return Kn(this,void 0,void 0,function*(){try{return{data:yield b_(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(pe(n))return{data:null,error:n};throw n}})}emptyBucket(e){return Kn(this,void 0,void 0,function*(){try{return{data:yield lt(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(pe(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Kn(this,void 0,void 0,function*(){try{return{data:yield Ra(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(pe(t))return{data:null,error:t};throw t}})}};var ai=class extends oi{constructor(e,t={},n){super(e,t,n)}from(e){return new ii(this.url,this.headers,e,this.fetch)}};var x_="2.49.4";var ui="";typeof Deno!="undefined"?ui="deno":typeof document!="undefined"?ui="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?ui="react-native":ui="node";var kP={"X-Client-Info":`supabase-js-${ui}/${x_}`},S_={headers:kP},R_={schema:"public"},P_={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},C_={};sr();var DP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},OP=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=sh:e=fetch,(...t)=>e(...t)},NP=()=>typeof Headers=="undefined"?ih:Headers,k_=(r,e,t)=>{let n=OP(t),s=NP();return(i,a)=>DP(void 0,void 0,void 0,function*(){var u;let c=(u=yield e())!==null&&u!==void 0?u:r,h=new s(a==null?void 0:a.headers);return h.has("apikey")||h.set("apikey",r),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),n(i,Object.assign(Object.assign({},a),{headers:h}))})};var VP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})};function D_(r){return r.replace(/\/$/,"")}function O_(r,e){let{db:t,auth:n,realtime:s,global:i}=r,{db:a,auth:u,realtime:c,global:h}=e,f={db:Object.assign(Object.assign({},a),t),auth:Object.assign(Object.assign({},u),n),realtime:Object.assign(Object.assign({},c),s),global:Object.assign(Object.assign({},h),i),accessToken:()=>VP(this,void 0,void 0,function*(){return""})};return r.accessToken?f.accessToken=r.accessToken:delete f.accessToken,f}var Pa="2.69.1";var Cr=30*1e3,Ca=3,ka=Ca*Cr,N_="http://localhost:9999",V_="supabase.auth.token";var L_={"X-Client-Info":`gotrue-js/${Pa}`};var ci="X-Supabase-Api-Version",Ih={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},F_=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,M_=6e5;var li=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=n}};function z(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Da=class extends li{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}};function j_(r){return z(r)&&r.name==="AuthApiError"}var Hn=class extends li{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ht=class extends li{constructor(e,t,n,s){super(e,n,s),this.name=t,this.status=n}},ze=class extends ht{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function U_(r){return z(r)&&r.name==="AuthSessionMissingError"}var Wn=class extends ht{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},kr=class extends ht{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Dr=class extends ht{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function B_(r){return z(r)&&r.name==="AuthImplicitGrantRedirectError"}var hi=class extends ht{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},Qn=class extends ht{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Oa(r){return z(r)&&r.name==="AuthRetryableFetchError"}var di=class extends ht{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}};var Ct=class extends ht{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var $_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),q_=`
28
+ \r=`.split(""),LP=(()=>{let r=new Array(128);for(let e=0;e<r.length;e+=1)r[e]=-1;for(let e=0;e<q_.length;e+=1)r[q_[e].charCodeAt(0)]=-2;for(let e=0;e<$_.length;e+=1)r[$_[e].charCodeAt(0)]=e;return r})();function z_(r,e,t){let n=LP[r];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(r)}"`)}}function Ah(r){let e=[],t=a=>{e.push(String.fromCodePoint(a))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=a=>{jP(a,n,t)};for(let a=0;a<r.length;a+=1)z_(r.charCodeAt(a),s,i);return e.join("")}function FP(r,e){if(r<=127){e(r);return}else if(r<=2047){e(192|r>>6),e(128|r&63);return}else if(r<=65535){e(224|r>>12),e(128|r>>6&63),e(128|r&63);return}else if(r<=1114111){e(240|r>>18),e(128|r>>12&63),e(128|r>>6&63),e(128|r&63);return}throw new Error(`Unrecognized Unicode codepoint: ${r.toString(16)}`)}function MP(r,e){for(let t=0;t<r.length;t+=1){let n=r.charCodeAt(t);if(n>55295&&n<=56319){let s=(n-55296)*1024&65535;n=(r.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}FP(n,e)}}function jP(r,e,t){if(e.utf8seq===0){if(r<=127){t(r);return}for(let n=1;n<6;n+=1)if((r>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=r&31;else if(e.utf8seq===3)e.codepoint=r&15;else if(e.utf8seq===4)e.codepoint=r&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(r<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|r&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function G_(r){let e=[],t={queue:0,queuedBits:0},n=s=>{e.push(s)};for(let s=0;s<r.length;s+=1)z_(r.charCodeAt(s),t,n);return new Uint8Array(e)}function K_(r){let e=[];return MP(r,t=>e.push(t)),new Uint8Array(e)}function H_(r){return Math.round(Date.now()/1e3)+r}function W_(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}var Ye=()=>typeof window!="undefined"&&typeof document!="undefined",Or={tested:!1,writable:!1},or=()=>{if(!Ye())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Or.tested)return Or.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Or.tested=!0,Or.writable=!0}catch{Or.tested=!0,Or.writable=!1}return Or.writable};function Q_(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return t.searchParams.forEach((n,s)=>{e[s]=n}),e}var Na=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(sr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},J_=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",xh=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},pi=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},mi=async(r,e)=>{await r.removeItem(e)},fi=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};fi.promiseConstructor=Promise;function Va(r){let e=r.split(".");if(e.length!==3)throw new Ct("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!F_.test(e[n]))throw new Ct("JWT not in base64url format");return{header:JSON.parse(Ah(e[0])),payload:JSON.parse(Ah(e[1])),signature:G_(e[2]),raw:{header:e[0],payload:e[1]}}}async function Y_(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function X_(r,e){return new Promise((n,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let a=await r(i);if(!e(i,null,a)){n(a);return}}catch(a){if(!e(i,a)){s(a);return}}})()})}function UP(r){return("0"+r.toString(16)).substr(-2)}function BP(){let e=new Uint32Array(56);if(typeof crypto=="undefined"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=t.length,s="";for(let i=0;i<56;i++)s+=t.charAt(Math.floor(Math.random()*n));return s}return crypto.getRandomValues(e),Array.from(e,UP).join("")}async function $P(r){let t=new TextEncoder().encode(r),n=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(n);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function qP(r){if(!(typeof crypto!="undefined"&&typeof crypto.subtle!="undefined"&&typeof TextEncoder!="undefined"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),r;let t=await $P(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Nr(r,e,t=!1){let n=BP(),s=n;t&&(s+="/PASSWORD_RECOVERY"),await xh(r,`${e}-code-verifier`,s);let i=await qP(n);return[i,n===i?"plain":"s256"]}var zP=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Z_(r){let e=r.headers.get(ci);if(!e||!e.match(zP))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function ev(r){if(!r)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(r<=e)throw new Error("JWT has expired")}function tv(r){switch(r){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var GP=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(r);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(r,n[s])&&(t[n[s]]=r[n[s]]);return t},Vr=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),KP=[502,503,504];async function rv(r){var e;if(!J_(r))throw new Qn(Vr(r),0);if(KP.includes(r.status))throw new Qn(Vr(r),r.status);let t;try{t=await r.json()}catch(i){throw new Hn(Vr(i),i)}let n,s=Z_(r);if(s&&s.getTime()>=Ih["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?n=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(n=t.error_code),n){if(n==="weak_password")throw new di(Vr(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new ze}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,a)=>i&&typeof a=="string",!0))throw new di(Vr(t),r.status,t.weak_password.reasons);throw new Da(Vr(t),r.status||500,n)}var HP=(r,e,t,n)=>{let s={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),t))};async function H(r,e,t,n){var s;let i=Object.assign({},n==null?void 0:n.headers);i[ci]||(i[ci]=Ih["2024-01-01"].name),n!=null&&n.jwt&&(i.Authorization=`Bearer ${n.jwt}`);let a=(s=n==null?void 0:n.query)!==null&&s!==void 0?s:{};n!=null&&n.redirectTo&&(a.redirect_to=n.redirectTo);let u=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await WP(r,e,t+u,{headers:i,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(c):{data:Object.assign({},c),error:null}}async function WP(r,e,t,n,s,i){let a=HP(e,n,s,i),u;try{u=await r(t,Object.assign({},a))}catch(c){throw console.error(c),new Qn(Vr(c),0)}if(u.ok||await rv(u),n!=null&&n.noResolveJson)return u;try{return await u.json()}catch(c){await rv(c)}}function kt(r){var e;let t=null;QP(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=H_(r.expires_in)));let n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:n},error:null}}function Sh(r){let e=kt(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,n)=>t&&typeof n=="string",!0)&&(e.data.weak_password=r.weak_password),e}function dt(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function nv(r){return{data:r,error:null}}function sv(r){let{action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i}=r,a=GP(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),u={action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i},c=Object.assign({},a);return{data:{properties:u,user:c},error:null}}function iv(r){return r}function QP(r){return r.access_token&&r.refresh_token&&r.expires_in}var JP=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(r);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(r,n[s])&&(t[n[s]]=r[n[s]]);return t},Lr=class{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=Na(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await H(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(z(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,t={}){try{return await H(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:dt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:t}=e,n=JP(e,["options"]),s=Object.assign(Object.assign({},n),t);return"newEmail"in n&&(s.new_email=n==null?void 0:n.newEmail,delete s.newEmail),await H(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:sv,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(z(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await H(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:dt})}catch(t){if(z(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,n,s,i,a,u,c;try{let h={nextPage:null,lastPage:0,total:0},f=await H(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=e==null?void 0:e.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:iv});if(f.error)throw f.error;let m=await f.json(),g=(a=f.headers.get("x-total-count"))!==null&&a!==void 0?a:0,b=(c=(u=f.headers.get("link"))===null||u===void 0?void 0:u.split(","))!==null&&c!==void 0?c:[];return b.length>0&&(b.forEach(P=>{let C=parseInt(P.split(";")[0].split("=")[1].substring(0,1)),R=JSON.parse(P.split(";")[1].split("=")[1]);h[`${R}Page`]=C}),h.total=parseInt(g)),{data:Object.assign(Object.assign({},m),h),error:null}}catch(h){if(z(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await H(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:dt})}catch(t){if(z(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await H(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:dt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,t=!1){try{return await H(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:dt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{let{data:t,error:n}=await H(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:n}}catch(t){if(z(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await H(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(z(t))return{data:null,error:t};throw t}}};var ov={getItem:r=>or()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{or()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{or()&&globalThis.localStorage.removeItem(r)}};function Rh(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function av(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self!="undefined"&&(self.globalThis=self)}}var Fr={debug:!!(globalThis&&or()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},gi=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},La=class extends gi{};async function Ph(r,e,t){Fr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),Fr.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){Fr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,s.name);try{return await t()}finally{Fr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,s.name)}}else{if(e===0)throw Fr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new La(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Fr.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}av();var YP={url:N_,storageKey:V_,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:L_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function uv(r,e,t){return await t()}var Mr=class r{constructor(e){var t,n;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=r.nextInstanceID,r.nextInstanceID+=1,this.instanceID>0&&Ye()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let s=Object.assign(Object.assign({},YP),e);if(this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.persistSession=s.persistSession,this.storageKey=s.storageKey,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Lr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Na(s.fetch),this.lock=s.lock||uv,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:Ye()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=Ph:this.lock=uv,this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?s.storage?this.storage=s.storage:or()?this.storage=ov:(this.memoryStorage={},this.storage=Rh(this.memoryStorage)):(this.memoryStorage={},this.storage=Rh(this.memoryStorage)),Ye()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Pa}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let t=Q_(window.location.href),n="none";if(this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce"),Ye()&&this.detectSessionInUrl&&n!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),B_(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}let{session:a,redirectType:u}=s;return this._debug("#_initialize()","detected session in URL",a,"redirect type",u),await this._saveSession(a),setTimeout(async()=>{u==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return z(t)?{error:t}:{error:new Hn("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,s;try{let i=await H(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(t=e==null?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.captchaToken}},xform:kt}),{data:a,error:u}=i;if(u||!a)return{data:{user:null,session:null},error:u};let c=a.session,h=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(z(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var t,n,s;try{let i;if("email"in e){let{email:f,password:m,options:g}=e,b=null,P=null;this.flowType==="pkce"&&([b,P]=await Nr(this.storage,this.storageKey)),i=await H(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:f,password:m,data:(t=g==null?void 0:g.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken},code_challenge:b,code_challenge_method:P},xform:kt})}else if("phone"in e){let{phone:f,password:m,options:g}=e;i=await H(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:m,data:(n=g==null?void 0:g.data)!==null&&n!==void 0?n:{},channel:(s=g==null?void 0:g.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken}},xform:kt})}else throw new kr("You must provide either an email or phone number and a password");let{data:a,error:u}=i;if(u||!a)return{data:{user:null,session:null},error:u};let c=a.session,h=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(z(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:a,options:u}=e;t=await H(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Sh})}else if("phone"in e){let{phone:i,password:a,options:u}=e;t=await H(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Sh})}else throw new kr("You must provide either an email or phone number and a password");let{data:n,error:s}=t;return s?{data:{user:null,session:null},error:s}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new Wn}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:s})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,n,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await pi(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{let{data:i,error:a}=await H(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:kt});if(await mi(this.storage,`${this.storageKey}-code-verifier`),a)throw a;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Wn}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:s!=null?s:null}),error:a})}catch(i){if(z(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(e){try{let{options:t,provider:n,token:s,access_token:i,nonce:a}=e,u=await H(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:kt}),{data:c,error:h}=u;return h?{data:{user:null,session:null},error:h}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Wn}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,n,s,i,a;try{if("email"in e){let{email:u,options:c}=e,h=null,f=null;this.flowType==="pkce"&&([h,f]=await Nr(this.storage,this.storageKey));let{error:m}=await H(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:u,data:(t=c==null?void 0:c.data)!==null&&t!==void 0?t:{},create_user:(n=c==null?void 0:c.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:m}}if("phone"in e){let{phone:u,options:c}=e,{data:h,error:f}=await H(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:u,data:(s=c==null?void 0:c.data)!==null&&s!==void 0?s:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(a=c==null?void 0:c.channel)!==null&&a!==void 0?a:"sms"}});return{data:{user:null,session:null,messageId:h==null?void 0:h.message_id},error:f}}throw new kr("You must provide either an email or phone number.")}catch(u){if(z(u))return{data:{user:null,session:null},error:u};throw u}}async verifyOtp(e){var t,n;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:a,error:u}=await H(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:kt});if(u)throw u;if(!a)throw new Error("An error occurred on token verification.");let c=a.session,h=a.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(s){if(z(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithSSO(e){var t,n,s;try{let i=null,a=null;return this.flowType==="pkce"&&([i,a]=await Nr(this.storage,this.storageKey)),await H(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&n!==void 0?n:void 0}),!((s=e==null?void 0:e.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:a}),headers:this.headers,xform:nv})}catch(i){if(z(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)throw n;if(!t)throw new ze;let{error:s}=await H(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(z(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:n,type:s,options:i}=e,{error:a}=await H(this.fetch,"POST",t,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:a}}else if("phone"in e){let{phone:n,type:s,options:i}=e,{data:a,error:u}=await H(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:u}}throw new kr("You must provide either an email or phone number and a type")}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await n,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=t();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await pi(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<ka:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.storage.isServer){let a=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,h,f)=>(!a&&h==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),a=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,h,f))})}return{data:{session:e},error:null}}let{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:s},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await H(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:dt}):await this._useSession(async t=>{var n,s,i;let{data:a,error:u}=t;if(u)throw u;return!(!((n=a.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ze}:await H(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:dt})})}catch(t){if(z(t))return U_(t)&&(await this._removeSession(),await mi(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async n=>{let{data:s,error:i}=n;if(i)throw i;if(!s.session)throw new ze;let a=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await Nr(this.storage,this.storageKey));let{data:h,error:f}=await H(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:u,code_challenge_method:c}),jwt:a.access_token,xform:dt});if(f)throw f;return a.user=h.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),{data:{user:a.user},error:null}})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ze;let t=Date.now()/1e3,n=t,s=!0,i=null,{payload:a}=Va(e.access_token);if(a.exp&&(n=a.exp,s=n<=t),s){let{session:u,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!u)return{data:{user:null,session:null},error:null};i=u}else{let{data:u,error:c}=await this._getUser(e.access_token);if(c)throw c;i={access_token:e.access_token,refresh_token:e.refresh_token,user:u.user,token_type:"bearer",expires_in:n-t,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(t){if(z(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var n;if(!e){let{data:a,error:u}=t;if(u)throw u;e=(n=a.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new ze;let{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!Ye())throw new Dr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Dr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new hi("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Dr("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new hi("No code detected.");let{data:F,error:U}=await this._exchangeCodeForSession(e.code);if(U)throw U;let G=new URL(window.location.href);return G.searchParams.delete("code"),window.history.replaceState(window.history.state,"",G.toString()),{data:{session:F.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:a,expires_in:u,expires_at:c,token_type:h}=e;if(!i||!u||!a||!h)throw new Dr("No session defined in URL");let f=Math.round(Date.now()/1e3),m=parseInt(u),g=f+m;c&&(g=parseInt(c));let b=g-f;b*1e3<=Cr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${b}s, should have been closer to ${m}s`);let P=g-m;f-P>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",P,g,f):f-P<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",P,g,f);let{data:C,error:R}=await this._getUser(i);if(R)throw R;let N={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:m,expires_at:g,refresh_token:a,token_type:h,user:C.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:N,redirectType:e.type},error:null}}catch(n){if(z(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await pi(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var n;let{data:s,error:i}=t;if(i)return{error:i};let a=(n=s.session)===null||n===void 0?void 0:n.access_token;if(a){let{error:u}=await this.admin.signOut(a,e);if(u&&!(j_(u)&&(u.status===404||u.status===401||u.status===403)))return{error:u}}return e!=="others"&&(await this._removeSession(),await mi(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t=W_(),n={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,n),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async t=>{var n,s;try{let{data:{session:i},error:a}=t;if(a)throw a;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await Nr(this.storage,this.storageKey,!0));try{return await H(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(z(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{let{data:t,error:n}=await this.getUser();if(n)throw n;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(z(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:n,error:s}=await this._useSession(async i=>{var a,u,c,h,f;let{data:m,error:g}=i;if(g)throw g;let b=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(u=e.options)===null||u===void 0?void 0:u.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await H(this.fetch,"GET",b,{headers:this.headers,jwt:(f=(h=m.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(s)throw s;return Ye()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),{data:{provider:e.provider,url:n==null?void 0:n.url},error:null}}catch(n){if(z(n))return{data:{provider:e.provider,url:null},error:n};throw n}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:a}=t;if(a)throw a;return await H(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let n=Date.now();return await X_(async s=>(s>0&&await Y_(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await H(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:kt})),(s,i)=>{let a=200*Math.pow(2,s);return i&&Oa(i)&&Date.now()+a-n<Cr})}catch(n){if(this._debug(t,"error",n),z(n))return{data:{session:null,user:null},error:n};throw n}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",n),Ye()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let n=await pi(this.storage,this.storageKey);if(this._debug(t,"session from storage",n),!this._isValidSession(n)){this._debug(t,"session is not valid"),n!==null&&await this._removeSession();return}let s=((e=n.expires_at)!==null&&e!==void 0?e:1/0)*1e3-Date.now()<ka;if(this._debug(t,`session has${s?"":" not"} expired with margin of ${ka}s`),s){if(this.autoRefreshToken&&n.refresh_token){let{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),Oa(i)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(t,"error",n),console.error(n);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,n;if(!e)throw new ze;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new fi;let{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new ze;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let u={session:i.session,error:null};return this.refreshingDeferred.resolve(u),u}catch(i){if(this._debug(s,"error",i),z(i)){let a={session:null,error:i};return Oa(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(a),a}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,n=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],a=Array.from(this.stateChangeEmitters.values()).map(async u=>{try{await u.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(a),i.length>0){for(let u=0;u<i.length;u+=1)console.error(i[u]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await xh(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await mi(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ye()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Cr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:n}}=t;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((n.expires_at*1e3-e)/Cr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Cr}ms, refresh threshold is ${Ca} ticks`),s<=Ca&&await this._callRefreshToken(n.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof gi)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ye()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){let s=[`provider=${encodeURIComponent(t)}`];if(n!=null&&n.redirectTo&&s.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[i,a]=await Nr(this.storage,this.storageKey),u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});s.push(u.toString())}if(n!=null&&n.queryParams){let i=new URLSearchParams(n.queryParams);s.push(i.toString())}return n!=null&&n.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;return i?{data:null,error:i}:await H(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:a}=t;if(a)return{data:null,error:a};let u=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:c,error:h}=await H(this.fetch,"POST",`${this.url}/factors`,{body:u,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return h?{data:null,error:h}:(e.factorType==="totp"&&(!((s=c==null?void 0:c.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),{data:c,error:null})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;if(i)return{data:null,error:i};let{data:a,error:u}=await H(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});return u?{data:null,error:u}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),{data:a,error:u})})}catch(t){if(z(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;return i?{data:null,error:i}:await H(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token})})}catch(t){if(z(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?{data:null,error:n}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let n=(e==null?void 0:e.factors)||[],s=n.filter(a=>a.factor_type==="totp"&&a.status==="verified"),i=n.filter(a=>a.factor_type==="phone"&&a.status==="verified");return{data:{all:n,totp:s,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,n;let{data:{session:s},error:i}=e;if(i)return{data:null,error:i};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:a}=Va(s.access_token),u=null;a.aal&&(u=a.aal);let c=u;((n=(t=s.user.factors)===null||t===void 0?void 0:t.filter(m=>m.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(c="aal2");let f=a.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:f},error:null}}))}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(a=>a.kid===e);if(n||(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+M_>Date.now()))return n;let{data:s,error:i}=await H(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;if(!s.keys||s.keys.length===0)throw new Ct("JWKS is empty");if(this.jwks=s,this.jwks_cached_at=Date.now(),n=s.keys.find(a=>a.kid===e),!n)throw new Ct("No matching signing key found in JWKS");return n}async getClaims(e,t={keys:[]}){try{let n=e;if(!n){let{data:b,error:P}=await this.getSession();if(P||!b.session)return{data:null,error:P};n=b.session.access_token}let{header:s,payload:i,signature:a,raw:{header:u,payload:c}}=Va(n);if(ev(i.exp),!s.kid||s.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){let{error:b}=await this.getUser(n);if(b)throw b;return{data:{claims:i,header:s,signature:a},error:null}}let h=tv(s.alg),f=await this.fetchJwk(s.kid,t),m=await crypto.subtle.importKey("jwk",f,h,!0,["verify"]);if(!await crypto.subtle.verify(h,m,a,K_(`${u}.${c}`)))throw new Ct("Invalid JWT signature");return{data:{claims:i,header:s,signature:a},error:null}}catch(n){if(z(n))return{data:null,error:n};throw n}}};Mr.nextInstanceID=0;var XP=Mr,Ch=XP;var Fa=class extends Ch{constructor(e){super(e)}};var ZP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},Jn=class{constructor(e,t,n){var s,i,a;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let u=D_(e);this.realtimeUrl=`${u}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${u}/auth/v1`,this.storageUrl=`${u}/storage/v1`,this.functionsUrl=`${u}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:R_,realtime:C_,auth:Object.assign(Object.assign({},P_),{storageKey:c}),global:S_},f=O_(n!=null?n:{},h);this.storageKey=(s=f.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(i=f.global.headers)!==null&&i!==void 0?i:{},f.accessToken?(this.accessToken=f.accessToken,this.auth=new Proxy({},{get:(m,g)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(g)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((a=f.auth)!==null&&a!==void 0?a:{},this.headers,f.global.fetch),this.fetch=k_(t,this._getAccessToken.bind(this),f.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},f.realtime)),this.rest=new d_(`${u}/rest/v1`,{headers:this.headers,schema:f.db.schema,fetch:this.fetch}),f.accessToken||this._listenForAuthEvents()}get functions(){return new Js(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ai(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},n={}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return ZP(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();let{data:n}=yield this.auth.getSession();return(t=(e=n.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:s,storageKey:i,flowType:a,lock:u,debug:c},h,f){let m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Fa({url:this.authUrl,headers:Object.assign(Object.assign({},m),h),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:s,flowType:a,lock:u,debug:c,fetch:f,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new qn(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,n)=>{this._handleTokenChanged(t,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(e,t,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?this.changedAccessToken=n:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var cv=(r,e,t)=>new Jn(r,e,t);var gv=hu(pv(),1);var tC=Object.prototype.toString,rC=r=>tC.call(r)==="[object Error]",nC=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function kh(r){return r&&rC(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:nC.has(r.message):!1}var Dh=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},mv=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function yi(r,e){return new Promise((t,n)=>{var u,c,h;e={...e},(u=e.onFailedAttempt)!=null||(e.onFailedAttempt=()=>{}),(c=e.shouldRetry)!=null||(e.shouldRetry=()=>!0),(h=e.retries)!=null||(e.retries=10);let s=gv.default.operation(e),i=()=>{var f;s.stop(),n((f=e.signal)==null?void 0:f.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",i,{once:!0});let a=()=>{var f;(f=e.signal)==null||f.removeEventListener("abort",i),s.stop()};s.attempt(async f=>{try{let m=await r(f);a(),t(m)}catch(m){try{if(!(m instanceof Error))throw new TypeError(`Non-error was thrown: "${m}". You should only throw errors.`);if(m instanceof Dh)throw m.originalError;if(m instanceof TypeError&&!kh(m))throw m;if(mv(m,f,e),await e.shouldRetry(m)||(s.stop(),n(m)),await e.onFailedAttempt(m),!s.retry(m))throw s.mainError()}catch(g){mv(g,f,e),a(),n(g)}}})})}var sC=function(e,t){if(typeof e!="function")throw new Error("First argument to supabasey() must be a callback function");let n={session:null,retries:3,retry:{minTimeout:100,factor:2,randomize:!0,onFailedAttempt:i=>console.info(`[Attempt ${i.attemptNumber}/${i.attemptNumber+i.retriesLeft-1}] failed to run Supabase query`),shouldRetry:i=>(console.log("QUERY SHOULD-RETRY",i),!0)},...t},s=n.session?typeof n.session=="string"?ge.sessions[n.session]:typeof n.session=="object"?n.session:(()=>{throw new Error(`Unknown session type for supabasey(cb, {session}) - expected Object|String got ${typeof n.session}`)})():(()=>{throw new Error("supabasey(cb, {session}) cannot be empty - specify a session or use bindSession() first")})();return Promise.resolve().then(()=>yi(()=>e.call(s,s),{...n.retries&&{retries:n.retries},...t.retry})).then(i=>{if(i!=null&&i.error)ge.throw(i.error);else if(i.data)return i.data}).catch(i=>{throw console.log("Supabasey error:",i),i})},ge=sC;ge.bindSession=function(e){if(typeof e=="string"&&!ge.sessions[e])throw new Error(`Unable to bind to non-existant session "${e}"`);let t=(n,s)=>ge(n,{session:e,...s});return t.rpc=(n,s,i)=>ge.rpc(n,s,{session:e,...i}),t};ge.init=function(e){let t={env:{},init:!0,login:!1,session:"auto",...e},n=t.env,s=t.session=="auto"&&n.SUPABASE_URL?n.SUPABASE_URL:t.session?t.session:(()=>{throw new Error("Sesison should be truthy if using @iebh/supabasey.middleware({session:String})")})(),i=ge.sessions[s];return Promise.resolve().then(()=>{if(!i)if(t.init){if(!n.SUPABASE_URL||!n.SUPABASE_KEY)throw new Error("Both env.SUPABASE_URL + env.SUPABASE_KEY should be specified to use @iebh/supabasey.middleware(), otherwise disable with {init:false}");i=ge.sessions[s]=cv(n.SUPABASE_URL,n.SUPABASE_KEY)}else throw new Error("No Supabase session for middleware to work with!")}).then(()=>{if(t.login){if(i.supabaseyIsLoggedIn)return;if(!n.SUPABASE_USER||!n.SUPABASE_PASS)throw new Error("User credentials missing when using @iebh/supabasey.middleware(), provide in env.SUPABASE_USER + ..._PASS");return ge(a=>a.auth.signInWithPassword({email:n.SUPABASE_USER,password:n.SUPABASE_PASS}),{session:i}).then(()=>i.supabaseyIsLoggedIn=!0)}else return}).then(()=>ge.bindSession(i))};ge.middleware=function(e){let t={env:{},injectEnv:!0,...e};return async(n,s,i,a)=>ge.init({...e,env:i}).then(u=>{t.injectEnv&&(i.supabasey=u)}).catch(u=>ge.throw(u))};ge.throw=function(r){throw typeof r=="string"?new Error(r):r instanceof Error?r:/JSON object requested, multiple \(or no\) rows returned$/.test(r.message)?(console.warn("Supabase query resulted in NOT-FOUND:",r.message),console.warn("Supabase raw error",r),new Error("NOT-FOUND")):(console.warn("Supabase query threw",r.message||r||"Unknown error"),new Error(`${(r==null?void 0:r.code)||"UnknownError"}: ${(r==null?void 0:r.message)||"Unknown Supabase error"}`))};ge.rpc=function(r,e,t){return ge(async n=>await n.rpc(r,e),t)};ge.sessions={};var yv=ge;function iC(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function Ma(r,e){return Array.isArray(r)?r.map(t=>Ma(t,e)):typeof r=="object"?r==null?null:Object.fromEntries(Object.entries(iC(r,e)).map(([t,n])=>[t,Ma(n,e)])):r}var _v={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var vv={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var wv={id:"~infinity",test:r=>r===1/0||r===-1/0,serialize:r=>({_:"~infinity",v:r===1/0?1:0}),deserialize:r=>r.v==1?1/0:-1/0};var bv={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var Tv={id:"~regexp",test:r=>r instanceof RegExp,serialize:r=>({_:"~regexp",v:r.source,f:r.flags}),deserialize:r=>new RegExp(r.v,r.f)};var Ev={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var Iv={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var Yn={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[_v,vv,wv,bv,Tv,Ev,Iv],circular:!0,symetric:!1},loadedModules:{},loadModules(r){return r.map(e=>{if(Z(e)){if(!e.id)throw new Error("Provided custom module does not expose an `id` property");return Yn.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=ao(e,Yn.settings),n=Yn.loadModules(t.modules),s=t.symetric?Ma(r):t.clone?Wt(r):r,i=new Map,a=(u,c)=>{let h=Z(u);if(h&&t.circular){let g=i.get(u);if(g)return Qt(s,c,{_:"~circular",p:g.join(".")});i.set(u,c)}let f=n.find(g=>g.test(u,c)),m=(!t.depth||c.length<t.depth)&&h;if(f){let g=f.serialize(u,c);if(f.recursive&&m){let b=xe(u);t.symetric&&b.sort(),Qt(s,c,g),b.forEach(P=>a(u[P],c.concat(P)))}else c.length?Qt(s,c,g):s=g}else if(m){let g=xe(u);t.symetric&&g.sort(),g.forEach(b=>a(u[b],c.concat(b)))}};return a(s,[]),t.stringify?JSON.stringify(s):s},deserialize(r,e){let t=ao(e,Yn.settings),n=Yn.loadModules(t.modules),s=vu(n,"id"),i=t.destringify?JSON.parse(r):t.clone?Wt(r):r,a=(u,c)=>{if(Z(u)&&u._&&typeof u._=="string"&&u._.startsWith("~")&&s[u._]){let h=s[u._].deserialize(u,c);c.length?s[u._].recursive&&Z(h)?(Qt(i,c,h),xe(h).forEach(f=>a(u[f],[...c,f]))):Qt(i,c,h):i=h}else t.circular&&Z(u)&&u._&&u._=="~circular"?Qt(i,c,vs(i,u.p)):(!t.depth||c.length<t.depth)&&Z(u)&&xe(u).forEach(h=>a(u[h],c.concat(h)))};return a(i,[]),i}},ja=Yn;var Av="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var xv=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Av[t[r]&63];return e};var Dt=class r{constructor(e,t){this.throttle=250;this.config={heartbeatInterval:5e4,syncroRegistryUrl:"https://tera-tools.com/api/sync",context:{}};this.isDirty=!1;this._destroyActions=[];this.path=e,Object.assign(this,{...t,config:{...this.config,...t==null?void 0:t.config}}),r.session||(r.session=`syncro_${xv()}`)}debug(...e){}debugError(...e){console.log(`[Syncro ${this.path}]`,...e)}destroy(){return this.debug("Destroy!"),Promise.all(this._destroyActions.map(e=>e())).then(()=>this._destroyActions=[])}getReactive(e){console.warn("Syncro.getReactive has not been subclassed, assuming a POJO response");let t={...e};return{doc:t,setState(n){Object.entries(n||{}).forEach(([s,i])=>t[s]=i)},getState(){return Wt(t)},watch(n){}}}static pathSplit(e,t){var a;let n={allowAsterisk:!1,...t},i={...(a=new RegExp("^(?<entity>\\w+?)::(?<id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:::(?<relation>[\\w\\-"+(n.allowAsterisk?"\\*":"")+"]+?))?$").exec(e))==null?void 0:a.groups};if(!i||!i.entity||!i.id)throw new Error(`Invalid session path syntax "${e}"`);if(r.SyncroEntities&&!(i.entity in r.SyncroEntities))throw new Error(`Unsupported entity "${e}" -> Entity="${i.entity}"`);return{entity:i.entity,id:i.id,relation:i.relation,fsCollection:i.entity,fsId:i.relation?`${i.id}::${i.relation}`:i.id}}static toFirestore(e={}){return ja.serialize(e,{...Sv,stringify:!1})}static fromFirestore(e={}){return ja.deserialize(e,{...Sv,destringify:!1})}static toFirestoreFields(e){let t={};for(let[n,s]of Object.entries(e)){let i=typeof s;i==="string"?t[n]={stringValue:s}:i==="number"?t[n]={doubleValue:s}:i==="boolean"?t[n]={booleanValue:s}:s===null?t[n]={nullValue:null}:Array.isArray(s)?t[n]={arrayValue:{values:s.map(a=>r.toFirestoreFields({item:a}).item)}}:i==="object"&&(t[n]={mapValue:{fields:r.toFirestoreFields(s)}})}return t}static fromFirestoreFields(e={}){let t={};for(let n in e){let s=e[n],i=["stringValue","booleanValue","doubleValue","integerValue","timestampValue","mapValue","arrayValue","nullValue"].find(a=>a===Object.keys(s)[0]);if(i)if(i==="mapValue")t[n]=r.fromFirestoreFields(s.mapValue.fields||{});else if(i==="arrayValue"){let a=s.arrayValue.values;t[n]=a?a.map(u=>r.fromFirestoreFields(u)):[]}else i==="nullValue"?t[n]=null:t[n]=s[i];else t[n]=r.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=r.pathSplit(e);return Promise.resolve().then(async()=>th(fa(r.firestore,t,n))).then(s=>s.exists()?r.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:i,fsId:a}=r.pathSplit(e),u=fa(r.firestore,i,a),c=r.toFirestore(t);return Promise.resolve().then(()=>s.method==="merge"?nh(u,c):rh(u,c)).then(()=>t)}mount(e){let t={initialState:null,retries:5,retryMinTime:250,...e},{fsCollection:n,fsId:s,entity:i}=r.pathSplit(this.path),a,u;return yi(async()=>{await this.setHeartbeat(!1),this.docRef=fa(r.firestore,n,s);let c=await this.getFirestoreState();if(a=this.getReactive(c),!a.doc||!a.setState||!a.getState||!a.watch)throw new Error("Syncro.getReactive() requires a returned `doc`, `setState()`, `getState()` + `watch()`");this.value=u=a.doc,this.debug("Initial state",{doc:u});let h=Qy(this.docRef,f=>{let m=r.fromFirestore(f.data());this.debug("Incoming snapshot",{snapshotData:m}),a.setState(m)});if(this._destroyActions.push(h),_u(u))if(t.initialState)this.debug("Populate initial Syncro state (from provided initialState)"),await this.setFirestoreState(t.initialState,{method:"set"});else{this.debug(`Populate initial Syncro state (from "${i}" Syncro worker)`);let f=await fetch(`${this.config.syncroRegistryUrl}/${this.path}`);if(!f.ok)throw new Error(`Failed to check Syncro "${n}::${s}" status - ${f.statusText}`)}return a.watch(wu(f=>{this.debug("Local change",{newState:f}),this.markDirty(),this.setFirestoreState(f,{method:"merge"})},this.throttle)),await this.setHeartbeat(!0,{immediate:!0}),this},{retries:t.retries,minTimeout:t.retryMinTime,randomize:!0,factor:3,onFailedAttempt:async c=>{this.debugError(`[Attempt ${c.attemptNumber}/${c.attemptNumber+c.retriesLeft-1}] to mount syncro`,c),await this.destroy()}})}async set(e,t,n){let s;if(typeof e=="string")s[e]=t;else if(typeof e=="object")[s,n]=[e,t];else throw new Error("Unknown call signature for set() - call with string+value or object");let i={delta:!0,flush:!0,forceFlush:!1,flushDestroy:!1,...n},a=!1;return i.delta?Object.entries(s).filter(([u,c])=>!bs(this.value[u],c)).forEach(([u,c])=>{a=!0,this.value[u]=c}):(a=!0,Object.assign(this.value,s)),(i.forceFlush||a)&&i.flush&&await this.flush({destroy:i.flushDestroy}),this}setHeartbeat(e=!0,t){let n={immediate:!0,...t};if(clearTimeout(this._heartbeatTimer),e){let s=async()=>{await this.heartbeat(),e&&this.setHeartbeat(!0)};if(this._heartbeatTimer=setTimeout(s,this.config.heartbeatInterval),n.immediate)return this.heartbeat()}}async heartbeat(){this.debug("heartbeat!");try{let e=await fetch(`${this.config.syncroRegistryUrl}/${this.path}/heartbeat`,{method:"post",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:r.session,...this.isDirty&&{dirty:!0}})});e.ok||console.warn(this.path,`Heartbeat failed - ${e.statusText}`,{response:e}),this.isDirty=!1}catch(e){console.warn(this.path,"Heartbeat fetch error",e)}}async setFirestoreState(e,t,n=0){let s={method:"merge",...t};if(!this.docRef)throw new Error("mount() must be called before setting Firestore state");let i=r.toFirestore(e);try{return s.method==="merge"?await nh(this.docRef,i):await rh(this.docRef,i)}catch(a){if(a instanceof Qe&&a.code==="not-found"){if(n<3)return console.warn("Firebase syncro document does not exist during document update, reinitializing..."),(await fetch(`${this.config.syncroRegistryUrl}/${this.path}?force=1`)).ok||console.error("Failed to reinitialize Syncro"),await this.setFirestoreState(e,t,n+1);console.warn("Max retries exceeded while trying to recover firestore syncro document, throwing error")}throw console.error(`Error during Firestore operation (${s.method}) on doc: ${this.docRef.path}`,a),a}}getFirestoreState(){if(!this.docRef)throw new Error("mount() must be called before getting Firestore state");return th(this.docRef).then(e=>{var t;return r.fromFirestore((t=e.data())!=null?t:{})})}markDirty(){return this.isDirty=!0,this}flush(e){let t={destroy:!1,...e};return fetch(`${this.config.syncroRegistryUrl}/${this.path}/flush`+(t.destroy?"?destroy=1":"")).then(n=>n.ok?null:Promise.reject(n.statusText||"An error occured"))}};var Sv={circular:!1,clone:!0,modules:[{id:"~array",recursive:!0,test:r=>Array.isArray(r),serialize:r=>({_:"~array",...r}),deserialize:r=>{let e=Array.from({length:Object.keys(r).length-1});return Object.entries(r).filter(([t])=>t!=="_").forEach(([t,n])=>e[+t]=n),e}},{id:"~function",test:r=>typeof r=="function",serialize:(r,e)=>{throw console.warn("Marshal Warning: Stripping function from path",e.join(".")),new Error("Function serializing is forbidden")},deserialize:(r,e)=>{console.warn("Marshal Warning: Stripping function from path",e.join("."))}},...ja.settings.modules.filter(r=>r.id!="~function")]};var _i=class{init(){}constructor(e,t){}};var vi=class extends _i{constructor(){super(...arguments);this.syncros={};this.namespaces={}}async init(t){let n={firebaseApiKey:null,firebaseAuthDomain:null,firebaseProjectId:null,firebaseAppId:null,supabaseUrl:null,supabaseKey:null,...await this.getCredentials(),...t},s=Object.keys(n).filter(i=>i===null);if(s.length>0)throw new Error("Firebase plugin requires mandatory options: "+s.join(", "));Dt.firebase=ju({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),Dt.firestore=$y(Dt.firebase),Dt.supabasey=await yv.init({env:{SUPABASE_URL:n.supabaseUrl,SUPABASE_KEY:n.supabaseKey}})}_mountNamespace(t){let n;return Promise.resolve().then(()=>this.requireProject()).then(s=>{let i=t=="_PROJECT"?`projects::${s.id}`:`project_namespaces::${s.id}::${t}`;return n=this.syncros[t]=new Dt(i,{debug:(...a)=>this.debug(`SYNCRO://${i}`,...a),getReactive:this.getReactive}),n.mount()}).then(()=>{this.namespaces[t]=n.value})}_unmountNamespace(t){let n=this.syncros[t];return delete this.namespaces[t],delete this.syncros[t],n?n.destroy():Promise.resolve()}};var Oh=class extends vi{constructor(){super(...arguments);this.project=null;this.reactiveId=1001}async init(t){let n={app:null,Vue:null,globalName:"$tera",...t};if(!n.Vue)throw new Error("Vue instance to use must be specified in init options as `Vue`");if(this.Vue=n.Vue,!n.app)throw new Error("Vue Root / App instance to use must be specified in init options as `app`");this.app=n.app,n.globalName&&(this.Vue.prototype[n.globalName]=this),await super.init(n),this.project=await this.mountNamespace("_PROJECT")}getReactive(t){let n=this.Vue.observable(t),s=`_teraFy_${this.reactiveId++}`;return this.app[s]=n,{doc:n,setState:i=>{Object.entries(i||{}).filter(([a])=>!bs(n[a],i[a])).forEach(([a,u])=>n[a]=u)},getState:()=>Wt(n),watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Oh as default};
29
29
  /*! Bundled license information:
30
30
 
31
31
  lodash-es/lodash.js: