@iebh/tera-fy 2.0.15 → 2.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/plugin.vue2.es2019.js +13 -13
- package/lib/syncro/syncro.js +77 -48
- package/lib/terafy.server.js +2 -1
- package/package.json +2 -1
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
var Vv=Object.create;var ds=Object.defineProperty;var Lv=Object.getOwnPropertyDescriptor;var Mv=Object.getOwnPropertyNames;var Fv=Object.getPrototypeOf,jv=Object.prototype.hasOwnProperty;var Uv=(r,e,t)=>e in r?ds(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Bv=(r,e)=>()=>(r&&(e=r(r=0)),e);var Je=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),$v=(r,e)=>{for(var t in e)ds(r,t,{get:e[t],enumerable:!0})},Id=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Mv(e))!jv.call(r,s)&&s!==t&&ds(r,s,{get:()=>e[s],enumerable:!(n=Lv(e,s))||n.enumerable});return r};var Ad=(r,e,t)=>(t=r!=null?Vv(Fv(r)):{},Id(e||!r||!r.__esModule?ds(t,"default",{value:r,enumerable:!0}):t,r)),qv=r=>Id(ds({},"__esModule",{value:!0}),r);var de=(r,e,t)=>Uv(r,typeof e!="symbol"?e+"":e,t);var Er={};$v(Er,{Headers:()=>Ql,Request:()=>CR,Response:()=>kR,default:()=>Wl,fetch:()=>PR});var RR,Vn,PR,Wl,Ql,CR,kR,rr=Bv(()=>{"use strict";RR=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")},Vn=RR(),PR=Vn.fetch,Wl=Vn.fetch.bind(Vn),Ql=Vn.Headers,CR=Vn.Request,kR=Vn.Response});var Xl=Je(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var Jl=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Yl.default=Jl});var eh=Je(Hs=>{"use strict";var $y=Hs&&Hs.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Hs,"__esModule",{value:!0});var OR=$y((rr(),qv(Er))),NR=$y(Xl()),Zl=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=OR.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,E=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,E="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,E="OK")}catch{i.status===404&&C===""?(g=204,E="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,E="OK"),h&&this.shouldThrowOnError)throw new NR.default(h)}return{error:h,data:f,count:m,status:g,statusText:E}});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)}};Hs.default=Zl});var rh=Je(Ws=>{"use strict";var VR=Ws&&Ws.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ws,"__esModule",{value:!0});var LR=VR(eh()),th=class extends LR.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}};Ws.default=th});var ga=Je(Qs=>{"use strict";var MR=Qs&&Qs.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Qs,"__esModule",{value:!0});var FR=MR(rh()),nh=class extends FR.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}};Qs.default=nh});var ih=Je(Ys=>{"use strict";var jR=Ys&&Ys.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ys,"__esModule",{value:!0});var Js=jR(ga()),sh=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 Js.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 Js.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 Js.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 Js.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 Js.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Ys.default=sh});var qy=Je(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.version=void 0;ya.version="0.0.0-automated"});var zy=Je(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.DEFAULT_HEADERS=void 0;var UR=qy();_a.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${UR.version}`}});var Ky=Je(Xs=>{"use strict";var Gy=Xs&&Xs.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xs,"__esModule",{value:!0});var BR=Gy(ih()),$R=Gy(ga()),qR=zy(),oh=class r{constructor(e,{headers:t={},schema:n,fetch:s}={}){this.url=e,this.headers=Object.assign(Object.assign({},qR.DEFAULT_HEADERS),t),this.schemaName=n,this.fetch=s}from(e){let t=new URL(`${this.url}/${e}`);return new BR.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 $R.default({method:a,url:u,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};Xs.default=oh});var Zy=Je(Te=>{"use strict";var Ln=Te&&Te.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Te,"__esModule",{value:!0});Te.PostgrestError=Te.PostgrestBuilder=Te.PostgrestTransformBuilder=Te.PostgrestFilterBuilder=Te.PostgrestQueryBuilder=Te.PostgrestClient=void 0;var Hy=Ln(Ky());Te.PostgrestClient=Hy.default;var Wy=Ln(ih());Te.PostgrestQueryBuilder=Wy.default;var Qy=Ln(ga());Te.PostgrestFilterBuilder=Qy.default;var Jy=Ln(rh());Te.PostgrestTransformBuilder=Jy.default;var Yy=Ln(eh());Te.PostgrestBuilder=Yy.default;var Xy=Ln(Xl());Te.PostgrestError=Xy.default;Te.default={PostgrestClient:Hy.default,PostgrestQueryBuilder:Wy.default,PostgrestFilterBuilder:Qy.default,PostgrestTransformBuilder:Jy.default,PostgrestBuilder:Yy.default,PostgrestError:Xy.default}});var u_=Je((e2,a_)=>{"use strict";a_.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var zv=typeof global=="object"&&global&&global.Object===Object&&global,Vi=zv;var Gv=typeof self=="object"&&self&&self.Object===Object&&self,Kv=Vi||Gv||Function("return this")(),ce=Kv;var Hv=ce.Symbol,De=Hv;var xd=Object.prototype,Wv=xd.hasOwnProperty,Qv=xd.toString,fs=De?De.toStringTag:void 0;function Jv(r){var e=Wv.call(r,fs),t=r[fs];try{r[fs]=void 0;var n=!0}catch{}var s=Qv.call(r);return n&&(e?r[fs]=t:delete r[fs]),s}var Sd=Jv;var Yv=Object.prototype,Xv=Yv.toString;function Zv(r){return Xv.call(r)}var Rd=Zv;var ew="[object Null]",tw="[object Undefined]",Pd=De?De.toStringTag:void 0;function rw(r){return r==null?r===void 0?tw:ew:Pd&&Pd in Object(r)?Sd(r):Rd(r)}var Ke=rw;function nw(r){return r!=null&&typeof r=="object"}var Oe=nw;var sw="[object Symbol]";function iw(r){return typeof r=="symbol"||Oe(r)&&Ke(r)==sw}var Vt=iw;function ow(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 Cd=ow;var aw=Array.isArray,he=aw;var uw=1/0,kd=De?De.prototype:void 0,Dd=kd?kd.toString:void 0;function Od(r){if(typeof r=="string")return r;if(he(r))return Cd(r,Od)+"";if(Vt(r))return Dd?Dd.call(r):"";var e=r+"";return e=="0"&&1/r==-uw?"-0":e}var Nd=Od;var cw=/\s/;function lw(r){for(var e=r.length;e--&&cw.test(r.charAt(e)););return e}var Vd=lw;var hw=/^\s+/;function dw(r){return r&&r.slice(0,Vd(r)+1).replace(hw,"")}var Ld=dw;function fw(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Z=fw;var Md=NaN,pw=/^[-+]0x[0-9a-f]+$/i,mw=/^0b[01]+$/i,gw=/^0o[0-7]+$/i,yw=parseInt;function _w(r){if(typeof r=="number")return r;if(Vt(r))return Md;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=Ld(r);var t=mw.test(r);return t||gw.test(r)?yw(r.slice(2),t?2:8):pw.test(r)?Md:+r}var su=_w;function vw(r){return r}var Br=vw;var ww="[object AsyncFunction]",bw="[object Function]",Tw="[object GeneratorFunction]",Ew="[object Proxy]";function Iw(r){if(!Z(r))return!1;var e=Ke(r);return e==bw||e==Tw||e==ww||e==Ew}var Li=Iw;var Aw=ce["__core-js_shared__"],Mi=Aw;var Fd=function(){var r=/[^.]+$/.exec(Mi&&Mi.keys&&Mi.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function xw(r){return!!Fd&&Fd in r}var jd=xw;var Sw=Function.prototype,Rw=Sw.toString;function Pw(r){if(r!=null){try{return Rw.call(r)}catch{}try{return r+""}catch{}}return""}var pt=Pw;var Cw=/[\\^$.*+?()[\]{}|]/g,kw=/^\[object .+?Constructor\]$/,Dw=Function.prototype,Ow=Object.prototype,Nw=Dw.toString,Vw=Ow.hasOwnProperty,Lw=RegExp("^"+Nw.call(Vw).replace(Cw,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Mw(r){if(!Z(r)||jd(r))return!1;var e=Li(r)?Lw:kw;return e.test(pt(r))}var Ud=Mw;function Fw(r,e){return r==null?void 0:r[e]}var Bd=Fw;function jw(r,e){var t=Bd(r,e);return Ud(t)?t:void 0}var Ne=jw;var Uw=Ne(ce,"WeakMap"),Fi=Uw;var $d=Object.create,Bw=function(){function r(){}return function(e){if(!Z(e))return{};if($d)return $d(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}}(),qd=Bw;function $w(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 zd=$w;function qw(r,e){var t=-1,n=r.length;for(e||(e=Array(n));++t<n;)e[t]=r[t];return e}var Gd=qw;var zw=800,Gw=16,Kw=Date.now;function Hw(r){var e=0,t=0;return function(){var n=Kw(),s=Gw-(n-t);if(t=n,s>0){if(++e>=zw)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}var Kd=Hw;function Ww(r){return function(){return r}}var Hd=Ww;var Qw=function(){try{var r=Ne(Object,"defineProperty");return r({},"",{}),r}catch{}}(),$r=Qw;var Jw=$r?function(r,e){return $r(r,"toString",{configurable:!0,enumerable:!1,value:Hd(e),writable:!0})}:Br,Wd=Jw;var Yw=Kd(Wd),Qd=Yw;function Xw(r,e){for(var t=-1,n=r==null?0:r.length;++t<n&&e(r[t],t,r)!==!1;);return r}var Jd=Xw;var Zw=9007199254740991,eb=/^(?:0|[1-9]\d*)$/;function tb(r,e){var t=typeof r;return e=e==null?Zw:e,!!e&&(t=="number"||t!="symbol"&&eb.test(r))&&r>-1&&r%1==0&&r<e}var Lt=tb;function rb(r,e,t){e=="__proto__"&&$r?$r(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}var qr=rb;function nb(r,e){return r===e||r!==r&&e!==e}var Ye=nb;var sb=Object.prototype,ib=sb.hasOwnProperty;function ob(r,e,t){var n=r[e];(!(ib.call(r,e)&&Ye(n,t))||t===void 0&&!(e in r))&&qr(r,e,t)}var zr=ob;function ab(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?qr(t,u,c):zr(t,u,c)}return t}var Mt=ab;var Yd=Math.max;function ub(r,e,t){return e=Yd(e===void 0?r.length-1:e,0),function(){for(var n=arguments,s=-1,i=Yd(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),zd(r,this,u)}}var Xd=ub;function cb(r,e){return Qd(Xd(r,e,Br),r+"")}var Zd=cb;var lb=9007199254740991;function hb(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=lb}var Gr=hb;function db(r){return r!=null&&Gr(r.length)&&!Li(r)}var Ft=db;function fb(r,e,t){if(!Z(t))return!1;var n=typeof e;return(n=="number"?Ft(t)&&Lt(e,t.length):n=="string"&&e in t)?Ye(t[e],r):!1}var ef=fb;var pb=Object.prototype;function mb(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||pb;return r===t}var jt=mb;function gb(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}var tf=gb;var yb="[object Arguments]";function _b(r){return Oe(r)&&Ke(r)==yb}var iu=_b;var rf=Object.prototype,vb=rf.hasOwnProperty,wb=rf.propertyIsEnumerable,bb=iu(function(){return arguments}())?iu:function(r){return Oe(r)&&vb.call(r,"callee")&&!wb.call(r,"callee")},Kr=bb;function Tb(){return!1}var nf=Tb;var af=typeof exports=="object"&&exports&&!exports.nodeType&&exports,sf=af&&typeof module=="object"&&module&&!module.nodeType&&module,Eb=sf&&sf.exports===af,of=Eb?ce.Buffer:void 0,Ib=of?of.isBuffer:void 0,Ab=Ib||nf,mt=Ab;var xb="[object Arguments]",Sb="[object Array]",Rb="[object Boolean]",Pb="[object Date]",Cb="[object Error]",kb="[object Function]",Db="[object Map]",Ob="[object Number]",Nb="[object Object]",Vb="[object RegExp]",Lb="[object Set]",Mb="[object String]",Fb="[object WeakMap]",jb="[object ArrayBuffer]",Ub="[object DataView]",Bb="[object Float32Array]",$b="[object Float64Array]",qb="[object Int8Array]",zb="[object Int16Array]",Gb="[object Int32Array]",Kb="[object Uint8Array]",Hb="[object Uint8ClampedArray]",Wb="[object Uint16Array]",Qb="[object Uint32Array]",oe={};oe[Bb]=oe[$b]=oe[qb]=oe[zb]=oe[Gb]=oe[Kb]=oe[Hb]=oe[Wb]=oe[Qb]=!0;oe[xb]=oe[Sb]=oe[jb]=oe[Rb]=oe[Ub]=oe[Pb]=oe[Cb]=oe[kb]=oe[Db]=oe[Ob]=oe[Nb]=oe[Vb]=oe[Lb]=oe[Mb]=oe[Fb]=!1;function Jb(r){return Oe(r)&&Gr(r.length)&&!!oe[Ke(r)]}var uf=Jb;function Yb(r){return function(e){return r(e)}}var Hr=Yb;var cf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ps=cf&&typeof module=="object"&&module&&!module.nodeType&&module,Xb=ps&&ps.exports===cf,ou=Xb&&Vi.process,Zb=function(){try{var r=ps&&ps.require&&ps.require("util").types;return r||ou&&ou.binding&&ou.binding("util")}catch{}}(),gt=Zb;var lf=gt&>.isTypedArray,eT=lf?Hr(lf):uf,Wr=eT;var tT=Object.prototype,rT=tT.hasOwnProperty;function nT(r,e){var t=he(r),n=!t&&Kr(r),s=!t&&!n&&mt(r),i=!t&&!n&&!s&&Wr(r),a=t||n||s||i,u=a?tf(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")||Lt(h,c)))&&u.push(h);return u}var ji=nT;function sT(r,e){return function(t){return r(e(t))}}var Ui=sT;var iT=Ui(Object.keys,Object),hf=iT;var oT=Object.prototype,aT=oT.hasOwnProperty;function uT(r){if(!jt(r))return hf(r);var e=[];for(var t in Object(r))aT.call(r,t)&&t!="constructor"&&e.push(t);return e}var Bi=uT;function cT(r){return Ft(r)?ji(r):Bi(r)}var Se=cT;function lT(r){var e=[];if(r!=null)for(var t in Object(r))e.push(t);return e}var df=lT;var hT=Object.prototype,dT=hT.hasOwnProperty;function fT(r){if(!Z(r))return df(r);var e=jt(r),t=[];for(var n in r)n=="constructor"&&(e||!dT.call(r,n))||t.push(n);return t}var ff=fT;function pT(r){return Ft(r)?ji(r,!0):ff(r)}var Ut=pT;var mT=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,gT=/^\w*$/;function yT(r,e){if(he(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Vt(r)?!0:gT.test(r)||!mT.test(r)||e!=null&&r in Object(e)}var Qr=yT;var _T=Ne(Object,"create"),yt=_T;function vT(){this.__data__=yt?yt(null):{},this.size=0}var pf=vT;function wT(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var mf=wT;var bT="__lodash_hash_undefined__",TT=Object.prototype,ET=TT.hasOwnProperty;function IT(r){var e=this.__data__;if(yt){var t=e[r];return t===bT?void 0:t}return ET.call(e,r)?e[r]:void 0}var gf=IT;var AT=Object.prototype,xT=AT.hasOwnProperty;function ST(r){var e=this.__data__;return yt?e[r]!==void 0:xT.call(e,r)}var yf=ST;var RT="__lodash_hash_undefined__";function PT(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=yt&&e===void 0?RT:e,this}var _f=PT;function Jr(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])}}Jr.prototype.clear=pf;Jr.prototype.delete=mf;Jr.prototype.get=gf;Jr.prototype.has=yf;Jr.prototype.set=_f;var au=Jr;function CT(){this.__data__=[],this.size=0}var vf=CT;function kT(r,e){for(var t=r.length;t--;)if(Ye(r[t][0],e))return t;return-1}var Bt=kT;var DT=Array.prototype,OT=DT.splice;function NT(r){var e=this.__data__,t=Bt(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():OT.call(e,t,1),--this.size,!0}var wf=NT;function VT(r){var e=this.__data__,t=Bt(e,r);return t<0?void 0:e[t][1]}var bf=VT;function LT(r){return Bt(this.__data__,r)>-1}var Tf=LT;function MT(r,e){var t=this.__data__,n=Bt(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}var Ef=MT;function Yr(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])}}Yr.prototype.clear=vf;Yr.prototype.delete=wf;Yr.prototype.get=bf;Yr.prototype.has=Tf;Yr.prototype.set=Ef;var $t=Yr;var FT=Ne(ce,"Map"),qt=FT;function jT(){this.size=0,this.__data__={hash:new au,map:new(qt||$t),string:new au}}var If=jT;function UT(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var Af=UT;function BT(r,e){var t=r.__data__;return Af(e)?t[typeof e=="string"?"string":"hash"]:t.map}var zt=BT;function $T(r){var e=zt(this,r).delete(r);return this.size-=e?1:0,e}var xf=$T;function qT(r){return zt(this,r).get(r)}var Sf=qT;function zT(r){return zt(this,r).has(r)}var Rf=zT;function GT(r,e){var t=zt(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}var Pf=GT;function Xr(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])}}Xr.prototype.clear=If;Xr.prototype.delete=xf;Xr.prototype.get=Sf;Xr.prototype.has=Rf;Xr.prototype.set=Pf;var lr=Xr;var KT="Expected a function";function uu(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(KT);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(uu.Cache||lr),t}uu.Cache=lr;var Cf=uu;var HT=500;function WT(r){var e=Cf(r,function(n){return t.size===HT&&t.clear(),n}),t=e.cache;return e}var kf=WT;var QT=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,JT=/\\(\\)?/g,YT=kf(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(QT,function(t,n,s,i){e.push(s?i.replace(JT,"$1"):n||t)}),e}),Df=YT;function XT(r){return r==null?"":Nd(r)}var Of=XT;function ZT(r,e){return he(r)?r:Qr(r,e)?[r]:Df(Of(r))}var Zr=ZT;var e0=1/0;function t0(r){if(typeof r=="string"||Vt(r))return r;var e=r+"";return e=="0"&&1/r==-e0?"-0":e}var Xe=t0;function r0(r,e){e=Zr(e,r);for(var t=0,n=e.length;r!=null&&t<n;)r=r[Xe(e[t++])];return t&&t==n?r:void 0}var $i=r0;function n0(r,e,t){var n=r==null?void 0:$i(r,e);return n===void 0?t:n}var ms=n0;function s0(r,e){for(var t=-1,n=e.length,s=r.length;++t<n;)r[s+t]=e[t];return r}var qi=s0;var i0=Ui(Object.getPrototypeOf,Object),zi=i0;function o0(){this.__data__=new $t,this.size=0}var Nf=o0;function a0(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}var Vf=a0;function u0(r){return this.__data__.get(r)}var Lf=u0;function c0(r){return this.__data__.has(r)}var Mf=c0;var l0=200;function h0(r,e){var t=this.__data__;if(t instanceof $t){var n=t.__data__;if(!qt||n.length<l0-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new lr(n)}return t.set(r,e),this.size=t.size,this}var Ff=h0;function en(r){var e=this.__data__=new $t(r);this.size=e.size}en.prototype.clear=Nf;en.prototype.delete=Vf;en.prototype.get=Lf;en.prototype.has=Mf;en.prototype.set=Ff;var Gt=en;function d0(r,e){return r&&Mt(e,Se(e),r)}var jf=d0;function f0(r,e){return r&&Mt(e,Ut(e),r)}var Uf=f0;var zf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Bf=zf&&typeof module=="object"&&module&&!module.nodeType&&module,p0=Bf&&Bf.exports===zf,$f=p0?ce.Buffer:void 0,qf=$f?$f.allocUnsafe:void 0;function m0(r,e){if(e)return r.slice();var t=r.length,n=qf?qf(t):new r.constructor(t);return r.copy(n),n}var Gf=m0;function g0(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 Kf=g0;function y0(){return[]}var Gi=y0;var _0=Object.prototype,v0=_0.propertyIsEnumerable,Hf=Object.getOwnPropertySymbols,w0=Hf?function(r){return r==null?[]:(r=Object(r),Kf(Hf(r),function(e){return v0.call(r,e)}))}:Gi,tn=w0;function b0(r,e){return Mt(r,tn(r),e)}var Wf=b0;var T0=Object.getOwnPropertySymbols,E0=T0?function(r){for(var e=[];r;)qi(e,tn(r)),r=zi(r);return e}:Gi,Ki=E0;function I0(r,e){return Mt(r,Ki(r),e)}var Qf=I0;function A0(r,e,t){var n=e(r);return he(r)?n:qi(n,t(r))}var Hi=A0;function x0(r){return Hi(r,Se,tn)}var gs=x0;function S0(r){return Hi(r,Ut,Ki)}var Jf=S0;var R0=Ne(ce,"DataView"),Wi=R0;var P0=Ne(ce,"Promise"),Qi=P0;var C0=Ne(ce,"Set"),Ji=C0;var Yf="[object Map]",k0="[object Object]",Xf="[object Promise]",Zf="[object Set]",ep="[object WeakMap]",tp="[object DataView]",D0=pt(Wi),O0=pt(qt),N0=pt(Qi),V0=pt(Ji),L0=pt(Fi),hr=Ke;(Wi&&hr(new Wi(new ArrayBuffer(1)))!=tp||qt&&hr(new qt)!=Yf||Qi&&hr(Qi.resolve())!=Xf||Ji&&hr(new Ji)!=Zf||Fi&&hr(new Fi)!=ep)&&(hr=function(r){var e=Ke(r),t=e==k0?r.constructor:void 0,n=t?pt(t):"";if(n)switch(n){case D0:return tp;case O0:return Yf;case N0:return Xf;case V0:return Zf;case L0:return ep}return e});var He=hr;var M0=Object.prototype,F0=M0.hasOwnProperty;function j0(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&F0.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var rp=j0;var U0=ce.Uint8Array,rn=U0;function B0(r){var e=new r.constructor(r.byteLength);return new rn(e).set(new rn(r)),e}var nn=B0;function $0(r,e){var t=e?nn(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.byteLength)}var np=$0;var q0=/\w*$/;function z0(r){var e=new r.constructor(r.source,q0.exec(r));return e.lastIndex=r.lastIndex,e}var sp=z0;var ip=De?De.prototype:void 0,op=ip?ip.valueOf:void 0;function G0(r){return op?Object(op.call(r)):{}}var ap=G0;function K0(r,e){var t=e?nn(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.length)}var up=K0;var H0="[object Boolean]",W0="[object Date]",Q0="[object Map]",J0="[object Number]",Y0="[object RegExp]",X0="[object Set]",Z0="[object String]",eE="[object Symbol]",tE="[object ArrayBuffer]",rE="[object DataView]",nE="[object Float32Array]",sE="[object Float64Array]",iE="[object Int8Array]",oE="[object Int16Array]",aE="[object Int32Array]",uE="[object Uint8Array]",cE="[object Uint8ClampedArray]",lE="[object Uint16Array]",hE="[object Uint32Array]";function dE(r,e,t){var n=r.constructor;switch(e){case tE:return nn(r);case H0:case W0:return new n(+r);case rE:return np(r,t);case nE:case sE:case iE:case oE:case aE:case uE:case cE:case lE:case hE:return up(r,t);case Q0:return new n;case J0:case Z0:return new n(r);case Y0:return sp(r);case X0:return new n;case eE:return ap(r)}}var cp=dE;function fE(r){return typeof r.constructor=="function"&&!jt(r)?qd(zi(r)):{}}var lp=fE;var pE="[object Map]";function mE(r){return Oe(r)&&He(r)==pE}var hp=mE;var dp=gt&>.isMap,gE=dp?Hr(dp):hp,fp=gE;var yE="[object Set]";function _E(r){return Oe(r)&&He(r)==yE}var pp=_E;var mp=gt&>.isSet,vE=mp?Hr(mp):pp,gp=vE;var wE=1,bE=2,TE=4,yp="[object Arguments]",EE="[object Array]",IE="[object Boolean]",AE="[object Date]",xE="[object Error]",_p="[object Function]",SE="[object GeneratorFunction]",RE="[object Map]",PE="[object Number]",vp="[object Object]",CE="[object RegExp]",kE="[object Set]",DE="[object String]",OE="[object Symbol]",NE="[object WeakMap]",VE="[object ArrayBuffer]",LE="[object DataView]",ME="[object Float32Array]",FE="[object Float64Array]",jE="[object Int8Array]",UE="[object Int16Array]",BE="[object Int32Array]",$E="[object Uint8Array]",qE="[object Uint8ClampedArray]",zE="[object Uint16Array]",GE="[object Uint32Array]",ne={};ne[yp]=ne[EE]=ne[VE]=ne[LE]=ne[IE]=ne[AE]=ne[ME]=ne[FE]=ne[jE]=ne[UE]=ne[BE]=ne[RE]=ne[PE]=ne[vp]=ne[CE]=ne[kE]=ne[DE]=ne[OE]=ne[$E]=ne[qE]=ne[zE]=ne[GE]=!0;ne[xE]=ne[_p]=ne[NE]=!1;function Yi(r,e,t,n,s,i){var a,u=e&wE,c=e&bE,h=e&TE;if(t&&(a=s?t(r,n,s,i):t(r)),a!==void 0)return a;if(!Z(r))return r;var f=he(r);if(f){if(a=rp(r),!u)return Gd(r,a)}else{var m=He(r),g=m==_p||m==SE;if(mt(r))return Gf(r,u);if(m==vp||m==yp||g&&!s){if(a=c||g?{}:lp(r),!u)return c?Qf(r,Uf(a,r)):Wf(r,jf(a,r))}else{if(!ne[m])return s?r:{};a=cp(r,m,u)}}i||(i=new Gt);var E=i.get(r);if(E)return E;i.set(r,a),gp(r)?r.forEach(function(R){a.add(Yi(R,e,t,R,r,i))}):fp(r)&&r.forEach(function(R,N){a.set(N,Yi(R,e,t,N,r,i))});var P=h?c?Jf:gs:c?Ut:Se,C=f?void 0:P(r);return Jd(C||r,function(R,N){C&&(N=R,R=r[N]),zr(a,N,Yi(R,e,t,N,r,i))}),a}var wp=Yi;var KE=1,HE=4;function WE(r){return wp(r,KE|HE)}var Kt=WE;var QE="__lodash_hash_undefined__";function JE(r){return this.__data__.set(r,QE),this}var bp=JE;function YE(r){return this.__data__.has(r)}var Tp=YE;function Xi(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new lr;++e<t;)this.add(r[e])}Xi.prototype.add=Xi.prototype.push=bp;Xi.prototype.has=Tp;var Ep=Xi;function XE(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 Ip=XE;function ZE(r,e){return r.has(e)}var Ap=ZE;var eI=1,tI=2;function rI(r,e,t,n,s,i){var a=t&eI,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,E=t&tI?new Ep: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(E){if(!Ip(e,function(N,M){if(!Ap(E,M)&&(P===N||s(P,N,t,n,i)))return E.push(M)})){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 Zi=rI;function nI(r){var e=-1,t=Array(r.size);return r.forEach(function(n,s){t[++e]=[s,n]}),t}var xp=nI;function sI(r){var e=-1,t=Array(r.size);return r.forEach(function(n){t[++e]=n}),t}var Sp=sI;var iI=1,oI=2,aI="[object Boolean]",uI="[object Date]",cI="[object Error]",lI="[object Map]",hI="[object Number]",dI="[object RegExp]",fI="[object Set]",pI="[object String]",mI="[object Symbol]",gI="[object ArrayBuffer]",yI="[object DataView]",Rp=De?De.prototype:void 0,cu=Rp?Rp.valueOf:void 0;function _I(r,e,t,n,s,i,a){switch(t){case yI:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case gI:return!(r.byteLength!=e.byteLength||!i(new rn(r),new rn(e)));case aI:case uI:case hI:return Ye(+r,+e);case cI:return r.name==e.name&&r.message==e.message;case dI:case pI:return r==e+"";case lI:var u=xp;case fI:var c=n&iI;if(u||(u=Sp),r.size!=e.size&&!c)return!1;var h=a.get(r);if(h)return h==e;n|=oI,a.set(r,e);var f=Zi(u(r),u(e),n,s,i,a);return a.delete(r),f;case mI:if(cu)return cu.call(r)==cu.call(e)}return!1}var Pp=_I;var vI=1,wI=Object.prototype,bI=wI.hasOwnProperty;function TI(r,e,t,n,s,i){var a=t&vI,u=gs(r),c=u.length,h=gs(e),f=h.length;if(c!=f&&!a)return!1;for(var m=c;m--;){var g=u[m];if(!(a?g in e:bI.call(e,g)))return!1}var E=i.get(r),P=i.get(e);if(E&&P)return E==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],M=e[g];if(n)var U=a?n(M,N,g,e,r,i):n(N,M,g,r,e,i);if(!(U===void 0?N===M||s(N,M,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 Cp=TI;var EI=1,kp="[object Arguments]",Dp="[object Array]",eo="[object Object]",II=Object.prototype,Op=II.hasOwnProperty;function AI(r,e,t,n,s,i){var a=he(r),u=he(e),c=a?Dp:He(r),h=u?Dp:He(e);c=c==kp?eo:c,h=h==kp?eo:h;var f=c==eo,m=h==eo,g=c==h;if(g&&mt(r)){if(!mt(e))return!1;a=!0,f=!1}if(g&&!f)return i||(i=new Gt),a||Wr(r)?Zi(r,e,t,n,s,i):Pp(r,e,c,t,n,s,i);if(!(t&EI)){var E=f&&Op.call(r,"__wrapped__"),P=m&&Op.call(e,"__wrapped__");if(E||P){var C=E?r.value():r,R=P?e.value():e;return i||(i=new Gt),s(C,R,t,n,i)}}return g?(i||(i=new Gt),Cp(r,e,t,n,s,i)):!1}var Np=AI;function Vp(r,e,t,n,s){return r===e?!0:r==null||e==null||!Oe(r)&&!Oe(e)?r!==r&&e!==e:Np(r,e,t,n,Vp,s)}var sn=Vp;var xI=1,SI=2;function RI(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 Gt;if(n)var g=n(h,f,c,r,e,m);if(!(g===void 0?sn(f,h,xI|SI,n,m):g))return!1}}return!0}var Lp=RI;function PI(r){return r===r&&!Z(r)}var to=PI;function CI(r){for(var e=Se(r),t=e.length;t--;){var n=e[t],s=r[n];e[t]=[n,s,to(s)]}return e}var Mp=CI;function kI(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}var ro=kI;function DI(r){var e=Mp(r);return e.length==1&&e[0][2]?ro(e[0][0],e[0][1]):function(t){return t===r||Lp(t,r,e)}}var Fp=DI;function OI(r,e){return r!=null&&e in Object(r)}var jp=OI;function NI(r,e,t){e=Zr(e,r);for(var n=-1,s=e.length,i=!1;++n<s;){var a=Xe(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&&Gr(s)&&Lt(a,s)&&(he(r)||Kr(r)))}var Up=NI;function VI(r,e){return r!=null&&Up(r,e,jp)}var Bp=VI;var LI=1,MI=2;function FI(r,e){return Qr(r)&&to(e)?ro(Xe(r),e):function(t){var n=ms(t,r);return n===void 0&&n===e?Bp(t,r):sn(e,n,LI|MI)}}var $p=FI;function jI(r){return function(e){return e==null?void 0:e[r]}}var qp=jI;function UI(r){return function(e){return $i(e,r)}}var zp=UI;function BI(r){return Qr(r)?qp(Xe(r)):zp(r)}var Gp=BI;function $I(r){return typeof r=="function"?r:r==null?Br:typeof r=="object"?he(r)?$p(r[0],r[1]):Fp(r):Gp(r)}var Kp=$I;function qI(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 Hp=qI;var zI=Hp(),Wp=zI;function GI(r,e){return r&&Wp(r,e,Se)}var Qp=GI;var KI=function(){return ce.Date.now()},no=KI;var HI="Expected a function",WI=Math.max,QI=Math.min;function JI(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(HI);e=su(e)||0,Z(t)&&(f=!!t.leading,m="maxWait"in t,i=m?WI(su(t.maxWait)||0,e):i,g="trailing"in t?!!t.trailing:g);function E(B){var T=n,y=s;return n=s=void 0,h=B,a=r.apply(y,T),a}function P(B){return h=B,u=setTimeout(N,e),f?E(B):a}function C(B){var T=B-c,y=B-h,w=e-T;return m?QI(w,i-y):w}function R(B){var T=B-c,y=B-h;return c===void 0||T>=e||T<0||m&&y>=i}function N(){var B=no();if(R(B))return M(B);u=setTimeout(N,C(B))}function M(B){return u=void 0,g&&n?E(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:M(no())}function Y(){var B=no(),T=R(B);if(n=arguments,s=this,c=B,T){if(u===void 0)return P(c);if(m)return clearTimeout(u),u=setTimeout(N,e),E(c)}return u===void 0&&(u=setTimeout(N,e)),a}return Y.cancel=U,Y.flush=G,Y}var Jp=JI;var Yp=Object.prototype,YI=Yp.hasOwnProperty,XI=Zd(function(r,e){r=Object(r);var t=-1,n=e.length,s=n>2?e[2]:void 0;for(s&&ef(e[0],e[1],s)&&(n=1);++t<n;)for(var i=e[t],a=Ut(i),u=-1,c=a.length;++u<c;){var h=a[u],f=r[h];(f===void 0||Ye(f,Yp[h])&&!YI.call(r,h))&&(r[h]=i[h])}return r}),so=XI;var ZI="[object Map]",eA="[object Set]",tA=Object.prototype,rA=tA.hasOwnProperty;function nA(r){if(r==null)return!0;if(Ft(r)&&(he(r)||typeof r=="string"||typeof r.splice=="function"||mt(r)||Wr(r)||Kr(r)))return!r.length;var e=He(r);if(e==ZI||e==eA)return!r.size;if(jt(r))return!Bi(r).length;for(var t in r)if(rA.call(r,t))return!1;return!0}var lu=nA;function sA(r,e){return sn(r,e)}var hu=sA;function iA(r,e){var t={};return e=Kp(e,3),Qp(r,function(n,s,i){qr(t,e(n,s,i),n)}),t}var du=iA;function oA(r,e,t,n){if(!Z(r))return r;e=Zr(e,r);for(var s=-1,i=e.length,a=i-1,u=r;u!=null&&++s<i;){var c=Xe(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:Lt(e[s+1])?[]:{})}zr(u,c,h),u=u[c]}return r}var Xp=oA;function aA(r,e,t){return r==null?r:Xp(r,e,t)}var Ht=aA;var uA="Expected a function";function cA(r,e,t){var n=!0,s=!0;if(typeof r!="function")throw new TypeError(uA);return Z(t)&&(n="leading"in t?!!t.leading:n,s="trailing"in t?!!t.trailing:s),Jp(r,e,{leading:n,maxWait:e,trailing:s})}var fu=cA;var em=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("")},tm={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,E=h&63;c||(E=64,a||(g=64)),n.push(t[f],t[m],t[g],t[E])}return n.join("")},encodeString(r,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(r):this.encodeByteArray(em(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 pu;let g=i<<2|u>>4;if(n.push(g),h!==64){let E=u<<4&240|h>>2;if(n.push(E),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)}}},pu=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},hA=function(r){let e=em(r);return tm.encodeByteArray(e,!0)},ys=function(r){return hA(r).replace(/\./g,"")},rm=function(r){try{return tm.decodeString(r,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function dA(){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 fA=()=>dA().__FIREBASE_DEFAULTS__,pA=()=>{if(typeof process=="undefined"||typeof process.env=="undefined")return;let r=process.env.__FIREBASE_DEFAULTS__;if(r)return JSON.parse(r)},mA=()=>{if(typeof document=="undefined")return;let r;try{r=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}let e=r&&rm(r[1]);return e&&JSON.parse(e)},mu=()=>{try{return fA()||pA()||mA()}catch(r){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${r}`);return}},gA=r=>{var e,t;return(t=(e=mu())===null||e===void 0?void 0:e.emulatorHosts)===null||t===void 0?void 0:t[r]},nm=r=>{let e=gA(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]},gu=()=>{var r;return(r=mu())===null||r===void 0?void 0:r.config};var io=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 sm(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[ys(JSON.stringify(t)),ys(JSON.stringify(a)),""].join(".")}function im(){return typeof navigator!="undefined"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function yA(){var r;let e=(r=mu())===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 om(){return!yA()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function yu(){try{return typeof indexedDB=="object"}catch{return!1}}function am(){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 _A="FirebaseError",_t=class r extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name=_A,Object.setPrototypeOf(this,r.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,_s.prototype.create)}},_s=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?vA(i,n):"Error",u=`${this.serviceName}: ${a} (${s}).`;return new _t(s,u,n)}};function vA(r,e){return r.replace(wA,(t,n)=>{let s=e[n];return s!=null?String(s):`<${n}?>`})}var wA=/\{\$([^}]+)}/g;function vs(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(Zp(i)&&Zp(a)){if(!vs(i,a))return!1}else if(i!==a)return!1}for(let s of n)if(!t.includes(s))return!1;return!0}function Zp(r){return r!==null&&typeof r=="object"}var DM=4*60*60*1e3;function vt(r){return r&&r._delegate?r._delegate:r}var wt=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 dr="[DEFAULT]";var _u=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 io;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(TA(e))try{this.getOrInitializeService({instanceIdentifier:dr})}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=dr){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=dr){return this.instances.has(e)}getOptions(e=dr){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:bA(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=dr){return this.component?this.component.multipleInstances?e:dr:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}};function bA(r){return r===dr?void 0:r}function TA(r){return r.instantiationMode==="EAGER"}var oo=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 _u(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}};var EA=[],W;(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"})(W||(W={}));var IA={debug:W.DEBUG,verbose:W.VERBOSE,info:W.INFO,warn:W.WARN,error:W.ERROR,silent:W.SILENT},AA=W.INFO,xA={[W.DEBUG]:"log",[W.VERBOSE]:"log",[W.INFO]:"info",[W.WARN]:"warn",[W.ERROR]:"error"},SA=(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})`)},on=class{constructor(e){this.name=e,this._logLevel=AA,this._logHandler=SA,this._userLogHandler=null,EA.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in W))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?IA[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,W.DEBUG,...e),this._logHandler(this,W.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,W.VERBOSE,...e),this._logHandler(this,W.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,W.INFO,...e),this._logHandler(this,W.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,W.WARN,...e),this._logHandler(this,W.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,W.ERROR,...e),this._logHandler(this,W.ERROR,...e)}};var RA=(r,e)=>e.some(t=>r instanceof t),um,cm;function PA(){return um||(um=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function CA(){return cm||(cm=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var lm=new WeakMap,wu=new WeakMap,hm=new WeakMap,vu=new WeakMap,Tu=new WeakMap;function kA(r){let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("success",i),r.removeEventListener("error",a)},i=()=>{t(Ze(r.result)),s()},a=()=>{n(r.error),s()};r.addEventListener("success",i),r.addEventListener("error",a)});return e.then(t=>{t instanceof IDBCursor&&lm.set(t,r)}).catch(()=>{}),Tu.set(e,r),e}function DA(r){if(wu.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)});wu.set(r,e)}var bu={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return wu.get(r);if(e==="objectStoreNames")return r.objectStoreNames||hm.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return Ze(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 dm(r){bu=r(bu)}function OA(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let n=r.call(ao(this),e,...t);return hm.set(n,e.sort?e.sort():[e]),Ze(n)}:CA().includes(r)?function(...e){return r.apply(ao(this),e),Ze(lm.get(this))}:function(...e){return Ze(r.apply(ao(this),e))}}function NA(r){return typeof r=="function"?OA(r):(r instanceof IDBTransaction&&DA(r),RA(r,PA())?new Proxy(r,bu):r)}function Ze(r){if(r instanceof IDBRequest)return kA(r);if(vu.has(r))return vu.get(r);let e=NA(r);return e!==r&&(vu.set(r,e),Tu.set(e,r)),e}var ao=r=>Tu.get(r);function pm(r,e,{blocked:t,upgrade:n,blocking:s,terminated:i}={}){let a=indexedDB.open(r,e),u=Ze(a);return n&&a.addEventListener("upgradeneeded",c=>{n(Ze(a.result),c.oldVersion,c.newVersion,Ze(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 VA=["get","getKey","getAll","getAllKeys","count"],LA=["put","add","delete","clear"],Eu=new Map;function fm(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(Eu.get(e))return Eu.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,s=LA.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(s||VA.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 Eu.set(e,i),i}dm(r=>({...r,get:(e,t,n)=>fm(e,t)||r.get(e,t,n),has:(e,t)=>!!fm(e,t)||r.has(e,t)}));var Au=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(t=>{if(MA(t)){let n=t.getImmediate();return`${n.library}/${n.version}`}else return null}).filter(t=>t).join(" ")}};function MA(r){let e=r.getComponent();return(e==null?void 0:e.type)==="VERSION"}var xu="@firebase/app",mm="0.11.1";var bt=new on("@firebase/app"),FA="@firebase/app-compat",jA="@firebase/analytics-compat",UA="@firebase/analytics",BA="@firebase/app-check-compat",$A="@firebase/app-check",qA="@firebase/auth",zA="@firebase/auth-compat",GA="@firebase/database",KA="@firebase/data-connect",HA="@firebase/database-compat",WA="@firebase/functions",QA="@firebase/functions-compat",JA="@firebase/installations",YA="@firebase/installations-compat",XA="@firebase/messaging",ZA="@firebase/messaging-compat",ex="@firebase/performance",tx="@firebase/performance-compat",rx="@firebase/remote-config",nx="@firebase/remote-config-compat",sx="@firebase/storage",ix="@firebase/storage-compat",ox="@firebase/firestore",ax="@firebase/vertexai",ux="@firebase/firestore-compat",cx="firebase",lx="11.3.1";var Su="[DEFAULT]",hx={[xu]:"fire-core",[FA]:"fire-core-compat",[UA]:"fire-analytics",[jA]:"fire-analytics-compat",[$A]:"fire-app-check",[BA]:"fire-app-check-compat",[qA]:"fire-auth",[zA]:"fire-auth-compat",[GA]:"fire-rtdb",[KA]:"fire-data-connect",[HA]:"fire-rtdb-compat",[WA]:"fire-fn",[QA]:"fire-fn-compat",[JA]:"fire-iid",[YA]:"fire-iid-compat",[XA]:"fire-fcm",[ZA]:"fire-fcm-compat",[ex]:"fire-perf",[tx]:"fire-perf-compat",[rx]:"fire-rc",[nx]:"fire-rc-compat",[sx]:"fire-gcs",[ix]:"fire-gcs-compat",[ox]:"fire-fst",[ux]:"fire-fst-compat",[ax]:"fire-vertex","fire-js":"fire-js",[cx]:"fire-js-all"};var uo=new Map,dx=new Map,Ru=new Map;function gm(r,e){try{r.container.addComponent(e)}catch(t){bt.debug(`Component ${e.name} failed to register with FirebaseApp ${r.name}`,t)}}function ws(r){let e=r.name;if(Ru.has(e))return bt.debug(`There were multiple attempts to register component ${e}.`),!1;Ru.set(e,r);for(let t of uo.values())gm(t,r);for(let t of dx.values())gm(t,r);return!0}function wm(r,e){let t=r.container.getProvider("heartbeat").getImmediate({optional:!0});return t&&t.triggerHeartbeat(),r.container.getProvider(e)}function bm(r){return r==null?!1:r.settings!==void 0}var fx={"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."},Wt=new _s("app","Firebase",fx);var Pu=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 wt("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 Wt.create("app-deleted",{appName:this._name})}};var Tm=lx;function Du(r,e={}){let t=r;typeof e!="object"&&(e={name:e});let n=Object.assign({name:Su,automaticDataCollectionEnabled:!1},e),s=n.name;if(typeof s!="string"||!s)throw Wt.create("bad-app-name",{appName:String(s)});if(t||(t=gu()),!t)throw Wt.create("no-options");let i=uo.get(s);if(i){if(vs(t,i.options)&&vs(n,i.config))return i;throw Wt.create("duplicate-app",{appName:s})}let a=new oo(s);for(let c of Ru.values())a.addComponent(c);let u=new Pu(t,n,a);return uo.set(s,u),u}function Em(r=Su){let e=uo.get(r);if(!e&&r===Su&&gu())return Du();if(!e)throw Wt.create("no-app",{appName:r});return e}function Qt(r,e,t){var n;let s=(n=hx[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 "/")`),bt.warn(u.join(" "));return}ws(new wt(`${s}-version`,()=>({library:s,version:e}),"VERSION"))}var px="firebase-heartbeat-database",mx=1,bs="firebase-heartbeat-store",Iu=null;function Im(){return Iu||(Iu=pm(px,mx,{upgrade:(r,e)=>{switch(e){case 0:try{r.createObjectStore(bs)}catch(t){console.warn(t)}}}}).catch(r=>{throw Wt.create("idb-open",{originalErrorMessage:r.message})})),Iu}async function gx(r){try{let t=(await Im()).transaction(bs),n=await t.objectStore(bs).get(Am(r));return await t.done,n}catch(e){if(e instanceof _t)bt.warn(e.message);else{let t=Wt.create("idb-get",{originalErrorMessage:e==null?void 0:e.message});bt.warn(t.message)}}}async function ym(r,e){try{let n=(await Im()).transaction(bs,"readwrite");await n.objectStore(bs).put(e,Am(r)),await n.done}catch(t){if(t instanceof _t)bt.warn(t.message);else{let n=Wt.create("idb-set",{originalErrorMessage:t==null?void 0:t.message});bt.warn(n.message)}}}function Am(r){return`${r.name}!${r.options.appId}`}var yx=1024,_x=30,Cu=class{constructor(e){this.container=e,this._heartbeatsCache=null;let t=this.container.getProvider("app").getImmediate();this._storage=new ku(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=_m();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>_x){let a=wx(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(a,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(n){bt.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=_m(),{heartbeatsToSend:n,unsentEntries:s}=vx(this._heartbeatsCache.heartbeats),i=ys(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 bt.warn(t),""}}};function _m(){return new Date().toISOString().substring(0,10)}function vx(r,e=yx){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),vm(t)>e){i.dates.pop();break}}else if(t.push({agent:s.agent,dates:[s.date]}),vm(t)>e){t.pop();break}n=n.slice(1)}return{heartbeatsToSend:t,unsentEntries:n}}var ku=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return yu()?am().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let t=await gx(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 ym(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 ym(this.app,{lastSentHeartbeatDate:(t=e.lastSentHeartbeatDate)!==null&&t!==void 0?t:s.lastSentHeartbeatDate,heartbeats:[...s.heartbeats,...e.heartbeats]})}else return}};function vm(r){return ys(JSON.stringify({version:2,heartbeats:r})).length}function wx(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 bx(r){ws(new wt("platform-logger",e=>new Au(e),"PRIVATE")),ws(new wt("heartbeat",e=>new Cu(e),"PRIVATE")),Qt(xu,mm,r),Qt(xu,mm,"esm2017"),Qt("fire-js","")}bx("");var Tx="firebase",Ex="11.3.1";Qt(Tx,Ex,"app");var xm=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Sm={};var Tt,Ou;(function(){var r;function e(T,y){function w(){}w.prototype=y.prototype,T.D=y.prototype,T.prototype=new w,T.prototype.constructor=T,T.C=function(b,I,x){for(var _=Array(arguments.length-2),ht=2;ht<arguments.length;ht++)_[ht-2]=arguments[ht];return y.prototype[I].apply(b,_)}}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(T,y,w){w||(w=0);var b=Array(16);if(typeof y=="string")for(var I=0;16>I;++I)b[I]=y.charCodeAt(w++)|y.charCodeAt(w++)<<8|y.charCodeAt(w++)<<16|y.charCodeAt(w++)<<24;else for(I=0;16>I;++I)b[I]=y[w++]|y[w++]<<8|y[w++]<<16|y[w++]<<24;y=T.g[0],w=T.g[1],I=T.g[2];var x=T.g[3],_=y+(x^w&(I^x))+b[0]+3614090360&4294967295;y=w+(_<<7&4294967295|_>>>25),_=x+(I^y&(w^I))+b[1]+3905402710&4294967295,x=y+(_<<12&4294967295|_>>>20),_=I+(w^x&(y^w))+b[2]+606105819&4294967295,I=x+(_<<17&4294967295|_>>>15),_=w+(y^I&(x^y))+b[3]+3250441966&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(x^w&(I^x))+b[4]+4118548399&4294967295,y=w+(_<<7&4294967295|_>>>25),_=x+(I^y&(w^I))+b[5]+1200080426&4294967295,x=y+(_<<12&4294967295|_>>>20),_=I+(w^x&(y^w))+b[6]+2821735955&4294967295,I=x+(_<<17&4294967295|_>>>15),_=w+(y^I&(x^y))+b[7]+4249261313&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(x^w&(I^x))+b[8]+1770035416&4294967295,y=w+(_<<7&4294967295|_>>>25),_=x+(I^y&(w^I))+b[9]+2336552879&4294967295,x=y+(_<<12&4294967295|_>>>20),_=I+(w^x&(y^w))+b[10]+4294925233&4294967295,I=x+(_<<17&4294967295|_>>>15),_=w+(y^I&(x^y))+b[11]+2304563134&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(x^w&(I^x))+b[12]+1804603682&4294967295,y=w+(_<<7&4294967295|_>>>25),_=x+(I^y&(w^I))+b[13]+4254626195&4294967295,x=y+(_<<12&4294967295|_>>>20),_=I+(w^x&(y^w))+b[14]+2792965006&4294967295,I=x+(_<<17&4294967295|_>>>15),_=w+(y^I&(x^y))+b[15]+1236535329&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(I^x&(w^I))+b[1]+4129170786&4294967295,y=w+(_<<5&4294967295|_>>>27),_=x+(w^I&(y^w))+b[6]+3225465664&4294967295,x=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(x^y))+b[11]+643717713&4294967295,I=x+(_<<14&4294967295|_>>>18),_=w+(x^y&(I^x))+b[0]+3921069994&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(I^x&(w^I))+b[5]+3593408605&4294967295,y=w+(_<<5&4294967295|_>>>27),_=x+(w^I&(y^w))+b[10]+38016083&4294967295,x=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(x^y))+b[15]+3634488961&4294967295,I=x+(_<<14&4294967295|_>>>18),_=w+(x^y&(I^x))+b[4]+3889429448&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(I^x&(w^I))+b[9]+568446438&4294967295,y=w+(_<<5&4294967295|_>>>27),_=x+(w^I&(y^w))+b[14]+3275163606&4294967295,x=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(x^y))+b[3]+4107603335&4294967295,I=x+(_<<14&4294967295|_>>>18),_=w+(x^y&(I^x))+b[8]+1163531501&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(I^x&(w^I))+b[13]+2850285829&4294967295,y=w+(_<<5&4294967295|_>>>27),_=x+(w^I&(y^w))+b[2]+4243563512&4294967295,x=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(x^y))+b[7]+1735328473&4294967295,I=x+(_<<14&4294967295|_>>>18),_=w+(x^y&(I^x))+b[12]+2368359562&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(w^I^x)+b[5]+4294588738&4294967295,y=w+(_<<4&4294967295|_>>>28),_=x+(y^w^I)+b[8]+2272392833&4294967295,x=y+(_<<11&4294967295|_>>>21),_=I+(x^y^w)+b[11]+1839030562&4294967295,I=x+(_<<16&4294967295|_>>>16),_=w+(I^x^y)+b[14]+4259657740&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(w^I^x)+b[1]+2763975236&4294967295,y=w+(_<<4&4294967295|_>>>28),_=x+(y^w^I)+b[4]+1272893353&4294967295,x=y+(_<<11&4294967295|_>>>21),_=I+(x^y^w)+b[7]+4139469664&4294967295,I=x+(_<<16&4294967295|_>>>16),_=w+(I^x^y)+b[10]+3200236656&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(w^I^x)+b[13]+681279174&4294967295,y=w+(_<<4&4294967295|_>>>28),_=x+(y^w^I)+b[0]+3936430074&4294967295,x=y+(_<<11&4294967295|_>>>21),_=I+(x^y^w)+b[3]+3572445317&4294967295,I=x+(_<<16&4294967295|_>>>16),_=w+(I^x^y)+b[6]+76029189&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(w^I^x)+b[9]+3654602809&4294967295,y=w+(_<<4&4294967295|_>>>28),_=x+(y^w^I)+b[12]+3873151461&4294967295,x=y+(_<<11&4294967295|_>>>21),_=I+(x^y^w)+b[15]+530742520&4294967295,I=x+(_<<16&4294967295|_>>>16),_=w+(I^x^y)+b[2]+3299628645&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(I^(w|~x))+b[0]+4096336452&4294967295,y=w+(_<<6&4294967295|_>>>26),_=x+(w^(y|~I))+b[7]+1126891415&4294967295,x=y+(_<<10&4294967295|_>>>22),_=I+(y^(x|~w))+b[14]+2878612391&4294967295,I=x+(_<<15&4294967295|_>>>17),_=w+(x^(I|~y))+b[5]+4237533241&4294967295,w=I+(_<<21&4294967295|_>>>11),_=y+(I^(w|~x))+b[12]+1700485571&4294967295,y=w+(_<<6&4294967295|_>>>26),_=x+(w^(y|~I))+b[3]+2399980690&4294967295,x=y+(_<<10&4294967295|_>>>22),_=I+(y^(x|~w))+b[10]+4293915773&4294967295,I=x+(_<<15&4294967295|_>>>17),_=w+(x^(I|~y))+b[1]+2240044497&4294967295,w=I+(_<<21&4294967295|_>>>11),_=y+(I^(w|~x))+b[8]+1873313359&4294967295,y=w+(_<<6&4294967295|_>>>26),_=x+(w^(y|~I))+b[15]+4264355552&4294967295,x=y+(_<<10&4294967295|_>>>22),_=I+(y^(x|~w))+b[6]+2734768916&4294967295,I=x+(_<<15&4294967295|_>>>17),_=w+(x^(I|~y))+b[13]+1309151649&4294967295,w=I+(_<<21&4294967295|_>>>11),_=y+(I^(w|~x))+b[4]+4149444226&4294967295,y=w+(_<<6&4294967295|_>>>26),_=x+(w^(y|~I))+b[11]+3174756917&4294967295,x=y+(_<<10&4294967295|_>>>22),_=I+(y^(x|~w))+b[2]+718787259&4294967295,I=x+(_<<15&4294967295|_>>>17),_=w+(x^(I|~y))+b[9]+3951481745&4294967295,T.g[0]=T.g[0]+y&4294967295,T.g[1]=T.g[1]+(I+(_<<21&4294967295|_>>>11))&4294967295,T.g[2]=T.g[2]+I&4294967295,T.g[3]=T.g[3]+x&4294967295}n.prototype.u=function(T,y){y===void 0&&(y=T.length);for(var w=y-this.blockSize,b=this.B,I=this.h,x=0;x<y;){if(I==0)for(;x<=w;)s(this,T,x),x+=this.blockSize;if(typeof T=="string"){for(;x<y;)if(b[I++]=T.charCodeAt(x++),I==this.blockSize){s(this,b),I=0;break}}else for(;x<y;)if(b[I++]=T[x++],I==this.blockSize){s(this,b),I=0;break}}this.h=I,this.o+=y},n.prototype.v=function(){var T=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);T[0]=128;for(var y=1;y<T.length-8;++y)T[y]=0;var w=8*this.o;for(y=T.length-8;y<T.length;++y)T[y]=w&255,w/=256;for(this.u(T),T=Array(16),y=w=0;4>y;++y)for(var b=0;32>b;b+=8)T[w++]=this.g[y]>>>b&255;return T};function i(T,y){var w=u;return Object.prototype.hasOwnProperty.call(w,T)?w[T]:w[T]=y(T)}function a(T,y){this.h=y;for(var w=[],b=!0,I=T.length-1;0<=I;I--){var x=T[I]|0;b&&x==y||(w[I]=x,b=!1)}this.g=w}var u={};function c(T){return-128<=T&&128>T?i(T,function(y){return new a([y|0],0>y?-1:0)}):new a([T|0],0>T?-1:0)}function h(T){if(isNaN(T)||!isFinite(T))return m;if(0>T)return R(h(-T));for(var y=[],w=1,b=0;T>=w;b++)y[b]=T/w|0,w*=4294967296;return new a(y,0)}function f(T,y){if(T.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(T.charAt(0)=="-")return R(f(T.substring(1),y));if(0<=T.indexOf("-"))throw Error('number format error: interior "-" character');for(var w=h(Math.pow(y,8)),b=m,I=0;I<T.length;I+=8){var x=Math.min(8,T.length-I),_=parseInt(T.substring(I,I+x),y);8>x?(x=h(Math.pow(y,x)),b=b.j(x).add(h(_))):(b=b.j(w),b=b.add(h(_)))}return b}var m=c(0),g=c(1),E=c(16777216);r=a.prototype,r.m=function(){if(C(this))return-R(this).m();for(var T=0,y=1,w=0;w<this.g.length;w++){var b=this.i(w);T+=(0<=b?b:4294967296+b)*y,y*=4294967296}return T},r.toString=function(T){if(T=T||10,2>T||36<T)throw Error("radix out of range: "+T);if(P(this))return"0";if(C(this))return"-"+R(this).toString(T);for(var y=h(Math.pow(T,6)),w=this,b="";;){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(T);if(w=I,P(w))return x+b;for(;6>x.length;)x="0"+x;b=x+b}},r.i=function(T){return 0>T?0:T<this.g.length?this.g[T]:this.h};function P(T){if(T.h!=0)return!1;for(var y=0;y<T.g.length;y++)if(T.g[y]!=0)return!1;return!0}function C(T){return T.h==-1}r.l=function(T){return T=N(this,T),C(T)?-1:P(T)?0:1};function R(T){for(var y=T.g.length,w=[],b=0;b<y;b++)w[b]=~T.g[b];return new a(w,~T.h).add(g)}r.abs=function(){return C(this)?R(this):this},r.add=function(T){for(var y=Math.max(this.g.length,T.g.length),w=[],b=0,I=0;I<=y;I++){var x=b+(this.i(I)&65535)+(T.i(I)&65535),_=(x>>>16)+(this.i(I)>>>16)+(T.i(I)>>>16);b=_>>>16,x&=65535,_&=65535,w[I]=_<<16|x}return new a(w,w[w.length-1]&-2147483648?-1:0)};function N(T,y){return T.add(R(y))}r.j=function(T){if(P(this)||P(T))return m;if(C(this))return C(T)?R(this).j(R(T)):R(R(this).j(T));if(C(T))return R(this.j(R(T)));if(0>this.l(E)&&0>T.l(E))return h(this.m()*T.m());for(var y=this.g.length+T.g.length,w=[],b=0;b<2*y;b++)w[b]=0;for(b=0;b<this.g.length;b++)for(var I=0;I<T.g.length;I++){var x=this.i(b)>>>16,_=this.i(b)&65535,ht=T.i(I)>>>16,Hn=T.i(I)&65535;w[2*b+2*I]+=_*Hn,M(w,2*b+2*I),w[2*b+2*I+1]+=x*Hn,M(w,2*b+2*I+1),w[2*b+2*I+1]+=_*ht,M(w,2*b+2*I+1),w[2*b+2*I+2]+=x*ht,M(w,2*b+2*I+2)}for(b=0;b<y;b++)w[b]=w[2*b+1]<<16|w[2*b];for(b=y;b<2*y;b++)w[b]=0;return new a(w,0)};function M(T,y){for(;(T[y]&65535)!=T[y];)T[y+1]+=T[y]>>>16,T[y]&=65535,y++}function U(T,y){this.g=T,this.h=y}function G(T,y){if(P(y))throw Error("division by zero");if(P(T))return new U(m,m);if(C(T))return y=G(R(T),y),new U(R(y.g),R(y.h));if(C(y))return y=G(T,R(y)),new U(R(y.g),y.h);if(30<T.g.length){if(C(T)||C(y))throw Error("slowDivide_ only works with positive integers.");for(var w=g,b=y;0>=b.l(T);)w=Y(w),b=Y(b);var I=B(w,1),x=B(b,1);for(b=B(b,2),w=B(w,2);!P(b);){var _=x.add(b);0>=_.l(T)&&(I=I.add(w),x=_),b=B(b,1),w=B(w,1)}return y=N(T,I.j(y)),new U(I,y)}for(I=m;0<=T.l(y);){for(w=Math.max(1,Math.floor(T.m()/y.m())),b=Math.ceil(Math.log(w)/Math.LN2),b=48>=b?1:Math.pow(2,b-48),x=h(w),_=x.j(y);C(_)||0<_.l(T);)w-=b,x=h(w),_=x.j(y);P(x)&&(x=g),I=I.add(x),T=N(T,_)}return new U(I,T)}r.A=function(T){return G(this,T).h},r.and=function(T){for(var y=Math.max(this.g.length,T.g.length),w=[],b=0;b<y;b++)w[b]=this.i(b)&T.i(b);return new a(w,this.h&T.h)},r.or=function(T){for(var y=Math.max(this.g.length,T.g.length),w=[],b=0;b<y;b++)w[b]=this.i(b)|T.i(b);return new a(w,this.h|T.h)},r.xor=function(T){for(var y=Math.max(this.g.length,T.g.length),w=[],b=0;b<y;b++)w[b]=this.i(b)^T.i(b);return new a(w,this.h^T.h)};function Y(T){for(var y=T.g.length+1,w=[],b=0;b<y;b++)w[b]=T.i(b)<<1|T.i(b-1)>>>31;return new a(w,T.h)}function B(T,y){var w=y>>5;y%=32;for(var b=T.g.length-w,I=[],x=0;x<b;x++)I[x]=0<y?T.i(x+w)>>>y|T.i(x+w+1)<<32-y:T.i(x+w);return new a(I,T.h)}n.prototype.digest=n.prototype.v,n.prototype.reset=n.prototype.s,n.prototype.update=n.prototype.u,Ou=Sm.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,Tt=Sm.Integer=a}).apply(typeof xm!="undefined"?xm:typeof self!="undefined"?self:typeof window!="undefined"?window:{});var co=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Et={};var Nu,Ix,an,Vu,Ts,lo,Lu,Mu,Fu;(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 co=="object"&&co];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 E(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 M(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 T(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 b(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=Oa;let l=null;return o.g&&(l=o.g,o.g=o.g.next,o.g||(o.h=null),l.next=null),l}class ht{constructor(){this.h=this.g=null}add(l,d){let p=Hn.get();p.set(l,d),this.h?this.h.next=p:this.g=p,this.h=p}}var Hn=new N(()=>new tv,o=>o.reset());class tv{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 Wn,Qn=!1,Oa=new ht,Eh=()=>{let o=u.Promise.resolve(void 0);Wn=()=>{o.then(rv)}};var rv=()=>{for(var o;o=_();){try{o.h.call(o.g)}catch(d){x(d)}var l=Hn;l.j(o),100>l.h&&(l.h++,o.next=l.g,l.g=o)}Qn=!1};function kt(){this.s=this.s,this.C=this.C}kt.prototype.s=!1,kt.prototype.ma=function(){this.s||(this.s=!0,this.N())},kt.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function Ee(o,l){this.type=o,this.g=this.target=l,this.defaultPrevented=!1}Ee.prototype.h=function(){this.defaultPrevented=!0};var nv=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 Jn(o,l){if(Ee.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:sv[o.pointerType]||"",this.state=o.state,this.i=o,o.defaultPrevented&&Jn.aa.h.call(this)}}P(Jn,Ee);var sv={2:"touch",3:"pen",4:"mouse"};Jn.prototype.h=function(){Jn.aa.h.call(this);var o=this.i;o.preventDefault?o.preventDefault():o.returnValue=!1};var Yn="closure_listenable_"+(1e6*Math.random()|0),iv=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=++iv,this.da=this.fa=!1}function _i(o){o.da=!0,o.listener=null,o.proxy=null,o.src=null,o.ha=null}function vi(o){this.src=o,this.g={},this.h=0}vi.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=Va(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 Na(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&&(_i(l),o.g[d].length==0&&(delete o.g[d],o.h--))}}function Va(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 La="closure_lm_"+(1e6*Math.random()|0),Ma={};function Ih(o,l,d,p,A){if(p&&p.once)return xh(o,l,d,p,A);if(Array.isArray(l)){for(var S=0;S<l.length;S++)Ih(o,l[S],d,p,A);return null}return d=Ba(d),o&&o[Yn]?o.K(l,d,h(p)?!!p.capture:!!p,A):Ah(o,l,d,!1,p,A)}function Ah(o,l,d,p,A,S){if(!l)throw Error("Invalid event type");var O=h(A)?!!A.capture:!!A,te=ja(o);if(te||(o[La]=te=new vi(o)),d=te.add(l,d,p,O,S),d.proxy)return d;if(p=av(),d.proxy=p,p.src=o,p.listener=d,o.addEventListener)nv||(A=O),A===void 0&&(A=!1),o.addEventListener(l.toString(),p,A);else if(o.attachEvent)o.attachEvent(Rh(l.toString()),p);else if(o.addListener&&o.removeListener)o.addListener(p);else throw Error("addEventListener and attachEvent are unavailable.");return d}function av(){function o(d){return l.call(o.src,o.listener,d)}let l=uv;return o}function xh(o,l,d,p,A){if(Array.isArray(l)){for(var S=0;S<l.length;S++)xh(o,l[S],d,p,A);return null}return d=Ba(d),o&&o[Yn]?o.L(l,d,h(p)?!!p.capture:!!p,A):Ah(o,l,d,!0,p,A)}function Sh(o,l,d,p,A){if(Array.isArray(l))for(var S=0;S<l.length;S++)Sh(o,l[S],d,p,A);else p=h(p)?!!p.capture:!!p,d=Ba(d),o&&o[Yn]?(o=o.i,l=String(l).toString(),l in o.g&&(S=o.g[l],d=Va(S,d,p,A),-1<d&&(_i(S[d]),Array.prototype.splice.call(S,d,1),S.length==0&&(delete o.g[l],o.h--)))):o&&(o=ja(o))&&(l=o.g[l.toString()],o=-1,l&&(o=Va(l,d,p,A)),(d=-1<o?l[o]:null)&&Fa(d))}function Fa(o){if(typeof o!="number"&&o&&!o.da){var l=o.src;if(l&&l[Yn])Na(l.i,o);else{var d=o.type,p=o.proxy;l.removeEventListener?l.removeEventListener(d,p,o.capture):l.detachEvent?l.detachEvent(Rh(d),p):l.addListener&&l.removeListener&&l.removeListener(p),(d=ja(l))?(Na(d,o),d.h==0&&(d.src=null,l[La]=null)):_i(o)}}}function Rh(o){return o in Ma?Ma[o]:Ma[o]="on"+o}function uv(o,l){if(o.da)o=!0;else{l=new Jn(l,this);var d=o.listener,p=o.ha||o.src;o.fa&&Fa(o),o=d.call(p,l)}return o}function ja(o){return o=o[La],o instanceof vi?o:null}var Ua="__closure_events_fn_"+(1e9*Math.random()>>>0);function Ba(o){return typeof o=="function"?o:(o[Ua]||(o[Ua]=function(l){return o.handleEvent(l)}),o[Ua])}function Ie(){kt.call(this),this.i=new vi(this),this.M=this,this.F=null}P(Ie,kt),Ie.prototype[Yn]=!0,Ie.prototype.removeEventListener=function(o,l,d,p){Sh(this,o,l,d,p)};function Ce(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 Ee(l,o);else if(l instanceof Ee)l.target=l.target||o;else{var A=l;l=new Ee(p,o),b(l,A)}if(A=!0,d)for(var S=d.length-1;0<=S;S--){var O=l.g=d[S];A=wi(O,p,!0,l)&&A}if(O=l.g=o,A=wi(O,p,!0,l)&&A,A=wi(O,p,!1,l)&&A,d)for(S=0;S<d.length;S++)O=l.g=d[S],A=wi(O,p,!1,l)&&A}Ie.prototype.N=function(){if(Ie.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++)_i(d[p]);delete o.g[l],o.h--}}this.F=null},Ie.prototype.K=function(o,l,d,p){return this.i.add(String(o),l,!1,d,p)},Ie.prototype.L=function(o,l,d,p){return this.i.add(String(o),l,!0,d,p)};function wi(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,we=O.ha||O.src;O.fa&&Na(o.i,O),A=te.call(we,p)!==!1&&A}}return A&&!p.defaultPrevented}function Ph(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 Ch(o){o.g=Ph(()=>{o.g=null,o.i&&(o.i=!1,Ch(o))},o.l);let l=o.h;o.h=null,o.m.apply(null,l)}class cv extends kt{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:Ch(this)}N(){super.N(),this.g&&(u.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Xn(o){kt.call(this),this.h=o,this.g={}}P(Xn,kt);var kh=[];function Dh(o){B(o.g,function(l,d){this.g.hasOwnProperty(d)&&Fa(l)},o),o.g={}}Xn.prototype.N=function(){Xn.aa.N.call(this),Dh(this)},Xn.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var $a=u.JSON.stringify,lv=u.JSON.parse,hv=class{stringify(o){return u.JSON.stringify(o,void 0)}parse(o){return u.JSON.parse(o,void 0)}};function qa(){}qa.prototype.h=null;function Oh(o){return o.h||(o.h=o.i())}function Nh(){}var Zn={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function za(){Ee.call(this,"d")}P(za,Ee);function Ga(){Ee.call(this,"c")}P(Ga,Ee);var or={},Vh=null;function bi(){return Vh=Vh||new Ie}or.La="serverreachability";function Lh(o){Ee.call(this,or.La,o)}P(Lh,Ee);function es(o){let l=bi();Ce(l,new Lh(l))}or.STAT_EVENT="statevent";function Mh(o,l){Ee.call(this,or.STAT_EVENT,o),this.stat=l}P(Mh,Ee);function ke(o){let l=bi();Ce(l,new Mh(l,o))}or.Ma="timingevent";function Fh(o,l){Ee.call(this,or.Ma,o),this.size=l}P(Fh,Ee);function ts(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 rs(){this.g=!0}rs.prototype.xa=function(){this.g=!1};function dv(o,l,d,p,A,S){o.info(function(){if(o.g)if(S)for(var O="",te=S.split("&"),we=0;we<te.length;we++){var X=te[we].split("=");if(1<X.length){var Ae=X[0];X=X[1];var xe=Ae.split("_");O=2<=xe.length&&xe[1]=="type"?O+(Ae+"="+X+"&"):O+(Ae+"=redacted&")}}else O=null;else O=S;return"XMLHTTP REQ ("+p+") [attempt "+A+"]: "+l+`
|
|
1
|
+
var Hv=Object.create;var ps=Object.defineProperty;var Wv=Object.getOwnPropertyDescriptor;var Qv=Object.getOwnPropertyNames;var Jv=Object.getPrototypeOf,Yv=Object.prototype.hasOwnProperty;var Xv=(r,e,t)=>e in r?ps(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Zv=(r,e)=>()=>(r&&(e=r(r=0)),e);var je=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ew=(r,e)=>{for(var t in e)ps(r,t,{get:e[t],enumerable:!0})},Cd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Qv(e))!Yv.call(r,s)&&s!==t&&ps(r,s,{get:()=>e[s],enumerable:!(n=Wv(e,s))||n.enumerable});return r};var ou=(r,e,t)=>(t=r!=null?Hv(Jv(r)):{},Cd(e||!r||!r.__esModule?ps(t,"default",{value:r,enumerable:!0}):t,r)),tw=r=>Cd(ps({},"__esModule",{value:!0}),r);var de=(r,e,t)=>Xv(r,typeof e!="symbol"?e+"":e,t);var Ir={};ew(Ir,{Headers:()=>Xl,Request:()=>$R,Response:()=>qR,default:()=>Yl,fetch:()=>BR});var UR,Mn,BR,Yl,Xl,$R,qR,nr=Zv(()=>{"use strict";UR=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")},Mn=UR(),BR=Mn.fetch,Yl=Mn.fetch.bind(Mn),Xl=Mn.Headers,$R=Mn.Request,qR=Mn.Response});var th=je(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});var Zl=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};eh.default=Zl});var nh=je(Qs=>{"use strict";var Hy=Qs&&Qs.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Qs,"__esModule",{value:!0});var GR=Hy((nr(),tw(Ir))),KR=Hy(th()),rh=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=GR.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,E=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,E="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,E="OK")}catch{i.status===404&&C===""?(g=204,E="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,E="OK"),h&&this.shouldThrowOnError)throw new KR.default(h)}return{error:h,data:f,count:m,status:g,statusText:E}});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)}};Qs.default=rh});var ih=je(Js=>{"use strict";var HR=Js&&Js.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Js,"__esModule",{value:!0});var WR=HR(nh()),sh=class extends WR.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}};Js.default=sh});var _a=je(Ys=>{"use strict";var QR=Ys&&Ys.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ys,"__esModule",{value:!0});var JR=QR(ih()),oh=class extends JR.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}};Ys.default=oh});var uh=je(Zs=>{"use strict";var YR=Zs&&Zs.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Zs,"__esModule",{value:!0});var Xs=YR(_a()),ah=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 Xs.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 Xs.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 Xs.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 Xs.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 Xs.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Zs.default=ah});var Wy=je(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.version=void 0;va.version="0.0.0-automated"});var Qy=je(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.DEFAULT_HEADERS=void 0;var XR=Wy();wa.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${XR.version}`}});var Yy=je(ei=>{"use strict";var Jy=ei&&ei.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ei,"__esModule",{value:!0});var ZR=Jy(uh()),eP=Jy(_a()),tP=Qy(),ch=class r{constructor(e,{headers:t={},schema:n,fetch:s}={}){this.url=e,this.headers=Object.assign(Object.assign({},tP.DEFAULT_HEADERS),t),this.schemaName=n,this.fetch=s}from(e){let t=new URL(`${this.url}/${e}`);return new ZR.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 eP.default({method:a,url:u,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};ei.default=ch});var s_=je(Te=>{"use strict";var Fn=Te&&Te.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Te,"__esModule",{value:!0});Te.PostgrestError=Te.PostgrestBuilder=Te.PostgrestTransformBuilder=Te.PostgrestFilterBuilder=Te.PostgrestQueryBuilder=Te.PostgrestClient=void 0;var Xy=Fn(Yy());Te.PostgrestClient=Xy.default;var Zy=Fn(uh());Te.PostgrestQueryBuilder=Zy.default;var e_=Fn(_a());Te.PostgrestFilterBuilder=e_.default;var t_=Fn(ih());Te.PostgrestTransformBuilder=t_.default;var r_=Fn(nh());Te.PostgrestBuilder=r_.default;var n_=Fn(th());Te.PostgrestError=n_.default;Te.default={PostgrestClient:Xy.default,PostgrestQueryBuilder:Zy.default,PostgrestFilterBuilder:e_.default,PostgrestTransformBuilder:t_.default,PostgrestBuilder:r_.default,PostgrestError:n_.default}});var f_=je((g2,d_)=>{"use strict";d_.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var ov=je((PU,iv)=>{function Ke(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))}iv.exports=Ke;Ke.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Ke.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Ke.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};Ke.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)};Ke.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Ke.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Ke.prototype.start=Ke.prototype.try;Ke.prototype.errors=function(){return this._errors};Ke.prototype.attempts=function(){return this._attempts};Ke.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 av=je(Fr=>{var jP=ov();Fr.operation=function(r){var e=Fr.timeouts(r);return new jP(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Fr.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};Fr.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};Fr.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=Fr.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 cv=je((kU,uv)=>{uv.exports=av()});var rw=typeof global=="object"&&global&&global.Object===Object&&global,Mi=rw;var nw=typeof self=="object"&&self&&self.Object===Object&&self,sw=Mi||nw||Function("return this")(),ce=sw;var iw=ce.Symbol,De=iw;var kd=Object.prototype,ow=kd.hasOwnProperty,aw=kd.toString,ms=De?De.toStringTag:void 0;function uw(r){var e=ow.call(r,ms),t=r[ms];try{r[ms]=void 0;var n=!0}catch{}var s=aw.call(r);return n&&(e?r[ms]=t:delete r[ms]),s}var Dd=uw;var cw=Object.prototype,lw=cw.toString;function hw(r){return lw.call(r)}var Od=hw;var dw="[object Null]",fw="[object Undefined]",Nd=De?De.toStringTag:void 0;function pw(r){return r==null?r===void 0?fw:dw:Nd&&Nd in Object(r)?Dd(r):Od(r)}var We=pw;function mw(r){return r!=null&&typeof r=="object"}var Oe=mw;var gw="[object Symbol]";function yw(r){return typeof r=="symbol"||Oe(r)&&We(r)==gw}var Lt=yw;function _w(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 Vd=_w;var vw=Array.isArray,he=vw;var ww=1/0,Ld=De?De.prototype:void 0,Md=Ld?Ld.toString:void 0;function Fd(r){if(typeof r=="string")return r;if(he(r))return Vd(r,Fd)+"";if(Lt(r))return Md?Md.call(r):"";var e=r+"";return e=="0"&&1/r==-ww?"-0":e}var jd=Fd;var bw=/\s/;function Tw(r){for(var e=r.length;e--&&bw.test(r.charAt(e)););return e}var Ud=Tw;var Ew=/^\s+/;function Iw(r){return r&&r.slice(0,Ud(r)+1).replace(Ew,"")}var Bd=Iw;function xw(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Z=xw;var $d=NaN,Aw=/^[-+]0x[0-9a-f]+$/i,Sw=/^0b[01]+$/i,Rw=/^0o[0-7]+$/i,Pw=parseInt;function Cw(r){if(typeof r=="number")return r;if(Lt(r))return $d;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=Bd(r);var t=Sw.test(r);return t||Rw.test(r)?Pw(r.slice(2),t?2:8):Aw.test(r)?$d:+r}var au=Cw;function kw(r){return r}var qr=kw;var Dw="[object AsyncFunction]",Ow="[object Function]",Nw="[object GeneratorFunction]",Vw="[object Proxy]";function Lw(r){if(!Z(r))return!1;var e=We(r);return e==Ow||e==Nw||e==Dw||e==Vw}var Fi=Lw;var Mw=ce["__core-js_shared__"],ji=Mw;var qd=function(){var r=/[^.]+$/.exec(ji&&ji.keys&&ji.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function Fw(r){return!!qd&&qd in r}var zd=Fw;var jw=Function.prototype,Uw=jw.toString;function Bw(r){if(r!=null){try{return Uw.call(r)}catch{}try{return r+""}catch{}}return""}var mt=Bw;var $w=/[\\^$.*+?()[\]{}|]/g,qw=/^\[object .+?Constructor\]$/,zw=Function.prototype,Gw=Object.prototype,Kw=zw.toString,Hw=Gw.hasOwnProperty,Ww=RegExp("^"+Kw.call(Hw).replace($w,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Qw(r){if(!Z(r)||zd(r))return!1;var e=Fi(r)?Ww:qw;return e.test(mt(r))}var Gd=Qw;function Jw(r,e){return r==null?void 0:r[e]}var Kd=Jw;function Yw(r,e){var t=Kd(r,e);return Gd(t)?t:void 0}var Ne=Yw;var Xw=Ne(ce,"WeakMap"),Ui=Xw;var Hd=Object.create,Zw=function(){function r(){}return function(e){if(!Z(e))return{};if(Hd)return Hd(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}}(),Wd=Zw;function eb(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 Qd=eb;function tb(r,e){var t=-1,n=r.length;for(e||(e=Array(n));++t<n;)e[t]=r[t];return e}var Jd=tb;var rb=800,nb=16,sb=Date.now;function ib(r){var e=0,t=0;return function(){var n=sb(),s=nb-(n-t);if(t=n,s>0){if(++e>=rb)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}var Yd=ib;function ob(r){return function(){return r}}var Xd=ob;var ab=function(){try{var r=Ne(Object,"defineProperty");return r({},"",{}),r}catch{}}(),zr=ab;var ub=zr?function(r,e){return zr(r,"toString",{configurable:!0,enumerable:!1,value:Xd(e),writable:!0})}:qr,Zd=ub;var cb=Yd(Zd),ef=cb;function lb(r,e){for(var t=-1,n=r==null?0:r.length;++t<n&&e(r[t],t,r)!==!1;);return r}var tf=lb;var hb=9007199254740991,db=/^(?:0|[1-9]\d*)$/;function fb(r,e){var t=typeof r;return e=e==null?hb:e,!!e&&(t=="number"||t!="symbol"&&db.test(r))&&r>-1&&r%1==0&&r<e}var Mt=fb;function pb(r,e,t){e=="__proto__"&&zr?zr(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}var Gr=pb;function mb(r,e){return r===e||r!==r&&e!==e}var Xe=mb;var gb=Object.prototype,yb=gb.hasOwnProperty;function _b(r,e,t){var n=r[e];(!(yb.call(r,e)&&Xe(n,t))||t===void 0&&!(e in r))&&Gr(r,e,t)}var Kr=_b;function vb(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?Gr(t,u,c):Kr(t,u,c)}return t}var Ft=vb;var rf=Math.max;function wb(r,e,t){return e=rf(e===void 0?r.length-1:e,0),function(){for(var n=arguments,s=-1,i=rf(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),Qd(r,this,u)}}var nf=wb;function bb(r,e){return ef(nf(r,e,qr),r+"")}var sf=bb;var Tb=9007199254740991;function Eb(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Tb}var Hr=Eb;function Ib(r){return r!=null&&Hr(r.length)&&!Fi(r)}var jt=Ib;function xb(r,e,t){if(!Z(t))return!1;var n=typeof e;return(n=="number"?jt(t)&&Mt(e,t.length):n=="string"&&e in t)?Xe(t[e],r):!1}var of=xb;var Ab=Object.prototype;function Sb(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Ab;return r===t}var Ut=Sb;function Rb(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}var af=Rb;var Pb="[object Arguments]";function Cb(r){return Oe(r)&&We(r)==Pb}var uu=Cb;var uf=Object.prototype,kb=uf.hasOwnProperty,Db=uf.propertyIsEnumerable,Ob=uu(function(){return arguments}())?uu:function(r){return Oe(r)&&kb.call(r,"callee")&&!Db.call(r,"callee")},Wr=Ob;function Nb(){return!1}var cf=Nb;var df=typeof exports=="object"&&exports&&!exports.nodeType&&exports,lf=df&&typeof module=="object"&&module&&!module.nodeType&&module,Vb=lf&&lf.exports===df,hf=Vb?ce.Buffer:void 0,Lb=hf?hf.isBuffer:void 0,Mb=Lb||cf,gt=Mb;var Fb="[object Arguments]",jb="[object Array]",Ub="[object Boolean]",Bb="[object Date]",$b="[object Error]",qb="[object Function]",zb="[object Map]",Gb="[object Number]",Kb="[object Object]",Hb="[object RegExp]",Wb="[object Set]",Qb="[object String]",Jb="[object WeakMap]",Yb="[object ArrayBuffer]",Xb="[object DataView]",Zb="[object Float32Array]",eT="[object Float64Array]",tT="[object Int8Array]",rT="[object Int16Array]",nT="[object Int32Array]",sT="[object Uint8Array]",iT="[object Uint8ClampedArray]",oT="[object Uint16Array]",aT="[object Uint32Array]",oe={};oe[Zb]=oe[eT]=oe[tT]=oe[rT]=oe[nT]=oe[sT]=oe[iT]=oe[oT]=oe[aT]=!0;oe[Fb]=oe[jb]=oe[Yb]=oe[Ub]=oe[Xb]=oe[Bb]=oe[$b]=oe[qb]=oe[zb]=oe[Gb]=oe[Kb]=oe[Hb]=oe[Wb]=oe[Qb]=oe[Jb]=!1;function uT(r){return Oe(r)&&Hr(r.length)&&!!oe[We(r)]}var ff=uT;function cT(r){return function(e){return r(e)}}var Qr=cT;var pf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,gs=pf&&typeof module=="object"&&module&&!module.nodeType&&module,lT=gs&&gs.exports===pf,cu=lT&&Mi.process,hT=function(){try{var r=gs&&gs.require&&gs.require("util").types;return r||cu&&cu.binding&&cu.binding("util")}catch{}}(),yt=hT;var mf=yt&&yt.isTypedArray,dT=mf?Qr(mf):ff,Jr=dT;var fT=Object.prototype,pT=fT.hasOwnProperty;function mT(r,e){var t=he(r),n=!t&&Wr(r),s=!t&&!n&>(r),i=!t&&!n&&!s&&Jr(r),a=t||n||s||i,u=a?af(r.length,String):[],c=u.length;for(var h in r)(e||pT.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 Bi=mT;function gT(r,e){return function(t){return r(e(t))}}var $i=gT;var yT=$i(Object.keys,Object),gf=yT;var _T=Object.prototype,vT=_T.hasOwnProperty;function wT(r){if(!Ut(r))return gf(r);var e=[];for(var t in Object(r))vT.call(r,t)&&t!="constructor"&&e.push(t);return e}var qi=wT;function bT(r){return jt(r)?Bi(r):qi(r)}var Se=bT;function TT(r){var e=[];if(r!=null)for(var t in Object(r))e.push(t);return e}var yf=TT;var ET=Object.prototype,IT=ET.hasOwnProperty;function xT(r){if(!Z(r))return yf(r);var e=Ut(r),t=[];for(var n in r)n=="constructor"&&(e||!IT.call(r,n))||t.push(n);return t}var _f=xT;function AT(r){return jt(r)?Bi(r,!0):_f(r)}var Bt=AT;var ST=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,RT=/^\w*$/;function PT(r,e){if(he(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Lt(r)?!0:RT.test(r)||!ST.test(r)||e!=null&&r in Object(e)}var Yr=PT;var CT=Ne(Object,"create"),_t=CT;function kT(){this.__data__=_t?_t(null):{},this.size=0}var vf=kT;function DT(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var wf=DT;var OT="__lodash_hash_undefined__",NT=Object.prototype,VT=NT.hasOwnProperty;function LT(r){var e=this.__data__;if(_t){var t=e[r];return t===OT?void 0:t}return VT.call(e,r)?e[r]:void 0}var bf=LT;var MT=Object.prototype,FT=MT.hasOwnProperty;function jT(r){var e=this.__data__;return _t?e[r]!==void 0:FT.call(e,r)}var Tf=jT;var UT="__lodash_hash_undefined__";function BT(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=_t&&e===void 0?UT:e,this}var Ef=BT;function Xr(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])}}Xr.prototype.clear=vf;Xr.prototype.delete=wf;Xr.prototype.get=bf;Xr.prototype.has=Tf;Xr.prototype.set=Ef;var lu=Xr;function $T(){this.__data__=[],this.size=0}var If=$T;function qT(r,e){for(var t=r.length;t--;)if(Xe(r[t][0],e))return t;return-1}var $t=qT;var zT=Array.prototype,GT=zT.splice;function KT(r){var e=this.__data__,t=$t(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():GT.call(e,t,1),--this.size,!0}var xf=KT;function HT(r){var e=this.__data__,t=$t(e,r);return t<0?void 0:e[t][1]}var Af=HT;function WT(r){return $t(this.__data__,r)>-1}var Sf=WT;function QT(r,e){var t=this.__data__,n=$t(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}var Rf=QT;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=xf;Zr.prototype.get=Af;Zr.prototype.has=Sf;Zr.prototype.set=Rf;var qt=Zr;var JT=Ne(ce,"Map"),zt=JT;function YT(){this.size=0,this.__data__={hash:new lu,map:new(zt||qt),string:new lu}}var Pf=YT;function XT(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var Cf=XT;function ZT(r,e){var t=r.__data__;return Cf(e)?t[typeof e=="string"?"string":"hash"]:t.map}var Gt=ZT;function eE(r){var e=Gt(this,r).delete(r);return this.size-=e?1:0,e}var kf=eE;function tE(r){return Gt(this,r).get(r)}var Df=tE;function rE(r){return Gt(this,r).has(r)}var Of=rE;function nE(r,e){var t=Gt(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}var Nf=nE;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=kf;en.prototype.get=Df;en.prototype.has=Of;en.prototype.set=Nf;var hr=en;var sE="Expected a function";function hu(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(sE);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(hu.Cache||hr),t}hu.Cache=hr;var Vf=hu;var iE=500;function oE(r){var e=Vf(r,function(n){return t.size===iE&&t.clear(),n}),t=e.cache;return e}var Lf=oE;var aE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,uE=/\\(\\)?/g,cE=Lf(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(aE,function(t,n,s,i){e.push(s?i.replace(uE,"$1"):n||t)}),e}),Mf=cE;function lE(r){return r==null?"":jd(r)}var Ff=lE;function hE(r,e){return he(r)?r:Yr(r,e)?[r]:Mf(Ff(r))}var tn=hE;var dE=1/0;function fE(r){if(typeof r=="string"||Lt(r))return r;var e=r+"";return e=="0"&&1/r==-dE?"-0":e}var Ze=fE;function pE(r,e){e=tn(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 zi=pE;function mE(r,e,t){var n=r==null?void 0:zi(r,e);return n===void 0?t:n}var ys=mE;function gE(r,e){for(var t=-1,n=e.length,s=r.length;++t<n;)r[s+t]=e[t];return r}var Gi=gE;var yE=$i(Object.getPrototypeOf,Object),Ki=yE;function _E(){this.__data__=new qt,this.size=0}var jf=_E;function vE(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}var Uf=vE;function wE(r){return this.__data__.get(r)}var Bf=wE;function bE(r){return this.__data__.has(r)}var $f=bE;var TE=200;function EE(r,e){var t=this.__data__;if(t instanceof qt){var n=t.__data__;if(!zt||n.length<TE-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 qf=EE;function rn(r){var e=this.__data__=new qt(r);this.size=e.size}rn.prototype.clear=jf;rn.prototype.delete=Uf;rn.prototype.get=Bf;rn.prototype.has=$f;rn.prototype.set=qf;var Kt=rn;function IE(r,e){return r&&Ft(e,Se(e),r)}var zf=IE;function xE(r,e){return r&&Ft(e,Bt(e),r)}var Gf=xE;var Qf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Kf=Qf&&typeof module=="object"&&module&&!module.nodeType&&module,AE=Kf&&Kf.exports===Qf,Hf=AE?ce.Buffer:void 0,Wf=Hf?Hf.allocUnsafe:void 0;function SE(r,e){if(e)return r.slice();var t=r.length,n=Wf?Wf(t):new r.constructor(t);return r.copy(n),n}var Jf=SE;function RE(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 Yf=RE;function PE(){return[]}var Hi=PE;var CE=Object.prototype,kE=CE.propertyIsEnumerable,Xf=Object.getOwnPropertySymbols,DE=Xf?function(r){return r==null?[]:(r=Object(r),Yf(Xf(r),function(e){return kE.call(r,e)}))}:Hi,nn=DE;function OE(r,e){return Ft(r,nn(r),e)}var Zf=OE;var NE=Object.getOwnPropertySymbols,VE=NE?function(r){for(var e=[];r;)Gi(e,nn(r)),r=Ki(r);return e}:Hi,Wi=VE;function LE(r,e){return Ft(r,Wi(r),e)}var ep=LE;function ME(r,e,t){var n=e(r);return he(r)?n:Gi(n,t(r))}var Qi=ME;function FE(r){return Qi(r,Se,nn)}var _s=FE;function jE(r){return Qi(r,Bt,Wi)}var tp=jE;var UE=Ne(ce,"DataView"),Ji=UE;var BE=Ne(ce,"Promise"),Yi=BE;var $E=Ne(ce,"Set"),Xi=$E;var rp="[object Map]",qE="[object Object]",np="[object Promise]",sp="[object Set]",ip="[object WeakMap]",op="[object DataView]",zE=mt(Ji),GE=mt(zt),KE=mt(Yi),HE=mt(Xi),WE=mt(Ui),dr=We;(Ji&&dr(new Ji(new ArrayBuffer(1)))!=op||zt&&dr(new zt)!=rp||Yi&&dr(Yi.resolve())!=np||Xi&&dr(new Xi)!=sp||Ui&&dr(new Ui)!=ip)&&(dr=function(r){var e=We(r),t=e==qE?r.constructor:void 0,n=t?mt(t):"";if(n)switch(n){case zE:return op;case GE:return rp;case KE:return np;case HE:return sp;case WE:return ip}return e});var Qe=dr;var QE=Object.prototype,JE=QE.hasOwnProperty;function YE(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&JE.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var ap=YE;var XE=ce.Uint8Array,sn=XE;function ZE(r){var e=new r.constructor(r.byteLength);return new sn(e).set(new sn(r)),e}var on=ZE;function e0(r,e){var t=e?on(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.byteLength)}var up=e0;var t0=/\w*$/;function r0(r){var e=new r.constructor(r.source,t0.exec(r));return e.lastIndex=r.lastIndex,e}var cp=r0;var lp=De?De.prototype:void 0,hp=lp?lp.valueOf:void 0;function n0(r){return hp?Object(hp.call(r)):{}}var dp=n0;function s0(r,e){var t=e?on(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.length)}var fp=s0;var i0="[object Boolean]",o0="[object Date]",a0="[object Map]",u0="[object Number]",c0="[object RegExp]",l0="[object Set]",h0="[object String]",d0="[object Symbol]",f0="[object ArrayBuffer]",p0="[object DataView]",m0="[object Float32Array]",g0="[object Float64Array]",y0="[object Int8Array]",_0="[object Int16Array]",v0="[object Int32Array]",w0="[object Uint8Array]",b0="[object Uint8ClampedArray]",T0="[object Uint16Array]",E0="[object Uint32Array]";function I0(r,e,t){var n=r.constructor;switch(e){case f0:return on(r);case i0:case o0:return new n(+r);case p0:return up(r,t);case m0:case g0:case y0:case _0:case v0:case w0:case b0:case T0:case E0:return fp(r,t);case a0:return new n;case u0:case h0:return new n(r);case c0:return cp(r);case l0:return new n;case d0:return dp(r)}}var pp=I0;function x0(r){return typeof r.constructor=="function"&&!Ut(r)?Wd(Ki(r)):{}}var mp=x0;var A0="[object Map]";function S0(r){return Oe(r)&&Qe(r)==A0}var gp=S0;var yp=yt&&yt.isMap,R0=yp?Qr(yp):gp,_p=R0;var P0="[object Set]";function C0(r){return Oe(r)&&Qe(r)==P0}var vp=C0;var wp=yt&&yt.isSet,k0=wp?Qr(wp):vp,bp=k0;var D0=1,O0=2,N0=4,Tp="[object Arguments]",V0="[object Array]",L0="[object Boolean]",M0="[object Date]",F0="[object Error]",Ep="[object Function]",j0="[object GeneratorFunction]",U0="[object Map]",B0="[object Number]",Ip="[object Object]",$0="[object RegExp]",q0="[object Set]",z0="[object String]",G0="[object Symbol]",K0="[object WeakMap]",H0="[object ArrayBuffer]",W0="[object DataView]",Q0="[object Float32Array]",J0="[object Float64Array]",Y0="[object Int8Array]",X0="[object Int16Array]",Z0="[object Int32Array]",eI="[object Uint8Array]",tI="[object Uint8ClampedArray]",rI="[object Uint16Array]",nI="[object Uint32Array]",ne={};ne[Tp]=ne[V0]=ne[H0]=ne[W0]=ne[L0]=ne[M0]=ne[Q0]=ne[J0]=ne[Y0]=ne[X0]=ne[Z0]=ne[U0]=ne[B0]=ne[Ip]=ne[$0]=ne[q0]=ne[z0]=ne[G0]=ne[eI]=ne[tI]=ne[rI]=ne[nI]=!0;ne[F0]=ne[Ep]=ne[K0]=!1;function Zi(r,e,t,n,s,i){var a,u=e&D0,c=e&O0,h=e&N0;if(t&&(a=s?t(r,n,s,i):t(r)),a!==void 0)return a;if(!Z(r))return r;var f=he(r);if(f){if(a=ap(r),!u)return Jd(r,a)}else{var m=Qe(r),g=m==Ep||m==j0;if(gt(r))return Jf(r,u);if(m==Ip||m==Tp||g&&!s){if(a=c||g?{}:mp(r),!u)return c?ep(r,Gf(a,r)):Zf(r,zf(a,r))}else{if(!ne[m])return s?r:{};a=pp(r,m,u)}}i||(i=new Kt);var E=i.get(r);if(E)return E;i.set(r,a),bp(r)?r.forEach(function(R){a.add(Zi(R,e,t,R,r,i))}):_p(r)&&r.forEach(function(R,N){a.set(N,Zi(R,e,t,N,r,i))});var P=h?c?tp:_s:c?Bt:Se,C=f?void 0:P(r);return tf(C||r,function(R,N){C&&(N=R,R=r[N]),Kr(a,N,Zi(R,e,t,N,r,i))}),a}var xp=Zi;var sI=1,iI=4;function oI(r){return xp(r,sI|iI)}var Ht=oI;var aI="__lodash_hash_undefined__";function uI(r){return this.__data__.set(r,aI),this}var Ap=uI;function cI(r){return this.__data__.has(r)}var Sp=cI;function eo(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new hr;++e<t;)this.add(r[e])}eo.prototype.add=eo.prototype.push=Ap;eo.prototype.has=Sp;var Rp=eo;function lI(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 Pp=lI;function hI(r,e){return r.has(e)}var Cp=hI;var dI=1,fI=2;function pI(r,e,t,n,s,i){var a=t&dI,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,E=t&fI?new Rp: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(E){if(!Pp(e,function(N,M){if(!Cp(E,M)&&(P===N||s(P,N,t,n,i)))return E.push(M)})){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 to=pI;function mI(r){var e=-1,t=Array(r.size);return r.forEach(function(n,s){t[++e]=[s,n]}),t}var kp=mI;function gI(r){var e=-1,t=Array(r.size);return r.forEach(function(n){t[++e]=n}),t}var Dp=gI;var yI=1,_I=2,vI="[object Boolean]",wI="[object Date]",bI="[object Error]",TI="[object Map]",EI="[object Number]",II="[object RegExp]",xI="[object Set]",AI="[object String]",SI="[object Symbol]",RI="[object ArrayBuffer]",PI="[object DataView]",Op=De?De.prototype:void 0,du=Op?Op.valueOf:void 0;function CI(r,e,t,n,s,i,a){switch(t){case PI:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case RI:return!(r.byteLength!=e.byteLength||!i(new sn(r),new sn(e)));case vI:case wI:case EI:return Xe(+r,+e);case bI:return r.name==e.name&&r.message==e.message;case II:case AI:return r==e+"";case TI:var u=kp;case xI:var c=n&yI;if(u||(u=Dp),r.size!=e.size&&!c)return!1;var h=a.get(r);if(h)return h==e;n|=_I,a.set(r,e);var f=to(u(r),u(e),n,s,i,a);return a.delete(r),f;case SI:if(du)return du.call(r)==du.call(e)}return!1}var Np=CI;var kI=1,DI=Object.prototype,OI=DI.hasOwnProperty;function NI(r,e,t,n,s,i){var a=t&kI,u=_s(r),c=u.length,h=_s(e),f=h.length;if(c!=f&&!a)return!1;for(var m=c;m--;){var g=u[m];if(!(a?g in e:OI.call(e,g)))return!1}var E=i.get(r),P=i.get(e);if(E&&P)return E==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],M=e[g];if(n)var U=a?n(M,N,g,e,r,i):n(N,M,g,r,e,i);if(!(U===void 0?N===M||s(N,M,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 Vp=NI;var VI=1,Lp="[object Arguments]",Mp="[object Array]",ro="[object Object]",LI=Object.prototype,Fp=LI.hasOwnProperty;function MI(r,e,t,n,s,i){var a=he(r),u=he(e),c=a?Mp:Qe(r),h=u?Mp:Qe(e);c=c==Lp?ro:c,h=h==Lp?ro:h;var f=c==ro,m=h==ro,g=c==h;if(g&>(r)){if(!gt(e))return!1;a=!0,f=!1}if(g&&!f)return i||(i=new Kt),a||Jr(r)?to(r,e,t,n,s,i):Np(r,e,c,t,n,s,i);if(!(t&VI)){var E=f&&Fp.call(r,"__wrapped__"),P=m&&Fp.call(e,"__wrapped__");if(E||P){var C=E?r.value():r,R=P?e.value():e;return i||(i=new Kt),s(C,R,t,n,i)}}return g?(i||(i=new Kt),Vp(r,e,t,n,s,i)):!1}var jp=MI;function Up(r,e,t,n,s){return r===e?!0:r==null||e==null||!Oe(r)&&!Oe(e)?r!==r&&e!==e:jp(r,e,t,n,Up,s)}var an=Up;var FI=1,jI=2;function UI(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 Kt;if(n)var g=n(h,f,c,r,e,m);if(!(g===void 0?an(f,h,FI|jI,n,m):g))return!1}}return!0}var Bp=UI;function BI(r){return r===r&&!Z(r)}var no=BI;function $I(r){for(var e=Se(r),t=e.length;t--;){var n=e[t],s=r[n];e[t]=[n,s,no(s)]}return e}var $p=$I;function qI(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}var so=qI;function zI(r){var e=$p(r);return e.length==1&&e[0][2]?so(e[0][0],e[0][1]):function(t){return t===r||Bp(t,r,e)}}var qp=zI;function GI(r,e){return r!=null&&e in Object(r)}var zp=GI;function KI(r,e,t){e=tn(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&&Hr(s)&&Mt(a,s)&&(he(r)||Wr(r)))}var Gp=KI;function HI(r,e){return r!=null&&Gp(r,e,zp)}var Kp=HI;var WI=1,QI=2;function JI(r,e){return Yr(r)&&no(e)?so(Ze(r),e):function(t){var n=ys(t,r);return n===void 0&&n===e?Kp(t,r):an(e,n,WI|QI)}}var Hp=JI;function YI(r){return function(e){return e==null?void 0:e[r]}}var Wp=YI;function XI(r){return function(e){return zi(e,r)}}var Qp=XI;function ZI(r){return Yr(r)?Wp(Ze(r)):Qp(r)}var Jp=ZI;function ex(r){return typeof r=="function"?r:r==null?qr:typeof r=="object"?he(r)?Hp(r[0],r[1]):qp(r):Jp(r)}var Yp=ex;function tx(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 Xp=tx;var rx=Xp(),Zp=rx;function nx(r,e){return r&&Zp(r,e,Se)}var em=nx;var sx=function(){return ce.Date.now()},io=sx;var ix="Expected a function",ox=Math.max,ax=Math.min;function ux(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(ix);e=au(e)||0,Z(t)&&(f=!!t.leading,m="maxWait"in t,i=m?ox(au(t.maxWait)||0,e):i,g="trailing"in t?!!t.trailing:g);function E(B){var T=n,y=s;return n=s=void 0,h=B,a=r.apply(y,T),a}function P(B){return h=B,u=setTimeout(N,e),f?E(B):a}function C(B){var T=B-c,y=B-h,w=e-T;return m?ax(w,i-y):w}function R(B){var T=B-c,y=B-h;return c===void 0||T>=e||T<0||m&&y>=i}function N(){var B=io();if(R(B))return M(B);u=setTimeout(N,C(B))}function M(B){return u=void 0,g&&n?E(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:M(io())}function Y(){var B=io(),T=R(B);if(n=arguments,s=this,c=B,T){if(u===void 0)return P(c);if(m)return clearTimeout(u),u=setTimeout(N,e),E(c)}return u===void 0&&(u=setTimeout(N,e)),a}return Y.cancel=U,Y.flush=G,Y}var tm=ux;var rm=Object.prototype,cx=rm.hasOwnProperty,lx=sf(function(r,e){r=Object(r);var t=-1,n=e.length,s=n>2?e[2]:void 0;for(s&&of(e[0],e[1],s)&&(n=1);++t<n;)for(var i=e[t],a=Bt(i),u=-1,c=a.length;++u<c;){var h=a[u],f=r[h];(f===void 0||Xe(f,rm[h])&&!cx.call(r,h))&&(r[h]=i[h])}return r}),oo=lx;var hx="[object Map]",dx="[object Set]",fx=Object.prototype,px=fx.hasOwnProperty;function mx(r){if(r==null)return!0;if(jt(r)&&(he(r)||typeof r=="string"||typeof r.splice=="function"||gt(r)||Jr(r)||Wr(r)))return!r.length;var e=Qe(r);if(e==hx||e==dx)return!r.size;if(Ut(r))return!qi(r).length;for(var t in r)if(px.call(r,t))return!1;return!0}var fu=mx;function gx(r,e){return an(r,e)}var pu=gx;function yx(r,e){var t={};return e=Yp(e,3),em(r,function(n,s,i){Gr(t,e(n,s,i),n)}),t}var mu=yx;function _x(r,e,t,n){if(!Z(r))return r;e=tn(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])?[]:{})}Kr(u,c,h),u=u[c]}return r}var nm=_x;function vx(r,e,t){return r==null?r:nm(r,e,t)}var Wt=vx;var wx="Expected a function";function bx(r,e,t){var n=!0,s=!0;if(typeof r!="function")throw new TypeError(wx);return Z(t)&&(n="leading"in t?!!t.leading:n,s="trailing"in t?!!t.trailing:s),tm(r,e,{leading:n,maxWait:e,trailing:s})}var gu=bx;var im=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},Tx=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("")},om={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,E=h&63;c||(E=64,a||(g=64)),n.push(t[f],t[m],t[g],t[E])}return n.join("")},encodeString(r,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(r):this.encodeByteArray(im(r),e)},decodeString(r,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(r):Tx(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 yu;let g=i<<2|u>>4;if(n.push(g),h!==64){let E=u<<4&240|h>>2;if(n.push(E),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)}}},yu=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},Ex=function(r){let e=im(r);return om.encodeByteArray(e,!0)},vs=function(r){return Ex(r).replace(/\./g,"")},am=function(r){try{return om.decodeString(r,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function Ix(){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 xx=()=>Ix().__FIREBASE_DEFAULTS__,Ax=()=>{if(typeof process=="undefined"||typeof process.env=="undefined")return;let r=process.env.__FIREBASE_DEFAULTS__;if(r)return JSON.parse(r)},Sx=()=>{if(typeof document=="undefined")return;let r;try{r=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}let e=r&&am(r[1]);return e&&JSON.parse(e)},_u=()=>{try{return xx()||Ax()||Sx()}catch(r){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${r}`);return}},Rx=r=>{var e,t;return(t=(e=_u())===null||e===void 0?void 0:e.emulatorHosts)===null||t===void 0?void 0:t[r]},um=r=>{let e=Rx(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]},vu=()=>{var r;return(r=_u())===null||r===void 0?void 0:r.config};var ao=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 cm(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[vs(JSON.stringify(t)),vs(JSON.stringify(a)),""].join(".")}function lm(){return typeof navigator!="undefined"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function Px(){var r;let e=(r=_u())===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 hm(){return!Px()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function wu(){try{return typeof indexedDB=="object"}catch{return!1}}function dm(){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 Cx="FirebaseError",vt=class r extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name=Cx,Object.setPrototypeOf(this,r.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ws.prototype.create)}},ws=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?kx(i,n):"Error",u=`${this.serviceName}: ${a} (${s}).`;return new vt(s,u,n)}};function kx(r,e){return r.replace(Dx,(t,n)=>{let s=e[n];return s!=null?String(s):`<${n}?>`})}var Dx=/\{\$([^}]+)}/g;function bs(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(sm(i)&&sm(a)){if(!bs(i,a))return!1}else if(i!==a)return!1}for(let s of n)if(!t.includes(s))return!1;return!0}function sm(r){return r!==null&&typeof r=="object"}var WM=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 bu=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 ao;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(Nx(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:Ox(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 Ox(r){return r===fr?void 0:r}function Nx(r){return r.instantiationMode==="EAGER"}var uo=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 bu(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}};var Vx=[],W;(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"})(W||(W={}));var Lx={debug:W.DEBUG,verbose:W.VERBOSE,info:W.INFO,warn:W.WARN,error:W.ERROR,silent:W.SILENT},Mx=W.INFO,Fx={[W.DEBUG]:"log",[W.VERBOSE]:"log",[W.INFO]:"info",[W.WARN]:"warn",[W.ERROR]:"error"},jx=(r,e,...t)=>{if(e<r.logLevel)return;let n=new Date().toISOString(),s=Fx[e];if(s)console[s](`[${n}] ${r.name}:`,...t);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},un=class{constructor(e){this.name=e,this._logLevel=Mx,this._logHandler=jx,this._userLogHandler=null,Vx.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in W))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?Lx[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,W.DEBUG,...e),this._logHandler(this,W.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,W.VERBOSE,...e),this._logHandler(this,W.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,W.INFO,...e),this._logHandler(this,W.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,W.WARN,...e),this._logHandler(this,W.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,W.ERROR,...e),this._logHandler(this,W.ERROR,...e)}};var Ux=(r,e)=>e.some(t=>r instanceof t),fm,pm;function Bx(){return fm||(fm=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function $x(){return pm||(pm=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var mm=new WeakMap,Eu=new WeakMap,gm=new WeakMap,Tu=new WeakMap,xu=new WeakMap;function qx(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&&mm.set(t,r)}).catch(()=>{}),xu.set(e,r),e}function zx(r){if(Eu.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)});Eu.set(r,e)}var Iu={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return Eu.get(r);if(e==="objectStoreNames")return r.objectStoreNames||gm.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 ym(r){Iu=r(Iu)}function Gx(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let n=r.call(co(this),e,...t);return gm.set(n,e.sort?e.sort():[e]),et(n)}:$x().includes(r)?function(...e){return r.apply(co(this),e),et(mm.get(this))}:function(...e){return et(r.apply(co(this),e))}}function Kx(r){return typeof r=="function"?Gx(r):(r instanceof IDBTransaction&&zx(r),Ux(r,Bx())?new Proxy(r,Iu):r)}function et(r){if(r instanceof IDBRequest)return qx(r);if(Tu.has(r))return Tu.get(r);let e=Kx(r);return e!==r&&(Tu.set(r,e),xu.set(e,r)),e}var co=r=>xu.get(r);function vm(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 Hx=["get","getKey","getAll","getAllKeys","count"],Wx=["put","add","delete","clear"],Au=new Map;function _m(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(Au.get(e))return Au.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,s=Wx.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(s||Hx.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 Au.set(e,i),i}ym(r=>({...r,get:(e,t,n)=>_m(e,t)||r.get(e,t,n),has:(e,t)=>!!_m(e,t)||r.has(e,t)}));var Ru=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(t=>{if(Qx(t)){let n=t.getImmediate();return`${n.library}/${n.version}`}else return null}).filter(t=>t).join(" ")}};function Qx(r){let e=r.getComponent();return(e==null?void 0:e.type)==="VERSION"}var Pu="@firebase/app",wm="0.11.1";var Tt=new un("@firebase/app"),Jx="@firebase/app-compat",Yx="@firebase/analytics-compat",Xx="@firebase/analytics",Zx="@firebase/app-check-compat",eA="@firebase/app-check",tA="@firebase/auth",rA="@firebase/auth-compat",nA="@firebase/database",sA="@firebase/data-connect",iA="@firebase/database-compat",oA="@firebase/functions",aA="@firebase/functions-compat",uA="@firebase/installations",cA="@firebase/installations-compat",lA="@firebase/messaging",hA="@firebase/messaging-compat",dA="@firebase/performance",fA="@firebase/performance-compat",pA="@firebase/remote-config",mA="@firebase/remote-config-compat",gA="@firebase/storage",yA="@firebase/storage-compat",_A="@firebase/firestore",vA="@firebase/vertexai",wA="@firebase/firestore-compat",bA="firebase",TA="11.3.1";var Cu="[DEFAULT]",EA={[Pu]:"fire-core",[Jx]:"fire-core-compat",[Xx]:"fire-analytics",[Yx]:"fire-analytics-compat",[eA]:"fire-app-check",[Zx]:"fire-app-check-compat",[tA]:"fire-auth",[rA]:"fire-auth-compat",[nA]:"fire-rtdb",[sA]:"fire-data-connect",[iA]:"fire-rtdb-compat",[oA]:"fire-fn",[aA]:"fire-fn-compat",[uA]:"fire-iid",[cA]:"fire-iid-compat",[lA]:"fire-fcm",[hA]:"fire-fcm-compat",[dA]:"fire-perf",[fA]:"fire-perf-compat",[pA]:"fire-rc",[mA]:"fire-rc-compat",[gA]:"fire-gcs",[yA]:"fire-gcs-compat",[_A]:"fire-fst",[wA]:"fire-fst-compat",[vA]:"fire-vertex","fire-js":"fire-js",[bA]:"fire-js-all"};var lo=new Map,IA=new Map,ku=new Map;function bm(r,e){try{r.container.addComponent(e)}catch(t){Tt.debug(`Component ${e.name} failed to register with FirebaseApp ${r.name}`,t)}}function Ts(r){let e=r.name;if(ku.has(e))return Tt.debug(`There were multiple attempts to register component ${e}.`),!1;ku.set(e,r);for(let t of lo.values())bm(t,r);for(let t of IA.values())bm(t,r);return!0}function xm(r,e){let t=r.container.getProvider("heartbeat").getImmediate({optional:!0});return t&&t.triggerHeartbeat(),r.container.getProvider(e)}function Am(r){return r==null?!1:r.settings!==void 0}var xA={"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."},Qt=new ws("app","Firebase",xA);var Du=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 Qt.create("app-deleted",{appName:this._name})}};var Sm=TA;function Vu(r,e={}){let t=r;typeof e!="object"&&(e={name:e});let n=Object.assign({name:Cu,automaticDataCollectionEnabled:!1},e),s=n.name;if(typeof s!="string"||!s)throw Qt.create("bad-app-name",{appName:String(s)});if(t||(t=vu()),!t)throw Qt.create("no-options");let i=lo.get(s);if(i){if(bs(t,i.options)&&bs(n,i.config))return i;throw Qt.create("duplicate-app",{appName:s})}let a=new uo(s);for(let c of ku.values())a.addComponent(c);let u=new Du(t,n,a);return lo.set(s,u),u}function Rm(r=Cu){let e=lo.get(r);if(!e&&r===Cu&&vu())return Vu();if(!e)throw Qt.create("no-app",{appName:r});return e}function Jt(r,e,t){var n;let s=(n=EA[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}Ts(new bt(`${s}-version`,()=>({library:s,version:e}),"VERSION"))}var AA="firebase-heartbeat-database",SA=1,Es="firebase-heartbeat-store",Su=null;function Pm(){return Su||(Su=vm(AA,SA,{upgrade:(r,e)=>{switch(e){case 0:try{r.createObjectStore(Es)}catch(t){console.warn(t)}}}}).catch(r=>{throw Qt.create("idb-open",{originalErrorMessage:r.message})})),Su}async function RA(r){try{let t=(await Pm()).transaction(Es),n=await t.objectStore(Es).get(Cm(r));return await t.done,n}catch(e){if(e instanceof vt)Tt.warn(e.message);else{let t=Qt.create("idb-get",{originalErrorMessage:e==null?void 0:e.message});Tt.warn(t.message)}}}async function Tm(r,e){try{let n=(await Pm()).transaction(Es,"readwrite");await n.objectStore(Es).put(e,Cm(r)),await n.done}catch(t){if(t instanceof vt)Tt.warn(t.message);else{let n=Qt.create("idb-set",{originalErrorMessage:t==null?void 0:t.message});Tt.warn(n.message)}}}function Cm(r){return`${r.name}!${r.options.appId}`}var PA=1024,CA=30,Ou=class{constructor(e){this.container=e,this._heartbeatsCache=null;let t=this.container.getProvider("app").getImmediate();this._storage=new Nu(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=Em();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>CA){let a=DA(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=Em(),{heartbeatsToSend:n,unsentEntries:s}=kA(this._heartbeatsCache.heartbeats),i=vs(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 Em(){return new Date().toISOString().substring(0,10)}function kA(r,e=PA){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),Im(t)>e){i.dates.pop();break}}else if(t.push({agent:s.agent,dates:[s.date]}),Im(t)>e){t.pop();break}n=n.slice(1)}return{heartbeatsToSend:t,unsentEntries:n}}var Nu=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return wu()?dm().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let t=await RA(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 Tm(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 Tm(this.app,{lastSentHeartbeatDate:(t=e.lastSentHeartbeatDate)!==null&&t!==void 0?t:s.lastSentHeartbeatDate,heartbeats:[...s.heartbeats,...e.heartbeats]})}else return}};function Im(r){return vs(JSON.stringify({version:2,heartbeats:r})).length}function DA(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 OA(r){Ts(new bt("platform-logger",e=>new Ru(e),"PRIVATE")),Ts(new bt("heartbeat",e=>new Ou(e),"PRIVATE")),Jt(Pu,wm,r),Jt(Pu,wm,"esm2017"),Jt("fire-js","")}OA("");var NA="firebase",VA="11.3.1";Jt(NA,VA,"app");var km=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Dm={};var Et,Lu;(function(){var r;function e(T,y){function w(){}w.prototype=y.prototype,T.D=y.prototype,T.prototype=new w,T.prototype.constructor=T,T.C=function(b,I,A){for(var _=Array(arguments.length-2),dt=2;dt<arguments.length;dt++)_[dt-2]=arguments[dt];return y.prototype[I].apply(b,_)}}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(T,y,w){w||(w=0);var b=Array(16);if(typeof y=="string")for(var I=0;16>I;++I)b[I]=y.charCodeAt(w++)|y.charCodeAt(w++)<<8|y.charCodeAt(w++)<<16|y.charCodeAt(w++)<<24;else for(I=0;16>I;++I)b[I]=y[w++]|y[w++]<<8|y[w++]<<16|y[w++]<<24;y=T.g[0],w=T.g[1],I=T.g[2];var A=T.g[3],_=y+(A^w&(I^A))+b[0]+3614090360&4294967295;y=w+(_<<7&4294967295|_>>>25),_=A+(I^y&(w^I))+b[1]+3905402710&4294967295,A=y+(_<<12&4294967295|_>>>20),_=I+(w^A&(y^w))+b[2]+606105819&4294967295,I=A+(_<<17&4294967295|_>>>15),_=w+(y^I&(A^y))+b[3]+3250441966&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(A^w&(I^A))+b[4]+4118548399&4294967295,y=w+(_<<7&4294967295|_>>>25),_=A+(I^y&(w^I))+b[5]+1200080426&4294967295,A=y+(_<<12&4294967295|_>>>20),_=I+(w^A&(y^w))+b[6]+2821735955&4294967295,I=A+(_<<17&4294967295|_>>>15),_=w+(y^I&(A^y))+b[7]+4249261313&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(A^w&(I^A))+b[8]+1770035416&4294967295,y=w+(_<<7&4294967295|_>>>25),_=A+(I^y&(w^I))+b[9]+2336552879&4294967295,A=y+(_<<12&4294967295|_>>>20),_=I+(w^A&(y^w))+b[10]+4294925233&4294967295,I=A+(_<<17&4294967295|_>>>15),_=w+(y^I&(A^y))+b[11]+2304563134&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(A^w&(I^A))+b[12]+1804603682&4294967295,y=w+(_<<7&4294967295|_>>>25),_=A+(I^y&(w^I))+b[13]+4254626195&4294967295,A=y+(_<<12&4294967295|_>>>20),_=I+(w^A&(y^w))+b[14]+2792965006&4294967295,I=A+(_<<17&4294967295|_>>>15),_=w+(y^I&(A^y))+b[15]+1236535329&4294967295,w=I+(_<<22&4294967295|_>>>10),_=y+(I^A&(w^I))+b[1]+4129170786&4294967295,y=w+(_<<5&4294967295|_>>>27),_=A+(w^I&(y^w))+b[6]+3225465664&4294967295,A=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(A^y))+b[11]+643717713&4294967295,I=A+(_<<14&4294967295|_>>>18),_=w+(A^y&(I^A))+b[0]+3921069994&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(I^A&(w^I))+b[5]+3593408605&4294967295,y=w+(_<<5&4294967295|_>>>27),_=A+(w^I&(y^w))+b[10]+38016083&4294967295,A=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(A^y))+b[15]+3634488961&4294967295,I=A+(_<<14&4294967295|_>>>18),_=w+(A^y&(I^A))+b[4]+3889429448&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(I^A&(w^I))+b[9]+568446438&4294967295,y=w+(_<<5&4294967295|_>>>27),_=A+(w^I&(y^w))+b[14]+3275163606&4294967295,A=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(A^y))+b[3]+4107603335&4294967295,I=A+(_<<14&4294967295|_>>>18),_=w+(A^y&(I^A))+b[8]+1163531501&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(I^A&(w^I))+b[13]+2850285829&4294967295,y=w+(_<<5&4294967295|_>>>27),_=A+(w^I&(y^w))+b[2]+4243563512&4294967295,A=y+(_<<9&4294967295|_>>>23),_=I+(y^w&(A^y))+b[7]+1735328473&4294967295,I=A+(_<<14&4294967295|_>>>18),_=w+(A^y&(I^A))+b[12]+2368359562&4294967295,w=I+(_<<20&4294967295|_>>>12),_=y+(w^I^A)+b[5]+4294588738&4294967295,y=w+(_<<4&4294967295|_>>>28),_=A+(y^w^I)+b[8]+2272392833&4294967295,A=y+(_<<11&4294967295|_>>>21),_=I+(A^y^w)+b[11]+1839030562&4294967295,I=A+(_<<16&4294967295|_>>>16),_=w+(I^A^y)+b[14]+4259657740&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(w^I^A)+b[1]+2763975236&4294967295,y=w+(_<<4&4294967295|_>>>28),_=A+(y^w^I)+b[4]+1272893353&4294967295,A=y+(_<<11&4294967295|_>>>21),_=I+(A^y^w)+b[7]+4139469664&4294967295,I=A+(_<<16&4294967295|_>>>16),_=w+(I^A^y)+b[10]+3200236656&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(w^I^A)+b[13]+681279174&4294967295,y=w+(_<<4&4294967295|_>>>28),_=A+(y^w^I)+b[0]+3936430074&4294967295,A=y+(_<<11&4294967295|_>>>21),_=I+(A^y^w)+b[3]+3572445317&4294967295,I=A+(_<<16&4294967295|_>>>16),_=w+(I^A^y)+b[6]+76029189&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(w^I^A)+b[9]+3654602809&4294967295,y=w+(_<<4&4294967295|_>>>28),_=A+(y^w^I)+b[12]+3873151461&4294967295,A=y+(_<<11&4294967295|_>>>21),_=I+(A^y^w)+b[15]+530742520&4294967295,I=A+(_<<16&4294967295|_>>>16),_=w+(I^A^y)+b[2]+3299628645&4294967295,w=I+(_<<23&4294967295|_>>>9),_=y+(I^(w|~A))+b[0]+4096336452&4294967295,y=w+(_<<6&4294967295|_>>>26),_=A+(w^(y|~I))+b[7]+1126891415&4294967295,A=y+(_<<10&4294967295|_>>>22),_=I+(y^(A|~w))+b[14]+2878612391&4294967295,I=A+(_<<15&4294967295|_>>>17),_=w+(A^(I|~y))+b[5]+4237533241&4294967295,w=I+(_<<21&4294967295|_>>>11),_=y+(I^(w|~A))+b[12]+1700485571&4294967295,y=w+(_<<6&4294967295|_>>>26),_=A+(w^(y|~I))+b[3]+2399980690&4294967295,A=y+(_<<10&4294967295|_>>>22),_=I+(y^(A|~w))+b[10]+4293915773&4294967295,I=A+(_<<15&4294967295|_>>>17),_=w+(A^(I|~y))+b[1]+2240044497&4294967295,w=I+(_<<21&4294967295|_>>>11),_=y+(I^(w|~A))+b[8]+1873313359&4294967295,y=w+(_<<6&4294967295|_>>>26),_=A+(w^(y|~I))+b[15]+4264355552&4294967295,A=y+(_<<10&4294967295|_>>>22),_=I+(y^(A|~w))+b[6]+2734768916&4294967295,I=A+(_<<15&4294967295|_>>>17),_=w+(A^(I|~y))+b[13]+1309151649&4294967295,w=I+(_<<21&4294967295|_>>>11),_=y+(I^(w|~A))+b[4]+4149444226&4294967295,y=w+(_<<6&4294967295|_>>>26),_=A+(w^(y|~I))+b[11]+3174756917&4294967295,A=y+(_<<10&4294967295|_>>>22),_=I+(y^(A|~w))+b[2]+718787259&4294967295,I=A+(_<<15&4294967295|_>>>17),_=w+(A^(I|~y))+b[9]+3951481745&4294967295,T.g[0]=T.g[0]+y&4294967295,T.g[1]=T.g[1]+(I+(_<<21&4294967295|_>>>11))&4294967295,T.g[2]=T.g[2]+I&4294967295,T.g[3]=T.g[3]+A&4294967295}n.prototype.u=function(T,y){y===void 0&&(y=T.length);for(var w=y-this.blockSize,b=this.B,I=this.h,A=0;A<y;){if(I==0)for(;A<=w;)s(this,T,A),A+=this.blockSize;if(typeof T=="string"){for(;A<y;)if(b[I++]=T.charCodeAt(A++),I==this.blockSize){s(this,b),I=0;break}}else for(;A<y;)if(b[I++]=T[A++],I==this.blockSize){s(this,b),I=0;break}}this.h=I,this.o+=y},n.prototype.v=function(){var T=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);T[0]=128;for(var y=1;y<T.length-8;++y)T[y]=0;var w=8*this.o;for(y=T.length-8;y<T.length;++y)T[y]=w&255,w/=256;for(this.u(T),T=Array(16),y=w=0;4>y;++y)for(var b=0;32>b;b+=8)T[w++]=this.g[y]>>>b&255;return T};function i(T,y){var w=u;return Object.prototype.hasOwnProperty.call(w,T)?w[T]:w[T]=y(T)}function a(T,y){this.h=y;for(var w=[],b=!0,I=T.length-1;0<=I;I--){var A=T[I]|0;b&&A==y||(w[I]=A,b=!1)}this.g=w}var u={};function c(T){return-128<=T&&128>T?i(T,function(y){return new a([y|0],0>y?-1:0)}):new a([T|0],0>T?-1:0)}function h(T){if(isNaN(T)||!isFinite(T))return m;if(0>T)return R(h(-T));for(var y=[],w=1,b=0;T>=w;b++)y[b]=T/w|0,w*=4294967296;return new a(y,0)}function f(T,y){if(T.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(T.charAt(0)=="-")return R(f(T.substring(1),y));if(0<=T.indexOf("-"))throw Error('number format error: interior "-" character');for(var w=h(Math.pow(y,8)),b=m,I=0;I<T.length;I+=8){var A=Math.min(8,T.length-I),_=parseInt(T.substring(I,I+A),y);8>A?(A=h(Math.pow(y,A)),b=b.j(A).add(h(_))):(b=b.j(w),b=b.add(h(_)))}return b}var m=c(0),g=c(1),E=c(16777216);r=a.prototype,r.m=function(){if(C(this))return-R(this).m();for(var T=0,y=1,w=0;w<this.g.length;w++){var b=this.i(w);T+=(0<=b?b:4294967296+b)*y,y*=4294967296}return T},r.toString=function(T){if(T=T||10,2>T||36<T)throw Error("radix out of range: "+T);if(P(this))return"0";if(C(this))return"-"+R(this).toString(T);for(var y=h(Math.pow(T,6)),w=this,b="";;){var I=G(w,y).g;w=N(w,I.j(y));var A=((0<w.g.length?w.g[0]:w.h)>>>0).toString(T);if(w=I,P(w))return A+b;for(;6>A.length;)A="0"+A;b=A+b}},r.i=function(T){return 0>T?0:T<this.g.length?this.g[T]:this.h};function P(T){if(T.h!=0)return!1;for(var y=0;y<T.g.length;y++)if(T.g[y]!=0)return!1;return!0}function C(T){return T.h==-1}r.l=function(T){return T=N(this,T),C(T)?-1:P(T)?0:1};function R(T){for(var y=T.g.length,w=[],b=0;b<y;b++)w[b]=~T.g[b];return new a(w,~T.h).add(g)}r.abs=function(){return C(this)?R(this):this},r.add=function(T){for(var y=Math.max(this.g.length,T.g.length),w=[],b=0,I=0;I<=y;I++){var A=b+(this.i(I)&65535)+(T.i(I)&65535),_=(A>>>16)+(this.i(I)>>>16)+(T.i(I)>>>16);b=_>>>16,A&=65535,_&=65535,w[I]=_<<16|A}return new a(w,w[w.length-1]&-2147483648?-1:0)};function N(T,y){return T.add(R(y))}r.j=function(T){if(P(this)||P(T))return m;if(C(this))return C(T)?R(this).j(R(T)):R(R(this).j(T));if(C(T))return R(this.j(R(T)));if(0>this.l(E)&&0>T.l(E))return h(this.m()*T.m());for(var y=this.g.length+T.g.length,w=[],b=0;b<2*y;b++)w[b]=0;for(b=0;b<this.g.length;b++)for(var I=0;I<T.g.length;I++){var A=this.i(b)>>>16,_=this.i(b)&65535,dt=T.i(I)>>>16,Qn=T.i(I)&65535;w[2*b+2*I]+=_*Qn,M(w,2*b+2*I),w[2*b+2*I+1]+=A*Qn,M(w,2*b+2*I+1),w[2*b+2*I+1]+=_*dt,M(w,2*b+2*I+1),w[2*b+2*I+2]+=A*dt,M(w,2*b+2*I+2)}for(b=0;b<y;b++)w[b]=w[2*b+1]<<16|w[2*b];for(b=y;b<2*y;b++)w[b]=0;return new a(w,0)};function M(T,y){for(;(T[y]&65535)!=T[y];)T[y+1]+=T[y]>>>16,T[y]&=65535,y++}function U(T,y){this.g=T,this.h=y}function G(T,y){if(P(y))throw Error("division by zero");if(P(T))return new U(m,m);if(C(T))return y=G(R(T),y),new U(R(y.g),R(y.h));if(C(y))return y=G(T,R(y)),new U(R(y.g),y.h);if(30<T.g.length){if(C(T)||C(y))throw Error("slowDivide_ only works with positive integers.");for(var w=g,b=y;0>=b.l(T);)w=Y(w),b=Y(b);var I=B(w,1),A=B(b,1);for(b=B(b,2),w=B(w,2);!P(b);){var _=A.add(b);0>=_.l(T)&&(I=I.add(w),A=_),b=B(b,1),w=B(w,1)}return y=N(T,I.j(y)),new U(I,y)}for(I=m;0<=T.l(y);){for(w=Math.max(1,Math.floor(T.m()/y.m())),b=Math.ceil(Math.log(w)/Math.LN2),b=48>=b?1:Math.pow(2,b-48),A=h(w),_=A.j(y);C(_)||0<_.l(T);)w-=b,A=h(w),_=A.j(y);P(A)&&(A=g),I=I.add(A),T=N(T,_)}return new U(I,T)}r.A=function(T){return G(this,T).h},r.and=function(T){for(var y=Math.max(this.g.length,T.g.length),w=[],b=0;b<y;b++)w[b]=this.i(b)&T.i(b);return new a(w,this.h&T.h)},r.or=function(T){for(var y=Math.max(this.g.length,T.g.length),w=[],b=0;b<y;b++)w[b]=this.i(b)|T.i(b);return new a(w,this.h|T.h)},r.xor=function(T){for(var y=Math.max(this.g.length,T.g.length),w=[],b=0;b<y;b++)w[b]=this.i(b)^T.i(b);return new a(w,this.h^T.h)};function Y(T){for(var y=T.g.length+1,w=[],b=0;b<y;b++)w[b]=T.i(b)<<1|T.i(b-1)>>>31;return new a(w,T.h)}function B(T,y){var w=y>>5;y%=32;for(var b=T.g.length-w,I=[],A=0;A<b;A++)I[A]=0<y?T.i(A+w)>>>y|T.i(A+w+1)<<32-y:T.i(A+w);return new a(I,T.h)}n.prototype.digest=n.prototype.v,n.prototype.reset=n.prototype.s,n.prototype.update=n.prototype.u,Lu=Dm.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=Dm.Integer=a}).apply(typeof km!="undefined"?km:typeof self!="undefined"?self:typeof window!="undefined"?window:{});var ho=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},It={};var Mu,LA,cn,Fu,Is,fo,ju,Uu,Bu;(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 ho=="object"&&ho];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 x=o[p];if(!(x in d))break e;d=d[x]}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,x={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 x[Symbol.iterator]=function(){return x},x}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 x=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(x,p),o.apply(l,x)}}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 E(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,x,S){for(var O=Array(arguments.length-2),te=2;te<arguments.length;te++)O[te-2]=arguments[te];return l.prototype[x].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 x=o.length||0,S=p.length||0;o.length=x+S;for(let O=0;O<S;O++)o[x+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 M(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 T(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 b(o,l){let d,p;for(let x=1;x<arguments.length;x++){p=arguments[x];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 A(o){u.setTimeout(()=>{throw o},0)}function _(){var o=Va;let l=null;return o.g&&(l=o.g,o.g=o.g.next,o.g||(o.h=null),l.next=null),l}class dt{constructor(){this.h=this.g=null}add(l,d){let p=Qn.get();p.set(l,d),this.h?this.h.next=p:this.g=p,this.h=p}}var Qn=new N(()=>new fv,o=>o.reset());class fv{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 Jn,Yn=!1,Va=new dt,Ph=()=>{let o=u.Promise.resolve(void 0);Jn=()=>{o.then(pv)}};var pv=()=>{for(var o;o=_();){try{o.h.call(o.g)}catch(d){A(d)}var l=Qn;l.j(o),100>l.h&&(l.h++,o.next=l.g,l.g=o)}Yn=!1};function Dt(){this.s=this.s,this.C=this.C}Dt.prototype.s=!1,Dt.prototype.ma=function(){this.s||(this.s=!0,this.N())},Dt.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function Ee(o,l){this.type=o,this.g=this.target=l,this.defaultPrevented=!1}Ee.prototype.h=function(){this.defaultPrevented=!0};var mv=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 Xn(o,l){if(Ee.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 x=!0;break e}catch{}x=!1}x||(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:gv[o.pointerType]||"",this.state=o.state,this.i=o,o.defaultPrevented&&Xn.aa.h.call(this)}}P(Xn,Ee);var gv={2:"touch",3:"pen",4:"mouse"};Xn.prototype.h=function(){Xn.aa.h.call(this);var o=this.i;o.preventDefault?o.preventDefault():o.returnValue=!1};var Zn="closure_listenable_"+(1e6*Math.random()|0),yv=0;function _v(o,l,d,p,x){this.listener=o,this.proxy=null,this.src=l,this.type=d,this.capture=!!p,this.ha=x,this.key=++yv,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,x){var S=o.toString();o=this.g[S],o||(o=this.g[S]=[],this.h++);var O=Ma(o,l,p,x);return-1<O?(l=o[O],d||(l.fa=!1)):(l=new _v(l,this.src,S,!!p,x),l.fa=d,o.push(l)),l};function La(o,l){var d=l.type;if(d in o.g){var p=o.g[d],x=Array.prototype.indexOf.call(p,l,void 0),S;(S=0<=x)&&Array.prototype.splice.call(p,x,1),S&&(wi(l),o.g[d].length==0&&(delete o.g[d],o.h--))}}function Ma(o,l,d,p){for(var x=0;x<o.length;++x){var S=o[x];if(!S.da&&S.listener==l&&S.capture==!!d&&S.ha==p)return x}return-1}var Fa="closure_lm_"+(1e6*Math.random()|0),ja={};function Ch(o,l,d,p,x){if(p&&p.once)return Dh(o,l,d,p,x);if(Array.isArray(l)){for(var S=0;S<l.length;S++)Ch(o,l[S],d,p,x);return null}return d=qa(d),o&&o[Zn]?o.K(l,d,h(p)?!!p.capture:!!p,x):kh(o,l,d,!1,p,x)}function kh(o,l,d,p,x,S){if(!l)throw Error("Invalid event type");var O=h(x)?!!x.capture:!!x,te=Ba(o);if(te||(o[Fa]=te=new bi(o)),d=te.add(l,d,p,O,S),d.proxy)return d;if(p=vv(),d.proxy=p,p.src=o,p.listener=d,o.addEventListener)mv||(x=O),x===void 0&&(x=!1),o.addEventListener(l.toString(),p,x);else if(o.attachEvent)o.attachEvent(Nh(l.toString()),p);else if(o.addListener&&o.removeListener)o.addListener(p);else throw Error("addEventListener and attachEvent are unavailable.");return d}function vv(){function o(d){return l.call(o.src,o.listener,d)}let l=wv;return o}function Dh(o,l,d,p,x){if(Array.isArray(l)){for(var S=0;S<l.length;S++)Dh(o,l[S],d,p,x);return null}return d=qa(d),o&&o[Zn]?o.L(l,d,h(p)?!!p.capture:!!p,x):kh(o,l,d,!0,p,x)}function Oh(o,l,d,p,x){if(Array.isArray(l))for(var S=0;S<l.length;S++)Oh(o,l[S],d,p,x);else p=h(p)?!!p.capture:!!p,d=qa(d),o&&o[Zn]?(o=o.i,l=String(l).toString(),l in o.g&&(S=o.g[l],d=Ma(S,d,p,x),-1<d&&(wi(S[d]),Array.prototype.splice.call(S,d,1),S.length==0&&(delete o.g[l],o.h--)))):o&&(o=Ba(o))&&(l=o.g[l.toString()],o=-1,l&&(o=Ma(l,d,p,x)),(d=-1<o?l[o]:null)&&Ua(d))}function Ua(o){if(typeof o!="number"&&o&&!o.da){var l=o.src;if(l&&l[Zn])La(l.i,o);else{var d=o.type,p=o.proxy;l.removeEventListener?l.removeEventListener(d,p,o.capture):l.detachEvent?l.detachEvent(Nh(d),p):l.addListener&&l.removeListener&&l.removeListener(p),(d=Ba(l))?(La(d,o),d.h==0&&(d.src=null,l[Fa]=null)):wi(o)}}}function Nh(o){return o in ja?ja[o]:ja[o]="on"+o}function wv(o,l){if(o.da)o=!0;else{l=new Xn(l,this);var d=o.listener,p=o.ha||o.src;o.fa&&Ua(o),o=d.call(p,l)}return o}function Ba(o){return o=o[Fa],o instanceof bi?o:null}var $a="__closure_events_fn_"+(1e9*Math.random()>>>0);function qa(o){return typeof o=="function"?o:(o[$a]||(o[$a]=function(l){return o.handleEvent(l)}),o[$a])}function Ie(){Dt.call(this),this.i=new bi(this),this.M=this,this.F=null}P(Ie,Dt),Ie.prototype[Zn]=!0,Ie.prototype.removeEventListener=function(o,l,d,p){Oh(this,o,l,d,p)};function Ce(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 Ee(l,o);else if(l instanceof Ee)l.target=l.target||o;else{var x=l;l=new Ee(p,o),b(l,x)}if(x=!0,d)for(var S=d.length-1;0<=S;S--){var O=l.g=d[S];x=Ti(O,p,!0,l)&&x}if(O=l.g=o,x=Ti(O,p,!0,l)&&x,x=Ti(O,p,!1,l)&&x,d)for(S=0;S<d.length;S++)O=l.g=d[S],x=Ti(O,p,!1,l)&&x}Ie.prototype.N=function(){if(Ie.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},Ie.prototype.K=function(o,l,d,p){return this.i.add(String(o),l,!1,d,p)},Ie.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 x=!0,S=0;S<l.length;++S){var O=l[S];if(O&&!O.da&&O.capture==d){var te=O.listener,we=O.ha||O.src;O.fa&&La(o.i,O),x=te.call(we,p)!==!1&&x}}return x&&!p.defaultPrevented}function Vh(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 Lh(o){o.g=Vh(()=>{o.g=null,o.i&&(o.i=!1,Lh(o))},o.l);let l=o.h;o.h=null,o.m.apply(null,l)}class bv extends Dt{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:Lh(this)}N(){super.N(),this.g&&(u.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function es(o){Dt.call(this),this.h=o,this.g={}}P(es,Dt);var Mh=[];function Fh(o){B(o.g,function(l,d){this.g.hasOwnProperty(d)&&Ua(l)},o),o.g={}}es.prototype.N=function(){es.aa.N.call(this),Fh(this)},es.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var za=u.JSON.stringify,Tv=u.JSON.parse,Ev=class{stringify(o){return u.JSON.stringify(o,void 0)}parse(o){return u.JSON.parse(o,void 0)}};function Ga(){}Ga.prototype.h=null;function jh(o){return o.h||(o.h=o.i())}function Uh(){}var ts={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function Ka(){Ee.call(this,"d")}P(Ka,Ee);function Ha(){Ee.call(this,"c")}P(Ha,Ee);var ar={},Bh=null;function Ei(){return Bh=Bh||new Ie}ar.La="serverreachability";function $h(o){Ee.call(this,ar.La,o)}P($h,Ee);function rs(o){let l=Ei();Ce(l,new $h(l))}ar.STAT_EVENT="statevent";function qh(o,l){Ee.call(this,ar.STAT_EVENT,o),this.stat=l}P(qh,Ee);function ke(o){let l=Ei();Ce(l,new qh(l,o))}ar.Ma="timingevent";function zh(o,l){Ee.call(this,ar.Ma,o),this.size=l}P(zh,Ee);function ns(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 ss(){this.g=!0}ss.prototype.xa=function(){this.g=!1};function Iv(o,l,d,p,x,S){o.info(function(){if(o.g)if(S)for(var O="",te=S.split("&"),we=0;we<te.length;we++){var X=te[we].split("=");if(1<X.length){var xe=X[0];X=X[1];var Ae=xe.split("_");O=2<=Ae.length&&Ae[1]=="type"?O+(xe+"="+X+"&"):O+(xe+"=redacted&")}}else O=null;else O=S;return"XMLHTTP REQ ("+p+") [attempt "+x+"]: "+l+`
|
|
2
2
|
`+d+`
|
|
3
|
-
`+O})}function
|
|
3
|
+
`+O})}function xv(o,l,d,p,x,S,O){o.info(function(){return"XMLHTTP RESP ("+p+") [ attempt "+x+"]: "+l+`
|
|
4
4
|
`+d+`
|
|
5
|
-
`+S+" "+O})}function
|
|
6
|
-
`,d);return p==-1?Ha:(d=Number(l.substring(d,p)),isNaN(d)?Bh:(p+=1,p+d>l.length?Ha:(l=l.slice(p,p+d),o.C=p+d,l)))}Dt.prototype.cancel=function(){this.J=!0,ar(this)};function Ii(o){o.S=Date.now()+o.I,zh(o,o.I)}function zh(o,l){if(o.B!=null)throw Error("WatchDog timer not null");o.B=ts(g(o.ba,o),l)}function Qa(o){o.B&&(u.clearTimeout(o.B),o.B=null)}Dt.prototype.ba=function(){this.B=null;let o=Date.now();0<=o-this.S?(pv(this.i,this.A),this.L!=2&&(es(),ke(17)),ar(this),this.s=2,ns(this)):zh(this,this.S-o)};function ns(o){o.j.G==0||o.J||gd(o.j,o)}function ar(o){Qa(o);var l=o.M;l&&typeof l.ma=="function"&&l.ma(),o.M=null,Dh(o.U),o.g&&(l=o.g,o.g=null,l.abort(),l.ma())}function Ja(o,l){try{var d=o.j;if(d.G!=0&&(d.g==o||Ya(d.h,o))){if(!o.K&&Ya(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)Di(d),Ci(d);else break e;tu(d),ke(18)}}else d.za=A[1],0<d.za-d.T&&37500>A[2]&&d.F&&d.v==0&&!d.C&&(d.C=ts(g(d.Za,d),6e3));if(1>=Hh(d.h)&&d.ca){try{d.ca()}catch{}d.ca=void 0}}else cr(d,11)}else if((o.K||d.g==o)&&Di(d),!M(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 Ae=X[3];Ae!=null&&(d.la=Ae,d.j.info("VER="+d.la));let xe=X[4];xe!=null&&(d.Aa=xe,d.j.info("SVER="+d.Aa));let Ur=X[5];Ur!=null&&typeof Ur=="number"&&0<Ur&&(p=1.5*Ur,d.L=p,d.j.info("backChannelRequestTimeoutMs_="+p)),p=d;let Ge=o.g;if(Ge){let Ni=Ge.g?Ge.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(Ni){var S=p.h;S.g||Ni.indexOf("spdy")==-1&&Ni.indexOf("quic")==-1&&Ni.indexOf("h2")==-1||(S.j=S.l,S.g=new Set,S.h&&(Xa(S,S.h),S.h=null))}if(p.D){let nu=Ge.g?Ge.g.getResponseHeader("X-HTTP-Session-Id"):null;nu&&(p.ya=nu,ie(p.I,p.D,nu))}}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=vd(p,p.J?p.ia:null,p.W),O.K){Wh(p.h,O);var te=O,we=p.L;we&&(te.I=we),te.B&&(Qa(te),Ii(te)),p.g=O}else pd(p);0<d.i.length&&ki(d)}else X[0]!="stop"&&X[0]!="close"||cr(d,7);else d.G==3&&(X[0]=="stop"||X[0]=="close"?X[0]=="stop"?cr(d,7):eu(d):X[0]!="noop"&&d.l&&d.l.ta(X),d.v=0)}}es(4)}catch{}}var yv=class{constructor(o,l){this.g=o,this.map=l}};function Gh(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 Kh(o){return o.h?!0:o.g?o.g.size>=o.j:!1}function Hh(o){return o.h?1:o.g?o.g.size:0}function Ya(o,l){return o.h?o.h==l:o.g?o.g.has(l):!1}function Xa(o,l){o.g?o.g.add(l):o.h=l}function Wh(o,l){o.h&&o.h==l?o.h=null:o.g&&o.g.has(l)&&o.g.delete(l)}Gh.prototype.cancel=function(){if(this.i=Qh(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 Qh(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 _v(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 vv(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 Jh(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=vv(o),p=_v(o),A=p.length,S=0;S<A;S++)l.call(void 0,p[S],d&&d[S],o)}var Yh=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function wv(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 ur(o){if(this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,o instanceof ur){this.h=o.h,Ai(this,o.j),this.o=o.o,this.g=o.g,xi(this,o.s),this.l=o.l;var l=o.i,d=new os;d.i=l.i,l.g&&(d.g=new Map(l.g),d.h=l.h),Xh(this,d),this.m=o.m}else o&&(l=String(o).match(Yh))?(this.h=!1,Ai(this,l[1]||"",!0),this.o=ss(l[2]||""),this.g=ss(l[3]||"",!0),xi(this,l[4]),this.l=ss(l[5]||"",!0),Xh(this,l[6]||"",!0),this.m=ss(l[7]||"")):(this.h=!1,this.i=new os(null,this.h))}ur.prototype.toString=function(){var o=[],l=this.j;l&&o.push(is(l,Zh,!0),":");var d=this.g;return(d||l=="file")&&(o.push("//"),(l=this.o)&&o.push(is(l,Zh,!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(is(d,d.charAt(0)=="/"?Ev:Tv,!0))),(d=this.i.toString())&&o.push("?",d),(d=this.m)&&o.push("#",is(d,Av)),o.join("")};function dt(o){return new ur(o)}function Ai(o,l,d){o.j=d?ss(l,!0):l,o.j&&(o.j=o.j.replace(/:$/,""))}function xi(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 Xh(o,l,d){l instanceof os?(o.i=l,xv(o.i,o.h)):(d||(l=is(l,Iv)),o.i=new os(l,o.h))}function ie(o,l,d){o.i.set(l,d)}function Si(o){return ie(o,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),o}function ss(o,l){return o?l?decodeURI(o.replace(/%25/g,"%2525")):decodeURIComponent(o):""}function is(o,l,d){return typeof o=="string"?(o=encodeURI(o).replace(l,bv),d&&(o=o.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),o):null}function bv(o){return o=o.charCodeAt(0),"%"+(o>>4&15).toString(16)+(o&15).toString(16)}var Zh=/[#\/\?@]/g,Tv=/[#\?:]/g,Ev=/[#\?]/g,Iv=/[#\?@]/g,Av=/#/g;function os(o,l){this.h=this.g=null,this.i=o||null,this.j=!!l}function Ot(o){o.g||(o.g=new Map,o.h=0,o.i&&wv(o.i,function(l,d){o.add(decodeURIComponent(l.replace(/\+/g," ")),d)}))}r=os.prototype,r.add=function(o,l){Ot(this),this.i=null,o=Fr(this,o);var d=this.g.get(o);return d||this.g.set(o,d=[]),d.push(l),this.h+=1,this};function ed(o,l){Ot(o),l=Fr(o,l),o.g.has(l)&&(o.i=null,o.h-=o.g.get(l).length,o.g.delete(l))}function td(o,l){return Ot(o),l=Fr(o,l),o.g.has(l)}r.forEach=function(o,l){Ot(this),this.g.forEach(function(d,p){d.forEach(function(A){o.call(l,A,p,this)},this)},this)},r.na=function(){Ot(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){Ot(this);let l=[];if(typeof o=="string")td(this,o)&&(l=l.concat(this.g.get(Fr(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 Ot(this),this.i=null,o=Fr(this,o),td(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 rd(o,l,d){ed(o,l),0<d.length&&(o.i=null,o.g.set(Fr(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 Fr(o,l){return l=String(l),o.j&&(l=l.toLowerCase()),l}function xv(o,l){l&&!o.j&&(Ot(o),o.i=null,o.g.forEach(function(d,p){var A=p.toLowerCase();p!=A&&(ed(this,p),rd(this,A,d))},o)),o.j=l}function Sv(o,l){let d=new rs;if(u.Image){let p=new Image;p.onload=E(Nt,d,"TestLoadImage: loaded",!0,l,p),p.onerror=E(Nt,d,"TestLoadImage: error",!1,l,p),p.onabort=E(Nt,d,"TestLoadImage: abort",!1,l,p),p.ontimeout=E(Nt,d,"TestLoadImage: timeout",!1,l,p),u.setTimeout(function(){p.ontimeout&&p.ontimeout()},1e4),p.src=o}else l(!1)}function Rv(o,l){let d=new rs,p=new AbortController,A=setTimeout(()=>{p.abort(),Nt(d,"TestPingServer: timeout",!1,l)},1e4);fetch(o,{signal:p.signal}).then(S=>{clearTimeout(A),S.ok?Nt(d,"TestPingServer: ok",!0,l):Nt(d,"TestPingServer: server error",!1,l)}).catch(()=>{clearTimeout(A),Nt(d,"TestPingServer: error",!1,l)})}function Nt(o,l,d,p,A){try{A&&(A.onload=null,A.onerror=null,A.onabort=null,A.ontimeout=null),p(d)}catch{}}function Pv(){this.g=new hv}function Cv(o,l,d){let p=d||"";try{Jh(o,function(A,S){let O=A;h(A)&&(O=$a(A)),l.push(p+S+"="+encodeURIComponent(O))})}catch(A){throw l.push(p+"type="+encodeURIComponent("_badmap")),A}}function as(o){this.l=o.Ub||null,this.j=o.eb||!1}P(as,qa),as.prototype.g=function(){return new Ri(this.l,this.j)},as.prototype.i=function(o){return function(){return o}}({});function Ri(o,l){Ie.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(Ri,Ie),r=Ri.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,cs(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,us(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,cs(this)),this.g&&(this.readyState=3,cs(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;nd(this)}else o.text().then(this.Ra.bind(this),this.ga.bind(this))};function nd(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?us(this):cs(this),this.readyState==3&&nd(this)}},r.Ra=function(o){this.g&&(this.response=this.responseText=o,us(this))},r.Qa=function(o){this.g&&(this.response=o,us(this))},r.ga=function(){this.g&&us(this)};function us(o){o.readyState=4,o.l=null,o.j=null,o.v=null,cs(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
|
|
8
|
-
`}),l}function
|
|
9
|
-
`);for(let p=0;p<o.length;p++){if(M(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)}T(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 ls(o,l,d){return d&&d.internalChannelParams&&d.internalChannelParams[o]||l}function ld(o){this.Aa=0,this.i=[],this.j=new rs,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=ls("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=ls("baseRetryDelayMs",5e3,o),this.cb=ls("retryDelaySeedMs",1e4,o),this.Wa=ls("forwardChannelMaxRetries",2,o),this.wa=ls("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 Gh(o&&o.concurrentRequestLimit),this.Da=new Pv,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=ld.prototype,r.la=8,r.G=1,r.connect=function(o,l,d,p){ke(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=vd(this,null,this.W),ki(this)};function eu(o){if(hd(o),o.G==3){var l=o.U++,d=dt(o.I);if(ie(d,"SID",o.K),ie(d,"RID",l),ie(d,"TYPE","terminate"),hs(o,d),l=new Dt(o,o.j,l),l.L=2,l.v=Si(dt(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=wd(l.j,null),l.g.ea(l.v)),l.F=Date.now(),Ii(l)}_d(o)}function Ci(o){o.g&&(ru(o),o.g.cancel(),o.g=null)}function hd(o){Ci(o),o.u&&(u.clearTimeout(o.u),o.u=null),Di(o),o.h.cancel(),o.s&&(typeof o.s=="number"&&u.clearTimeout(o.s),o.s=null)}function ki(o){if(!Kh(o.h)&&!o.s){o.s=!0;var l=o.Ga;Wn||Eh(),Qn||(Wn(),Qn=!0),Oa.add(l,o),o.B=0}}function Nv(o,l){return Hh(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=ts(g(o.Ga,o,l),yd(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 Dt(this,this.j,o),S=this.o;if(this.S&&(S?(S=y(S),b(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=fd(this,A,l),d=dt(this.I),ie(d,"RID",o),ie(d,"CVER",22),this.D&&ie(d,"X-HTTP-Session-Id",this.D),hs(this,d),S&&(this.O?l="headers="+encodeURIComponent(String(sd(S)))+"&"+l:this.m&&Za(d,this.m,S)),Xa(this.h,A),this.Ua&&ie(d,"TYPE","init"),this.P?(ie(d,"$req",l),ie(d,"SID","null"),A.T=!0,Wa(A,d,null)):Wa(A,d,l),this.G=2}}else this.G==3&&(o?dd(this,o):this.i.length==0||Kh(this.h)||dd(this))};function dd(o,l){var d;l?d=l.l:d=o.U++;let p=dt(o.I);ie(p,"SID",o.K),ie(p,"RID",d),ie(p,"AID",o.T),hs(o,p),o.m&&o.o&&Za(p,o.m,o.o),d=new Dt(o,o.j,d,o.B+1),o.m===null&&(d.H=o.o),l&&(o.i=l.D.concat(o.i)),l=fd(o,d,1e3),d.I=Math.round(.5*o.wa)+Math.round(.5*o.wa*Math.random()),Xa(o.h,d),Wa(d,p,l)}function hs(o,l){o.H&&B(o.H,function(d,p){ie(l,p,d)}),o.l&&Jh({},function(d,p){ie(l,p,d)})}function fd(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 we=0;we<d;we++){let X=A[we].g,Ae=A[we].map;if(X-=S,0>X)S=Math.max(0,A[we].g-100),te=!1;else try{Cv(Ae,O,"req"+X+"_")}catch{p&&p(Ae)}}if(te){p=O.join("&");break e}}}return o=o.i.splice(0,d),l.D=o,p}function pd(o){if(!o.g&&!o.u){o.Y=1;var l=o.Fa;Wn||Eh(),Qn||(Wn(),Qn=!0),Oa.add(l,o),o.v=0}}function tu(o){return o.g||o.u||3<=o.v?!1:(o.Y++,o.u=ts(g(o.Fa,o),yd(o,o.v)),o.v++,!0)}r.Fa=function(){if(this.u=null,md(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=ts(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,ke(10),Ci(this),md(this))};function ru(o){o.A!=null&&(u.clearTimeout(o.A),o.A=null)}function md(o){o.g=new Dt(o,o.j,"rpc",o.Y),o.m===null&&(o.g.H=o.o),o.g.O=0;var l=dt(o.qa);ie(l,"RID","rpc"),ie(l,"SID",o.K),ie(l,"AID",o.T),ie(l,"CI",o.F?"0":"1"),!o.F&&o.ja&&ie(l,"TO",o.ja),ie(l,"TYPE","xmlhttp"),hs(o,l),o.m&&o.o&&Za(l,o.m,o.o),o.L&&(o.g.I=o.L);var d=o.g;o=o.ia,d.L=1,d.v=Si(dt(l)),d.m=null,d.P=!0,$h(d,o)}r.Za=function(){this.C!=null&&(this.C=null,Ci(this),tu(this),ke(19))};function Di(o){o.C!=null&&(u.clearTimeout(o.C),o.C=null)}function gd(o,l){var d=null;if(o.g==l){Di(o),ru(o),o.g=null;var p=2}else if(Ya(o.h,l))d=l.D,Wh(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=bi(),Ce(p,new Fh(p,d)),ki(o)}else pd(o);else if(A=l.s,A==3||A==0&&0<l.X||!(p==1&&Nv(o,l)||p==2&&tu(o)))switch(d&&0<d.length&&(l=o.h,l.i=l.i.concat(d)),A){case 1:cr(o,5);break;case 4:cr(o,10);break;case 3:cr(o,6);break;default:cr(o,2)}}}function yd(o,l){let d=o.Ta+Math.floor(Math.random()*o.cb);return o.isActive()||(d*=2),d*l}function cr(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 ur(p||"//www.google.com/images/cleardot.gif"),u.location&&u.location.protocol=="http"||Ai(p,"https"),Si(p),A?Sv(p.toString(),d):Rv(p.toString(),d)}else ke(2);o.G=0,o.l&&o.l.sa(l),_d(o),hd(o)}r.fb=function(o){o?(this.j.info("Successfully pinged google.com"),ke(2)):(this.j.info("Failed to ping google.com"),ke(1))};function _d(o){if(o.G=0,o.ka=[],o.l){let l=Qh(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 vd(o,l,d){var p=d instanceof ur?dt(d):new ur(d);if(p.g!="")l&&(p.g=l+"."+p.g),xi(p,p.s);else{var A=u.location;p=A.protocol,l=l?l+"."+A.hostname:A.hostname,A=+A.port;var S=new ur(null);p&&Ai(S,p),l&&(S.g=l),A&&xi(S,A),d&&(S.l=d),p=S}return d=o.D,l=o.ya,d&&l&&ie(p,d,l),ie(p,"VER",o.la),hs(o,p),p}function wd(o,l,d){if(l&&!o.J)throw Error("Can't create secondary domain capable XhrIo object.");return l=o.Ca&&!o.pa?new ue(new as({eb:d})):new ue(o.pa),l.Ha(o.J),l}r.isActive=function(){return!!this.l&&this.l.isActive(this)};function bd(){}r=bd.prototype,r.ua=function(){},r.ta=function(){},r.sa=function(){},r.ra=function(){},r.isActive=function(){return!0},r.Na=function(){};function Oi(){}Oi.prototype.g=function(o,l){return new Fe(o,l)};function Fe(o,l){Ie.call(this),this.g=new ld(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)&&!M(o)&&(this.g.m=o),this.v=l&&l.supportsCrossDomainXhr||!1,this.u=l&&l.sendRawJson||!1,(l=l&&l.httpSessionIdParam)&&!M(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 jr(this)}P(Fe,Ie),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(){eu(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__=$a(o),o=d);l.i.push(new yv(l.Ya++,o)),l.G==3&&ki(l)},Fe.prototype.N=function(){this.g.l=null,delete this.j,eu(this.g),delete this.g,Fe.aa.N.call(this)};function Td(o){za.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(Td,za);function Ed(){Ga.call(this),this.status=1}P(Ed,Ga);function jr(o){this.g=o}P(jr,bd),jr.prototype.ua=function(){Ce(this.g,"a")},jr.prototype.ta=function(o){Ce(this.g,new Td(o))},jr.prototype.sa=function(o){Ce(this.g,new Ed)},jr.prototype.ra=function(){Ce(this.g,"b")},Oi.prototype.createWebChannel=Oi.prototype.g,Fe.prototype.send=Fe.prototype.o,Fe.prototype.open=Fe.prototype.m,Fe.prototype.close=Fe.prototype.close,Fu=Et.createWebChannelTransport=function(){return new Oi},Mu=Et.getStatEventTarget=function(){return bi()},Lu=Et.Event=or,lo=Et.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},Ti.NO_ERROR=0,Ti.TIMEOUT=8,Ti.HTTP_ERROR=6,Ts=Et.ErrorCode=Ti,jh.COMPLETE="complete",Vu=Et.EventType=jh,Nh.EventType=Zn,Zn.OPEN="a",Zn.CLOSE="b",Zn.ERROR="c",Zn.MESSAGE="d",Ie.prototype.listen=Ie.prototype.K,an=Et.WebChannel=Nh,Ix=Et.FetchXmlHttpFactory=as,ue.prototype.listenOnce=ue.prototype.L,ue.prototype.getLastError=ue.prototype.Ka,ue.prototype.getLastErrorCode=ue.prototype.Ba,ue.prototype.getStatus=ue.prototype.Z,ue.prototype.getResponseJson=ue.prototype.Oa,ue.prototype.getResponseText=ue.prototype.oa,ue.prototype.send=ue.prototype.ea,ue.prototype.setWithCredentials=ue.prototype.Ha,Nu=Et.XhrIo=ue}).apply(typeof co!="undefined"?co:typeof self!="undefined"?self:typeof window!="undefined"?window:{});var Rm="@firebase/firestore",Pm="4.7.8";var _e=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}};_e.UNAUTHENTICATED=new _e(null),_e.GOOGLE_CREDENTIALS=new _e("google-credentials-uid"),_e.FIRST_PARTY=new _e("first-party-uid"),_e.MOCK_USER=new _e("mock-user");var kn="11.3.1";var gr=new on("@firebase/firestore");function un(){return gr.logLevel}function V(r,...e){if(gr.logLevel<=W.DEBUG){let t=e.map(Il);gr.debug(`Firestore (${kn}): ${r}`,...t)}}function It(r,...e){if(gr.logLevel<=W.ERROR){let t=e.map(Il);gr.error(`Firestore (${kn}): ${r}`,...t)}}function mn(r,...e){if(gr.logLevel<=W.WARN){let t=e.map(Il);gr.warn(`Firestore (${kn}): ${r}`,...t)}}function Il(r){if(typeof r=="string")return r;try{return function(t){return JSON.stringify(t)}(r)}catch{return r}}function F(r="Unexpected state"){let e=`FIRESTORE (${kn}) INTERNAL ASSERTION FAILED: `+r;throw It(e),new Error(e)}function ee(r,e){r||F()}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 _t{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}};var et=class{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}};var _o=class{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}},qu=class{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(_e.UNAUTHENTICATED))}shutdown(){}},zu=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}},Gu=class{constructor(e){this.t=e,this.currentUser=_e.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 et;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new et,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 et)}},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 _o(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 _e(e)}},Ku=class{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=_e.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}},Hu=class{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new Ku(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(_e.FIRST_PARTY))}shutdown(){}invalidateToken(){}},vo=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)}},Wu=class{constructor(e,t){this.A=t,this.forceRefresh=!1,this.appCheck=null,this.R=null,this.V=null,bm(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 vo(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 vo(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 Ax(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}var wo=class{static newId(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(4.129032258064516),n="";for(;n.length<20;){let s=Ax(40);for(let i=0;i<s.length;++i)n.length<20&&s[i]<t&&(n+=e.charAt(s[i]%62))}return n}};function Q(r,e){return r<e?-1:r>e?1:0}function gn(r,e,t){return r.length===e.length&&r.every((n,s)=>t(n,e[s]))}var Cm=-62135596800,km=1e6,be=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)*km);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<Cm)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/km}_compareTo(e){return this.seconds===e.seconds?Q(this.nanoseconds,e.nanoseconds):Q(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-Cm;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 be(0,0))}static max(){return new r(new be(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 Dm="__name__",bo=class r{constructor(e,t,n){t===void 0?t=0:t>e.length&&F(),n===void 0?n=e.length-t:n>e.length-t&&F(),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 Math.sign(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)):e<t?-1:e>t?1:0}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return Tt.fromString(e.substring(4,e.length-2))}},me=class r extends bo{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([])}},xx=/^[_a-zA-Z][_a-zA-Z0-9]*$/,Ue=class r extends bo{construct(e,t,n){return new r(e,t,n)}static isValidIdentifier(e){return xx.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)===Dm}static keyField(){return new r([Dm])}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(me.fromString(e))}static fromName(e){return new r(me.fromString(e).popFirst(5))}static empty(){return new r(me.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&&me.comparator(this.path,e.path)===0}toString(){return this.path.toString()}static comparator(e,t){return me.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new r(new me(e.slice()))}};var Rs=-1,Qu=class{constructor(e,t,n,s){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=s}};Qu.UNKNOWN_ID=-1;function Sx(r,e){let t=r.toTimestamp().seconds,n=r.toTimestamp().nanoseconds+1,s=q.fromTimestamp(n===1e9?new be(t+1,0):new be(t,n));return new yr(s,j.empty(),e)}function Rx(r){return new yr(r.readTime,r.key,Rs)}var yr=class r{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new r(q.min(),j.empty(),Rs)}static max(){return new r(q.max(),j.empty(),Rs)}};function Px(r,e){let t=r.readTime.compareTo(e.readTime);return t!==0?t:(t=j.comparator(r.documentKey,e.documentKey),t!==0?t:Q(r.largestBatchId,e.largestBatchId))}var Cx="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",Ju=class{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}};async function Dn(r){if(r.code!==D.FAILED_PRECONDITION||r.message!==Cx)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&&F(),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 kx(r){let e=r.match(/Android ([\d.]+)/i),t=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(t)}function On(r){return r.name==="IndexedDbTransactionError"}var yn=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}};yn.ae=-1;var Al=-1;function ra(r){return r==null}function Ps(r){return r===0&&1/r==-1/0}function Dx(r){return typeof r=="number"&&Number.isInteger(r)&&!Ps(r)&&r<=Number.MAX_SAFE_INTEGER&&r>=Number.MIN_SAFE_INTEGER}var mg="";function Ox(r){let e="";for(let t=0;t<r.length;t++)e.length>0&&(e=Om(e)),e=Nx(r.get(t),e);return Om(e)}function Nx(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 mg:t+="";break;default:t+=i}}return t}function Om(r){return r+mg+""}var Vx="remoteDocuments",gg="owner";var yg="mutationQueues";var _g="mutations";var vg="documentMutations",Lx="remoteDocumentsV14";var wg="remoteDocumentGlobal";var bg="targets";var Tg="targetDocuments";var Eg="targetGlobal",Ig="collectionParents";var Ag="clientMetadata";var xg="bundles";var Sg="namedQueries";var Mx="indexConfiguration";var Fx="indexState";var jx="indexEntries";var Rg="documentOverlays";var Ux="globals";var Bx=[yg,_g,vg,Vx,bg,gg,Eg,Tg,Ag,wg,Ig,xg,Sg],hF=[...Bx,Rg],$x=[yg,_g,vg,Lx,bg,gg,Eg,Tg,Ag,wg,Ig,xg,Sg,Rg],qx=$x,zx=[...qx,Mx,Fx,jx];var dF=[...zx,Ux];function Nm(r){let e=0;for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e++;return e}function tr(r,e){for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e(t,r[t])}function Pg(r){for(let e in r)if(Object.prototype.hasOwnProperty.call(r,e))return!1;return!0}var le=class r{constructor(e,t){this.comparator=e,this.root=t||tt.EMPTY}insert(e,t){return new r(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,tt.BLACK,null,null))}remove(e){return new r(this.comparator,this.root.remove(e,this.comparator).copy(null,null,tt.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 dn(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new dn(this.root,e,this.comparator,!1)}getReverseIterator(){return new dn(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new dn(this.root,e,this.comparator,!0)}},dn=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}}},tt=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 F();let e=this.left.check();if(e!==this.right.check())throw F();return e+(this.isRed()?0:1)}};tt.EMPTY=null,tt.RED=!0,tt.BLACK=!1;tt.EMPTY=new class{constructor(){this.size=0}get key(){throw F()}get value(){throw F()}get color(){throw F()}get left(){throw F()}get right(){throw F()}copy(e,t,n,s,i){return this}insert(e,t,n){return new tt(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 ve=class r{constructor(e){this.comparator=e,this.data=new le(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 To(this.data.getIterator())}getIteratorFrom(e){return new To(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}},To=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 ve(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 gn(this.fields,e.fields,(t,n)=>t.isEqual(n))}};var Eo=class extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}};var Pe=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 Eo("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 Q(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}};Pe.EMPTY_BYTE_STRING=new Pe("");var Gx=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function At(r){if(ee(!!r),typeof r=="string"){let e=0,t=Gx.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:ae(r.seconds),nanos:ae(r.nanos)}}function ae(r){return typeof r=="number"?r:typeof r=="string"?Number(r):0}function xt(r){return typeof r=="string"?Pe.fromBase64String(r):Pe.fromUint8Array(r)}var Cg="server_timestamp",kg="__type__",Dg="__previous_value__",Og="__local_write_time__";function xl(r){var e,t;return((t=(((e=r==null?void 0:r.mapValue)===null||e===void 0?void 0:e.fields)||{})[kg])===null||t===void 0?void 0:t.stringValue)===Cg}function na(r){let e=r.mapValue.fields[Dg];return xl(e)?na(e):e}function Cs(r){let e=At(r.mapValue.fields[Og].timestampValue);return new be(e.seconds,e.nanos)}var Yu=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}},Io="(default)",Ao=class r{constructor(e,t){this.projectId=e,this.database=t||Io}static empty(){return new r("","")}get isDefaultDatabase(){return this.database===Io}isEqual(e){return e instanceof r&&e.projectId===this.projectId&&e.database===this.database}};var Sl="__type__",Ng="__max__",ho={mapValue:{fields:{__type__:{stringValue:Ng}}}},Rl="__vector__",_n="value";function Yt(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?xl(r)?4:Lg(r)?9007199254740991:Vg(r)?10:11:F()}function it(r,e){if(r===e)return!0;let t=Yt(r);if(t!==Yt(e))return!1;switch(t){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===e.booleanValue;case 4:return Cs(r).isEqual(Cs(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=At(s.timestampValue),u=At(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 xt(s.bytesValue).isEqual(xt(i.bytesValue))}(r,e);case 7:return r.referenceValue===e.referenceValue;case 8:return function(s,i){return ae(s.geoPointValue.latitude)===ae(i.geoPointValue.latitude)&&ae(s.geoPointValue.longitude)===ae(i.geoPointValue.longitude)}(r,e);case 2:return function(s,i){if("integerValue"in s&&"integerValue"in i)return ae(s.integerValue)===ae(i.integerValue);if("doubleValue"in s&&"doubleValue"in i){let a=ae(s.doubleValue),u=ae(i.doubleValue);return a===u?Ps(a)===Ps(u):isNaN(a)&&isNaN(u)}return!1}(r,e);case 9:return gn(r.arrayValue.values||[],e.arrayValue.values||[],it);case 10:case 11:return function(s,i){let a=s.mapValue.fields||{},u=i.mapValue.fields||{};if(Nm(a)!==Nm(u))return!1;for(let c in a)if(a.hasOwnProperty(c)&&(u[c]===void 0||!it(a[c],u[c])))return!1;return!0}(r,e);default:return F()}}function ks(r,e){return(r.values||[]).find(t=>it(t,e))!==void 0}function vn(r,e){if(r===e)return 0;let t=Yt(r),n=Yt(e);if(t!==n)return Q(t,n);switch(t){case 0:case 9007199254740991:return 0;case 1:return Q(r.booleanValue,e.booleanValue);case 2:return function(i,a){let u=ae(i.integerValue||i.doubleValue),c=ae(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 Vm(r.timestampValue,e.timestampValue);case 4:return Vm(Cs(r),Cs(e));case 5:return Q(r.stringValue,e.stringValue);case 6:return function(i,a){let u=xt(i),c=xt(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=Q(u[h],c[h]);if(f!==0)return f}return Q(u.length,c.length)}(r.referenceValue,e.referenceValue);case 8:return function(i,a){let u=Q(ae(i.latitude),ae(a.latitude));return u!==0?u:Q(ae(i.longitude),ae(a.longitude))}(r.geoPointValue,e.geoPointValue);case 9:return Lm(r.arrayValue,e.arrayValue);case 10:return function(i,a){var u,c,h,f;let m=i.fields||{},g=a.fields||{},E=(u=m[_n])===null||u===void 0?void 0:u.arrayValue,P=(c=g[_n])===null||c===void 0?void 0:c.arrayValue,C=Q(((h=E==null?void 0:E.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:Lm(E,P)}(r.mapValue,e.mapValue);case 11:return function(i,a){if(i===ho.mapValue&&a===ho.mapValue)return 0;if(i===ho.mapValue)return 1;if(a===ho.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=Q(c[m],f[m]);if(g!==0)return g;let E=vn(u[c[m]],h[f[m]]);if(E!==0)return E}return Q(c.length,f.length)}(r.mapValue,e.mapValue);default:throw F()}}function Vm(r,e){if(typeof r=="string"&&typeof e=="string"&&r.length===e.length)return Q(r,e);let t=At(r),n=At(e),s=Q(t.seconds,n.seconds);return s!==0?s:Q(t.nanos,n.nanos)}function Lm(r,e){let t=r.values||[],n=e.values||[];for(let s=0;s<t.length&&s<n.length;++s){let i=vn(t[s],n[s]);if(i)return i}return Q(t.length,n.length)}function wn(r){return Xu(r)}function Xu(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=At(t);return`time(${n.seconds},${n.nanos})`}(r.timestampValue):"stringValue"in r?r.stringValue:"bytesValue"in r?function(t){return xt(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+=Xu(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}:${Xu(t.fields[a])}`;return s+"}"}(r.mapValue):F()}function mo(r){switch(Yt(r)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let e=na(r);return e?16+mo(e):16;case 5:return 2*r.stringValue.length;case 6:return xt(r.bytesValue).approximateByteSize();case 7:return r.referenceValue.length;case 9:return function(n){return(n.values||[]).reduce((s,i)=>s+mo(i),0)}(r.arrayValue);case 10:case 11:return function(n){let s=0;return tr(n.fields,(i,a)=>{s+=i.length+mo(a)}),s}(r.mapValue);default:throw F()}}function Zu(r){return!!r&&"integerValue"in r}function Pl(r){return!!r&&"arrayValue"in r}function Mm(r){return!!r&&"nullValue"in r}function Fm(r){return!!r&&"doubleValue"in r&&isNaN(Number(r.doubleValue))}function go(r){return!!r&&"mapValue"in r}function Vg(r){var e,t;return((t=(((e=r==null?void 0:r.mapValue)===null||e===void 0?void 0:e.fields)||{})[Sl])===null||t===void 0?void 0:t.stringValue)===Rl}function Is(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 tr(r.mapValue.fields,(t,n)=>e.mapValue.fields[t]=Is(n)),e}if(r.arrayValue){let e={arrayValue:{values:[]}};for(let t=0;t<(r.arrayValue.values||[]).length;++t)e.arrayValue.values[t]=Is(r.arrayValue.values[t]);return e}return Object.assign({},r)}function Lg(r){return(((r.mapValue||{}).fields||{}).__type__||{}).stringValue===Ng}var pF={mapValue:{fields:{[Sl]:{stringValue:Rl},[_n]:{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)],!go(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Is(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()]=Is(a):s.push(u.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,n,s)}delete(e){let t=this.field(e.popLast());go(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return it(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)];go(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=s),t=s}return t.mapValue.fields}applyChanges(e,t,n){tr(t,(s,i)=>e[s]=i);for(let s of n)delete e[s]}clone(){return new r(Is(this.value))}};function Mg(r){let e=[];return tr(r.fields,(t,n)=>{let s=new Ue([t]);if(go(n)){let i=Mg(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 We=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 bn=class{constructor(e,t){this.position=e,this.inclusive=t}};function jm(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=vn(a,t.data.field(i.field)),i.dir==="desc"&&(n*=-1),n!==0)break}return n}function Um(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(!it(r.position[t],e.position[t]))return!1;return!0}var Tn=class{constructor(e,t="asc"){this.field=e,this.dir=t}};function Kx(r,e){return r.dir===e.dir&&r.field.isEqual(e.field)}var xo=class{},ye=class r extends xo{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 tc(e,t,n):t==="array-contains"?new sc(e,n):t==="in"?new ic(e,n):t==="not-in"?new oc(e,n):t==="array-contains-any"?new ac(e,n):new r(e,t,n)}static createKeyFieldInFilter(e,t,n){return t==="in"?new rc(e,n):new nc(e,n)}matches(e){let t=e.data.field(this.field);return this.op==="!="?t!==null&&this.matchesComparison(vn(t,this.value)):t!==null&&Yt(this.value)===Yt(t)&&this.matchesComparison(vn(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 F()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}},ot=class r extends xo{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 Fg(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 Fg(r){return r.op==="and"}function jg(r){return Hx(r)&&Fg(r)}function Hx(r){for(let e of r.filters)if(e instanceof ot)return!1;return!0}function ec(r){if(r instanceof ye)return r.field.canonicalString()+r.op.toString()+wn(r.value);if(jg(r))return r.filters.map(e=>ec(e)).join(",");{let e=r.filters.map(t=>ec(t)).join(",");return`${r.op}(${e})`}}function Ug(r,e){return r instanceof ye?function(n,s){return s instanceof ye&&n.op===s.op&&n.field.isEqual(s.field)&&it(n.value,s.value)}(r,e):r instanceof ot?function(n,s){return s instanceof ot&&n.op===s.op&&n.filters.length===s.filters.length?n.filters.reduce((i,a,u)=>i&&Ug(a,s.filters[u]),!0):!1}(r,e):void F()}function Bg(r){return r instanceof ye?function(t){return`${t.field.canonicalString()} ${t.op} ${wn(t.value)}`}(r):r instanceof ot?function(t){return t.op.toString()+" {"+t.getFilters().map(Bg).join(" ,")+"}"}(r):"Filter"}var tc=class extends ye{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)}},rc=class extends ye{constructor(e,t){super(e,"in",t),this.keys=$g("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}},nc=class extends ye{constructor(e,t){super(e,"not-in",t),this.keys=$g("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}};function $g(r,e){var t;return(((t=e.arrayValue)===null||t===void 0?void 0:t.values)||[]).map(n=>j.fromName(n.referenceValue))}var sc=class extends ye{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return Pl(t)&&ks(t.arrayValue,this.value)}},ic=class extends ye{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return t!==null&&ks(this.value.arrayValue,t)}},oc=class extends ye{constructor(e,t){super(e,"not-in",t)}matches(e){if(ks(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return t!==null&&!ks(this.value.arrayValue,t)}},ac=class extends ye{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!Pl(t)||!t.arrayValue.values)&&t.arrayValue.values.some(n=>ks(this.value.arrayValue,n))}};var uc=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 Bm(r,e=null,t=[],n=[],s=null,i=null,a=null){return new uc(r,e,t,n,s,i,a)}function Cl(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=>ec(n)).join(","),t+="|ob:",t+=e.orderBy.map(n=>function(i){return i.field.canonicalString()+i.dir}(n)).join(","),ra(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(n=>wn(n)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(n=>wn(n)).join(",")),e.le=t}return e.le}function kl(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(!Kx(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(!Ug(r.filters[t],e.filters[t]))return!1;return r.collectionGroup===e.collectionGroup&&!!r.path.isEqual(e.path)&&!!Um(r.startAt,e.startAt)&&Um(r.endAt,e.endAt)}function cc(r){return j.isDocumentKey(r.path)&&r.collectionGroup===null&&r.filters.length===0}var En=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 Wx(r,e,t,n,s,i,a,u){return new En(r,e,t,n,s,i,a,u)}function sa(r){return new En(r)}function $m(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 Qx(r){return r.collectionGroup!==null}function As(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 ve(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 Tn(i,n))}),t.has(Ue.keyField().canonicalString())||e.he.push(new Tn(Ue.keyField(),n))}return e.he}function rt(r){let e=$(r);return e.Pe||(e.Pe=Jx(e,As(r))),e.Pe}function Jx(r,e){if(r.limitType==="F")return Bm(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 Tn(s.field,i)});let t=r.endAt?new bn(r.endAt.position,r.endAt.inclusive):null,n=r.startAt?new bn(r.startAt.position,r.startAt.inclusive):null;return Bm(r.path,r.collectionGroup,e,r.filters,r.limit,t,n)}}function lc(r,e,t){return new En(r.path,r.collectionGroup,r.explicitOrderBy.slice(),r.filters.slice(),e,t,r.startAt,r.endAt)}function ia(r,e){return kl(rt(r),rt(e))&&r.limitType===e.limitType}function qg(r){return`${Cl(rt(r))}|lt:${r.limitType}`}function cn(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=>Bg(s)).join(", ")}]`),ra(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=>wn(s)).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(s=>wn(s)).join(",")),`Target(${n})`}(rt(r))}; limitType=${r.limitType})`}function oa(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 As(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=jm(a,u,c);return a.inclusive?h<=0:h<0}(n.startAt,As(n),s)||n.endAt&&!function(a,u,c){let h=jm(a,u,c);return a.inclusive?h>=0:h>0}(n.endAt,As(n),s))}(r,e)}function Yx(r){return r.collectionGroup||(r.path.length%2==1?r.path.lastSegment():r.path.get(r.path.length-2))}function zg(r){return(e,t)=>{let n=!1;for(let s of As(r)){let i=Xx(s,e,t);if(i!==0)return i;n=n||s.field.isKeyField()}return 0}}function Xx(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?vn(c,h):F()}(r.field,e,t);switch(r.dir){case"asc":return n;case"desc":return-1*n;default:return F()}}var St=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){tr(this.inner,(t,n)=>{for(let[s,i]of n)e(s,i)})}isEmpty(){return Pg(this.inner)}size(){return this.innerSize}};var Zx=new le(j.comparator);function Rt(){return Zx}var Gg=new le(j.comparator);function Es(...r){let e=Gg;for(let t of r)e=e.insert(t.key,t);return e}function Kg(r){let e=Gg;return r.forEach((t,n)=>e=e.insert(t,n.overlayedDocument)),e}function fr(){return xs()}function Hg(){return xs()}function xs(){return new St(r=>r.toString(),(r,e)=>r.isEqual(e))}var eS=new le(j.comparator),tS=new ve(j.comparator);function H(...r){let e=tS;for(let t of r)e=e.add(t);return e}var rS=new ve(Q);function nS(){return rS}function Dl(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:Ps(e)?"-0":e}}function Wg(r){return{integerValue:""+r}}function sS(r,e){return Dx(e)?Wg(e):Dl(r,e)}var In=class{constructor(){this._=void 0}};function iS(r,e,t){return r instanceof An?function(s,i){let a={fields:{[kg]:{stringValue:Cg},[Og]:{timestampValue:{seconds:s.seconds,nanos:s.nanoseconds}}}};return i&&xl(i)&&(i=na(i)),i&&(a.fields[Dg]=i),{mapValue:a}}(t,e):r instanceof _r?Jg(r,e):r instanceof vr?Yg(r,e):function(s,i){let a=Qg(s,i),u=qm(a)+qm(s.Ie);return Zu(a)&&Zu(s.Ie)?Wg(u):Dl(s.serializer,u)}(r,e)}function oS(r,e,t){return r instanceof _r?Jg(r,e):r instanceof vr?Yg(r,e):t}function Qg(r,e){return r instanceof xn?function(n){return Zu(n)||function(i){return!!i&&"doubleValue"in i}(n)}(e)?e:{integerValue:0}:null}var An=class extends In{},_r=class extends In{constructor(e){super(),this.elements=e}};function Jg(r,e){let t=Xg(e);for(let n of r.elements)t.some(s=>it(s,n))||t.push(n);return{arrayValue:{values:t}}}var vr=class extends In{constructor(e){super(),this.elements=e}};function Yg(r,e){let t=Xg(e);for(let n of r.elements)t=t.filter(s=>!it(s,n));return{arrayValue:{values:t}}}var xn=class extends In{constructor(e,t){super(),this.serializer=e,this.Ie=t}};function qm(r){return ae(r.integerValue||r.doubleValue)}function Xg(r){return Pl(r)&&r.arrayValue.values?r.arrayValue.values.slice():[]}function aS(r,e){return r.field.isEqual(e.field)&&function(n,s){return n instanceof _r&&s instanceof _r||n instanceof vr&&s instanceof vr?gn(n.elements,s.elements,it):n instanceof xn&&s instanceof xn?it(n.Ie,s.Ie):n instanceof An&&s instanceof An}(r.transform,e.transform)}var hc=class{constructor(e,t){this.version=e,this.transformResults=t}},Jt=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 yo(r,e){return r.updateTime!==void 0?e.isFoundDocument()&&e.version.isEqual(r.updateTime):r.exists===void 0||r.exists===e.isFoundDocument()}var Sn=class{};function Zg(r,e){if(!r.hasLocalMutations||e&&e.fields.length===0)return null;if(e===null)return r.isNoDocument()?new So(r.key,Jt.none()):new wr(r.key,r.data,Jt.none());{let t=r.data,n=je.empty(),s=new ve(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 at(r.key,n,new qe(s.toArray()),Jt.none())}}function uS(r,e,t){r instanceof wr?function(s,i,a){let u=s.value.clone(),c=Gm(s.fieldTransforms,i,a.transformResults);u.setAll(c),i.convertToFoundDocument(a.version,u).setHasCommittedMutations()}(r,e,t):r instanceof at?function(s,i,a){if(!yo(s.precondition,i))return void i.convertToUnknownDocument(a.version);let u=Gm(s.fieldTransforms,i,a.transformResults),c=i.data;c.setAll(ey(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 Ss(r,e,t,n){return r instanceof wr?function(i,a,u,c){if(!yo(i.precondition,a))return u;let h=i.value.clone(),f=Km(i.fieldTransforms,c,a);return h.setAll(f),a.convertToFoundDocument(a.version,h).setHasLocalMutations(),null}(r,e,t,n):r instanceof at?function(i,a,u,c){if(!yo(i.precondition,a))return u;let h=Km(i.fieldTransforms,c,a),f=a.data;return f.setAll(ey(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 yo(i.precondition,a)?(a.convertToNoDocument(a.version).setHasLocalMutations(),null):u}(r,e,t)}function cS(r,e){let t=null;for(let n of r.fieldTransforms){let s=e.data.field(n.field),i=Qg(n.transform,s||null);i!=null&&(t===null&&(t=je.empty()),t.set(n.field,i))}return t||null}function zm(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)&&gn(n,s,(i,a)=>aS(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 wr=class extends Sn{constructor(e,t,n,s=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}},at=class extends Sn{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 ey(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 Gm(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 Km(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,iS(i,a,e))}return n}var So=class extends Sn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}},dc=class extends Sn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}};var fc=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)&&uS(i,e,n[s])}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=Ss(n,e,t,this.localWriteTime));for(let n of this.mutations)n.key.isEqual(e.key)&&(t=Ss(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let n=Hg();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=Zg(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),H())}isEqual(e){return this.batchId===e.batchId&&gn(this.mutations,e.mutations,(t,n)=>zm(t,n))&&gn(this.baseMutations,e.baseMutations,(t,n)=>zm(t,n))}},pc=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 eS}(),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 mc=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 jr(o,l,d,p){o.info(function(){return"XMLHTTP TEXT ("+l+"): "+Sv(o,d)+(p?" "+p:"")})}function Av(o,l){o.info(function(){return"TIMEOUT: "+l})}ss.prototype.info=function(){};function Sv(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 x=p[1];if(Array.isArray(x)&&!(1>x.length)){var S=x[0];if(S!="noop"&&S!="stop"&&S!="close")for(var O=1;O<x.length;O++)x[O]=""}}}}return za(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},Gh={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"},Wa;function xi(){}P(xi,Ga),xi.prototype.g=function(){return new XMLHttpRequest},xi.prototype.i=function(){return{}},Wa=new xi;function Ot(o,l,d,p){this.j=o,this.i=l,this.l=d,this.R=p||1,this.U=new es(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 Kh}function Kh(){this.i=null,this.g="",this.h=!1}var Hh={},Qa={};function Ja(o,l,d){o.L=1,o.v=Pi(ft(l)),o.m=d,o.P=!0,Wh(o,null)}function Wh(o,l){o.F=Date.now(),Ai(o),o.A=ft(o.v);var d=o.A,p=o.R;Array.isArray(p)||(p=[String(p)]),ud(d.i,"t",p),o.C=0,d=o.j.J,o.h=new Kh,o.g=Ad(o.j,d?l:null,!o.m),0<o.O&&(o.M=new bv(g(o.Y,o,o.g),o.O)),l=o.U,d=o.g,p=o.ca;var x="readystatechange";Array.isArray(x)||(x&&(Mh[0]=x.toString()),x=Mh);for(var S=0;S<x.length;S++){var O=Ch(d,x[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)),rs(),Iv(o.i,o.u,o.A,o.l,o.R,o.m)}Ot.prototype.ca=function(o){o=o.target;let l=this.M;l&&pt(o)==3?l.j():this.Y(o)},Ot.prototype.Y=function(o){try{if(o==this.g)e:{let Ae=pt(this.g);var l=this.g.Ba();let $r=this.g.Z();if(!(3>Ae)&&(Ae!=3||this.g&&(this.h.h||this.g.oa()||md(this.g)))){this.J||Ae!=4||l==7||(l==8||0>=$r?rs(3):rs(2)),Ya(this);var d=this.g.Z();this.X=d;t:if(Qh(this)){var p=md(this.g);o="";var x=p.length,S=pt(this.g)==4;if(!this.h.i){if(typeof TextDecoder=="undefined"){ur(this),is(this);var O="";break t}this.h.i=new u.TextDecoder}for(l=0;l<x;l++)this.h.h=!0,o+=this.h.i.decode(p[l],{stream:!(S&&l==x-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,xv(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,we=this.g;if((te=we.g?we.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!M(te)){var X=te;break t}}X=null}if(d=X)jr(this.i,this.l,d,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Xa(this,d);else{this.o=!1,this.s=3,ke(12),ur(this),is(this);break e}}if(this.P){d=!0;let He;for(;!this.J&&this.C<O.length;)if(He=Rv(this,O),He==Qa){Ae==4&&(this.s=4,ke(14),d=!1),jr(this.i,this.l,null,"[Incomplete Response]");break}else if(He==Hh){this.s=4,ke(15),jr(this.i,this.l,O,"[Invalid Chunk]"),d=!1;break}else jr(this.i,this.l,He,null),Xa(this,He);if(Qh(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,ke(16),d=!1),this.o=this.o&&d,!d)jr(this.i,this.l,O,"[Invalid Chunked Response]"),ur(this),is(this);else if(0<O.length&&!this.W){this.W=!0;var xe=this.j;xe.g==this&&xe.ba&&!xe.M&&(xe.j.info("Great, no buffering proxy detected. Bytes received: "+O.length),su(xe),xe.M=!0,ke(11))}}else jr(this.i,this.l,O,null),Xa(this,O);Ae==4&&ur(this),this.o&&!this.J&&(Ae==4?Td(this.j,this):(this.o=!1,Ai(this)))}else Gv(this.g),d==400&&0<O.indexOf("Unknown SID")?(this.s=3,ke(12)):(this.s=0,ke(13)),ur(this),is(this)}}}catch{}finally{}};function Qh(o){return o.g?o.u=="GET"&&o.L!=2&&o.j.Ca:!1}function Rv(o,l){var d=o.C,p=l.indexOf(`
|
|
6
|
+
`,d);return p==-1?Qa:(d=Number(l.substring(d,p)),isNaN(d)?Hh:(p+=1,p+d>l.length?Qa:(l=l.slice(p,p+d),o.C=p+d,l)))}Ot.prototype.cancel=function(){this.J=!0,ur(this)};function Ai(o){o.S=Date.now()+o.I,Jh(o,o.I)}function Jh(o,l){if(o.B!=null)throw Error("WatchDog timer not null");o.B=ns(g(o.ba,o),l)}function Ya(o){o.B&&(u.clearTimeout(o.B),o.B=null)}Ot.prototype.ba=function(){this.B=null;let o=Date.now();0<=o-this.S?(Av(this.i,this.A),this.L!=2&&(rs(),ke(17)),ur(this),this.s=2,is(this)):Jh(this,this.S-o)};function is(o){o.j.G==0||o.J||Td(o.j,o)}function ur(o){Ya(o);var l=o.M;l&&typeof l.ma=="function"&&l.ma(),o.M=null,Fh(o.U),o.g&&(l=o.g,o.g=null,l.abort(),l.ma())}function Xa(o,l){try{var d=o.j;if(d.G!=0&&(d.g==o||Za(d.h,o))){if(!o.K&&Za(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 x=p;if(x[0]==0){e:if(!d.u){if(d.g)if(d.g.F+3e3<o.F)Ni(d),Di(d);else break e;nu(d),ke(18)}}else d.za=x[1],0<d.za-d.T&&37500>x[2]&&d.F&&d.v==0&&!d.C&&(d.C=ns(g(d.Za,d),6e3));if(1>=Zh(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),!M(l))for(x=d.Da.g.parse(l),l=0;l<x.length;l++){let X=x[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 xe=X[3];xe!=null&&(d.la=xe,d.j.info("VER="+d.la));let Ae=X[4];Ae!=null&&(d.Aa=Ae,d.j.info("SVER="+d.Aa));let $r=X[5];$r!=null&&typeof $r=="number"&&0<$r&&(p=1.5*$r,d.L=p,d.j.info("backChannelRequestTimeoutMs_="+p)),p=d;let He=o.g;if(He){let Li=He.g?He.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&&(eu(S,S.h),S.h=null))}if(p.D){let iu=He.g?He.g.getResponseHeader("X-HTTP-Session-Id"):null;iu&&(p.ya=iu,ie(p.I,p.D,iu))}}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=xd(p,p.J?p.ia:null,p.W),O.K){ed(p.h,O);var te=O,we=p.L;we&&(te.I=we),te.B&&(Ya(te),Ai(te)),p.g=O}else wd(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):ru(d):X[0]!="noop"&&d.l&&d.l.ta(X),d.v=0)}}rs(4)}catch{}}var Pv=class{constructor(o,l){this.g=o,this.map=l}};function Yh(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 Xh(o){return o.h?!0:o.g?o.g.size>=o.j:!1}function Zh(o){return o.h?1:o.g?o.g.size:0}function Za(o,l){return o.h?o.h==l:o.g?o.g.has(l):!1}function eu(o,l){o.g?o.g.add(l):o.h=l}function ed(o,l){o.h&&o.h==l?o.h=null:o.g&&o.g.has(l)&&o.g.delete(l)}Yh.prototype.cancel=function(){if(this.i=td(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 td(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 Cv(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 rd(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=Cv(o),x=p.length,S=0;S<x;S++)l.call(void 0,p[S],d&&d[S],o)}var nd=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function Dv(o,l){if(o){o=o.split("&");for(var d=0;d<o.length;d++){var p=o[d].indexOf("="),x=null;if(0<=p){var S=o[d].substring(0,p);x=o[d].substring(p+1)}else S=o[d];l(S,x?decodeURIComponent(x.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 us;d.i=l.i,l.g&&(d.g=new Map(l.g),d.h=l.h),sd(this,d),this.m=o.m}else o&&(l=String(o).match(nd))?(this.h=!1,Si(this,l[1]||"",!0),this.o=os(l[2]||""),this.g=os(l[3]||"",!0),Ri(this,l[4]),this.l=os(l[5]||"",!0),sd(this,l[6]||"",!0),this.m=os(l[7]||"")):(this.h=!1,this.i=new us(null,this.h))}cr.prototype.toString=function(){var o=[],l=this.j;l&&o.push(as(l,id,!0),":");var d=this.g;return(d||l=="file")&&(o.push("//"),(l=this.o)&&o.push(as(l,id,!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(as(d,d.charAt(0)=="/"?Vv:Nv,!0))),(d=this.i.toString())&&o.push("?",d),(d=this.m)&&o.push("#",as(d,Mv)),o.join("")};function ft(o){return new cr(o)}function Si(o,l,d){o.j=d?os(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 sd(o,l,d){l instanceof us?(o.i=l,Fv(o.i,o.h)):(d||(l=as(l,Lv)),o.i=new us(l,o.h))}function ie(o,l,d){o.i.set(l,d)}function Pi(o){return ie(o,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),o}function os(o,l){return o?l?decodeURI(o.replace(/%25/g,"%2525")):decodeURIComponent(o):""}function as(o,l,d){return typeof o=="string"?(o=encodeURI(o).replace(l,Ov),d&&(o=o.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),o):null}function Ov(o){return o=o.charCodeAt(0),"%"+(o>>4&15).toString(16)+(o&15).toString(16)}var id=/[#\/\?@]/g,Nv=/[#\?:]/g,Vv=/[#\?]/g,Lv=/[#\?@]/g,Mv=/#/g;function us(o,l){this.h=this.g=null,this.i=o||null,this.j=!!l}function Nt(o){o.g||(o.g=new Map,o.h=0,o.i&&Dv(o.i,function(l,d){o.add(decodeURIComponent(l.replace(/\+/g," ")),d)}))}r=us.prototype,r.add=function(o,l){Nt(this),this.i=null,o=Ur(this,o);var d=this.g.get(o);return d||this.g.set(o,d=[]),d.push(l),this.h+=1,this};function od(o,l){Nt(o),l=Ur(o,l),o.g.has(l)&&(o.i=null,o.h-=o.g.get(l).length,o.g.delete(l))}function ad(o,l){return Nt(o),l=Ur(o,l),o.g.has(l)}r.forEach=function(o,l){Nt(this),this.g.forEach(function(d,p){d.forEach(function(x){o.call(l,x,p,this)},this)},this)},r.na=function(){Nt(this);let o=Array.from(this.g.values()),l=Array.from(this.g.keys()),d=[];for(let p=0;p<l.length;p++){let x=o[p];for(let S=0;S<x.length;S++)d.push(l[p])}return d},r.V=function(o){Nt(this);let l=[];if(typeof o=="string")ad(this,o)&&(l=l.concat(this.g.get(Ur(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 Nt(this),this.i=null,o=Ur(this,o),ad(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 ud(o,l,d){od(o,l),0<d.length&&(o.i=null,o.g.set(Ur(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 x=S;O[p]!==""&&(x+="="+encodeURIComponent(String(O[p]))),o.push(x)}}return this.i=o.join("&")};function Ur(o,l){return l=String(l),o.j&&(l=l.toLowerCase()),l}function Fv(o,l){l&&!o.j&&(Nt(o),o.i=null,o.g.forEach(function(d,p){var x=p.toLowerCase();p!=x&&(od(this,p),ud(this,x,d))},o)),o.j=l}function jv(o,l){let d=new ss;if(u.Image){let p=new Image;p.onload=E(Vt,d,"TestLoadImage: loaded",!0,l,p),p.onerror=E(Vt,d,"TestLoadImage: error",!1,l,p),p.onabort=E(Vt,d,"TestLoadImage: abort",!1,l,p),p.ontimeout=E(Vt,d,"TestLoadImage: timeout",!1,l,p),u.setTimeout(function(){p.ontimeout&&p.ontimeout()},1e4),p.src=o}else l(!1)}function Uv(o,l){let d=new ss,p=new AbortController,x=setTimeout(()=>{p.abort(),Vt(d,"TestPingServer: timeout",!1,l)},1e4);fetch(o,{signal:p.signal}).then(S=>{clearTimeout(x),S.ok?Vt(d,"TestPingServer: ok",!0,l):Vt(d,"TestPingServer: server error",!1,l)}).catch(()=>{clearTimeout(x),Vt(d,"TestPingServer: error",!1,l)})}function Vt(o,l,d,p,x){try{x&&(x.onload=null,x.onerror=null,x.onabort=null,x.ontimeout=null),p(d)}catch{}}function Bv(){this.g=new Ev}function $v(o,l,d){let p=d||"";try{rd(o,function(x,S){let O=x;h(x)&&(O=za(x)),l.push(p+S+"="+encodeURIComponent(O))})}catch(x){throw l.push(p+"type="+encodeURIComponent("_badmap")),x}}function cs(o){this.l=o.Ub||null,this.j=o.eb||!1}P(cs,Ga),cs.prototype.g=function(){return new Ci(this.l,this.j)},cs.prototype.i=function(o){return function(){return o}}({});function Ci(o,l){Ie.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,Ie),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,hs(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,ls(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,hs(this)),this.g&&(this.readyState=3,hs(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;cd(this)}else o.text().then(this.Ra.bind(this),this.ga.bind(this))};function cd(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?ls(this):hs(this),this.readyState==3&&cd(this)}},r.Ra=function(o){this.g&&(this.response=this.responseText=o,ls(this))},r.Qa=function(o){this.g&&(this.response=o,ls(this))},r.ga=function(){this.g&&ls(this)};function ls(o){o.readyState=4,o.l=null,o.j=null,o.v=null,hs(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 hs(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 ld(o){let l="";return B(o,function(d,p){l+=p,l+=":",l+=d,l+=`\r
|
|
8
|
+
`}),l}function tu(o,l,d){e:{for(p in d){var p=!1;break e}p=!0}p||(d=ld(d),typeof o=="string"?d!=null&&encodeURIComponent(String(d)):ie(o,l,d))}function ue(o){Ie.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(ue,Ie);var qv=/^https?$/i,zv=["POST","PUT"];r=ue.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():Wa.g(),this.v=this.o?jh(this.o):jh(Wa),this.g.onreadystatechange=g(this.Ea,this);try{this.B=!0,this.g.open(l,String(o),!0),this.B=!1}catch(S){hd(this,S);return}if(o=d||"",d=new Map(this.headers),p)if(Object.getPrototypeOf(p)===Object.prototype)for(var x in p)d.set(x,p[x]);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"),x=u.FormData&&o instanceof u.FormData,!(0<=Array.prototype.indexOf.call(zv,l,void 0))||p||x||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{pd(this),this.u=!0,this.g.send(o),this.u=!1}catch(S){hd(this,S)}};function hd(o,l){o.h=!1,o.g&&(o.j=!0,o.g.abort(),o.j=!1),o.l=l,o.m=5,dd(o),ki(o)}function dd(o){o.A||(o.A=!0,Ce(o,"complete"),Ce(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,Ce(this,"complete"),Ce(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)),ue.aa.N.call(this)},r.Ea=function(){this.s||(this.B||this.u||this.j?fd(this):this.bb())},r.bb=function(){fd(this)};function fd(o){if(o.h&&typeof a!="undefined"&&(!o.v[1]||pt(o)!=4||o.Z()!=2)){if(o.u&&pt(o)==4)Vh(o.Ea,0,o);else if(Ce(o,"readystatechange"),pt(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 x=String(o.D).match(nd)[1]||null;!x&&u.self&&u.self.location&&(x=u.self.location.protocol.slice(0,-1)),p=!qv.test(x?x.toLowerCase():"")}d=p}if(d)Ce(o,"complete"),Ce(o,"success");else{o.m=6;try{var S=2<pt(o)?o.g.statusText:""}catch{S=""}o.l=S+" ["+o.Z()+"]",dd(o)}}finally{ki(o)}}}}function ki(o,l){if(o.g){pd(o);let d=o.g,p=o.v[0]?()=>{}:null;o.g=null,o.v=null,l||Ce(o,"ready");try{d.onreadystatechange=p}catch{}}}function pd(o){o.I&&(u.clearTimeout(o.I),o.I=null)}r.isActive=function(){return!!this.g};function pt(o){return o.g?o.g.readyState:0}r.Z=function(){try{return 2<pt(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)),Tv(l)}};function md(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 Gv(o){let l={};o=(o.g&&2<=pt(o)&&o.g.getAllResponseHeaders()||"").split(`\r
|
|
9
|
+
`);for(let p=0;p<o.length;p++){if(M(o[p]))continue;var d=I(o[p]);let x=d[0];if(d=d[1],typeof d!="string")continue;d=d.trim();let S=l[x]||[];l[x]=S,S.push(d)}T(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 ds(o,l,d){return d&&d.internalChannelParams&&d.internalChannelParams[o]||l}function gd(o){this.Aa=0,this.i=[],this.j=new ss,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=ds("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=ds("baseRetryDelayMs",5e3,o),this.cb=ds("retryDelaySeedMs",1e4,o),this.Wa=ds("forwardChannelMaxRetries",2,o),this.wa=ds("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 Yh(o&&o.concurrentRequestLimit),this.Da=new Bv,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=gd.prototype,r.la=8,r.G=1,r.connect=function(o,l,d,p){ke(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=xd(this,null,this.W),Oi(this)};function ru(o){if(yd(o),o.G==3){var l=o.U++,d=ft(o.I);if(ie(d,"SID",o.K),ie(d,"RID",l),ie(d,"TYPE","terminate"),fs(o,d),l=new Ot(o,o.j,l),l.L=2,l.v=Pi(ft(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=Ad(l.j,null),l.g.ea(l.v)),l.F=Date.now(),Ai(l)}Id(o)}function Di(o){o.g&&(su(o),o.g.cancel(),o.g=null)}function yd(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(!Xh(o.h)&&!o.s){o.s=!0;var l=o.Ga;Jn||Ph(),Yn||(Jn(),Yn=!0),Va.add(l,o),o.B=0}}function Kv(o,l){return Zh(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=ns(g(o.Ga,o,l),Ed(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 x=new Ot(this,this.j,o),S=this.o;if(this.S&&(S?(S=y(S),b(S,this.S)):S=this.S),this.m!==null||this.O||(x.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=vd(this,x,l),d=ft(this.I),ie(d,"RID",o),ie(d,"CVER",22),this.D&&ie(d,"X-HTTP-Session-Id",this.D),fs(this,d),S&&(this.O?l="headers="+encodeURIComponent(String(ld(S)))+"&"+l:this.m&&tu(d,this.m,S)),eu(this.h,x),this.Ua&&ie(d,"TYPE","init"),this.P?(ie(d,"$req",l),ie(d,"SID","null"),x.T=!0,Ja(x,d,null)):Ja(x,d,l),this.G=2}}else this.G==3&&(o?_d(this,o):this.i.length==0||Xh(this.h)||_d(this))};function _d(o,l){var d;l?d=l.l:d=o.U++;let p=ft(o.I);ie(p,"SID",o.K),ie(p,"RID",d),ie(p,"AID",o.T),fs(o,p),o.m&&o.o&&tu(p,o.m,o.o),d=new Ot(o,o.j,d,o.B+1),o.m===null&&(d.H=o.o),l&&(o.i=l.D.concat(o.i)),l=vd(o,d,1e3),d.I=Math.round(.5*o.wa)+Math.round(.5*o.wa*Math.random()),eu(o.h,d),Ja(d,p,l)}function fs(o,l){o.H&&B(o.H,function(d,p){ie(l,p,d)}),o.l&&rd({},function(d,p){ie(l,p,d)})}function vd(o,l,d){d=Math.min(o.i.length,d);var p=o.l?g(o.l.Na,o.l,o):null;e:{var x=o.i;let S=-1;for(;;){let O=["count="+d];S==-1?0<d?(S=x[0].g,O.push("ofs="+S)):S=0:O.push("ofs="+S);let te=!0;for(let we=0;we<d;we++){let X=x[we].g,xe=x[we].map;if(X-=S,0>X)S=Math.max(0,x[we].g-100),te=!1;else try{$v(xe,O,"req"+X+"_")}catch{p&&p(xe)}}if(te){p=O.join("&");break e}}}return o=o.i.splice(0,d),l.D=o,p}function wd(o){if(!o.g&&!o.u){o.Y=1;var l=o.Fa;Jn||Ph(),Yn||(Jn(),Yn=!0),Va.add(l,o),o.v=0}}function nu(o){return o.g||o.u||3<=o.v?!1:(o.Y++,o.u=ns(g(o.Fa,o),Ed(o,o.v)),o.v++,!0)}r.Fa=function(){if(this.u=null,bd(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=ns(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,ke(10),Di(this),bd(this))};function su(o){o.A!=null&&(u.clearTimeout(o.A),o.A=null)}function bd(o){o.g=new Ot(o,o.j,"rpc",o.Y),o.m===null&&(o.g.H=o.o),o.g.O=0;var l=ft(o.qa);ie(l,"RID","rpc"),ie(l,"SID",o.K),ie(l,"AID",o.T),ie(l,"CI",o.F?"0":"1"),!o.F&&o.ja&&ie(l,"TO",o.ja),ie(l,"TYPE","xmlhttp"),fs(o,l),o.m&&o.o&&tu(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(ft(l)),d.m=null,d.P=!0,Wh(d,o)}r.Za=function(){this.C!=null&&(this.C=null,Di(this),nu(this),ke(19))};function Ni(o){o.C!=null&&(u.clearTimeout(o.C),o.C=null)}function Td(o,l){var d=null;if(o.g==l){Ni(o),su(o),o.g=null;var p=2}else if(Za(o.h,l))d=l.D,ed(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 x=o.B;p=Ei(),Ce(p,new zh(p,d)),Oi(o)}else wd(o);else if(x=l.s,x==3||x==0&&0<l.X||!(p==1&&Kv(o,l)||p==2&&nu(o)))switch(d&&0<d.length&&(l=o.h,l.i=l.i.concat(d)),x){case 1:lr(o,5);break;case 4:lr(o,10);break;case 3:lr(o,6);break;default:lr(o,2)}}}function Ed(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 x=!p;p=new cr(p||"//www.google.com/images/cleardot.gif"),u.location&&u.location.protocol=="http"||Si(p,"https"),Pi(p),x?jv(p.toString(),d):Uv(p.toString(),d)}else ke(2);o.G=0,o.l&&o.l.sa(l),Id(o),yd(o)}r.fb=function(o){o?(this.j.info("Successfully pinged google.com"),ke(2)):(this.j.info("Failed to ping google.com"),ke(1))};function Id(o){if(o.G=0,o.ka=[],o.l){let l=td(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 xd(o,l,d){var p=d instanceof cr?ft(d):new cr(d);if(p.g!="")l&&(p.g=l+"."+p.g),Ri(p,p.s);else{var x=u.location;p=x.protocol,l=l?l+"."+x.hostname:x.hostname,x=+x.port;var S=new cr(null);p&&Si(S,p),l&&(S.g=l),x&&Ri(S,x),d&&(S.l=d),p=S}return d=o.D,l=o.ya,d&&l&&ie(p,d,l),ie(p,"VER",o.la),fs(o,p),p}function Ad(o,l,d){if(l&&!o.J)throw Error("Can't create secondary domain capable XhrIo object.");return l=o.Ca&&!o.pa?new ue(new cs({eb:d})):new ue(o.pa),l.Ha(o.J),l}r.isActive=function(){return!!this.l&&this.l.isActive(this)};function Sd(){}r=Sd.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){Ie.call(this),this.g=new gd(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)&&!M(o)&&(this.g.m=o),this.v=l&&l.supportsCrossDomainXhr||!1,this.u=l&&l.sendRawJson||!1,(l=l&&l.httpSessionIdParam)&&!M(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 Br(this)}P(Fe,Ie),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(){ru(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__=za(o),o=d);l.i.push(new Pv(l.Ya++,o)),l.G==3&&Oi(l)},Fe.prototype.N=function(){this.g.l=null,delete this.j,ru(this.g),delete this.g,Fe.aa.N.call(this)};function Rd(o){Ka.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(Rd,Ka);function Pd(){Ha.call(this),this.status=1}P(Pd,Ha);function Br(o){this.g=o}P(Br,Sd),Br.prototype.ua=function(){Ce(this.g,"a")},Br.prototype.ta=function(o){Ce(this.g,new Rd(o))},Br.prototype.sa=function(o){Ce(this.g,new Pd)},Br.prototype.ra=function(){Ce(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,Bu=It.createWebChannelTransport=function(){return new Vi},Uu=It.getStatEventTarget=function(){return Ei()},ju=It.Event=ar,fo=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,Is=It.ErrorCode=Ii,Gh.COMPLETE="complete",Fu=It.EventType=Gh,Uh.EventType=ts,ts.OPEN="a",ts.CLOSE="b",ts.ERROR="c",ts.MESSAGE="d",Ie.prototype.listen=Ie.prototype.K,cn=It.WebChannel=Uh,LA=It.FetchXmlHttpFactory=cs,ue.prototype.listenOnce=ue.prototype.L,ue.prototype.getLastError=ue.prototype.Ka,ue.prototype.getLastErrorCode=ue.prototype.Ba,ue.prototype.getStatus=ue.prototype.Z,ue.prototype.getResponseJson=ue.prototype.Oa,ue.prototype.getResponseText=ue.prototype.oa,ue.prototype.send=ue.prototype.ea,ue.prototype.setWithCredentials=ue.prototype.Ha,Mu=It.XhrIo=ue}).apply(typeof ho!="undefined"?ho:typeof self!="undefined"?self:typeof window!="undefined"?window:{});var Om="@firebase/firestore",Nm="4.7.8";var _e=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}};_e.UNAUTHENTICATED=new _e(null),_e.GOOGLE_CREDENTIALS=new _e("google-credentials-uid"),_e.FIRST_PARTY=new _e("first-party-uid"),_e.MOCK_USER=new _e("mock-user");var On="11.3.1";var yr=new un("@firebase/firestore");function ln(){return yr.logLevel}function V(r,...e){if(yr.logLevel<=W.DEBUG){let t=e.map(Sl);yr.debug(`Firestore (${On}): ${r}`,...t)}}function xt(r,...e){if(yr.logLevel<=W.ERROR){let t=e.map(Sl);yr.error(`Firestore (${On}): ${r}`,...t)}}function yn(r,...e){if(yr.logLevel<=W.WARN){let t=e.map(Sl);yr.warn(`Firestore (${On}): ${r}`,...t)}}function Sl(r){if(typeof r=="string")return r;try{return function(t){return JSON.stringify(t)}(r)}catch{return r}}function F(r="Unexpected state"){let e=`FIRESTORE (${On}) INTERNAL ASSERTION FAILED: `+r;throw xt(e),new Error(e)}function ee(r,e){r||F()}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 vt{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 wo=class{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}},Ku=class{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(_e.UNAUTHENTICATED))}shutdown(){}},Hu=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}},Wu=class{constructor(e){this.t=e,this.currentUser=_e.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 wo(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 _e(e)}},Qu=class{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=_e.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}},Ju=class{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new Qu(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(_e.FIRST_PARTY))}shutdown(){}invalidateToken(){}},bo=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)}},Yu=class{constructor(e,t){this.A=t,this.forceRefresh=!1,this.appCheck=null,this.R=null,this.V=null,Am(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 bo(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 bo(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 MA(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}var To=class{static newId(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(4.129032258064516),n="";for(;n.length<20;){let s=MA(40);for(let i=0;i<s.length;++i)n.length<20&&s[i]<t&&(n+=e.charAt(s[i]%62))}return n}};function Q(r,e){return r<e?-1:r>e?1:0}function _n(r,e,t){return r.length===e.length&&r.every((n,s)=>t(n,e[s]))}var Vm=-62135596800,Lm=1e6,be=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)*Lm);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<Vm)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/Lm}_compareTo(e){return this.seconds===e.seconds?Q(this.nanoseconds,e.nanoseconds):Q(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-Vm;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 be(0,0))}static max(){return new r(new be(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 Mm="__name__",Eo=class r{constructor(e,t,n){t===void 0?t=0:t>e.length&&F(),n===void 0?n=e.length-t:n>e.length-t&&F(),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 Math.sign(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)):e<t?-1:e>t?1:0}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return Et.fromString(e.substring(4,e.length-2))}},me=class r extends Eo{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([])}},FA=/^[_a-zA-Z][_a-zA-Z0-9]*$/,Be=class r extends Eo{construct(e,t,n){return new r(e,t,n)}static isValidIdentifier(e){return FA.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)===Mm}static keyField(){return new r([Mm])}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(me.fromString(e))}static fromName(e){return new r(me.fromString(e).popFirst(5))}static empty(){return new r(me.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&&me.comparator(this.path,e.path)===0}toString(){return this.path.toString()}static comparator(e,t){return me.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new r(new me(e.slice()))}};var Cs=-1,Xu=class{constructor(e,t,n,s){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=s}};Xu.UNKNOWN_ID=-1;function jA(r,e){let t=r.toTimestamp().seconds,n=r.toTimestamp().nanoseconds+1,s=q.fromTimestamp(n===1e9?new be(t+1,0):new be(t,n));return new _r(s,j.empty(),e)}function UA(r){return new _r(r.readTime,r.key,Cs)}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(),Cs)}static max(){return new r(q.max(),j.empty(),Cs)}};function BA(r,e){let t=r.readTime.compareTo(e.readTime);return t!==0?t:(t=j.comparator(r.documentKey,e.documentKey),t!==0?t:Q(r.largestBatchId,e.largestBatchId))}var $A="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",Zu=class{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}};async function Nn(r){if(r.code!==D.FAILED_PRECONDITION||r.message!==$A)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&&F(),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 qA(r){let e=r.match(/Android ([\d.]+)/i),t=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(t)}function Vn(r){return r.name==="IndexedDbTransactionError"}var vn=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}};vn.ae=-1;var Rl=-1;function sa(r){return r==null}function ks(r){return r===0&&1/r==-1/0}function zA(r){return typeof r=="number"&&Number.isInteger(r)&&!ks(r)&&r<=Number.MAX_SAFE_INTEGER&&r>=Number.MIN_SAFE_INTEGER}var wg="";function GA(r){let e="";for(let t=0;t<r.length;t++)e.length>0&&(e=Fm(e)),e=KA(r.get(t),e);return Fm(e)}function KA(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 wg:t+="";break;default:t+=i}}return t}function Fm(r){return r+wg+""}var HA="remoteDocuments",bg="owner";var Tg="mutationQueues";var Eg="mutations";var Ig="documentMutations",WA="remoteDocumentsV14";var xg="remoteDocumentGlobal";var Ag="targets";var Sg="targetDocuments";var Rg="targetGlobal",Pg="collectionParents";var Cg="clientMetadata";var kg="bundles";var Dg="namedQueries";var QA="indexConfiguration";var JA="indexState";var YA="indexEntries";var Og="documentOverlays";var XA="globals";var ZA=[Tg,Eg,Ig,HA,Ag,bg,Rg,Sg,Cg,xg,Pg,kg,Dg],SF=[...ZA,Og],eS=[Tg,Eg,Ig,WA,Ag,bg,Rg,Sg,Cg,xg,Pg,kg,Dg,Og],tS=eS,rS=[...tS,QA,JA,YA];var RF=[...rS,XA];function jm(r){let e=0;for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e++;return e}function rr(r,e){for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e(t,r[t])}function Ng(r){for(let e in r)if(Object.prototype.hasOwnProperty.call(r,e))return!1;return!0}var le=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 pn(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new pn(this.root,e,this.comparator,!1)}getReverseIterator(){return new pn(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new pn(this.root,e,this.comparator,!0)}},pn=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 F();let e=this.left.check();if(e!==this.right.check())throw F();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 F()}get value(){throw F()}get color(){throw F()}get left(){throw F()}get right(){throw F()}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 ve=class r{constructor(e){this.comparator=e,this.data=new le(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 Io(this.data.getIterator())}getIteratorFrom(e){return new Io(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}},Io=class{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}};var ze=class r{constructor(e){this.fields=e,e.sort(Be.comparator)}static empty(){return new r([])}unionWith(e){let t=new ve(Be.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 _n(this.fields,e.fields,(t,n)=>t.isEqual(n))}};var xo=class extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}};var Pe=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 Q(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}};Pe.EMPTY_BYTE_STRING=new Pe("");var nS=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function At(r){if(ee(!!r),typeof r=="string"){let e=0,t=nS.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:ae(r.seconds),nanos:ae(r.nanos)}}function ae(r){return typeof r=="number"?r:typeof r=="string"?Number(r):0}function St(r){return typeof r=="string"?Pe.fromBase64String(r):Pe.fromUint8Array(r)}var Vg="server_timestamp",Lg="__type__",Mg="__previous_value__",Fg="__local_write_time__";function Pl(r){var e,t;return((t=(((e=r==null?void 0:r.mapValue)===null||e===void 0?void 0:e.fields)||{})[Lg])===null||t===void 0?void 0:t.stringValue)===Vg}function ia(r){let e=r.mapValue.fields[Mg];return Pl(e)?ia(e):e}function Ds(r){let e=At(r.mapValue.fields[Fg].timestampValue);return new be(e.seconds,e.nanos)}var ec=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}},Ao="(default)",So=class r{constructor(e,t){this.projectId=e,this.database=t||Ao}static empty(){return new r("","")}get isDefaultDatabase(){return this.database===Ao}isEqual(e){return e instanceof r&&e.projectId===this.projectId&&e.database===this.database}};var Cl="__type__",jg="__max__",po={mapValue:{fields:{__type__:{stringValue:jg}}}},kl="__vector__",wn="value";function Xt(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?Pl(r)?4:Bg(r)?9007199254740991:Ug(r)?10:11:F()}function ot(r,e){if(r===e)return!0;let t=Xt(r);if(t!==Xt(e))return!1;switch(t){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===e.booleanValue;case 4:return Ds(r).isEqual(Ds(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=At(s.timestampValue),u=At(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 ae(s.geoPointValue.latitude)===ae(i.geoPointValue.latitude)&&ae(s.geoPointValue.longitude)===ae(i.geoPointValue.longitude)}(r,e);case 2:return function(s,i){if("integerValue"in s&&"integerValue"in i)return ae(s.integerValue)===ae(i.integerValue);if("doubleValue"in s&&"doubleValue"in i){let a=ae(s.doubleValue),u=ae(i.doubleValue);return a===u?ks(a)===ks(u):isNaN(a)&&isNaN(u)}return!1}(r,e);case 9:return _n(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(jm(a)!==jm(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 F()}}function Os(r,e){return(r.values||[]).find(t=>ot(t,e))!==void 0}function bn(r,e){if(r===e)return 0;let t=Xt(r),n=Xt(e);if(t!==n)return Q(t,n);switch(t){case 0:case 9007199254740991:return 0;case 1:return Q(r.booleanValue,e.booleanValue);case 2:return function(i,a){let u=ae(i.integerValue||i.doubleValue),c=ae(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 Um(r.timestampValue,e.timestampValue);case 4:return Um(Ds(r),Ds(e));case 5:return Q(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=Q(u[h],c[h]);if(f!==0)return f}return Q(u.length,c.length)}(r.referenceValue,e.referenceValue);case 8:return function(i,a){let u=Q(ae(i.latitude),ae(a.latitude));return u!==0?u:Q(ae(i.longitude),ae(a.longitude))}(r.geoPointValue,e.geoPointValue);case 9:return Bm(r.arrayValue,e.arrayValue);case 10:return function(i,a){var u,c,h,f;let m=i.fields||{},g=a.fields||{},E=(u=m[wn])===null||u===void 0?void 0:u.arrayValue,P=(c=g[wn])===null||c===void 0?void 0:c.arrayValue,C=Q(((h=E==null?void 0:E.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:Bm(E,P)}(r.mapValue,e.mapValue);case 11:return function(i,a){if(i===po.mapValue&&a===po.mapValue)return 0;if(i===po.mapValue)return 1;if(a===po.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=Q(c[m],f[m]);if(g!==0)return g;let E=bn(u[c[m]],h[f[m]]);if(E!==0)return E}return Q(c.length,f.length)}(r.mapValue,e.mapValue);default:throw F()}}function Um(r,e){if(typeof r=="string"&&typeof e=="string"&&r.length===e.length)return Q(r,e);let t=At(r),n=At(e),s=Q(t.seconds,n.seconds);return s!==0?s:Q(t.nanos,n.nanos)}function Bm(r,e){let t=r.values||[],n=e.values||[];for(let s=0;s<t.length&&s<n.length;++s){let i=bn(t[s],n[s]);if(i)return i}return Q(t.length,n.length)}function Tn(r){return tc(r)}function tc(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=At(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+=tc(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}:${tc(t.fields[a])}`;return s+"}"}(r.mapValue):F()}function yo(r){switch(Xt(r)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let e=ia(r);return e?16+yo(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+yo(i),0)}(r.arrayValue);case 10:case 11:return function(n){let s=0;return rr(n.fields,(i,a)=>{s+=i.length+yo(a)}),s}(r.mapValue);default:throw F()}}function rc(r){return!!r&&"integerValue"in r}function Dl(r){return!!r&&"arrayValue"in r}function $m(r){return!!r&&"nullValue"in r}function qm(r){return!!r&&"doubleValue"in r&&isNaN(Number(r.doubleValue))}function _o(r){return!!r&&"mapValue"in r}function Ug(r){var e,t;return((t=(((e=r==null?void 0:r.mapValue)===null||e===void 0?void 0:e.fields)||{})[Cl])===null||t===void 0?void 0:t.stringValue)===kl}function As(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 rr(r.mapValue.fields,(t,n)=>e.mapValue.fields[t]=As(n)),e}if(r.arrayValue){let e={arrayValue:{values:[]}};for(let t=0;t<(r.arrayValue.values||[]).length;++t)e.arrayValue.values[t]=As(r.arrayValue.values[t]);return e}return Object.assign({},r)}function Bg(r){return(((r.mapValue||{}).fields||{}).__type__||{}).stringValue===jg}var CF={mapValue:{fields:{[Cl]:{stringValue:kl},[wn]:{arrayValue:{}}}}};var Ue=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)],!_o(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=As(t)}setAll(e){let t=Be.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()]=As(a):s.push(u.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,n,s)}delete(e){let t=this.field(e.popLast());_o(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)];_o(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=s),t=s}return t.mapValue.fields}applyChanges(e,t,n){rr(t,(s,i)=>e[s]=i);for(let s of n)delete e[s]}clone(){return new r(As(this.value))}};function $g(r){let e=[];return rr(r.fields,(t,n)=>{let s=new Be([t]);if(_o(n)){let i=$g(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 ze(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(),Ue.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(),Ue.empty(),0)}static newUnknownDocument(e,t){return new r(e,3,t,q.min(),q.min(),Ue.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=Ue.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Ue.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 En=class{constructor(e,t){this.position=e,this.inclusive=t}};function zm(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=bn(a,t.data.field(i.field)),i.dir==="desc"&&(n*=-1),n!==0)break}return n}function Gm(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 In=class{constructor(e,t="asc"){this.field=e,this.dir=t}};function sS(r,e){return r.dir===e.dir&&r.field.isEqual(e.field)}var Ro=class{},ye=class r extends Ro{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 sc(e,t,n):t==="array-contains"?new ac(e,n):t==="in"?new uc(e,n):t==="not-in"?new cc(e,n):t==="array-contains-any"?new lc(e,n):new r(e,t,n)}static createKeyFieldInFilter(e,t,n){return t==="in"?new ic(e,n):new oc(e,n)}matches(e){let t=e.data.field(this.field);return this.op==="!="?t!==null&&this.matchesComparison(bn(t,this.value)):t!==null&&Xt(this.value)===Xt(t)&&this.matchesComparison(bn(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 F()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}},at=class r extends Ro{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 qg(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 qg(r){return r.op==="and"}function zg(r){return iS(r)&&qg(r)}function iS(r){for(let e of r.filters)if(e instanceof at)return!1;return!0}function nc(r){if(r instanceof ye)return r.field.canonicalString()+r.op.toString()+Tn(r.value);if(zg(r))return r.filters.map(e=>nc(e)).join(",");{let e=r.filters.map(t=>nc(t)).join(",");return`${r.op}(${e})`}}function Gg(r,e){return r instanceof ye?function(n,s){return s instanceof ye&&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&&Gg(a,s.filters[u]),!0):!1}(r,e):void F()}function Kg(r){return r instanceof ye?function(t){return`${t.field.canonicalString()} ${t.op} ${Tn(t.value)}`}(r):r instanceof at?function(t){return t.op.toString()+" {"+t.getFilters().map(Kg).join(" ,")+"}"}(r):"Filter"}var sc=class extends ye{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)}},ic=class extends ye{constructor(e,t){super(e,"in",t),this.keys=Hg("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}},oc=class extends ye{constructor(e,t){super(e,"not-in",t),this.keys=Hg("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}};function Hg(r,e){var t;return(((t=e.arrayValue)===null||t===void 0?void 0:t.values)||[]).map(n=>j.fromName(n.referenceValue))}var ac=class extends ye{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return Dl(t)&&Os(t.arrayValue,this.value)}},uc=class extends ye{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return t!==null&&Os(this.value.arrayValue,t)}},cc=class extends ye{constructor(e,t){super(e,"not-in",t)}matches(e){if(Os(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return t!==null&&!Os(this.value.arrayValue,t)}},lc=class extends ye{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!Dl(t)||!t.arrayValue.values)&&t.arrayValue.values.some(n=>Os(this.value.arrayValue,n))}};var hc=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 Km(r,e=null,t=[],n=[],s=null,i=null,a=null){return new hc(r,e,t,n,s,i,a)}function Ol(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=>nc(n)).join(","),t+="|ob:",t+=e.orderBy.map(n=>function(i){return i.field.canonicalString()+i.dir}(n)).join(","),sa(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(n=>Tn(n)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(n=>Tn(n)).join(",")),e.le=t}return e.le}function Nl(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(!sS(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(!Gg(r.filters[t],e.filters[t]))return!1;return r.collectionGroup===e.collectionGroup&&!!r.path.isEqual(e.path)&&!!Gm(r.startAt,e.startAt)&&Gm(r.endAt,e.endAt)}function dc(r){return j.isDocumentKey(r.path)&&r.collectionGroup===null&&r.filters.length===0}var xn=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 oS(r,e,t,n,s,i,a,u){return new xn(r,e,t,n,s,i,a,u)}function oa(r){return new xn(r)}function Hm(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 aS(r){return r.collectionGroup!==null}function Ss(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 ve(Be.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 In(i,n))}),t.has(Be.keyField().canonicalString())||e.he.push(new In(Be.keyField(),n))}return e.he}function nt(r){let e=$(r);return e.Pe||(e.Pe=uS(e,Ss(r))),e.Pe}function uS(r,e){if(r.limitType==="F")return Km(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 In(s.field,i)});let t=r.endAt?new En(r.endAt.position,r.endAt.inclusive):null,n=r.startAt?new En(r.startAt.position,r.startAt.inclusive):null;return Km(r.path,r.collectionGroup,e,r.filters,r.limit,t,n)}}function fc(r,e,t){return new xn(r.path,r.collectionGroup,r.explicitOrderBy.slice(),r.filters.slice(),e,t,r.startAt,r.endAt)}function aa(r,e){return Nl(nt(r),nt(e))&&r.limitType===e.limitType}function Wg(r){return`${Ol(nt(r))}|lt:${r.limitType}`}function hn(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=>Kg(s)).join(", ")}]`),sa(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=>Tn(s)).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(s=>Tn(s)).join(",")),`Target(${n})`}(nt(r))}; limitType=${r.limitType})`}function ua(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 Ss(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=zm(a,u,c);return a.inclusive?h<=0:h<0}(n.startAt,Ss(n),s)||n.endAt&&!function(a,u,c){let h=zm(a,u,c);return a.inclusive?h>=0:h>0}(n.endAt,Ss(n),s))}(r,e)}function cS(r){return r.collectionGroup||(r.path.length%2==1?r.path.lastSegment():r.path.get(r.path.length-2))}function Qg(r){return(e,t)=>{let n=!1;for(let s of Ss(r)){let i=lS(s,e,t);if(i!==0)return i;n=n||s.field.isKeyField()}return 0}}function lS(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?bn(c,h):F()}(r.field,e,t);switch(r.dir){case"asc":return n;case"desc":return-1*n;default:return F()}}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){rr(this.inner,(t,n)=>{for(let[s,i]of n)e(s,i)})}isEmpty(){return Ng(this.inner)}size(){return this.innerSize}};var hS=new le(j.comparator);function Pt(){return hS}var Jg=new le(j.comparator);function xs(...r){let e=Jg;for(let t of r)e=e.insert(t.key,t);return e}function Yg(r){let e=Jg;return r.forEach((t,n)=>e=e.insert(t,n.overlayedDocument)),e}function pr(){return Rs()}function Xg(){return Rs()}function Rs(){return new Rt(r=>r.toString(),(r,e)=>r.isEqual(e))}var dS=new le(j.comparator),fS=new ve(j.comparator);function H(...r){let e=fS;for(let t of r)e=e.add(t);return e}var pS=new ve(Q);function mS(){return pS}function Vl(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:ks(e)?"-0":e}}function Zg(r){return{integerValue:""+r}}function gS(r,e){return zA(e)?Zg(e):Vl(r,e)}var An=class{constructor(){this._=void 0}};function yS(r,e,t){return r instanceof Sn?function(s,i){let a={fields:{[Lg]:{stringValue:Vg},[Fg]:{timestampValue:{seconds:s.seconds,nanos:s.nanoseconds}}}};return i&&Pl(i)&&(i=ia(i)),i&&(a.fields[Mg]=i),{mapValue:a}}(t,e):r instanceof vr?ty(r,e):r instanceof wr?ry(r,e):function(s,i){let a=ey(s,i),u=Wm(a)+Wm(s.Ie);return rc(a)&&rc(s.Ie)?Zg(u):Vl(s.serializer,u)}(r,e)}function _S(r,e,t){return r instanceof vr?ty(r,e):r instanceof wr?ry(r,e):t}function ey(r,e){return r instanceof Rn?function(n){return rc(n)||function(i){return!!i&&"doubleValue"in i}(n)}(e)?e:{integerValue:0}:null}var Sn=class extends An{},vr=class extends An{constructor(e){super(),this.elements=e}};function ty(r,e){let t=ny(e);for(let n of r.elements)t.some(s=>ot(s,n))||t.push(n);return{arrayValue:{values:t}}}var wr=class extends An{constructor(e){super(),this.elements=e}};function ry(r,e){let t=ny(e);for(let n of r.elements)t=t.filter(s=>!ot(s,n));return{arrayValue:{values:t}}}var Rn=class extends An{constructor(e,t){super(),this.serializer=e,this.Ie=t}};function Wm(r){return ae(r.integerValue||r.doubleValue)}function ny(r){return Dl(r)&&r.arrayValue.values?r.arrayValue.values.slice():[]}function vS(r,e){return r.field.isEqual(e.field)&&function(n,s){return n instanceof vr&&s instanceof vr||n instanceof wr&&s instanceof wr?_n(n.elements,s.elements,ot):n instanceof Rn&&s instanceof Rn?ot(n.Ie,s.Ie):n instanceof Sn&&s instanceof Sn}(r.transform,e.transform)}var pc=class{constructor(e,t){this.version=e,this.transformResults=t}},Yt=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 vo(r,e){return r.updateTime!==void 0?e.isFoundDocument()&&e.version.isEqual(r.updateTime):r.exists===void 0||r.exists===e.isFoundDocument()}var Pn=class{};function sy(r,e){if(!r.hasLocalMutations||e&&e.fields.length===0)return null;if(e===null)return r.isNoDocument()?new Po(r.key,Yt.none()):new br(r.key,r.data,Yt.none());{let t=r.data,n=Ue.empty(),s=new ve(Be.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 ze(s.toArray()),Yt.none())}}function wS(r,e,t){r instanceof br?function(s,i,a){let u=s.value.clone(),c=Jm(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(!vo(s.precondition,i))return void i.convertToUnknownDocument(a.version);let u=Jm(s.fieldTransforms,i,a.transformResults),c=i.data;c.setAll(iy(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 Ps(r,e,t,n){return r instanceof br?function(i,a,u,c){if(!vo(i.precondition,a))return u;let h=i.value.clone(),f=Ym(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(!vo(i.precondition,a))return u;let h=Ym(i.fieldTransforms,c,a),f=a.data;return f.setAll(iy(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 vo(i.precondition,a)?(a.convertToNoDocument(a.version).setHasLocalMutations(),null):u}(r,e,t)}function bS(r,e){let t=null;for(let n of r.fieldTransforms){let s=e.data.field(n.field),i=ey(n.transform,s||null);i!=null&&(t===null&&(t=Ue.empty()),t.set(n.field,i))}return t||null}function Qm(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)&&_n(n,s,(i,a)=>vS(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 Pn{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 Pn{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 iy(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 Jm(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,_S(a,u,t[s]))}return n}function Ym(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,yS(i,a,e))}return n}var Po=class extends Pn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}},mc=class extends Pn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}};var gc=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)&&wS(i,e,n[s])}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=Ps(n,e,t,this.localWriteTime));for(let n of this.mutations)n.key.isEqual(e.key)&&(t=Ps(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let n=Xg();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=sy(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),H())}isEqual(e){return this.batchId===e.batchId&&_n(this.mutations,e.mutations,(t,n)=>Qm(t,n))&&_n(this.baseMutations,e.baseMutations,(t,n)=>Qm(t,n))}},yc=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 dS}(),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 _c=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 gc=class{constructor(e,t){this.count=e,this.unchangedNames=t}};var fe,J;function lS(r){switch(r){case D.OK:return F();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 F()}}function ty(r){if(r===void 0)return It("GRPC error has no .code"),D.UNKNOWN;switch(r){case fe.OK:return D.OK;case fe.CANCELLED:return D.CANCELLED;case fe.UNKNOWN:return D.UNKNOWN;case fe.DEADLINE_EXCEEDED:return D.DEADLINE_EXCEEDED;case fe.RESOURCE_EXHAUSTED:return D.RESOURCE_EXHAUSTED;case fe.INTERNAL:return D.INTERNAL;case fe.UNAVAILABLE:return D.UNAVAILABLE;case fe.UNAUTHENTICATED:return D.UNAUTHENTICATED;case fe.INVALID_ARGUMENT:return D.INVALID_ARGUMENT;case fe.NOT_FOUND:return D.NOT_FOUND;case fe.ALREADY_EXISTS:return D.ALREADY_EXISTS;case fe.PERMISSION_DENIED:return D.PERMISSION_DENIED;case fe.FAILED_PRECONDITION:return D.FAILED_PRECONDITION;case fe.ABORTED:return D.ABORTED;case fe.OUT_OF_RANGE:return D.OUT_OF_RANGE;case fe.UNIMPLEMENTED:return D.UNIMPLEMENTED;case fe.DATA_LOSS:return D.DATA_LOSS;default:return F()}}(J=fe||(fe={}))[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 Hm=null;function hS(){return new TextEncoder}var dS=new Tt([4294967295,4294967295],0);function Wm(r){let e=hS().encode(r),t=new Ou;return t.update(e),new Uint8Array(t.digest())}function Qm(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 Tt([t,n],0),new Tt([s,i],0)]}var yc=class r{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new pr(`Invalid padding: ${t}`);if(n<0)throw new pr(`Invalid hash count: ${n}`);if(e.length>0&&this.hashCount===0)throw new pr(`Invalid hash count: ${n}`);if(e.length===0&&t!==0)throw new pr(`Invalid padding when bitmap length is 0: ${t}`);this.Ee=8*e.length-t,this.de=Tt.fromNumber(this.Ee)}Ae(e,t,n){let s=e.add(t.multiply(Tt.fromNumber(n)));return s.compare(dS)===1&&(s=new Tt([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=Wm(e),[n,s]=Qm(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=Wm(e),[n,s]=Qm(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}},pr=class extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}};var Ro=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,Ds.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new r(q.min(),s,new le(Q),Rt(),H())}},Ds=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,H(),H(),H())}};var fn=class{constructor(e,t,n,s){this.me=e,this.removedTargetIds=t,this.key=n,this.fe=s}},Po=class{constructor(e,t){this.targetId=e,this.ge=t}},Co=class{constructor(e,t,n=Pe.EMPTY_BYTE_STRING,s=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=s}},ko=class{constructor(){this.pe=0,this.ye=Jm(),this.we=Pe.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=H(),t=H(),n=H();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:F()}}),new Ds(this.we,this.Se,e,t,n)}Me(){this.be=!1,this.ye=Jm()}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}},_c=class{constructor(e){this.ke=e,this.qe=new Map,this.Qe=Rt(),this.$e=fo(),this.Ke=fo(),this.Ue=new le(Q)}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:F()}})}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(cc(i))if(n===0){let a=new j(i.path);this.ze(t,a,We.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.Ue=this.Ue.insert(t,h)}Hm==null||Hm.rt(function(f,m,g,E,P){var C,R,N,M,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:(M=(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&&M!==void 0?M: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:T=>{var y;return(y=E==null?void 0:E.mightContain(T))!==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=xt(n).toUint8Array()}catch(c){if(c instanceof Eo)return mn("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 yc(a,s,i)}catch(c){return mn(c instanceof pr?"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&&cc(u.target)){let c=new j(u.target.path);this._t(c).has(a)||this.ut(a,c)||this.ze(a,c,We.newNoDocument(c,e))}i.ve&&(t.set(a,i.Fe()),i.Me())}});let n=H();this.Ke.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 Ro(e,t,this.Ue,this.Qe,n);return this.Qe=Rt(),this.$e=fo(),this.Ke=fo(),this.Ue=new le(Q),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.Ke=this.Ke.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.Ke=this.Ke.insert(t,this.ct(t).delete(e)),this.Ke=this.Ke.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 ko,this.qe.set(e,t)),t}ct(e){let t=this.Ke.get(e);return t||(t=new ve(Q),this.Ke=this.Ke.insert(e,t)),t}_t(e){let t=this.$e.get(e);return t||(t=new ve(Q),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 ko),this.ke.getRemoteKeysForTarget(e).forEach(t=>{this.ze(e,t,null)})}ut(e,t){return this.ke.getRemoteKeysForTarget(e).has(t)}};function fo(){return new le(j.comparator)}function Jm(){return new le(j.comparator)}var fS={asc:"ASCENDING",desc:"DESCENDING"},pS={"<":"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"},mS={and:"AND",or:"OR"},vc=class{constructor(e,t){this.databaseId=e,this.useProto3Json=t}};function wc(r,e){return r.useProto3Json||ra(e)?e:{value:e}}function Do(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 ry(r,e){return r.useProto3Json?e.toBase64():e.toUint8Array()}function gS(r,e){return Do(r,e.toTimestamp())}function nt(r){return ee(!!r),q.fromTimestamp(function(t){let n=At(t);return new be(n.seconds,n.nanos)}(r))}function Ol(r,e){return bc(r,e).canonicalString()}function bc(r,e){let t=function(s){return new me(["projects",s.projectId,"databases",s.database])}(r).child("documents");return e===void 0?t:t.child(e)}function ny(r){let e=me.fromString(r);return ee(uy(e)),e}function Tc(r,e){return Ol(r.databaseId,e.path)}function ju(r,e){let t=ny(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(iy(t))}function sy(r,e){return Ol(r.databaseId,e)}function yS(r){let e=ny(r);return e.length===4?me.emptyPath():iy(e)}function Ec(r){return new me(["projects",r.databaseId.projectId,"databases",r.databaseId.database]).canonicalString()}function iy(r){return ee(r.length>4&&r.get(4)==="documents"),r.popFirst(5)}function Ym(r,e,t){return{name:Tc(r,e),fields:t.value.mapValue.fields}}function _S(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:F()}(e.targetChange.targetChangeType||"NO_CHANGE"),s=e.targetChange.targetIds||[],i=function(h,f){return h.useProto3Json?(ee(f===void 0||typeof f=="string"),Pe.fromBase64String(f||"")):(ee(f===void 0||f instanceof Buffer||f instanceof Uint8Array),Pe.fromUint8Array(f||new Uint8Array))}(r,e.targetChange.resumeToken),a=e.targetChange.cause,u=a&&function(h){let f=h.code===void 0?D.UNKNOWN:ty(h.code);return new L(f,h.message||"")}(a);t=new Co(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=ju(r,n.document.name),i=nt(n.document.updateTime),a=n.document.createTime?nt(n.document.createTime):q.min(),u=new je({mapValue:{fields:n.document.fields}}),c=We.newFoundDocument(s,i,a,u),h=n.targetIds||[],f=n.removedTargetIds||[];t=new fn(h,f,c.key,c)}else if("documentDelete"in e){e.documentDelete;let n=e.documentDelete;n.document;let s=ju(r,n.document),i=n.readTime?nt(n.readTime):q.min(),a=We.newNoDocument(s,i),u=n.removedTargetIds||[];t=new fn([],u,a.key,a)}else if("documentRemove"in e){e.documentRemove;let n=e.documentRemove;n.document;let s=ju(r,n.document),i=n.removedTargetIds||[];t=new fn([],i,s,null)}else{if(!("filter"in e))return F();{e.filter;let n=e.filter;n.targetId;let{count:s=0,unchangedNames:i}=n,a=new gc(s,i),u=n.targetId;t=new Po(u,a)}}return t}function vS(r,e){let t;if(e instanceof wr)t={update:Ym(r,e.key,e.value)};else if(e instanceof So)t={delete:Tc(r,e.key)};else if(e instanceof at)t={update:Ym(r,e.key,e.data),updateMask:RS(e.fieldMask)};else{if(!(e instanceof dc))return F();t={verify:Tc(r,e.key)}}return e.fieldTransforms.length>0&&(t.updateTransforms=e.fieldTransforms.map(n=>function(i,a){let u=a.transform;if(u instanceof An)return{fieldPath:a.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(u instanceof _r)return{fieldPath:a.field.canonicalString(),appendMissingElements:{values:u.elements}};if(u instanceof vr)return{fieldPath:a.field.canonicalString(),removeAllFromArray:{values:u.elements}};if(u instanceof xn)return{fieldPath:a.field.canonicalString(),increment:u.Ie};throw F()}(0,n))),e.precondition.isNone||(t.currentDocument=function(s,i){return i.updateTime!==void 0?{updateTime:gS(s,i.updateTime)}:i.exists!==void 0?{exists:i.exists}:F()}(r,e.precondition)),t}function wS(r,e){return r&&r.length>0?(ee(e!==void 0),r.map(t=>function(s,i){let a=s.updateTime?nt(s.updateTime):nt(i);return a.isEqual(q.min())&&(a=nt(i)),new hc(a,s.transformResults||[])}(t,e))):[]}function bS(r,e){return{documents:[sy(r,e.path)]}}function TS(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=sy(r,s);let i=function(h){if(h.length!==0)return ay(ot.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:ln(g.field),direction:AS(g.dir)}}(f))}(e.orderBy);a&&(t.structuredQuery.orderBy=a);let u=wc(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 ES(r){let e=yS(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=oy(m);return g instanceof ot&&jg(g)?g.getFilters():[g]}(t.where));let a=[];t.orderBy&&(a=function(m){return m.map(g=>function(P){return new Tn(hn(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,ra(g)?null:g}(t.limit));let c=null;t.startAt&&(c=function(m){let g=!!m.before,E=m.values||[];return new bn(E,g)}(t.startAt));let h=null;return t.endAt&&(h=function(m){let g=!m.before,E=m.values||[];return new bn(E,g)}(t.endAt)),Wx(e,s,a,i,u,"F",c,h)}function IS(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 F()}}(e.purpose);return t==null?null:{"goog-listen-tags":t}}function oy(r){return r.unaryFilter!==void 0?function(t){switch(t.unaryFilter.op){case"IS_NAN":let n=hn(t.unaryFilter.field);return ye.create(n,"==",{doubleValue:NaN});case"IS_NULL":let s=hn(t.unaryFilter.field);return ye.create(s,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let i=hn(t.unaryFilter.field);return ye.create(i,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let a=hn(t.unaryFilter.field);return ye.create(a,"!=",{nullValue:"NULL_VALUE"});default:return F()}}(r):r.fieldFilter!==void 0?function(t){return ye.create(hn(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 F()}}(t.fieldFilter.op),t.fieldFilter.value)}(r):r.compositeFilter!==void 0?function(t){return ot.create(t.compositeFilter.filters.map(n=>oy(n)),function(s){switch(s){case"AND":return"and";case"OR":return"or";default:return F()}}(t.compositeFilter.op))}(r):F()}function AS(r){return fS[r]}function xS(r){return pS[r]}function SS(r){return mS[r]}function ln(r){return{fieldPath:r.canonicalString()}}function hn(r){return Ue.fromServerFormat(r.fieldPath)}function ay(r){return r instanceof ye?function(t){if(t.op==="=="){if(Fm(t.value))return{unaryFilter:{field:ln(t.field),op:"IS_NAN"}};if(Mm(t.value))return{unaryFilter:{field:ln(t.field),op:"IS_NULL"}}}else if(t.op==="!="){if(Fm(t.value))return{unaryFilter:{field:ln(t.field),op:"IS_NOT_NAN"}};if(Mm(t.value))return{unaryFilter:{field:ln(t.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:ln(t.field),op:xS(t.op),value:t.value}}}(r):r instanceof ot?function(t){let n=t.getFilters().map(s=>ay(s));return n.length===1?n[0]:{compositeFilter:{op:SS(t.op),filters:n}}}(r):F()}function RS(r){let e=[];return r.fields.forEach(t=>e.push(t.canonicalString())),{fieldPaths:e}}function uy(r){return r.length>=4&&r.get(0)==="projects"&&r.get(2)==="databases"}var Os=class r{constructor(e,t,n,s,i=q.min(),a=q.min(),u=Pe.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 Ic=class{constructor(e){this.Tt=e}};function PS(r){let e=ES({parent:r.parent,structuredQuery:r.structuredQuery});return r.limitType==="LAST"?lc(e,e.limit,"L"):e}var Oo=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(ae(e.integerValue));else if("doubleValue"in e){let n=ae(e.doubleValue);isNaN(n)?this.ft(t,13):(this.ft(t,15),Ps(n)?t.gt(0):t.gt(n))}else if("timestampValue"in e){let n=e.timestampValue;this.ft(t,20),typeof n=="string"&&(n=At(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(xt(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?Lg(e)?this.ft(t,Number.MAX_SAFE_INTEGER):Vg(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)):F()}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=_n,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(ae(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)}};Oo.xt=new Oo;var Ac=class{constructor(){this.Tn=new xc}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(yr.min())}getMinOffsetFromCollectionGroup(e,t){return k.resolve(yr.min())}updateCollectionGroup(e,t,n){return k.resolve()}updateIndexEntries(e,t){return k.resolve()}},xc=class{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),s=this.index[t]||new ve(me.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 ve(me.comparator)).toArray()}};var mF=new Uint8Array(0);var Xm={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},cy=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(cy,$e.DEFAULT_COLLECTION_PERCENTILE,$e.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),$e.DISABLED=new $e(-1,0,0);var Ns=class r{constructor(e){this.$n=e}next(){return this.$n+=2,this.$n}static Kn(){return new r(0)}static Un(){return new r(-1)}};var Zm="LruGarbageCollector",CS=1048576;function eg([r,e],[t,n]){let s=Q(r,t);return s===0?Q(e,n):s}var Sc=class{constructor(e){this.Hn=e,this.buffer=new ve(eg),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();eg(t,n)<0&&(this.buffer=this.buffer.delete(n).add(t))}}get maxValue(){return this.buffer.last()[0]}},Rc=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(Zm,`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){On(t)?V(Zm,"Ignoring IndexedDB error during garbage collection: ",t):await Dn(t)}await this.er(3e5)})}},Pc=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(yn.ae);let n=new Sc(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(Xm)):this.getCacheSize(e).next(n=>n<this.params.cacheSizeCollectionThreshold?(V("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),Xm):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(),un()<=W.DEBUG&&V("LruGarbageCollector",`LRU Garbage Collection
|
|
12
|
+
}`}};var vc=class{constructor(e,t){this.count=e,this.unchangedNames=t}};var fe,J;function TS(r){switch(r){case D.OK:return F();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 F()}}function oy(r){if(r===void 0)return xt("GRPC error has no .code"),D.UNKNOWN;switch(r){case fe.OK:return D.OK;case fe.CANCELLED:return D.CANCELLED;case fe.UNKNOWN:return D.UNKNOWN;case fe.DEADLINE_EXCEEDED:return D.DEADLINE_EXCEEDED;case fe.RESOURCE_EXHAUSTED:return D.RESOURCE_EXHAUSTED;case fe.INTERNAL:return D.INTERNAL;case fe.UNAVAILABLE:return D.UNAVAILABLE;case fe.UNAUTHENTICATED:return D.UNAUTHENTICATED;case fe.INVALID_ARGUMENT:return D.INVALID_ARGUMENT;case fe.NOT_FOUND:return D.NOT_FOUND;case fe.ALREADY_EXISTS:return D.ALREADY_EXISTS;case fe.PERMISSION_DENIED:return D.PERMISSION_DENIED;case fe.FAILED_PRECONDITION:return D.FAILED_PRECONDITION;case fe.ABORTED:return D.ABORTED;case fe.OUT_OF_RANGE:return D.OUT_OF_RANGE;case fe.UNIMPLEMENTED:return D.UNIMPLEMENTED;case fe.DATA_LOSS:return D.DATA_LOSS;default:return F()}}(J=fe||(fe={}))[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 Xm=null;function ES(){return new TextEncoder}var IS=new Et([4294967295,4294967295],0);function Zm(r){let e=ES().encode(r),t=new Lu;return t.update(e),new Uint8Array(t.digest())}function eg(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 wc=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(IS)===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=Zm(e),[n,s]=eg(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=Zm(e),[n,s]=eg(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 Co=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,Ns.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new r(q.min(),s,new le(Q),Pt(),H())}},Ns=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,H(),H(),H())}};var mn=class{constructor(e,t,n,s){this.me=e,this.removedTargetIds=t,this.key=n,this.fe=s}},ko=class{constructor(e,t){this.targetId=e,this.ge=t}},Do=class{constructor(e,t,n=Pe.EMPTY_BYTE_STRING,s=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=s}},Oo=class{constructor(){this.pe=0,this.ye=tg(),this.we=Pe.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=H(),t=H(),n=H();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:F()}}),new Ns(this.we,this.Se,e,t,n)}Me(){this.be=!1,this.ye=tg()}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}},bc=class{constructor(e){this.ke=e,this.qe=new Map,this.Qe=Pt(),this.$e=mo(),this.Ke=mo(),this.Ue=new le(Q)}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:F()}})}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(dc(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.Ue=this.Ue.insert(t,h)}Xm==null||Xm.rt(function(f,m,g,E,P){var C,R,N,M,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:(M=(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&&M!==void 0?M: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:T=>{var y;return(y=E==null?void 0:E.mightContain(T))!==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 yn("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 wc(a,s,i)}catch(c){return yn(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&&dc(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=H();this.Ke.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 Co(e,t,this.Ue,this.Qe,n);return this.Qe=Pt(),this.$e=mo(),this.Ke=mo(),this.Ue=new le(Q),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.Ke=this.Ke.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.Ke=this.Ke.insert(t,this.ct(t).delete(e)),this.Ke=this.Ke.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 Oo,this.qe.set(e,t)),t}ct(e){let t=this.Ke.get(e);return t||(t=new ve(Q),this.Ke=this.Ke.insert(e,t)),t}_t(e){let t=this.$e.get(e);return t||(t=new ve(Q),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 Oo),this.ke.getRemoteKeysForTarget(e).forEach(t=>{this.ze(e,t,null)})}ut(e,t){return this.ke.getRemoteKeysForTarget(e).has(t)}};function mo(){return new le(j.comparator)}function tg(){return new le(j.comparator)}var xS={asc:"ASCENDING",desc:"DESCENDING"},AS={"<":"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"},SS={and:"AND",or:"OR"},Tc=class{constructor(e,t){this.databaseId=e,this.useProto3Json=t}};function Ec(r,e){return r.useProto3Json||sa(e)?e:{value:e}}function No(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 ay(r,e){return r.useProto3Json?e.toBase64():e.toUint8Array()}function RS(r,e){return No(r,e.toTimestamp())}function st(r){return ee(!!r),q.fromTimestamp(function(t){let n=At(t);return new be(n.seconds,n.nanos)}(r))}function Ll(r,e){return Ic(r,e).canonicalString()}function Ic(r,e){let t=function(s){return new me(["projects",s.projectId,"databases",s.database])}(r).child("documents");return e===void 0?t:t.child(e)}function uy(r){let e=me.fromString(r);return ee(fy(e)),e}function xc(r,e){return Ll(r.databaseId,e.path)}function $u(r,e){let t=uy(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(ly(t))}function cy(r,e){return Ll(r.databaseId,e)}function PS(r){let e=uy(r);return e.length===4?me.emptyPath():ly(e)}function Ac(r){return new me(["projects",r.databaseId.projectId,"databases",r.databaseId.database]).canonicalString()}function ly(r){return ee(r.length>4&&r.get(4)==="documents"),r.popFirst(5)}function rg(r,e,t){return{name:xc(r,e),fields:t.value.mapValue.fields}}function CS(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:F()}(e.targetChange.targetChangeType||"NO_CHANGE"),s=e.targetChange.targetIds||[],i=function(h,f){return h.useProto3Json?(ee(f===void 0||typeof f=="string"),Pe.fromBase64String(f||"")):(ee(f===void 0||f instanceof Buffer||f instanceof Uint8Array),Pe.fromUint8Array(f||new Uint8Array))}(r,e.targetChange.resumeToken),a=e.targetChange.cause,u=a&&function(h){let f=h.code===void 0?D.UNKNOWN:oy(h.code);return new L(f,h.message||"")}(a);t=new Do(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=$u(r,n.document.name),i=st(n.document.updateTime),a=n.document.createTime?st(n.document.createTime):q.min(),u=new Ue({mapValue:{fields:n.document.fields}}),c=Je.newFoundDocument(s,i,a,u),h=n.targetIds||[],f=n.removedTargetIds||[];t=new mn(h,f,c.key,c)}else if("documentDelete"in e){e.documentDelete;let n=e.documentDelete;n.document;let s=$u(r,n.document),i=n.readTime?st(n.readTime):q.min(),a=Je.newNoDocument(s,i),u=n.removedTargetIds||[];t=new mn([],u,a.key,a)}else if("documentRemove"in e){e.documentRemove;let n=e.documentRemove;n.document;let s=$u(r,n.document),i=n.removedTargetIds||[];t=new mn([],i,s,null)}else{if(!("filter"in e))return F();{e.filter;let n=e.filter;n.targetId;let{count:s=0,unchangedNames:i}=n,a=new vc(s,i),u=n.targetId;t=new ko(u,a)}}return t}function kS(r,e){let t;if(e instanceof br)t={update:rg(r,e.key,e.value)};else if(e instanceof Po)t={delete:xc(r,e.key)};else if(e instanceof ut)t={update:rg(r,e.key,e.data),updateMask:US(e.fieldMask)};else{if(!(e instanceof mc))return F();t={verify:xc(r,e.key)}}return e.fieldTransforms.length>0&&(t.updateTransforms=e.fieldTransforms.map(n=>function(i,a){let u=a.transform;if(u instanceof Sn)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 Rn)return{fieldPath:a.field.canonicalString(),increment:u.Ie};throw F()}(0,n))),e.precondition.isNone||(t.currentDocument=function(s,i){return i.updateTime!==void 0?{updateTime:RS(s,i.updateTime)}:i.exists!==void 0?{exists:i.exists}:F()}(r,e.precondition)),t}function DS(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 pc(a,s.transformResults||[])}(t,e))):[]}function OS(r,e){return{documents:[cy(r,e.path)]}}function NS(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=cy(r,s);let i=function(h){if(h.length!==0)return dy(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:dn(g.field),direction:MS(g.dir)}}(f))}(e.orderBy);a&&(t.structuredQuery.orderBy=a);let u=Ec(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 VS(r){let e=PS(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=hy(m);return g instanceof at&&zg(g)?g.getFilters():[g]}(t.where));let a=[];t.orderBy&&(a=function(m){return m.map(g=>function(P){return new In(fn(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,sa(g)?null:g}(t.limit));let c=null;t.startAt&&(c=function(m){let g=!!m.before,E=m.values||[];return new En(E,g)}(t.startAt));let h=null;return t.endAt&&(h=function(m){let g=!m.before,E=m.values||[];return new En(E,g)}(t.endAt)),oS(e,s,a,i,u,"F",c,h)}function LS(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 F()}}(e.purpose);return t==null?null:{"goog-listen-tags":t}}function hy(r){return r.unaryFilter!==void 0?function(t){switch(t.unaryFilter.op){case"IS_NAN":let n=fn(t.unaryFilter.field);return ye.create(n,"==",{doubleValue:NaN});case"IS_NULL":let s=fn(t.unaryFilter.field);return ye.create(s,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let i=fn(t.unaryFilter.field);return ye.create(i,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let a=fn(t.unaryFilter.field);return ye.create(a,"!=",{nullValue:"NULL_VALUE"});default:return F()}}(r):r.fieldFilter!==void 0?function(t){return ye.create(fn(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 F()}}(t.fieldFilter.op),t.fieldFilter.value)}(r):r.compositeFilter!==void 0?function(t){return at.create(t.compositeFilter.filters.map(n=>hy(n)),function(s){switch(s){case"AND":return"and";case"OR":return"or";default:return F()}}(t.compositeFilter.op))}(r):F()}function MS(r){return xS[r]}function FS(r){return AS[r]}function jS(r){return SS[r]}function dn(r){return{fieldPath:r.canonicalString()}}function fn(r){return Be.fromServerFormat(r.fieldPath)}function dy(r){return r instanceof ye?function(t){if(t.op==="=="){if(qm(t.value))return{unaryFilter:{field:dn(t.field),op:"IS_NAN"}};if($m(t.value))return{unaryFilter:{field:dn(t.field),op:"IS_NULL"}}}else if(t.op==="!="){if(qm(t.value))return{unaryFilter:{field:dn(t.field),op:"IS_NOT_NAN"}};if($m(t.value))return{unaryFilter:{field:dn(t.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:dn(t.field),op:FS(t.op),value:t.value}}}(r):r instanceof at?function(t){let n=t.getFilters().map(s=>dy(s));return n.length===1?n[0]:{compositeFilter:{op:jS(t.op),filters:n}}}(r):F()}function US(r){let e=[];return r.fields.forEach(t=>e.push(t.canonicalString())),{fieldPaths:e}}function fy(r){return r.length>=4&&r.get(0)==="projects"&&r.get(2)==="databases"}var Vs=class r{constructor(e,t,n,s,i=q.min(),a=q.min(),u=Pe.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 Sc=class{constructor(e){this.Tt=e}};function BS(r){let e=VS({parent:r.parent,structuredQuery:r.structuredQuery});return r.limitType==="LAST"?fc(e,e.limit,"L"):e}var Vo=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(ae(e.integerValue));else if("doubleValue"in e){let n=ae(e.doubleValue);isNaN(n)?this.ft(t,13):(this.ft(t,15),ks(n)?t.gt(0):t.gt(n))}else if("timestampValue"in e){let n=e.timestampValue;this.ft(t,20),typeof n=="string"&&(n=At(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?Bg(e)?this.ft(t,Number.MAX_SAFE_INTEGER):Ug(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)):F()}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=wn,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(ae(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)}};Vo.xt=new Vo;var Rc=class{constructor(){this.Tn=new Pc}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()}},Pc=class{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),s=this.index[t]||new ve(me.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 ve(me.comparator)).toArray()}};var kF=new Uint8Array(0);var ng={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},py=41943040,qe=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}};qe.DEFAULT_COLLECTION_PERCENTILE=10,qe.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,qe.DEFAULT=new qe(py,qe.DEFAULT_COLLECTION_PERCENTILE,qe.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),qe.DISABLED=new qe(-1,0,0);var Ls=class r{constructor(e){this.$n=e}next(){return this.$n+=2,this.$n}static Kn(){return new r(0)}static Un(){return new r(-1)}};var sg="LruGarbageCollector",$S=1048576;function ig([r,e],[t,n]){let s=Q(r,t);return s===0?Q(e,n):s}var Cc=class{constructor(e){this.Hn=e,this.buffer=new ve(ig),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();ig(t,n)<0&&(this.buffer=this.buffer.delete(n).add(t))}}get maxValue(){return this.buffer.last()[0]}},kc=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(sg,`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){Vn(t)?V(sg,"Ignoring IndexedDB error during garbage collection: ",t):await Nn(t)}await this.er(3e5)})}},Dc=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(vn.ae);let n=new Cc(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(ng)):this.getCacheSize(e).next(n=>n<this.params.cacheSizeCollectionThreshold?(V("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),ng):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(),ln()<=W.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 kS(r,e){return new Pc(r,e)}var Cc=class{constructor(){this.changes=new St(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,We.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 kc=class{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}};var Dc=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&&Ss(n.mutation,s,qe.empty(),be.now()),s))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(n=>this.getLocalViewOfDocuments(e,n,H()).next(()=>n))}getLocalViewOfDocuments(e,t,n=H()){let s=fr();return this.populateOverlays(e,s,t).next(()=>this.computeViews(e,t,s,n).next(i=>{let a=Es();return i.forEach((u,c)=>{a=a.insert(u,c.overlayedDocument)}),a}))}getOverlayedDocuments(e,t){let n=fr();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,H()))}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=Rt(),a=xs(),u=function(){return xs()}();return t.forEach((c,h)=>{let f=n.get(h.key);s.has(h.key)&&(f===void 0||f.mutation instanceof at)?i=i.insert(h.key,h):f!==void 0?(a.set(h.key,f.mutation.getFieldMask()),Ss(f.mutation,h,f.mutation.getFieldMask(),be.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 kc(f,(m=a.get(h))!==null&&m!==void 0?m:null))}),u))}recalculateAndSaveOverlays(e,t){let n=xs(),s=new le((a,u)=>a-u),i=H();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)||H()).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=Hg();f.forEach(g=>{if(!i.has(g)){let E=Zg(t.get(g),n.get(g));E!==null&&m.set(g,E),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):Qx(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(fr()),u=Rs,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,H())).next(f=>({batchId:u,changes:Kg(f)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new j(t)).next(n=>{let s=Es();return n.isFoundDocument()&&(s=s.insert(n.key,n)),s})}getDocumentsMatchingCollectionGroupQuery(e,t,n,s){let i=t.collectionGroup,a=Es();return this.indexManager.getCollectionParents(e,i).next(u=>k.forEach(u,c=>{let h=function(m,g){return new En(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,We.newInvalidDocument(f)))});let u=Es();return a.forEach((c,h)=>{let f=i.get(c);f!==void 0&&Ss(f.mutation,h,qe.empty(),be.now()),oa(t,h)&&(u=u.insert(c,h))}),u})}};var Oc=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:nt(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:PS(s.bundledQuery),readTime:nt(s.readTime)}}(t)),k.resolve()}};var Nc=class{constructor(){this.overlays=new le(j.comparator),this.Rr=new Map}getOverlay(e,t){return k.resolve(this.overlays.get(t))}getOverlays(e,t){let n=fr();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=fr(),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 le((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=fr(),i=i.insert(h.largestBatchId,f)),f.set(h.getKey(),h)}}let u=fr(),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 mc(t,n));let i=this.Rr.get(t);i===void 0&&(i=H(),this.Rr.set(t,i)),this.Rr.set(t,i.add(n.key))}};var Vc=class{constructor(){this.sessionToken=Pe.EMPTY_BYTE_STRING}getSessionToken(e){return k.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,k.resolve()}};var Vs=class{constructor(){this.Vr=new ve(pe.mr),this.gr=new ve(pe.pr)}isEmpty(){return this.Vr.isEmpty()}addReference(e,t){let n=new pe(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 pe(e,t))}Sr(e,t){e.forEach(n=>this.removeReference(n,t))}br(e){let t=new j(new me([])),n=new pe(t,e),s=new pe(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 me([])),n=new pe(t,e),s=new pe(t,e+1),i=H();return this.gr.forEachInRange([n,s],a=>{i=i.add(a.key)}),i}containsKey(e){let t=new pe(e,0),n=this.Vr.firstAfterOrEqual(t);return n!==null&&e.isEqual(n.key)}},pe=class{constructor(e,t){this.key=e,this.Cr=t}static mr(e,t){return j.comparator(e.key,t.key)||Q(e.Cr,t.Cr)}static pr(e,t){return Q(e.Cr,t.Cr)||j.comparator(e.key,t.key)}};var Lc=class{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Fr=1,this.Mr=new ve(pe.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 fc(i,t,n,s);this.mutationQueue.push(a);for(let u of s)this.Mr=this.Mr.add(new pe(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?Al:this.Fr-1)}getAllMutationBatches(e){return k.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new pe(t,0),s=new pe(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 ve(Q);return t.forEach(s=>{let i=new pe(s,0),a=new pe(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 pe(new j(i),0),u=new ve(Q);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 pe(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 pe(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 Mc=class{constructor(e){this.kr=e,this.docs=function(){return new le(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():We.newInvalidDocument(t))}getEntries(e,t){let n=Rt();return t.forEach(s=>{let i=this.docs.get(s);n=n.insert(s,i?i.document.mutableCopy():We.newInvalidDocument(s))}),k.resolve(n)}getDocumentsMatchingQuery(e,t,n,s){let i=Rt(),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||Px(Rx(f),n)<=0||(s.has(f.key)||oa(t,f))&&(i=i.insert(f.key,f.mutableCopy()))}return k.resolve(i)}getAllFromCollectionGroup(e,t,n,s){F()}qr(e,t){return k.forEach(this.docs,n=>t(n))}newChangeBuffer(e){return new Fc(this)}getSize(e){return k.resolve(this.size)}},Fc=class extends Cc{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 jc=class{constructor(e){this.persistence=e,this.Qr=new St(t=>Cl(t),kl),this.lastRemoteSnapshotVersion=q.min(),this.highestTargetId=0,this.$r=0,this.Kr=new Vs,this.targetCount=0,this.Ur=Ns.Kn()}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.Ur.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.Ur=new Ns(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.Kr.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.Kr.yr(t,n),k.resolve()}removeMatchingKeys(e,t,n){this.Kr.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.Kr.br(t),k.resolve()}getMatchingKeysForTargetId(e,t){let n=this.Kr.vr(t);return k.resolve(n)}containsKey(e,t){return k.resolve(this.Kr.containsKey(t))}};var No=class{constructor(e,t){this.Wr={},this.overlays={},this.Gr=new yn(0),this.zr=!1,this.zr=!0,this.jr=new Vc,this.referenceDelegate=e(this),this.Hr=new jc(this),this.indexManager=new Ac,this.remoteDocumentCache=function(s){return new Mc(s)}(n=>this.referenceDelegate.Jr(n)),this.serializer=new Ic(t),this.Yr=new Oc(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 Nc,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Wr[e.toKey()];return n||(n=new Lc(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 Uc(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)))}},Uc=class extends Ju{constructor(e){super(),this.currentSequenceNumber=e}},Bc=class r{constructor(e){this.persistence=e,this.ti=new Vs,this.ni=null}static ri(e){return new r(e)}get ii(){if(this.ni)return this.ni;throw F()}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)])}},Vo=class r{constructor(e,t){this.persistence=e,this.oi=new St(n=>Ox(n.path),(n,s)=>n.isEqual(s)),this.garbageCollector=kS(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+=mo(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 $c=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=H(),s=H();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 qc=class{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}};var zc=class{constructor(){this.Zi=!1,this.Xi=!1,this.es=100,this.ts=function(){return om()?8:kx(im())>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 qc;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?(un()<=W.DEBUG&&V("QueryEngine","SDK will not create cache indexes for query:",cn(t),"since it only creates cache indexes for collection contains","more than or equal to",this.es,"documents"),k.resolve()):(un()<=W.DEBUG&&V("QueryEngine","Query:",cn(t),"scans",n.documentReadCount,"local documents and returns",s,"documents as results."),n.documentReadCount>this.ts*s?(un()<=W.DEBUG&&V("QueryEngine","The SDK decides to create cache indexes for query:",cn(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,rt(t))):k.resolve())}rs(e,t){if($m(t))return k.resolve(null);let n=rt(t);return this.indexManager.getIndexType(e,n).next(s=>s===0?null:(t.limit!==null&&s===1&&(t=lc(t,null,"F"),n=rt(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next(i=>{let a=H(...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,lc(t,null,"F")):this.hs(e,h,t,c)}))})))}ss(e,t,n,s){return $m(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):(un()<=W.DEBUG&&V("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),cn(t)),this.hs(e,a,t,Sx(s,Rs)).next(u=>u))})}cs(e,t){let n=new ve(zg(e));return t.forEach((s,i)=>{oa(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 un()<=W.DEBUG&&V("QueryEngine","Using full collection scan to execute query:",cn(t)),this.ns.getDocumentsMatchingQuery(e,t,yr.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 Nl="LocalStore",DS=3e8,Gc=class{constructor(e,t,n,s){this.persistence=e,this.Ps=t,this.serializer=s,this.Ts=new le(Q),this.Is=new St(i=>Cl(i),kl),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 Dc(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 OS(r,e,t,n){return new Gc(r,e,t,n)}async function ly(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=H();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 NS(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(),E=k.resolve();return g.forEach(P=>{E=E.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)))})}),E.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=H();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 hy(r){let e=$(r);return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.Hr.getLastRemoteSnapshotVersion(t))}function VS(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 E=g.withSequenceNumber(i.currentSequenceNumber);e.targetMismatches.get(m)!==null?E=E.withResumeToken(Pe.EMPTY_BYTE_STRING,q.min()).withLastLimboFreeSnapshotVersion(q.min()):f.resumeToken.approximateByteSize()>0&&(E=E.withResumeToken(f.resumeToken,n)),s=s.insert(m,E),function(C,R,N){return C.resumeToken.approximateByteSize()===0||R.snapshotVersion.toMicroseconds()-C.snapshotVersion.toMicroseconds()>=DS?!0:N.addedDocuments.size+N.modifiedDocuments.size+N.removedDocuments.size>0}(g,E,f)&&u.push(t.Hr.updateTargetData(i,E))});let c=Rt(),h=H();if(e.documentUpdates.forEach(f=>{e.resolvedLimboDocuments.has(f)&&u.push(t.persistence.referenceDelegate.updateLimboDocument(i,f))}),u.push(LS(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 LS(r,e,t){let n=H(),s=H();return t.forEach(i=>n=n.add(i)),e.getEntries(r,n).next(i=>{let a=Rt();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(Nl,"Ignoring outdated watch update for ",u,". Current version:",h.version," Watch version:",c.version)}),{Vs:a,fs:s}})}function MS(r,e){let t=$(r);return t.persistence.runTransaction("Get next mutation batch","readonly",n=>(e===void 0&&(e=Al),t.mutationQueue.getNextMutationBatchAfterBatchId(n,e)))}function FS(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 Os(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 Kc(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(!On(a))throw a;V(Nl,`Failed to update sequence numbers for target ${e}: ${a}`)}n.Ts=n.Ts.remove(e),n.Is.delete(s.target)}function tg(r,e,t){let n=$(r),s=q.min(),i=H();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,rt(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:H())).next(u=>(jS(n,Yx(e),u),{documents:u,gs:i})))}function jS(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 Lo=class{constructor(){this.activeTargetIds=nS()}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 Hc=class{constructor(){this.ho=new Lo,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 Lo,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}};var Wc=class{To(e){}shutdown(){}};var rg="ConnectivityMonitor",Mo=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(rg,"Network connectivity changed: AVAILABLE");for(let e of this.Vo)e(0)}Ro(){V(rg,"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 po=null;function Qc(){return po===null?po=function(){return 268435456+Math.round(2147483648*Math.random())}():po++,"0x"+po.toString(16)}var Uu="RestConnection",US={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"},Jc=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===Io?`project_id=${n}`:`project_id=${n}&database_id=${s}`}So(e,t,n,s,i){let a=Qc(),u=this.bo(e,t.toUriEncodedString());V(Uu,`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(Uu,`Received RPC '${e}' ${a}: `,h),h),h=>{throw mn(Uu,`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/"+kn}(),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=US[e];return`${this.po}/v1/${t}:${n}`}terminate(){}};var Yc=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()}Ko(e){this.ko(e)}Uo(e){this.qo(e)}};var Re="WebChannelConnection",Xc=class extends Jc{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=Qc();return new Promise((a,u)=>{let c=new Nu;c.setWithCredentials(!0),c.listenOnce(Vu.COMPLETE,()=>{try{switch(c.getLastErrorCode()){case Ts.NO_ERROR:let f=c.getResponseJson();V(Re,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(f)),a(f);break;case Ts.TIMEOUT:V(Re,`RPC '${e}' ${i} timed out`),u(new L(D.DEADLINE_EXCEEDED,"Request time out"));break;case Ts.HTTP_ERROR:let m=c.getStatus();if(V(Re,`RPC '${e}' ${i} failed with status:`,m,"response text:",c.getResponseText()),m>0){let g=c.getResponseJson();Array.isArray(g)&&(g=g[0]);let E=g==null?void 0:g.error;if(E&&E.status&&E.message){let P=function(R){let N=R.toLowerCase().replace(/_/g,"-");return Object.values(D).indexOf(N)>=0?N:D.UNKNOWN}(E.status);u(new L(P,E.message))}else u(new L(D.UNKNOWN,"Server responded with status "+c.getStatus()))}else u(new L(D.UNAVAILABLE,"Connection failed."));break;default:F()}}finally{V(Re,`RPC '${e}' ${i} completed.`)}});let h=JSON.stringify(s);V(Re,`RPC '${e}' ${i} sending request:`,s),c.send(t,"POST",h,n,15)})}Wo(e,t,n){let s=Qc(),i=[this.po,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=Fu(),u=Mu(),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(Re,`Creating RPC '${e}' stream ${s}: ${f}`,c);let m=a.createWebChannel(f,c),g=!1,E=!1,P=new Yc({Fo:R=>{E?V(Re,`Not sending because RPC '${e}' stream ${s} is closed:`,R):(g||(V(Re,`Opening RPC '${e}' stream ${s} transport.`),m.open(),g=!0),V(Re,`RPC '${e}' stream ${s} sending:`,R),m.send(R))},Mo:()=>m.close()}),C=(R,N,M)=>{R.listen(N,U=>{try{M(U)}catch(G){setTimeout(()=>{throw G},0)}})};return C(m,an.EventType.OPEN,()=>{E||(V(Re,`RPC '${e}' stream ${s} transport opened.`),P.Qo())}),C(m,an.EventType.CLOSE,()=>{E||(E=!0,V(Re,`RPC '${e}' stream ${s} transport closed`),P.Ko())}),C(m,an.EventType.ERROR,R=>{E||(E=!0,mn(Re,`RPC '${e}' stream ${s} transport errored:`,R),P.Ko(new L(D.UNAVAILABLE,"The operation could not be completed")))}),C(m,an.EventType.MESSAGE,R=>{var N;if(!E){let M=R.data[0];ee(!!M);let U=M,G=(U==null?void 0:U.error)||((N=U[0])===null||N===void 0?void 0:N.error);if(G){V(Re,`RPC '${e}' stream ${s} received error:`,G);let Y=G.status,B=function(w){let b=fe[w];if(b!==void 0)return ty(b)}(Y),T=G.message;B===void 0&&(B=D.INTERNAL,T="Unknown error status: "+Y+" with message "+G.message),E=!0,P.Ko(new L(B,T)),m.close()}else V(Re,`RPC '${e}' stream ${s} received:`,M),P.Uo(M)}}),C(u,Lu.STAT_EVENT,R=>{R.stat===lo.PROXY?V(Re,`RPC '${e}' stream ${s} detected buffering proxy`):R.stat===lo.NOPROXY&&V(Re,`RPC '${e}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{P.$o()},0),P}};function Bu(){return typeof document!="undefined"?document:null}function aa(r){return new vc(r,!0)}var Fo=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 ng="PersistentStream",jo=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 Fo(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?(It(t.toString()),It("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(ng,`close with error: ${e}`),this.stream=null,this.close(4,e)}R_(e){return t=>{this.Ti.enqueueAndForget(()=>this.i_===e?t():(V(ng,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}},Zc=class extends jo{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=_S(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?nt(a.readTime):q.min()}(e);return this.listener.p_(t,n)}y_(e){let t={};t.database=Ec(this.serializer),t.addTarget=function(i,a){let u,c=a.target;if(u=cc(c)?{documents:bS(i,c)}:{query:TS(i,c).ht},u.targetId=a.targetId,a.resumeToken.approximateByteSize()>0){u.resumeToken=ry(i,a.resumeToken);let h=wc(i,a.expectedCount);h!==null&&(u.expectedCount=h)}else if(a.snapshotVersion.compareTo(q.min())>0){u.readTime=Do(i,a.snapshotVersion.toTimestamp());let h=wc(i,a.expectedCount);h!==null&&(u.expectedCount=h)}return u}(this.serializer,e);let n=IS(this.serializer,e);n&&(t.labels=n),this.I_(t)}w_(e){let t={};t.database=Ec(this.serializer),t.removeTarget=e,this.I_(t)}},el=class extends jo{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=wS(e.writeResults,e.commitTime),n=nt(e.commitTime);return this.listener.v_(n,t)}C_(){let e={};e.database=Ec(this.serializer),this.I_(e)}b_(e){let t={streamToken:this.lastStreamToken,writes:e.map(n=>vS(this.serializer,n))};this.I_(t)}};var tl=class{},rl=class extends tl{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,bc(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,bc(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()}},nl=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_?(
|
|
17
|
+
Total Duration: ${h-f}ms`),k.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:m})))}};function qS(r,e){return new Dc(r,e)}var Oc=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 Nc=class{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}};var Vc=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&&Ps(n.mutation,s,ze.empty(),be.now()),s))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(n=>this.getLocalViewOfDocuments(e,n,H()).next(()=>n))}getLocalViewOfDocuments(e,t,n=H()){let s=pr();return this.populateOverlays(e,s,t).next(()=>this.computeViews(e,t,s,n).next(i=>{let a=xs();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,H()))}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=Rs(),u=function(){return Rs()}();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()),Ps(f.mutation,h,f.mutation.getFieldMask(),be.now())):a.set(h.key,ze.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 Nc(f,(m=a.get(h))!==null&&m!==void 0?m:null))}),u))}recalculateAndSaveOverlays(e,t){let n=Rs(),s=new le((a,u)=>a-u),i=H();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)||ze.empty();f=u.applyToLocalView(h,f),n.set(c,f);let m=(s.get(u.batchId)||H()).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=Xg();f.forEach(g=>{if(!i.has(g)){let E=sy(t.get(g),n.get(g));E!==null&&m.set(g,E),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):aS(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=Cs,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,H())).next(f=>({batchId:u,changes:Yg(f)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new j(t)).next(n=>{let s=xs();return n.isFoundDocument()&&(s=s.insert(n.key,n)),s})}getDocumentsMatchingCollectionGroupQuery(e,t,n,s){let i=t.collectionGroup,a=xs();return this.indexManager.getCollectionParents(e,i).next(u=>k.forEach(u,c=>{let h=function(m,g){return new xn(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=xs();return a.forEach((c,h)=>{let f=i.get(c);f!==void 0&&Ps(f.mutation,h,ze.empty(),be.now()),ua(t,h)&&(u=u.insert(c,h))}),u})}};var Lc=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:BS(s.bundledQuery),readTime:st(s.readTime)}}(t)),k.resolve()}};var Mc=class{constructor(){this.overlays=new le(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 le((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 _c(t,n));let i=this.Rr.get(t);i===void 0&&(i=H(),this.Rr.set(t,i)),this.Rr.set(t,i.add(n.key))}};var Fc=class{constructor(){this.sessionToken=Pe.EMPTY_BYTE_STRING}getSessionToken(e){return k.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,k.resolve()}};var Ms=class{constructor(){this.Vr=new ve(pe.mr),this.gr=new ve(pe.pr)}isEmpty(){return this.Vr.isEmpty()}addReference(e,t){let n=new pe(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 pe(e,t))}Sr(e,t){e.forEach(n=>this.removeReference(n,t))}br(e){let t=new j(new me([])),n=new pe(t,e),s=new pe(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 me([])),n=new pe(t,e),s=new pe(t,e+1),i=H();return this.gr.forEachInRange([n,s],a=>{i=i.add(a.key)}),i}containsKey(e){let t=new pe(e,0),n=this.Vr.firstAfterOrEqual(t);return n!==null&&e.isEqual(n.key)}},pe=class{constructor(e,t){this.key=e,this.Cr=t}static mr(e,t){return j.comparator(e.key,t.key)||Q(e.Cr,t.Cr)}static pr(e,t){return Q(e.Cr,t.Cr)||j.comparator(e.key,t.key)}};var jc=class{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Fr=1,this.Mr=new ve(pe.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 gc(i,t,n,s);this.mutationQueue.push(a);for(let u of s)this.Mr=this.Mr.add(new pe(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?Rl:this.Fr-1)}getAllMutationBatches(e){return k.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new pe(t,0),s=new pe(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 ve(Q);return t.forEach(s=>{let i=new pe(s,0),a=new pe(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 pe(new j(i),0),u=new ve(Q);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 pe(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 pe(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 Uc=class{constructor(e){this.kr=e,this.docs=function(){return new le(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||BA(UA(f),n)<=0||(s.has(f.key)||ua(t,f))&&(i=i.insert(f.key,f.mutableCopy()))}return k.resolve(i)}getAllFromCollectionGroup(e,t,n,s){F()}qr(e,t){return k.forEach(this.docs,n=>t(n))}newChangeBuffer(e){return new Bc(this)}getSize(e){return k.resolve(this.size)}},Bc=class extends Oc{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 $c=class{constructor(e){this.persistence=e,this.Qr=new Rt(t=>Ol(t),Nl),this.lastRemoteSnapshotVersion=q.min(),this.highestTargetId=0,this.$r=0,this.Kr=new Ms,this.targetCount=0,this.Ur=Ls.Kn()}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.Ur.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.Ur=new Ls(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.Kr.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.Kr.yr(t,n),k.resolve()}removeMatchingKeys(e,t,n){this.Kr.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.Kr.br(t),k.resolve()}getMatchingKeysForTargetId(e,t){let n=this.Kr.vr(t);return k.resolve(n)}containsKey(e,t){return k.resolve(this.Kr.containsKey(t))}};var Lo=class{constructor(e,t){this.Wr={},this.overlays={},this.Gr=new vn(0),this.zr=!1,this.zr=!0,this.jr=new Fc,this.referenceDelegate=e(this),this.Hr=new $c(this),this.indexManager=new Rc,this.remoteDocumentCache=function(s){return new Uc(s)}(n=>this.referenceDelegate.Jr(n)),this.serializer=new Sc(t),this.Yr=new Lc(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 Mc,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Wr[e.toKey()];return n||(n=new jc(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 qc(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)))}},qc=class extends Zu{constructor(e){super(),this.currentSequenceNumber=e}},zc=class r{constructor(e){this.persistence=e,this.ti=new Ms,this.ni=null}static ri(e){return new r(e)}get ii(){if(this.ni)return this.ni;throw F()}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=>GA(n.path),(n,s)=>n.isEqual(s)),this.garbageCollector=qS(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+=yo(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 Gc=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=H(),s=H();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 Kc=class{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}};var Hc=class{constructor(){this.Zi=!1,this.Xi=!1,this.es=100,this.ts=function(){return hm()?8:qA(lm())>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 Kc;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?(ln()<=W.DEBUG&&V("QueryEngine","SDK will not create cache indexes for query:",hn(t),"since it only creates cache indexes for collection contains","more than or equal to",this.es,"documents"),k.resolve()):(ln()<=W.DEBUG&&V("QueryEngine","Query:",hn(t),"scans",n.documentReadCount,"local documents and returns",s,"documents as results."),n.documentReadCount>this.ts*s?(ln()<=W.DEBUG&&V("QueryEngine","The SDK decides to create cache indexes for query:",hn(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,nt(t))):k.resolve())}rs(e,t){if(Hm(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=fc(t,null,"F"),n=nt(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next(i=>{let a=H(...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,fc(t,null,"F")):this.hs(e,h,t,c)}))})))}ss(e,t,n,s){return Hm(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):(ln()<=W.DEBUG&&V("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),hn(t)),this.hs(e,a,t,jA(s,Cs)).next(u=>u))})}cs(e,t){let n=new ve(Qg(e));return t.forEach((s,i)=>{ua(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 ln()<=W.DEBUG&&V("QueryEngine","Using full collection scan to execute query:",hn(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 Ml="LocalStore",zS=3e8,Wc=class{constructor(e,t,n,s){this.persistence=e,this.Ps=t,this.serializer=s,this.Ts=new le(Q),this.Is=new Rt(i=>Ol(i),Nl),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 Vc(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 GS(r,e,t,n){return new Wc(r,e,t,n)}async function my(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=H();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 KS(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(),E=k.resolve();return g.forEach(P=>{E=E.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)))})}),E.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=H();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 gy(r){let e=$(r);return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.Hr.getLastRemoteSnapshotVersion(t))}function HS(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 E=g.withSequenceNumber(i.currentSequenceNumber);e.targetMismatches.get(m)!==null?E=E.withResumeToken(Pe.EMPTY_BYTE_STRING,q.min()).withLastLimboFreeSnapshotVersion(q.min()):f.resumeToken.approximateByteSize()>0&&(E=E.withResumeToken(f.resumeToken,n)),s=s.insert(m,E),function(C,R,N){return C.resumeToken.approximateByteSize()===0||R.snapshotVersion.toMicroseconds()-C.snapshotVersion.toMicroseconds()>=zS?!0:N.addedDocuments.size+N.modifiedDocuments.size+N.removedDocuments.size>0}(g,E,f)&&u.push(t.Hr.updateTargetData(i,E))});let c=Pt(),h=H();if(e.documentUpdates.forEach(f=>{e.resolvedLimboDocuments.has(f)&&u.push(t.persistence.referenceDelegate.updateLimboDocument(i,f))}),u.push(WS(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 WS(r,e,t){let n=H(),s=H();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(Ml,"Ignoring outdated watch update for ",u,". Current version:",h.version," Watch version:",c.version)}),{Vs:a,fs:s}})}function QS(r,e){let t=$(r);return t.persistence.runTransaction("Get next mutation batch","readonly",n=>(e===void 0&&(e=Rl),t.mutationQueue.getNextMutationBatchAfterBatchId(n,e)))}function JS(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 Vs(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 Qc(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(!Vn(a))throw a;V(Ml,`Failed to update sequence numbers for target ${e}: ${a}`)}n.Ts=n.Ts.remove(e),n.Is.delete(s.target)}function og(r,e,t){let n=$(r),s=q.min(),i=H();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:H())).next(u=>(YS(n,cS(e),u),{documents:u,gs:i})))}function YS(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 Fo=class{constructor(){this.activeTargetIds=mS()}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 Jc=class{constructor(){this.ho=new Fo,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 Fo,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}};var Yc=class{To(e){}shutdown(){}};var ag="ConnectivityMonitor",jo=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(ag,"Network connectivity changed: AVAILABLE");for(let e of this.Vo)e(0)}Ro(){V(ag,"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 go=null;function Xc(){return go===null?go=function(){return 268435456+Math.round(2147483648*Math.random())}():go++,"0x"+go.toString(16)}var qu="RestConnection",XS={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"},Zc=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===Ao?`project_id=${n}`:`project_id=${n}&database_id=${s}`}So(e,t,n,s,i){let a=Xc(),u=this.bo(e,t.toUriEncodedString());V(qu,`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(qu,`Received RPC '${e}' ${a}: `,h),h),h=>{throw yn(qu,`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/"+On}(),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=XS[e];return`${this.po}/v1/${t}:${n}`}terminate(){}};var el=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()}Ko(e){this.ko(e)}Uo(e){this.qo(e)}};var Re="WebChannelConnection",tl=class extends Zc{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=Xc();return new Promise((a,u)=>{let c=new Mu;c.setWithCredentials(!0),c.listenOnce(Fu.COMPLETE,()=>{try{switch(c.getLastErrorCode()){case Is.NO_ERROR:let f=c.getResponseJson();V(Re,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(f)),a(f);break;case Is.TIMEOUT:V(Re,`RPC '${e}' ${i} timed out`),u(new L(D.DEADLINE_EXCEEDED,"Request time out"));break;case Is.HTTP_ERROR:let m=c.getStatus();if(V(Re,`RPC '${e}' ${i} failed with status:`,m,"response text:",c.getResponseText()),m>0){let g=c.getResponseJson();Array.isArray(g)&&(g=g[0]);let E=g==null?void 0:g.error;if(E&&E.status&&E.message){let P=function(R){let N=R.toLowerCase().replace(/_/g,"-");return Object.values(D).indexOf(N)>=0?N:D.UNKNOWN}(E.status);u(new L(P,E.message))}else u(new L(D.UNKNOWN,"Server responded with status "+c.getStatus()))}else u(new L(D.UNAVAILABLE,"Connection failed."));break;default:F()}}finally{V(Re,`RPC '${e}' ${i} completed.`)}});let h=JSON.stringify(s);V(Re,`RPC '${e}' ${i} sending request:`,s),c.send(t,"POST",h,n,15)})}Wo(e,t,n){let s=Xc(),i=[this.po,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=Bu(),u=Uu(),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(Re,`Creating RPC '${e}' stream ${s}: ${f}`,c);let m=a.createWebChannel(f,c),g=!1,E=!1,P=new el({Fo:R=>{E?V(Re,`Not sending because RPC '${e}' stream ${s} is closed:`,R):(g||(V(Re,`Opening RPC '${e}' stream ${s} transport.`),m.open(),g=!0),V(Re,`RPC '${e}' stream ${s} sending:`,R),m.send(R))},Mo:()=>m.close()}),C=(R,N,M)=>{R.listen(N,U=>{try{M(U)}catch(G){setTimeout(()=>{throw G},0)}})};return C(m,cn.EventType.OPEN,()=>{E||(V(Re,`RPC '${e}' stream ${s} transport opened.`),P.Qo())}),C(m,cn.EventType.CLOSE,()=>{E||(E=!0,V(Re,`RPC '${e}' stream ${s} transport closed`),P.Ko())}),C(m,cn.EventType.ERROR,R=>{E||(E=!0,yn(Re,`RPC '${e}' stream ${s} transport errored:`,R),P.Ko(new L(D.UNAVAILABLE,"The operation could not be completed")))}),C(m,cn.EventType.MESSAGE,R=>{var N;if(!E){let M=R.data[0];ee(!!M);let U=M,G=(U==null?void 0:U.error)||((N=U[0])===null||N===void 0?void 0:N.error);if(G){V(Re,`RPC '${e}' stream ${s} received error:`,G);let Y=G.status,B=function(w){let b=fe[w];if(b!==void 0)return oy(b)}(Y),T=G.message;B===void 0&&(B=D.INTERNAL,T="Unknown error status: "+Y+" with message "+G.message),E=!0,P.Ko(new L(B,T)),m.close()}else V(Re,`RPC '${e}' stream ${s} received:`,M),P.Uo(M)}}),C(u,ju.STAT_EVENT,R=>{R.stat===fo.PROXY?V(Re,`RPC '${e}' stream ${s} detected buffering proxy`):R.stat===fo.NOPROXY&&V(Re,`RPC '${e}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{P.$o()},0),P}};function zu(){return typeof document!="undefined"?document:null}function ca(r){return new Tc(r,!0)}var Uo=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 ug="PersistentStream",Bo=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 Uo(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?(xt(t.toString()),xt("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(ug,`close with error: ${e}`),this.stream=null,this.close(4,e)}R_(e){return t=>{this.Ti.enqueueAndForget(()=>this.i_===e?t():(V(ug,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}},rl=class extends Bo{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=CS(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=Ac(this.serializer),t.addTarget=function(i,a){let u,c=a.target;if(u=dc(c)?{documents:OS(i,c)}:{query:NS(i,c).ht},u.targetId=a.targetId,a.resumeToken.approximateByteSize()>0){u.resumeToken=ay(i,a.resumeToken);let h=Ec(i,a.expectedCount);h!==null&&(u.expectedCount=h)}else if(a.snapshotVersion.compareTo(q.min())>0){u.readTime=No(i,a.snapshotVersion.toTimestamp());let h=Ec(i,a.expectedCount);h!==null&&(u.expectedCount=h)}return u}(this.serializer,e);let n=LS(this.serializer,e);n&&(t.labels=n),this.I_(t)}w_(e){let t={};t.database=Ac(this.serializer),t.removeTarget=e,this.I_(t)}},nl=class extends Bo{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=DS(e.writeResults,e.commitTime),n=st(e.commitTime);return this.listener.v_(n,t)}C_(){let e={};e.database=Ac(this.serializer),this.I_(e)}b_(e){let t={streamToken:this.lastStreamToken,writes:e.map(n=>kS(this.serializer,n))};this.I_(t)}};var sl=class{},il=class extends sl{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,Ic(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,Ic(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()}},ol=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_?(xt(t),this.N_=!1):V("OnlineStateTracker",t)}Q_(){this.O_!==null&&(this.O_.cancel(),this.O_=null)}};var Tr="RemoteStore",al=class{constructor(e,t,n,s,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.K_=[],this.U_=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 Gs(h),h.j_.set("Unknown"),h.W_.delete(4),await la(h)}(this))})}),this.j_=new ol(n,s)}};async function la(r){if(Er(r))for(let e of r.G_)await e(!0)}async function Gs(r){for(let e of r.G_)await e(!1)}function yy(r,e){let t=$(r);t.U_.has(e.targetId)||(t.U_.set(e.targetId,e),Bl(t)?Ul(t):Ln(t).c_()&&jl(t,e))}function Fl(r,e){let t=$(r),n=Ln(t);t.U_.delete(e),n.c_()&&_y(t,e),t.U_.size===0&&(n.c_()?n.P_():Er(t)&&t.j_.set("Unknown"))}function jl(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)}Ln(r).y_(e)}function _y(r,e){r.H_.Ne(e),Ln(r).w_(e)}function Ul(r){r.H_=new bc({getRemoteKeysForTarget:e=>r.remoteSyncer.getRemoteKeysForTarget(e),lt:e=>r.U_.get(e)||null,it:()=>r.datastore.serializer.databaseId}),Ln(r).start(),r.j_.B_()}function Bl(r){return Er(r)&&!Ln(r).u_()&&r.U_.size>0}function Er(r){return $(r).W_.size===0}function vy(r){r.H_=void 0}async function ZS(r){r.j_.set("Online")}async function eR(r){r.U_.forEach((e,t)=>{jl(r,e)})}async function tR(r,e){vy(r),Bl(r)?(r.j_.q_(e),Ul(r)):r.j_.set("Unknown")}async function rR(r,e,t){if(r.j_.set("Online"),e instanceof Do&&e.state===2&&e.cause)try{await async function(s,i){let a=i.cause;for(let u of i.targetIds)s.U_.has(u)&&(await s.remoteSyncer.rejectListen(u,a),s.U_.delete(u),s.H_.removeTarget(u))}(r,e)}catch(n){V(Tr,"Failed to remove targets %s: %s ",e.targetIds.join(","),n),await $o(r,n)}else if(e instanceof mn?r.H_.We(e):e instanceof ko?r.H_.Ze(e):r.H_.je(e),!t.isEqual(q.min()))try{let n=await gy(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.U_.get(h);f&&i.U_.set(h,f.withResumeToken(c.resumeToken,a))}}),u.targetMismatches.forEach((c,h)=>{let f=i.U_.get(c);if(!f)return;i.U_.set(c,f.withResumeToken(Pe.EMPTY_BYTE_STRING,f.snapshotVersion)),_y(i,c);let m=new Vs(f.target,c,h,f.sequenceNumber);jl(i,m)}),i.remoteSyncer.applyRemoteEvent(u)}(r,t)}catch(n){V(Tr,"Failed to raise snapshot:",n),await $o(r,n)}}async function $o(r,e,t){if(!Vn(e))throw e;r.W_.add(1),await Gs(r),r.j_.set("Offline"),t||(t=()=>gy(r.localStore)),r.asyncQueue.enqueueRetryable(async()=>{V(Tr,"Retrying IndexedDB access"),await t(),r.W_.delete(1),await la(r)})}function wy(r,e){return e().catch(t=>$o(r,t,e))}async function ha(r){let e=$(r),t=Zt(e),n=e.K_.length>0?e.K_[e.K_.length-1].batchId:Rl;for(;nR(e);)try{let s=await QS(e.localStore,n);if(s===null){e.K_.length===0&&t.P_();break}n=s.batchId,sR(e,s)}catch(s){await $o(e,s)}by(e)&&Ty(e)}function nR(r){return Er(r)&&r.K_.length<10}function sR(r,e){r.K_.push(e);let t=Zt(r);t.c_()&&t.S_&&t.b_(e.mutations)}function by(r){return Er(r)&&!Zt(r).u_()&&r.K_.length>0}function Ty(r){Zt(r).start()}async function iR(r){Zt(r).C_()}async function oR(r){let e=Zt(r);for(let t of r.K_)e.b_(t.mutations)}async function aR(r,e,t){let n=r.K_.shift(),s=yc.from(n,e,t);await wy(r,()=>r.remoteSyncer.applySuccessfulWrite(s)),await ha(r)}async function uR(r,e){e&&Zt(r).S_&&await async function(n,s){if(function(a){return TS(a)&&a!==D.ABORTED}(s.code)){let i=n.K_.shift();Zt(n).h_(),await wy(n,()=>n.remoteSyncer.rejectFailedWrite(i.batchId,s)),await ha(n)}}(r,e),by(r)&&Ty(r)}async function cg(r,e){let t=$(r);t.asyncQueue.verifyOperationInProgress(),V(Tr,"RemoteStore received new credentials");let n=Er(t);t.W_.add(3),await Gs(t),n&&t.j_.set("Unknown"),await t.remoteSyncer.handleCredentialChange(e),t.W_.delete(3),await la(t)}async function cR(r,e){let t=$(r);e?(t.W_.delete(2),await la(t)):e||(t.W_.add(2),await Gs(t),t.j_.set("Unknown"))}function Ln(r){return r.J_||(r.J_=function(t,n,s){let i=$(t);return i.M_(),new rl(n,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)}(r.datastore,r.asyncQueue,{xo:ZS.bind(null,r),No:eR.bind(null,r),Lo:tR.bind(null,r),p_:rR.bind(null,r)}),r.G_.push(async e=>{e?(r.J_.h_(),Bl(r)?Ul(r):r.j_.set("Unknown")):(await r.J_.stop(),vy(r))})),r.J_}function Zt(r){return r.Y_||(r.Y_=function(t,n,s){let i=$(t);return i.M_(),new nl(n,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)}(r.datastore,r.asyncQueue,{xo:()=>Promise.resolve(),No:iR.bind(null,r),Lo:uR.bind(null,r),D_:oR.bind(null,r),v_:aR.bind(null,r)}),r.G_.push(async e=>{e?(r.Y_.h_(),await ha(r)):(await r.Y_.stop(),r.K_.length>0&&(V(Tr,`Stopping write stream with ${r.K_.length} pending writes`),r.K_=[]))})),r.Y_}var ul=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 $l(r,e){if(xt("AsyncQueue",`${e}: ${r}`),Vn(r))return new L(D.UNAVAILABLE,`${e}: ${r}`);throw r}var qo=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=xs(),this.sortedSet=new le(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 $o=class{constructor(){this.Z_=new le(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}):F():this.Z_=this.Z_.insert(t,e)}X_(){let e=[];return this.Z_.inorderTraversal((t,n)=>{e.push(n)}),e}},Rn=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,Bo.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)&&ia(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 ol=class{constructor(){this.ea=void 0,this.ta=[]}na(){return this.ta.some(e=>e.ra())}},al=class{constructor(){this.queries=ig(),this.onlineState="Unknown",this.ia=new Set}terminate(){(function(t,n){let s=$(t),i=s.queries;s.queries=ig(),i.forEach((a,u)=>{for(let c of u.ta)c.onError(n)})})(this,new L(D.ABORTED,"Firestore shutting down"))}};function ig(){return new St(r=>qg(r),ia)}async function _y(r,e){let t=$(r),n=3,s=e.query,i=t.queries.get(s);i?!i.na()&&e.ra()&&(n=2):(i=new ol,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=jl(a,`Initialization of query '${cn(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)&&Ul(t)}async function vy(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 XS(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&&Ul(t)}function ZS(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 Ul(r){r.ia.forEach(e=>{e.next()})}var ul,og;(og=ul||(ul={}))._a="default",og.Cache="cache";var qo=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 Rn(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=Rn.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.ua=!0,this.aa.next(e)}ra(){return this.options.source!==ul.Cache}};var zo=class{constructor(e){this.key=e}},Go=class{constructor(e){this.key=e}},cl=class{constructor(e,t){this.query=e,this.fa=t,this.ga=null,this.hasCachedResults=!1,this.current=!1,this.pa=H(),this.mutatedKeys=H(),this.ya=zg(e),this.wa=new Bo(this.ya)}get Sa(){return this.fa}ba(e,t){let n=t?t.Da:new $o,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),E=oa(this.query,m)?m:null,P=!!g&&this.mutatedKeys.has(g.key),C=!!E&&(E.hasLocalMutations||this.mutatedKeys.has(E.key)&&E.hasCommittedMutations),R=!1;g&&E?g.data.isEqual(E.data)?P!==C&&(n.track({type:3,doc:E}),R=!0):this.va(g,E)||(n.track({type:2,doc:E}),R=!0,(c&&this.ya(E,c)>0||h&&this.ya(E,h)<0)&&(u=!0)):!g&&E?(n.track({type:0,doc:E}),R=!0):g&&!E&&(n.track({type:1,doc:g}),R=!0,(c||h)&&(u=!0)),R&&(E?(a=a.add(E),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(E,P){let C=R=>{switch(R){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return F()}};return C(E)-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 Rn(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 $o,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=H(),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 Go(n))}),this.pa.forEach(n=>{e.has(n)||t.push(new zo(n))}),t}Oa(e){this.fa=e.gs,this.pa=H();let t=this.ba(e.documents);return this.applyChanges(t,!0)}Na(){return Rn.fromInitialDocuments(this.query,this.wa,this.mutatedKeys,this.ga===0,this.hasCachedResults)}},Bl="SyncEngine",ll=class{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}},hl=class{constructor(e){this.key=e,this.Ba=!1}},dl=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 St(u=>qg(u),ia),this.qa=new Map,this.Qa=new Set,this.$a=new le(j.comparator),this.Ka=new Map,this.Ua=new Vs,this.Wa={},this.Ga=new Map,this.za=Ns.Un(),this.onlineState="Unknown",this.ja=void 0}get isPrimaryClient(){return this.ja===!0}};async function eR(r,e,t=!0){let n=Ay(r),s,i=n.ka.get(e);return i?(n.sharedClientState.addLocalQueryTarget(i.targetId),s=i.view.Na()):s=await wy(n,e,t,!0),s}async function tR(r,e){let t=Ay(r);await wy(t,e,!0,!1)}async function wy(r,e,t,n){let s=await FS(r.localStore,rt(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&&dy(r.remoteStore,s),u}async function rR(r,e,t,n,s){r.Ha=(m,g,E)=>async function(C,R,N,M){let U=R.view.ba(N);U.ls&&(U=await tg(C.localStore,R.query,!1).then(({documents:T})=>R.view.ba(T,U)));let G=M&&M.targetChanges.get(R.targetId),Y=M&&M.targetMismatches.get(R.targetId)!=null,B=R.view.applyChanges(U,C.isPrimaryClient,G,Y);return ug(C,R.targetId,B.Ma),B.snapshot}(r,m,g,E);let i=await tg(r.localStore,e,!0),a=new cl(e,i.gs),u=a.ba(i.documents),c=Ds.createSynthesizedTargetChangeForCurrentChange(t,n&&r.onlineState!=="Offline",s),h=a.applyChanges(u,r.isPrimaryClient,c);ug(r,t,h.Ma);let f=new ll(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 nR(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=>!ia(a,e))),void n.ka.delete(e);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(s.targetId),n.sharedClientState.isActiveQueryTarget(s.targetId)||await Kc(n.localStore,s.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(s.targetId),t&&Vl(n.remoteStore,s.targetId),fl(n,s.targetId)}).catch(Dn)):(fl(n,s.targetId),await Kc(n.localStore,s.targetId,!0))}async function sR(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),Vl(t.remoteStore,n.targetId))}async function iR(r,e,t){let n=dR(r);try{let s=await function(a,u){let c=$(a),h=be.now(),f=u.reduce((E,P)=>E.add(P.key),H()),m,g;return c.persistence.runTransaction("Locally write mutations","readwrite",E=>{let P=Rt(),C=H();return c.ds.getEntries(E,f).next(R=>{P=R,P.forEach((N,M)=>{M.isValidDocument()||(C=C.add(N))})}).next(()=>c.localDocuments.getOverlayedDocuments(E,P)).next(R=>{m=R;let N=[];for(let M of u){let U=cS(M,m.get(M.key).overlayedDocument);U!=null&&N.push(new at(M.key,U,Mg(U.value.mapValue),Jt.exists(!0)))}return c.mutationQueue.addMutationBatch(E,h,N,u)}).next(R=>{g=R;let N=R.applyToLocalDocumentSet(m,C);return c.documentOverlayCache.saveOverlays(E,R.batchId,N)})}).then(()=>({batchId:g.batchId,changes:Kg(m)}))}(n.localStore,e);n.sharedClientState.addPendingMutation(s.batchId),function(a,u,c){let h=a.Wa[a.currentUser.toKey()];h||(h=new le(Q)),h=h.insert(u,c),a.Wa[a.currentUser.toKey()]=h}(n,s.batchId,t),await zs(n,s.changes),await ca(n.remoteStore)}catch(s){let i=jl(s,"Failed to persist write");t.reject(i)}}async function by(r,e){let t=$(r);try{let n=await VS(t.localStore,e);e.targetChanges.forEach((s,i)=>{let a=t.Ka.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 zs(t,n,e)}catch(n){await Dn(n)}}function ag(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&&Ul(c)}(n.eventManager,e),s.length&&n.La.p_(s),n.onlineState=e,n.isPrimaryClient&&n.sharedClientState.setOnlineState(e)}}async function oR(r,e,t){let n=$(r);n.sharedClientState.updateQueryState(e,"rejected",t);let s=n.Ka.get(e),i=s&&s.key;if(i){let a=new le(j.comparator);a=a.insert(i,We.newNoDocument(i,q.min()));let u=H().add(i),c=new Ro(q.min(),new Map,new le(Q),a,u);await by(n,c),n.$a=n.$a.remove(i),n.Ka.delete(e),$l(n)}else await Kc(n.localStore,e,!1).then(()=>fl(n,e,t)).catch(Dn)}async function aR(r,e){let t=$(r),n=e.batch.batchId;try{let s=await NS(t.localStore,e);Ey(t,n,null),Ty(t,n),t.sharedClientState.updateMutationState(n,"acknowledged"),await zs(t,s)}catch(s){await Dn(s)}}async function uR(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);Ey(n,e,t),Ty(n,e),n.sharedClientState.updateMutationState(e,"rejected",t),await zs(n,s)}catch(s){await Dn(s)}}function Ty(r,e){(r.Ga.get(e)||[]).forEach(t=>{t.resolve()}),r.Ga.delete(e)}function Ey(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 fl(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.Ua.br(e).forEach(n=>{r.Ua.containsKey(n)||Iy(r,n)})}function Iy(r,e){r.Qa.delete(e.path.canonicalString());let t=r.$a.get(e);t!==null&&(Vl(r.remoteStore,t),r.$a=r.$a.remove(e),r.Ka.delete(t),$l(r))}function ug(r,e,t){for(let n of t)n instanceof zo?(r.Ua.addReference(n.key,e),cR(r,n)):n instanceof Go?(V(Bl,"Document no longer in limbo: "+n.key),r.Ua.removeReference(n.key,e),r.Ua.containsKey(n.key)||Iy(r,n.key)):F()}function cR(r,e){let t=e.key,n=t.path.canonicalString();r.$a.get(t)||r.Qa.has(n)||(V(Bl,"New document in limbo: "+t),r.Qa.add(n),$l(r))}function $l(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(me.fromString(e)),n=r.za.next();r.Ka.set(n,new hl(t)),r.$a=r.$a.insert(t,n),dy(r.remoteStore,new Os(rt(sa(t.path)),n,"TargetPurposeLimboResolution",yn.ae))}}async function zs(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=$c.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,E=>f.persistence.referenceDelegate.addReference(m,g.targetId,E)).next(()=>k.forEach(g.Ji,E=>f.persistence.referenceDelegate.removeReference(m,g.targetId,E)))))}catch(m){if(!On(m))throw m;V(Nl,"Failed to update sequence numbers: "+m)}for(let m of h){let g=m.targetId;if(!m.fromCache){let E=f.Ts.get(g),P=E.snapshotVersion,C=E.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(Bl,"User change. New user:",e.toKey());let n=await ly(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 zs(t,n.Rs)}}function hR(r,e){let t=$(r),n=t.Ka.get(e);if(n&&n.Ba)return H().add(n.key);{let s=H(),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 Ay(r){let e=$(r);return e.remoteStore.remoteSyncer.applyRemoteEvent=by.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=hR.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=oR.bind(null,e),e.La.p_=XS.bind(null,e.eventManager),e.La.Ja=ZS.bind(null,e.eventManager),e}function dR(r){let e=$(r);return e.remoteStore.remoteSyncer.applySuccessfulWrite=aR.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=uR.bind(null,e),e}var Pn=class{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=aa(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 OS(this.persistence,new zc,e.initialUser,this.serializer)}Xa(e){return new No(Bc.ri,this.serializer)}Za(e){return new Hc}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()}};Pn.provider={build:()=>new Pn};var pl=class extends Pn{constructor(e){super(),this.cacheSizeBytes=e}tu(e,t){ee(this.persistence.referenceDelegate instanceof Vo);let n=this.persistence.referenceDelegate.garbageCollector;return new Rc(n,e.asyncQueue,t)}Xa(e){let t=this.cacheSizeBytes!==void 0?$e.withCacheSize(this.cacheSizeBytes):$e.DEFAULT;return new No(n=>Vo.ri(n,t),this.serializer)}};var Ls=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=>ag(this.syncEngine,n,1),this.remoteStore.remoteSyncer.handleCredentialChange=lR.bind(null,this.syncEngine),await YS(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return function(){return new al}()}createDatastore(e){let t=aa(e.databaseInfo.databaseId),n=function(i){return new Xc(i)}(e.databaseInfo);return function(i,a,u,c){return new rl(i,a,u,c)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return function(n,s,i,a,u){return new sl(n,s,i,a,u)}(this.localStore,this.datastore,e.asyncQueue,t=>ag(this.syncEngine,t,0),function(){return Mo.D()?new Mo:new Wc}())}createSyncEngine(e,t){return function(s,i,a,u,c,h,f){let m=new dl(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(br,"RemoteStore shutting down."),i.W_.add(5),await qs(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()}};Ls.provider={build:()=>new Ls};var Ko=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):It("Uncaught Error in snapshot listener:",e.toString()))}su(){this.muted=!0}iu(e,t){setTimeout(()=>{this.muted||e(t)},0)}};var Zt="FirestoreClient",ml=class{constructor(e,t,n,s,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=s,this.user=_e.UNAUTHENTICATED,this.clientId=wo.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,async a=>{V(Zt,"Received user=",a.uid),await this.authCredentialListener(a),this.user=a}),this.appCheckCredentials.start(n,a=>(V(Zt,"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 et;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=jl(t,"Failed to shutdown persistence");e.reject(n)}}),e.promise}};async function $u(r,e){r.asyncQueue.verifyOperationInProgress(),V(Zt,"Initializing OfflineComponentProvider");let t=r.configuration;await e.initialize(t);let n=t.initialUser;r.setCredentialChangeListener(async s=>{n.isEqual(s)||(await ly(e.localStore,s),n=s)}),e.persistence.setDatabaseDeletedListener(()=>r.terminate()),r._offlineComponents=e}async function cg(r,e){r.asyncQueue.verifyOperationInProgress();let t=await fR(r);V(Zt,"Initializing OnlineComponentProvider"),await e.initialize(t,r.configuration),r.setCredentialChangeListener(n=>sg(e.remoteStore,n)),r.setAppCheckTokenChangeListener((n,s)=>sg(e.remoteStore,s)),r._onlineComponents=e}async function fR(r){if(!r._offlineComponents)if(r._uninitializedComponentsProvider){V(Zt,"Using user provided OfflineComponentProvider");try{await $u(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;mn("Error using user provided cache. Falling back to memory cache: "+t),await $u(r,new Pn)}}else V(Zt,"Using default OfflineComponentProvider"),await $u(r,new pl(void 0));return r._offlineComponents}async function xy(r){return r._onlineComponents||(r._uninitializedComponentsProvider?(V(Zt,"Using user provided OnlineComponentProvider"),await cg(r,r._uninitializedComponentsProvider._online)):(V(Zt,"Using default OnlineComponentProvider"),await cg(r,new Ls))),r._onlineComponents}function pR(r){return xy(r).then(e=>e.syncEngine)}async function gl(r){let e=await xy(r),t=e.eventManager;return t.onListen=eR.bind(null,e.syncEngine),t.onUnlisten=nR.bind(null,e.syncEngine),t.onFirstRemoteStoreListen=tR.bind(null,e.syncEngine),t.onLastRemoteStoreUnlisten=sR.bind(null,e.syncEngine),t}function mR(r,e,t={}){let n=new et;return r.asyncQueue.enqueueAndForget(async()=>function(i,a,u,c,h){let f=new Ko({next:g=>{f.su(),a.enqueueAndForget(()=>vy(i,m));let E=g.docs.has(u);!E&&g.fromCache?h.reject(new L(D.UNAVAILABLE,"Failed to get document because the client is offline.")):E&&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 qo(sa(u.path),f,{includeMetadataChanges:!0,Ta:!0});return _y(i,m)}(await gl(r),r.asyncQueue,e,t,n)),n.promise}function Sy(r){let e={};return r.timeoutSeconds!==void 0&&(e.timeoutSeconds=r.timeoutSeconds),e}var lg=new Map;function gR(r,e,t){if(!t)throw new L(D.INVALID_ARGUMENT,`Function ${r}() cannot be called with an empty ${e}.`)}function yR(r,e,t,n){if(e===!0&&n===!0)throw new L(D.INVALID_ARGUMENT,`${r} and ${t} cannot be used together.`)}function hg(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 ql(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":F()}function st(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=ql(r);throw new L(D.INVALID_ARGUMENT,`Expected type '${e.name}', but it was: ${t}`)}}return r}var Ry="firestore.googleapis.com",dg=!0,Ho=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=Ry,this.ssl=dg}else this.host=e.host,this.ssl=(t=e.ssl)!==null&&t!==void 0?t:dg;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e.cacheSizeBytes===void 0)this.cacheSizeBytes=cy;else{if(e.cacheSizeBytes!==-1&&e.cacheSizeBytes<CS)throw new L(D.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}yR("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=Sy((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}},Ms=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 Ho({}),this._settingsFrozen=!1,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 Ho(e),e.credentials!==void 0&&(this._authCredentials=function(n){if(!n)return new qu;switch(n.type){case"firstParty":return new Hu(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}_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=lg.get(t);n&&(V("ComponentProvider","Removing Datastore"),lg.delete(t),n.terminate())}(this),Promise.resolve()}};function _R(r,e,t,n={}){var s;let i=(r=st(r,Ms))._getSettings(),a=`${e}:${t}`;if(i.host!==Ry&&i.host!==a&&mn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),r._setSettings(Object.assign(Object.assign({},i),{host:a,ssl:!1})),n.mockUserToken){let u,c;if(typeof n.mockUserToken=="string")u=n.mockUserToken,c=_e.MOCK_USER;else{u=sm(n.mockUserToken,(s=r._app)===null||s===void 0?void 0:s.options.projectId);let h=n.mockUserToken.sub||n.mockUserToken.user_id;if(!h)throw new L(D.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");c=new _e(h)}r._authCredentials=new zu(new _o(u,c))}}var Wo=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)}},Ve=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 Fs(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new r(this.firestore,e,this._key)}},Fs=class r extends Wo{constructor(e,t,n){super(e,t,sa(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 Ve(this.firestore,null,new j(e))}withConverter(e){return new r(this.firestore,e,this._path)}};function la(r,e,...t){if(r=vt(r),arguments.length===1&&(e=wo.newId()),gR("doc","path",e),r instanceof Ms){let n=me.fromString(e,...t);return hg(n),new Ve(r,null,new j(n))}{if(!(r instanceof Ve||r instanceof Fs))throw new L(D.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let n=r._path.child(me.fromString(e,...t));return hg(n),new Ve(r.firestore,r instanceof Fs?r.converter:null,new j(n))}}var fg="AsyncQueue",Qo=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 Fo(this,"async_queue_retry"),this.Su=()=>{let n=Bu();n&&V(fg,"Visibility state changed to "+n.visibilityState),this.a_.t_()},this.bu=e;let t=Bu();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=Bu();t&&typeof t.removeEventListener=="function"&&t.removeEventListener("visibilitychange",this.Su)}}enqueue(e){if(this.Du(),this.mu)return new Promise(()=>{});let t=new et;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(!On(e))throw e;V(fg,"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 It("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=il.createAndSchedule(this,e,t,n,i=>this.Fu(i));return this.fu.push(s),s}Du(){this.gu&&F()}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 pg(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 er=class extends Ms{constructor(e,t,n,s){super(e,t,n,s),this.type="firestore",this._queue=new Qo,this._persistenceKey=(s==null?void 0:s.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new Qo(e),this._firestoreClient=void 0,await e}}};function Py(r,e){let t=typeof r=="object"?r:Em(),n=typeof r=="string"?r:e||Io,s=wm(t,"firestore").getImmediate({identifier:n});if(!s._initialized){let i=nm("firestore");i&&_R(s,...i)}return s}function zl(r){if(r._terminated)throw new L(D.FAILED_PRECONDITION,"The client has already been terminated.");return r._firestoreClient||vR(r),r._firestoreClient}function vR(r){var e,t,n;let s=r._freezeSettings(),i=function(u,c,h,f){return new Yu(u,c,h,f.host,f.ssl,f.experimentalForceLongPolling,f.experimentalAutoDetectLongPolling,Sy(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 ml(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 js=class r{constructor(e){this._byteString=e}static fromBase64String(e){try{return new r(Pe.fromBase64String(e))}catch(t){throw new L(D.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+t)}}static fromUint8Array(e){return new r(Pe.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 Cn=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 Us=class{constructor(e){this._methodName=e}};var Bs=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 Q(this._lat,e._lat)||Q(this._long,e._long)}};var $s=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 wR=/^__.*__$/,yl=class{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return this.fieldMask!==null?new at(e,this.data,this.fieldMask,t,this.fieldTransforms):new wr(e,this.data,t,this.fieldTransforms)}},Jo=class{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new at(e,this.data,this.fieldMask,t,this.fieldTransforms)}};function Cy(r){switch(r){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw F()}}var _l=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}Ku(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}Uu(e){return this.ku({path:void 0,Qu:!0})}Wu(e){return Xo(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(Cy(this.Lu)&&wR.test(e))throw this.Wu('Document fields cannot begin and end with "__"')}},vl=class{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||aa(e)}ju(e,t,n,s=!1){return new _l({Lu:e,methodName:t,zu:n,path:Ue.emptyPath(),Qu:!1,Gu:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function ky(r){let e=r._freezeSettings(),t=aa(r._databaseId);return new vl(r._databaseId,!!e.ignoreUndefinedProperties,t)}function bR(r,e,t,n,s,i={}){let a=r.ju(i.merge||i.mergeFields?2:0,e,t,s);Gl("Data must be an object, but it was:",a,n);let u=Dy(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=wl(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.`);Ny(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 yl(new je(u),c,h)}var Yo=class r extends Us{_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 TR(r,e,t,n){let s=r.ju(1,e,t);Gl("Data must be an object, but it was:",s,n);let i=[],a=je.empty();tr(n,(c,h)=>{let f=Kl(e,c,t);h=vt(h);let m=s.Ku(f);if(h instanceof Yo)i.push(f);else{let g=ha(h,m);g!=null&&(i.push(f),a.set(f,g))}});let u=new qe(i);return new Jo(a,u,s.fieldTransforms)}function ER(r,e,t,n,s,i){let a=r.ju(1,e,t),u=[wl(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(wl(e,i[g])),c.push(i[g+1]);let h=[],f=je.empty();for(let g=u.length-1;g>=0;--g)if(!Ny(h,u[g])){let E=u[g],P=c[g];P=vt(P);let C=a.Ku(E);if(P instanceof Yo)h.push(E);else{let R=ha(P,C);R!=null&&(h.push(E),f.set(E,R))}}let m=new qe(h);return new Jo(f,m,a.fieldTransforms)}function ha(r,e){if(Oy(r=vt(r)))return Gl("Unsupported field value:",e,r),Dy(r,e);if(r instanceof Us)return function(n,s){if(!Cy(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=ha(u,s.Uu(a));c==null&&(c={nullValue:"NULL_VALUE"}),i.push(c),a++}return{arrayValue:{values:i}}}(r,e)}return function(n,s){if((n=vt(n))===null)return{nullValue:"NULL_VALUE"};if(typeof n=="number")return sS(s.serializer,n);if(typeof n=="boolean")return{booleanValue:n};if(typeof n=="string")return{stringValue:n};if(n instanceof Date){let i=be.fromDate(n);return{timestampValue:Do(s.serializer,i)}}if(n instanceof be){let i=new be(n.seconds,1e3*Math.floor(n.nanoseconds/1e3));return{timestampValue:Do(s.serializer,i)}}if(n instanceof Bs)return{geoPointValue:{latitude:n.latitude,longitude:n.longitude}};if(n instanceof js)return{bytesValue:ry(s.serializer,n._byteString)};if(n instanceof Ve){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:Ol(n.firestore._databaseId||s.databaseId,n._key.path)}}if(n instanceof $s)return function(a,u){return{mapValue:{fields:{[Sl]:{stringValue:Rl},[_n]:{arrayValue:{values:a.toArray().map(h=>{if(typeof h!="number")throw u.Wu("VectorValues must only contain numeric values.");return Dl(u.serializer,h)})}}}}}}(n,s);throw s.Wu(`Unsupported field value: ${ql(n)}`)}(r,e)}function Dy(r,e){let t={};return Pg(r)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):tr(r,(n,s)=>{let i=ha(s,e.qu(n));i!=null&&(t[n]=i)}),{mapValue:{fields:t}}}function Oy(r){return!(typeof r!="object"||r===null||r instanceof Array||r instanceof Date||r instanceof be||r instanceof Bs||r instanceof js||r instanceof Ve||r instanceof Us||r instanceof $s)}function Gl(r,e,t){if(!Oy(t)||!function(s){return typeof s=="object"&&s!==null&&(Object.getPrototypeOf(s)===Object.prototype||Object.getPrototypeOf(s)===null)}(t)){let n=ql(t);throw n==="an object"?e.Wu(r+" a custom object"):e.Wu(r+" "+n)}}function wl(r,e,t){if((e=vt(e))instanceof Cn)return e._internalPath;if(typeof e=="string")return Kl(r,e);throw Xo("Field path arguments must be of type string or ",r,!1,void 0,t)}var IR=new RegExp("[~\\*/\\[\\]]");function Kl(r,e,t){if(e.search(IR)>=0)throw Xo(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,r,!1,void 0,t);try{return new Cn(...e.split("."))._internalPath}catch{throw Xo(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,r,!1,void 0,t)}}function Xo(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 Ny(r,e){return r.some(t=>t.isEqual(e))}var Zo=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 Ve(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new bl(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(Vy("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t)}}},bl=class extends Zo{data(){return super.data()}};function Vy(r,e){return typeof e=="string"?Kl(r,e):e instanceof Cn?e._internalPath:e._delegate._internalPath}function AR(r){if(r.limitType==="L"&&r.explicitOrderBy.length===0)throw new L(D.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var Tl=class{convertValue(e,t="none"){switch(Yt(e)){case 0:return null;case 1:return e.booleanValue;case 2:return ae(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(xt(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 F()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let n={};return tr(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[_n].arrayValue)===null||n===void 0?void 0:n.values)===null||s===void 0?void 0:s.map(a=>ae(a.doubleValue));return new $s(i)}convertGeoPoint(e){return new Bs(ae(e.latitude),ae(e.longitude))}convertArray(e,t){return(e.values||[]).map(n=>this.convertValue(n,t))}convertServerTimestamp(e,t){switch(t){case"previous":let n=na(e);return n==null?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Cs(e));default:return null}}convertTimestamp(e){let t=At(e);return new be(t.seconds,t.nanos)}convertDocumentKey(e,t){let n=me.fromString(e);ee(uy(n));let s=new Ao(n.get(1),n.get(3)),i=new j(n.popFirst(5));return s.isEqual(t)||It(`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 mr=class{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}},ea=class extends Zo{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 pn(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(Vy("DocumentSnapshot.get",e));if(n!==null)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}},pn=class extends ea{data(e={}){return super.data(e)}},El=class{constructor(e,t,n,s){this._firestore=e,this._userDataWriter=t,this._snapshot=s,this.metadata=new mr(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 pn(this._firestore,this._userDataWriter,n.key,n,new mr(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 pn(s._firestore,s._userDataWriter,u.doc.key,u.doc,new mr(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 pn(s._firestore,s._userDataWriter,u.doc.key,u.doc,new mr(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:SR(u.type),doc:c,oldIndex:h,newIndex:f}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}};function SR(r){switch(r){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return F()}}function Hl(r){r=st(r,Ve);let e=st(r.firestore,er);return mR(zl(e),r._key).then(t=>Uy(e,r,t))}var ta=class extends Tl{constructor(e){super(),this.firestore=e}convertBytes(e){return new js(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new Ve(this.firestore,null,t)}};function Ly(r,e,t){r=st(r,Ve);let n=st(r.firestore,er),s=xR(r.converter,e,t);return jy(n,[bR(ky(n),"setDoc",r._key,s,r.converter!==null,t).toMutation(r._key,Jt.none())])}function My(r,e,t,...n){r=st(r,Ve);let s=st(r.firestore,er),i=ky(s),a;return a=typeof(e=vt(e))=="string"||e instanceof Cn?ER(i,"updateDoc",r._key,e,t,n):TR(i,"updateDoc",r._key,e),jy(s,[a.toMutation(r._key,Jt.exists(!0))])}function Fy(r,...e){var t,n,s;r=vt(r);let i={includeMetadataChanges:!1,source:"default"},a=0;typeof e[a]!="object"||pg(e[a])||(i=e[a],a++);let u={includeMetadataChanges:i.includeMetadataChanges,source:i.source};if(pg(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 Ve)h=st(r.firestore,er),f=sa(r._key.path),c={next:m=>{e[a]&&e[a](Uy(h,r,m))},error:e[a+1],complete:e[a+2]};else{let m=st(r,Wo);h=st(m.firestore,er),f=m._query;let g=new ta(h);c={next:E=>{e[a]&&e[a](new El(h,g,m,E))},error:e[a+1],complete:e[a+2]},AR(r._query)}return function(g,E,P,C){let R=new Ko(C),N=new qo(E,R,P);return g.asyncQueue.enqueueAndForget(async()=>_y(await gl(g),N)),()=>{R.su(),g.asyncQueue.enqueueAndForget(async()=>vy(await gl(g),N))}}(zl(h),f,u,c)}function jy(r,e){return function(n,s){let i=new et;return n.asyncQueue.enqueueAndForget(async()=>iR(await pR(n),s,i)),i.promise}(zl(r),e)}function Uy(r,e,t){let n=t.docs.get(e._key),s=new ta(r);return new ea(r,s,e._key,n,new mr(t.hasPendingWrites,t.fromCache),e.converter)}(function(e,t=!0){(function(s){kn=s})(Tm),ws(new wt("firestore",(n,{instanceIdentifier:s,options:i})=>{let a=n.getProvider("app").getImmediate(),u=new er(new Gu(n.getProvider("auth-internal")),new Wu(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 Ao(h.options.projectId,f)}(a,s),a);return i=Object.assign({useFetchStreams:t},i),u._setSettings(i),u},"PUBLIC").setMultipleInstances(!0)),Qt(Rm,Pm,e),Qt(Rm,Pm,"esm2017")})();var By=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(rr(),Er)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)};var Gs=class extends Error{constructor(e,t="FunctionsError",n){super(e),this.name=t,this.context=n}},da=class extends Gs{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},fa=class extends Gs{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},pa=class extends Gs{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},ma;(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"})(ma||(ma={}));var DR=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())})},Ks=class{constructor(e,{headers:t={},customFetch:n,region:s=ma.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=By(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var n;return DR(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 da(P)}),m=f.headers.get("x-relay-error");if(m&&m==="true")throw new fa(f);if(!f.ok)throw new pa(f);let g=((n=f.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),E;return g==="application/json"?E=yield f.json():g==="application/octet-stream"?E=yield f.blob():g==="text/event-stream"?E=f:g==="multipart/form-data"?E=yield f.formData():E=yield f.text(),{data:E,error:null}}catch(s){return{data:null,error:s}}})}};var e_=Ad(Zy(),1),{PostgrestClient:t_,PostgrestQueryBuilder:VF,PostgrestFilterBuilder:LF,PostgrestTransformBuilder:MF,PostgrestBuilder:FF,PostgrestError:zR}=e_.default;var r_="2.11.2";var n_={"X-Client-Info":`realtime-js/${r_}`},s_="1.0.0",wa=1e4,i_=1e3,Ir;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(Ir||(Ir={}));var Le;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(Le||(Le={}));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 va;(function(r){r.websocket="websocket"})(va||(va={}));var nr;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(nr||(nr={}));var Zs=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 Ar=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 se;(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"})(se||(se={}));var uh=(r,e,t={})=>{var n;let s=(n=t.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((i,a)=>(i[a]=GR(a,r,e,s),i),{})},GR=(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)?o_(i,a):ah(a)},o_=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return QR(e,t)}switch(r){case se.bool:return KR(e);case se.float4:case se.float8:case se.int2:case se.int4:case se.int8:case se.numeric:case se.oid:return HR(e);case se.json:case se.jsonb:return WR(e);case se.timestamp:return JR(e);case se.abstime:case se.date:case se.daterange:case se.int4range:case se.int8range:case se.money:case se.reltime:case se.text:case se.time:case se.timestamptz:case se.timetz:case se.tsrange:case se.tstzrange:return ah(e);default:return ah(e)}},ah=r=>r,KR=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},HR=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},WR=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},QR=(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=>o_(e,u))}return r},JR=r=>typeof r=="string"?r.replace(" ","T"):r,ba=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var xr=class{constructor(e,t,n={},s=wa){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 ch;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(ch||(ch={}));var Mn=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),E=m.map(R=>R.presence_ref),P=f.filter(R=>E.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(E=>E.presence_ref),g=f.filter(E=>m.indexOf(E.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 lh;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(lh||(lh={}));var hh;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(hh||(hh={}));var ut;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(ut||(ut={}));var Fn=class r{constructor(e,t={config:{}},n){this.topic=e,this.params=t,this.socket=n,this.bindings={},this.state=Le.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 xr(this,Be.join,this.params,this.timeout),this.rejoinTimer=new Ar(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Le.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=Le.closed,this.socket._remove(this)}),this._onError(s=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,s),this.state=Le.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Le.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Be.reply,{},(s,i)=>{this._trigger(this._replyEventName(i),s)}),this.presence=new Mn(this),this.broadcastEndpointURL=ba(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(ut.CHANNEL_ERROR,f)),this._onClose(()=>e==null?void 0:e(ut.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(ut.SUBSCRIBED);return}else{let g=this.bindings.postgres_changes,E=(m=g==null?void 0:g.length)!==null&&m!==void 0?m:0,P=[];for(let C=0;C<E;C++){let R=g[C],{filter:{event:N,schema:M,table:U,filter:G}}=R,Y=f&&f[C];if(Y&&Y.event===N&&Y.schema===M&&Y.table===U&&Y.filter===G)P.push(Object.assign(Object.assign({},R),{id:Y.id}));else{this.unsubscribe(),e==null||e(ut.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=P,e&&e(ut.SUBSCRIBED);return}}).receive("error",f=>{e==null||e(ut.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(ut.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=Le.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 xr(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 xr(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(E=>{var P,C,R;return((P=E.filter)===null||P===void 0?void 0:P.event)==="*"||((R=(C=E.filter)===null||C===void 0?void 0:C.event)===null||R===void 0?void 0:R.toLocaleLowerCase())===a}).map(E=>E.callback(g,n)):(i=this.bindings[a])===null||i===void 0||i.filter(E=>{var P,C,R,N,M,U;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in E){let G=E.id,Y=(P=E.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=(M=(N=E==null?void 0:E.filter)===null||N===void 0?void 0:N.event)===null||M===void 0?void 0:M.toLocaleLowerCase();return G==="*"||G===((U=t==null?void 0:t.event)===null||U===void 0?void 0:U.toLocaleLowerCase())}else return E.type.toLocaleLowerCase()===a}).map(E=>{if(typeof g=="object"&&"ids"in g){let P=g.data,{schema:C,table:R,commit_timestamp:N,type:M,errors:U}=P;g=Object.assign(Object.assign({},{schema:C,table:R,commit_timestamp:N,eventType:M,new:{},old:{},errors:U}),this._getPayloadRecords(P))}E.callback(g,n)})}_isClosed(){return this.state===Le.closed}_isJoined(){return this.state===Le.joined}_isJoining(){return this.state===Le.joining}_isLeaving(){return this.state===Le.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=Le.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=uh(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=uh(e.columns,e.old_record)),t}};var XR=()=>{},ZR=typeof WebSocket!="undefined",eP=`
|
|
21
|
+
)`}copy(e,t){let n=new r;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}};var zo=class{constructor(){this.Z_=new le(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}):F():this.Z_=this.Z_.insert(t,e)}X_(){let e=[];return this.Z_.inorderTraversal((t,n)=>{e.push(n)}),e}},Cn=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,qo.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)&&aa(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 cl=class{constructor(){this.ea=void 0,this.ta=[]}na(){return this.ta.some(e=>e.ra())}},ll=class{constructor(){this.queries=lg(),this.onlineState="Unknown",this.ia=new Set}terminate(){(function(t,n){let s=$(t),i=s.queries;s.queries=lg(),i.forEach((a,u)=>{for(let c of u.ta)c.onError(n)})})(this,new L(D.ABORTED,"Firestore shutting down"))}};function lg(){return new Rt(r=>Wg(r),aa)}async function Ey(r,e){let t=$(r),n=3,s=e.query,i=t.queries.get(s);i?!i.na()&&e.ra()&&(n=2):(i=new cl,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=$l(a,`Initialization of query '${hn(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)&&ql(t)}async function Iy(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 lR(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&&ql(t)}function hR(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 ql(r){r.ia.forEach(e=>{e.next()})}var hl,hg;(hg=hl||(hl={}))._a="default",hg.Cache="cache";var Go=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 Cn(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=Cn.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.ua=!0,this.aa.next(e)}ra(){return this.options.source!==hl.Cache}};var Ko=class{constructor(e){this.key=e}},Ho=class{constructor(e){this.key=e}},dl=class{constructor(e,t){this.query=e,this.fa=t,this.ga=null,this.hasCachedResults=!1,this.current=!1,this.pa=H(),this.mutatedKeys=H(),this.ya=Qg(e),this.wa=new qo(this.ya)}get Sa(){return this.fa}ba(e,t){let n=t?t.Da:new zo,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),E=ua(this.query,m)?m:null,P=!!g&&this.mutatedKeys.has(g.key),C=!!E&&(E.hasLocalMutations||this.mutatedKeys.has(E.key)&&E.hasCommittedMutations),R=!1;g&&E?g.data.isEqual(E.data)?P!==C&&(n.track({type:3,doc:E}),R=!0):this.va(g,E)||(n.track({type:2,doc:E}),R=!0,(c&&this.ya(E,c)>0||h&&this.ya(E,h)<0)&&(u=!0)):!g&&E?(n.track({type:0,doc:E}),R=!0):g&&!E&&(n.track({type:1,doc:g}),R=!0,(c||h)&&(u=!0)),R&&(E?(a=a.add(E),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(E,P){let C=R=>{switch(R){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return F()}};return C(E)-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 Cn(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 zo,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=H(),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 Ho(n))}),this.pa.forEach(n=>{e.has(n)||t.push(new Ko(n))}),t}Oa(e){this.fa=e.gs,this.pa=H();let t=this.ba(e.documents);return this.applyChanges(t,!0)}Na(){return Cn.fromInitialDocuments(this.query,this.wa,this.mutatedKeys,this.ga===0,this.hasCachedResults)}},zl="SyncEngine",fl=class{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}},pl=class{constructor(e){this.key=e,this.Ba=!1}},ml=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=>Wg(u),aa),this.qa=new Map,this.Qa=new Set,this.$a=new le(j.comparator),this.Ka=new Map,this.Ua=new Ms,this.Wa={},this.Ga=new Map,this.za=Ls.Un(),this.onlineState="Unknown",this.ja=void 0}get isPrimaryClient(){return this.ja===!0}};async function dR(r,e,t=!0){let n=Cy(r),s,i=n.ka.get(e);return i?(n.sharedClientState.addLocalQueryTarget(i.targetId),s=i.view.Na()):s=await xy(n,e,t,!0),s}async function fR(r,e){let t=Cy(r);await xy(t,e,!0,!1)}async function xy(r,e,t,n){let s=await JS(r.localStore,nt(e)),i=s.targetId,a=r.sharedClientState.addLocalQueryTarget(i,t),u;return n&&(u=await pR(r,e,i,a==="current",s.resumeToken)),r.isPrimaryClient&&t&&yy(r.remoteStore,s),u}async function pR(r,e,t,n,s){r.Ha=(m,g,E)=>async function(C,R,N,M){let U=R.view.ba(N);U.ls&&(U=await og(C.localStore,R.query,!1).then(({documents:T})=>R.view.ba(T,U)));let G=M&&M.targetChanges.get(R.targetId),Y=M&&M.targetMismatches.get(R.targetId)!=null,B=R.view.applyChanges(U,C.isPrimaryClient,G,Y);return fg(C,R.targetId,B.Ma),B.snapshot}(r,m,g,E);let i=await og(r.localStore,e,!0),a=new dl(e,i.gs),u=a.ba(i.documents),c=Ns.createSynthesizedTargetChangeForCurrentChange(t,n&&r.onlineState!=="Offline",s),h=a.applyChanges(u,r.isPrimaryClient,c);fg(r,t,h.Ma);let f=new fl(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 mR(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=>!aa(a,e))),void n.ka.delete(e);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(s.targetId),n.sharedClientState.isActiveQueryTarget(s.targetId)||await Qc(n.localStore,s.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(s.targetId),t&&Fl(n.remoteStore,s.targetId),gl(n,s.targetId)}).catch(Nn)):(gl(n,s.targetId),await Qc(n.localStore,s.targetId,!0))}async function gR(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),Fl(t.remoteStore,n.targetId))}async function yR(r,e,t){let n=IR(r);try{let s=await function(a,u){let c=$(a),h=be.now(),f=u.reduce((E,P)=>E.add(P.key),H()),m,g;return c.persistence.runTransaction("Locally write mutations","readwrite",E=>{let P=Pt(),C=H();return c.ds.getEntries(E,f).next(R=>{P=R,P.forEach((N,M)=>{M.isValidDocument()||(C=C.add(N))})}).next(()=>c.localDocuments.getOverlayedDocuments(E,P)).next(R=>{m=R;let N=[];for(let M of u){let U=bS(M,m.get(M.key).overlayedDocument);U!=null&&N.push(new ut(M.key,U,$g(U.value.mapValue),Yt.exists(!0)))}return c.mutationQueue.addMutationBatch(E,h,N,u)}).next(R=>{g=R;let N=R.applyToLocalDocumentSet(m,C);return c.documentOverlayCache.saveOverlays(E,R.batchId,N)})}).then(()=>({batchId:g.batchId,changes:Yg(m)}))}(n.localStore,e);n.sharedClientState.addPendingMutation(s.batchId),function(a,u,c){let h=a.Wa[a.currentUser.toKey()];h||(h=new le(Q)),h=h.insert(u,c),a.Wa[a.currentUser.toKey()]=h}(n,s.batchId,t),await Ks(n,s.changes),await ha(n.remoteStore)}catch(s){let i=$l(s,"Failed to persist write");t.reject(i)}}async function Ay(r,e){let t=$(r);try{let n=await HS(t.localStore,e);e.targetChanges.forEach((s,i)=>{let a=t.Ka.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 Ks(t,n,e)}catch(n){await Nn(n)}}function dg(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&&ql(c)}(n.eventManager,e),s.length&&n.La.p_(s),n.onlineState=e,n.isPrimaryClient&&n.sharedClientState.setOnlineState(e)}}async function _R(r,e,t){let n=$(r);n.sharedClientState.updateQueryState(e,"rejected",t);let s=n.Ka.get(e),i=s&&s.key;if(i){let a=new le(j.comparator);a=a.insert(i,Je.newNoDocument(i,q.min()));let u=H().add(i),c=new Co(q.min(),new Map,new le(Q),a,u);await Ay(n,c),n.$a=n.$a.remove(i),n.Ka.delete(e),Gl(n)}else await Qc(n.localStore,e,!1).then(()=>gl(n,e,t)).catch(Nn)}async function vR(r,e){let t=$(r),n=e.batch.batchId;try{let s=await KS(t.localStore,e);Ry(t,n,null),Sy(t,n),t.sharedClientState.updateMutationState(n,"acknowledged"),await Ks(t,s)}catch(s){await Nn(s)}}async function wR(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);Ry(n,e,t),Sy(n,e),n.sharedClientState.updateMutationState(e,"rejected",t),await Ks(n,s)}catch(s){await Nn(s)}}function Sy(r,e){(r.Ga.get(e)||[]).forEach(t=>{t.resolve()}),r.Ga.delete(e)}function Ry(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 gl(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.Ua.br(e).forEach(n=>{r.Ua.containsKey(n)||Py(r,n)})}function Py(r,e){r.Qa.delete(e.path.canonicalString());let t=r.$a.get(e);t!==null&&(Fl(r.remoteStore,t),r.$a=r.$a.remove(e),r.Ka.delete(t),Gl(r))}function fg(r,e,t){for(let n of t)n instanceof Ko?(r.Ua.addReference(n.key,e),bR(r,n)):n instanceof Ho?(V(zl,"Document no longer in limbo: "+n.key),r.Ua.removeReference(n.key,e),r.Ua.containsKey(n.key)||Py(r,n.key)):F()}function bR(r,e){let t=e.key,n=t.path.canonicalString();r.$a.get(t)||r.Qa.has(n)||(V(zl,"New document in limbo: "+t),r.Qa.add(n),Gl(r))}function Gl(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(me.fromString(e)),n=r.za.next();r.Ka.set(n,new pl(t)),r.$a=r.$a.insert(t,n),yy(r.remoteStore,new Vs(nt(oa(t.path)),n,"TargetPurposeLimboResolution",vn.ae))}}async function Ks(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=Gc.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,E=>f.persistence.referenceDelegate.addReference(m,g.targetId,E)).next(()=>k.forEach(g.Ji,E=>f.persistence.referenceDelegate.removeReference(m,g.targetId,E)))))}catch(m){if(!Vn(m))throw m;V(Ml,"Failed to update sequence numbers: "+m)}for(let m of h){let g=m.targetId;if(!m.fromCache){let E=f.Ts.get(g),P=E.snapshotVersion,C=E.withLastLimboFreeSnapshotVersion(P);f.Ts=f.Ts.insert(g,C)}}}(n.localStore,i))}async function TR(r,e){let t=$(r);if(!t.currentUser.isEqual(e)){V(zl,"User change. New user:",e.toKey());let n=await my(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 Ks(t,n.Rs)}}function ER(r,e){let t=$(r),n=t.Ka.get(e);if(n&&n.Ba)return H().add(n.key);{let s=H(),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 Cy(r){let e=$(r);return e.remoteStore.remoteSyncer.applyRemoteEvent=Ay.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=ER.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=_R.bind(null,e),e.La.p_=lR.bind(null,e.eventManager),e.La.Ja=hR.bind(null,e.eventManager),e}function IR(r){let e=$(r);return e.remoteStore.remoteSyncer.applySuccessfulWrite=vR.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=wR.bind(null,e),e}var kn=class{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=ca(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 GS(this.persistence,new Hc,e.initialUser,this.serializer)}Xa(e){return new Lo(zc.ri,this.serializer)}Za(e){return new Jc}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()}};kn.provider={build:()=>new kn};var yl=class extends kn{constructor(e){super(),this.cacheSizeBytes=e}tu(e,t){ee(this.persistence.referenceDelegate instanceof Mo);let n=this.persistence.referenceDelegate.garbageCollector;return new kc(n,e.asyncQueue,t)}Xa(e){let t=this.cacheSizeBytes!==void 0?qe.withCacheSize(this.cacheSizeBytes):qe.DEFAULT;return new Lo(n=>Mo.ri(n,t),this.serializer)}};var Fs=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=>dg(this.syncEngine,n,1),this.remoteStore.remoteSyncer.handleCredentialChange=TR.bind(null,this.syncEngine),await cR(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return function(){return new ll}()}createDatastore(e){let t=ca(e.databaseInfo.databaseId),n=function(i){return new tl(i)}(e.databaseInfo);return function(i,a,u,c){return new il(i,a,u,c)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return function(n,s,i,a,u){return new al(n,s,i,a,u)}(this.localStore,this.datastore,e.asyncQueue,t=>dg(this.syncEngine,t,0),function(){return jo.D()?new jo:new Yc}())}createSyncEngine(e,t){return function(s,i,a,u,c,h,f){let m=new ml(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 Gs(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()}};Fs.provider={build:()=>new Fs};var Wo=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):xt("Uncaught Error in snapshot listener:",e.toString()))}su(){this.muted=!0}iu(e,t){setTimeout(()=>{this.muted||e(t)},0)}};var er="FirestoreClient",_l=class{constructor(e,t,n,s,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=s,this.user=_e.UNAUTHENTICATED,this.clientId=To.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,async a=>{V(er,"Received user=",a.uid),await this.authCredentialListener(a),this.user=a}),this.appCheckCredentials.start(n,a=>(V(er,"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=$l(t,"Failed to shutdown persistence");e.reject(n)}}),e.promise}};async function Gu(r,e){r.asyncQueue.verifyOperationInProgress(),V(er,"Initializing OfflineComponentProvider");let t=r.configuration;await e.initialize(t);let n=t.initialUser;r.setCredentialChangeListener(async s=>{n.isEqual(s)||(await my(e.localStore,s),n=s)}),e.persistence.setDatabaseDeletedListener(()=>r.terminate()),r._offlineComponents=e}async function pg(r,e){r.asyncQueue.verifyOperationInProgress();let t=await xR(r);V(er,"Initializing OnlineComponentProvider"),await e.initialize(t,r.configuration),r.setCredentialChangeListener(n=>cg(e.remoteStore,n)),r.setAppCheckTokenChangeListener((n,s)=>cg(e.remoteStore,s)),r._onlineComponents=e}async function xR(r){if(!r._offlineComponents)if(r._uninitializedComponentsProvider){V(er,"Using user provided OfflineComponentProvider");try{await Gu(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;yn("Error using user provided cache. Falling back to memory cache: "+t),await Gu(r,new kn)}}else V(er,"Using default OfflineComponentProvider"),await Gu(r,new yl(void 0));return r._offlineComponents}async function ky(r){return r._onlineComponents||(r._uninitializedComponentsProvider?(V(er,"Using user provided OnlineComponentProvider"),await pg(r,r._uninitializedComponentsProvider._online)):(V(er,"Using default OnlineComponentProvider"),await pg(r,new Fs))),r._onlineComponents}function AR(r){return ky(r).then(e=>e.syncEngine)}async function vl(r){let e=await ky(r),t=e.eventManager;return t.onListen=dR.bind(null,e.syncEngine),t.onUnlisten=mR.bind(null,e.syncEngine),t.onFirstRemoteStoreListen=fR.bind(null,e.syncEngine),t.onLastRemoteStoreUnlisten=gR.bind(null,e.syncEngine),t}function SR(r,e,t={}){let n=new tt;return r.asyncQueue.enqueueAndForget(async()=>function(i,a,u,c,h){let f=new Wo({next:g=>{f.su(),a.enqueueAndForget(()=>Iy(i,m));let E=g.docs.has(u);!E&&g.fromCache?h.reject(new L(D.UNAVAILABLE,"Failed to get document because the client is offline.")):E&&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 Go(oa(u.path),f,{includeMetadataChanges:!0,Ta:!0});return Ey(i,m)}(await vl(r),r.asyncQueue,e,t,n)),n.promise}function Dy(r){let e={};return r.timeoutSeconds!==void 0&&(e.timeoutSeconds=r.timeoutSeconds),e}var mg=new Map;function RR(r,e,t){if(!t)throw new L(D.INVALID_ARGUMENT,`Function ${r}() cannot be called with an empty ${e}.`)}function PR(r,e,t,n){if(e===!0&&n===!0)throw new L(D.INVALID_ARGUMENT,`${r} and ${t} cannot be used together.`)}function gg(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 Kl(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":F()}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=Kl(r);throw new L(D.INVALID_ARGUMENT,`Expected type '${e.name}', but it was: ${t}`)}}return r}var Oy="firestore.googleapis.com",yg=!0,Qo=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=Oy,this.ssl=yg}else this.host=e.host,this.ssl=(t=e.ssl)!==null&&t!==void 0?t:yg;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e.cacheSizeBytes===void 0)this.cacheSizeBytes=py;else{if(e.cacheSizeBytes!==-1&&e.cacheSizeBytes<$S)throw new L(D.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}PR("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=Dy((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}},js=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 Qo({}),this._settingsFrozen=!1,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 Qo(e),e.credentials!==void 0&&(this._authCredentials=function(n){if(!n)return new Ku;switch(n.type){case"firstParty":return new Ju(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}_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=mg.get(t);n&&(V("ComponentProvider","Removing Datastore"),mg.delete(t),n.terminate())}(this),Promise.resolve()}};function CR(r,e,t,n={}){var s;let i=(r=it(r,js))._getSettings(),a=`${e}:${t}`;if(i.host!==Oy&&i.host!==a&&yn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),r._setSettings(Object.assign(Object.assign({},i),{host:a,ssl:!1})),n.mockUserToken){let u,c;if(typeof n.mockUserToken=="string")u=n.mockUserToken,c=_e.MOCK_USER;else{u=cm(n.mockUserToken,(s=r._app)===null||s===void 0?void 0:s.options.projectId);let h=n.mockUserToken.sub||n.mockUserToken.user_id;if(!h)throw new L(D.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");c=new _e(h)}r._authCredentials=new Hu(new wo(u,c))}}var Jo=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)}},Ve=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 Us(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new r(this.firestore,e,this._key)}},Us=class r extends Jo{constructor(e,t,n){super(e,t,oa(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 Ve(this.firestore,null,new j(e))}withConverter(e){return new r(this.firestore,e,this._path)}};function da(r,e,...t){if(r=wt(r),arguments.length===1&&(e=To.newId()),RR("doc","path",e),r instanceof js){let n=me.fromString(e,...t);return gg(n),new Ve(r,null,new j(n))}{if(!(r instanceof Ve||r instanceof Us))throw new L(D.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let n=r._path.child(me.fromString(e,...t));return gg(n),new Ve(r.firestore,r instanceof Us?r.converter:null,new j(n))}}var _g="AsyncQueue",Yo=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 Uo(this,"async_queue_retry"),this.Su=()=>{let n=zu();n&&V(_g,"Visibility state changed to "+n.visibilityState),this.a_.t_()},this.bu=e;let t=zu();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=zu();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(!Vn(e))throw e;V(_g,"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 xt("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=ul.createAndSchedule(this,e,t,n,i=>this.Fu(i));return this.fu.push(s),s}Du(){this.gu&&F()}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 vg(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 tr=class extends js{constructor(e,t,n,s){super(e,t,n,s),this.type="firestore",this._queue=new Yo,this._persistenceKey=(s==null?void 0:s.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new Yo(e),this._firestoreClient=void 0,await e}}};function Ny(r,e){let t=typeof r=="object"?r:Rm(),n=typeof r=="string"?r:e||Ao,s=xm(t,"firestore").getImmediate({identifier:n});if(!s._initialized){let i=um("firestore");i&&CR(s,...i)}return s}function Hl(r){if(r._terminated)throw new L(D.FAILED_PRECONDITION,"The client has already been terminated.");return r._firestoreClient||kR(r),r._firestoreClient}function kR(r){var e,t,n;let s=r._freezeSettings(),i=function(u,c,h,f){return new ec(u,c,h,f.host,f.ssl,f.experimentalForceLongPolling,f.experimentalAutoDetectLongPolling,Dy(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 _l(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 Bs=class r{constructor(e){this._byteString=e}static fromBase64String(e){try{return new r(Pe.fromBase64String(e))}catch(t){throw new L(D.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+t)}}static fromUint8Array(e){return new r(Pe.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 Dn=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 Be(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}};var $s=class{constructor(e){this._methodName=e}};var qs=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 Q(this._lat,e._lat)||Q(this._long,e._long)}};var zs=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 DR=/^__.*__$/,wl=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)}},Xo=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 Vy(r){switch(r){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw F()}}var bl=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}Ku(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}Uu(e){return this.ku({path:void 0,Qu:!0})}Wu(e){return ea(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(Vy(this.Lu)&&DR.test(e))throw this.Wu('Document fields cannot begin and end with "__"')}},Tl=class{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||ca(e)}ju(e,t,n,s=!1){return new bl({Lu:e,methodName:t,zu:n,path:Be.emptyPath(),Qu:!1,Gu:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function Ly(r){let e=r._freezeSettings(),t=ca(r._databaseId);return new Tl(r._databaseId,!!e.ignoreUndefinedProperties,t)}function OR(r,e,t,n,s,i={}){let a=r.ju(i.merge||i.mergeFields?2:0,e,t,s);Wl("Data must be an object, but it was:",a,n);let u=My(n,a),c,h;if(i.merge)c=new ze(a.fieldMask),h=a.fieldTransforms;else if(i.mergeFields){let f=[];for(let m of i.mergeFields){let g=El(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.`);jy(f,g)||f.push(g)}c=new ze(f),h=a.fieldTransforms.filter(m=>c.covers(m.field))}else c=null,h=a.fieldTransforms;return new wl(new Ue(u),c,h)}var Zo=class r extends $s{_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 NR(r,e,t,n){let s=r.ju(1,e,t);Wl("Data must be an object, but it was:",s,n);let i=[],a=Ue.empty();rr(n,(c,h)=>{let f=Ql(e,c,t);h=wt(h);let m=s.Ku(f);if(h instanceof Zo)i.push(f);else{let g=fa(h,m);g!=null&&(i.push(f),a.set(f,g))}});let u=new ze(i);return new Xo(a,u,s.fieldTransforms)}function VR(r,e,t,n,s,i){let a=r.ju(1,e,t),u=[El(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(El(e,i[g])),c.push(i[g+1]);let h=[],f=Ue.empty();for(let g=u.length-1;g>=0;--g)if(!jy(h,u[g])){let E=u[g],P=c[g];P=wt(P);let C=a.Ku(E);if(P instanceof Zo)h.push(E);else{let R=fa(P,C);R!=null&&(h.push(E),f.set(E,R))}}let m=new ze(h);return new Xo(f,m,a.fieldTransforms)}function fa(r,e){if(Fy(r=wt(r)))return Wl("Unsupported field value:",e,r),My(r,e);if(r instanceof $s)return function(n,s){if(!Vy(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=fa(u,s.Uu(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 gS(s.serializer,n);if(typeof n=="boolean")return{booleanValue:n};if(typeof n=="string")return{stringValue:n};if(n instanceof Date){let i=be.fromDate(n);return{timestampValue:No(s.serializer,i)}}if(n instanceof be){let i=new be(n.seconds,1e3*Math.floor(n.nanoseconds/1e3));return{timestampValue:No(s.serializer,i)}}if(n instanceof qs)return{geoPointValue:{latitude:n.latitude,longitude:n.longitude}};if(n instanceof Bs)return{bytesValue:ay(s.serializer,n._byteString)};if(n instanceof Ve){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:Ll(n.firestore._databaseId||s.databaseId,n._key.path)}}if(n instanceof zs)return function(a,u){return{mapValue:{fields:{[Cl]:{stringValue:kl},[wn]:{arrayValue:{values:a.toArray().map(h=>{if(typeof h!="number")throw u.Wu("VectorValues must only contain numeric values.");return Vl(u.serializer,h)})}}}}}}(n,s);throw s.Wu(`Unsupported field value: ${Kl(n)}`)}(r,e)}function My(r,e){let t={};return Ng(r)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):rr(r,(n,s)=>{let i=fa(s,e.qu(n));i!=null&&(t[n]=i)}),{mapValue:{fields:t}}}function Fy(r){return!(typeof r!="object"||r===null||r instanceof Array||r instanceof Date||r instanceof be||r instanceof qs||r instanceof Bs||r instanceof Ve||r instanceof $s||r instanceof zs)}function Wl(r,e,t){if(!Fy(t)||!function(s){return typeof s=="object"&&s!==null&&(Object.getPrototypeOf(s)===Object.prototype||Object.getPrototypeOf(s)===null)}(t)){let n=Kl(t);throw n==="an object"?e.Wu(r+" a custom object"):e.Wu(r+" "+n)}}function El(r,e,t){if((e=wt(e))instanceof Dn)return e._internalPath;if(typeof e=="string")return Ql(r,e);throw ea("Field path arguments must be of type string or ",r,!1,void 0,t)}var LR=new RegExp("[~\\*/\\[\\]]");function Ql(r,e,t){if(e.search(LR)>=0)throw ea(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,r,!1,void 0,t);try{return new Dn(...e.split("."))._internalPath}catch{throw ea(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,r,!1,void 0,t)}}function ea(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 jy(r,e){return r.some(t=>t.isEqual(e))}var ta=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 Ve(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new Il(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(Uy("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t)}}},Il=class extends ta{data(){return super.data()}};function Uy(r,e){return typeof e=="string"?Ql(r,e):e instanceof Dn?e._internalPath:e._delegate._internalPath}function MR(r){if(r.limitType==="L"&&r.explicitOrderBy.length===0)throw new L(D.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var xl=class{convertValue(e,t="none"){switch(Xt(e)){case 0:return null;case 1:return e.booleanValue;case 2:return ae(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 F()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let n={};return rr(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[wn].arrayValue)===null||n===void 0?void 0:n.values)===null||s===void 0?void 0:s.map(a=>ae(a.doubleValue));return new zs(i)}convertGeoPoint(e){return new qs(ae(e.latitude),ae(e.longitude))}convertArray(e,t){return(e.values||[]).map(n=>this.convertValue(n,t))}convertServerTimestamp(e,t){switch(t){case"previous":let n=ia(e);return n==null?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Ds(e));default:return null}}convertTimestamp(e){let t=At(e);return new be(t.seconds,t.nanos)}convertDocumentKey(e,t){let n=me.fromString(e);ee(fy(n));let s=new So(n.get(1),n.get(3)),i=new j(n.popFirst(5));return s.isEqual(t)||xt(`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 FR(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}},ra=class extends ta{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 gn(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(Uy("DocumentSnapshot.get",e));if(n!==null)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}},gn=class extends ra{data(e={}){return super.data(e)}},Al=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 gn(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 gn(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 gn(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:jR(u.type),doc:c,oldIndex:h,newIndex:f}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}};function jR(r){switch(r){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return F()}}function Jl(r){r=it(r,Ve);let e=it(r.firestore,tr);return SR(Hl(e),r._key).then(t=>Gy(e,r,t))}var na=class extends xl{constructor(e){super(),this.firestore=e}convertBytes(e){return new Bs(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new Ve(this.firestore,null,t)}};function By(r,e,t){r=it(r,Ve);let n=it(r.firestore,tr),s=FR(r.converter,e,t);return zy(n,[OR(Ly(n),"setDoc",r._key,s,r.converter!==null,t).toMutation(r._key,Yt.none())])}function $y(r,e,t,...n){r=it(r,Ve);let s=it(r.firestore,tr),i=Ly(s),a;return a=typeof(e=wt(e))=="string"||e instanceof Dn?VR(i,"updateDoc",r._key,e,t,n):NR(i,"updateDoc",r._key,e),zy(s,[a.toMutation(r._key,Yt.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"||vg(e[a])||(i=e[a],a++);let u={includeMetadataChanges:i.includeMetadataChanges,source:i.source};if(vg(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 Ve)h=it(r.firestore,tr),f=oa(r._key.path),c={next:m=>{e[a]&&e[a](Gy(h,r,m))},error:e[a+1],complete:e[a+2]};else{let m=it(r,Jo);h=it(m.firestore,tr),f=m._query;let g=new na(h);c={next:E=>{e[a]&&e[a](new Al(h,g,m,E))},error:e[a+1],complete:e[a+2]},MR(r._query)}return function(g,E,P,C){let R=new Wo(C),N=new Go(E,R,P);return g.asyncQueue.enqueueAndForget(async()=>Ey(await vl(g),N)),()=>{R.su(),g.asyncQueue.enqueueAndForget(async()=>Iy(await vl(g),N))}}(Hl(h),f,u,c)}function zy(r,e){return function(n,s){let i=new tt;return n.asyncQueue.enqueueAndForget(async()=>yR(await AR(n),s,i)),i.promise}(Hl(r),e)}function Gy(r,e,t){let n=t.docs.get(e._key),s=new na(r);return new ra(r,s,e._key,n,new gr(t.hasPendingWrites,t.fromCache),e.converter)}(function(e,t=!0){(function(s){On=s})(Sm),Ts(new bt("firestore",(n,{instanceIdentifier:s,options:i})=>{let a=n.getProvider("app").getImmediate(),u=new tr(new Wu(n.getProvider("auth-internal")),new Yu(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 So(h.options.projectId,f)}(a,s),a);return i=Object.assign({useFetchStreams:t},i),u._setSettings(i),u},"PUBLIC").setMultipleInstances(!0)),Jt(Om,Nm,e),Jt(Om,Nm,"esm2017")})();var Ky=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(nr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)};var Hs=class extends Error{constructor(e,t="FunctionsError",n){super(e),this.name=t,this.context=n}},pa=class extends Hs{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},ma=class extends Hs{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},ga=class extends Hs{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},ya;(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"})(ya||(ya={}));var zR=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())})},Ws=class{constructor(e,{headers:t={},customFetch:n,region:s=ya.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=Ky(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var n;return zR(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 pa(P)}),m=f.headers.get("x-relay-error");if(m&&m==="true")throw new ma(f);if(!f.ok)throw new ga(f);let g=((n=f.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),E;return g==="application/json"?E=yield f.json():g==="application/octet-stream"?E=yield f.blob():g==="text/event-stream"?E=f:g==="multipart/form-data"?E=yield f.formData():E=yield f.text(),{data:E,error:null}}catch(s){return{data:null,error:s}}})}};var i_=ou(s_(),1),{PostgrestClient:o_,PostgrestQueryBuilder:YF,PostgrestFilterBuilder:XF,PostgrestTransformBuilder:ZF,PostgrestBuilder:e2,PostgrestError:rP}=i_.default;var a_="2.11.2";var u_={"X-Client-Info":`realtime-js/${a_}`},c_="1.0.0",Ta=1e4,l_=1e3,xr;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(xr||(xr={}));var Le;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(Le||(Le={}));var $e;(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"})($e||($e={}));var ba;(function(r){r.websocket="websocket"})(ba||(ba={}));var sr;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(sr||(sr={}));var ti=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 Ar=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 se;(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"})(se||(se={}));var hh=(r,e,t={})=>{var n;let s=(n=t.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((i,a)=>(i[a]=nP(a,r,e,s),i),{})},nP=(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)?h_(i,a):lh(a)},h_=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return aP(e,t)}switch(r){case se.bool:return sP(e);case se.float4:case se.float8:case se.int2:case se.int4:case se.int8:case se.numeric:case se.oid:return iP(e);case se.json:case se.jsonb:return oP(e);case se.timestamp:return uP(e);case se.abstime:case se.date:case se.daterange:case se.int4range:case se.int8range:case se.money:case se.reltime:case se.text:case se.time:case se.timestamptz:case se.timetz:case se.tsrange:case se.tstzrange:return lh(e);default:return lh(e)}},lh=r=>r,sP=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},iP=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},oP=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},aP=(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=>h_(e,u))}return r},uP=r=>typeof r=="string"?r.replace(" ","T"):r,Ea=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=Ta){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 dh;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(dh||(dh={}));var jn=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),E=m.map(R=>R.presence_ref),P=f.filter(R=>E.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(E=>E.presence_ref),g=f.filter(E=>m.indexOf(E.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 fh;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(fh||(fh={}));var ph;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(ph||(ph={}));var ct;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(ct||(ct={}));var Un=class r{constructor(e,t={config:{}},n){this.topic=e,this.params=t,this.socket=n,this.bindings={},this.state=Le.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,$e.join,this.params,this.timeout),this.rejoinTimer=new Ar(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Le.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=Le.closed,this.socket._remove(this)}),this._onError(s=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,s),this.state=Le.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Le.errored,this.rejoinTimer.scheduleTimeout())}),this._on($e.reply,{},(s,i)=>{this._trigger(this._replyEventName(i),s)}),this.presence=new jn(this),this.broadcastEndpointURL=Ea(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,E=(m=g==null?void 0:g.length)!==null&&m!==void 0?m:0,P=[];for(let C=0;C<E;C++){let R=g[C],{filter:{event:N,schema:M,table:U,filter:G}}=R,Y=f&&f[C];if(Y&&Y.event===N&&Y.schema===M&&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=Le.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger($e.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(n=>{let s=new Sr(this,$e.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}=$e;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(E=>{var P,C,R;return((P=E.filter)===null||P===void 0?void 0:P.event)==="*"||((R=(C=E.filter)===null||C===void 0?void 0:C.event)===null||R===void 0?void 0:R.toLocaleLowerCase())===a}).map(E=>E.callback(g,n)):(i=this.bindings[a])===null||i===void 0||i.filter(E=>{var P,C,R,N,M,U;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in E){let G=E.id,Y=(P=E.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=(M=(N=E==null?void 0:E.filter)===null||N===void 0?void 0:N.event)===null||M===void 0?void 0:M.toLocaleLowerCase();return G==="*"||G===((U=t==null?void 0:t.event)===null||U===void 0?void 0:U.toLocaleLowerCase())}else return E.type.toLocaleLowerCase()===a}).map(E=>{if(typeof g=="object"&&"ids"in g){let P=g.data,{schema:C,table:R,commit_timestamp:N,type:M,errors:U}=P;g=Object.assign(Object.assign({},{schema:C,table:R,commit_timestamp:N,eventType:M,new:{},old:{},errors:U}),this._getPayloadRecords(P))}E.callback(g,n)})}_isClosed(){return this.state===Le.closed}_isJoined(){return this.state===Le.joined}_isJoining(){return this.state===Le.joining}_isLeaving(){return this.state===Le.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($e.close,{},e)}_onError(e){this._on($e.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Le.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=hh(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=hh(e.columns,e.old_record)),t}};var lP=()=>{},hP=typeof WebSocket!="undefined",dP=`
|
|
23
23
|
addEventListener("message", (e) => {
|
|
24
24
|
if (e.data.event === "start") {
|
|
25
25
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
26
26
|
}
|
|
27
|
-
});`,jn=class{constructor(e,t){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=n_,this.params={},this.timeout=wa,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=XR,this.conn=null,this.sendBuffer=[],this.serializer=new Zs,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(()=>(rr(),Er)).then(({default:c})=>c(...u)):a=fetch,(...u)=>a(...u)},this.endPoint=`${e}/${va.websocket}`,this.httpEndpoint=ba(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 Ar(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(ZR){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new dh(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Ad(u_())).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:s_}))}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 Ir.connecting:return nr.Connecting;case Ir.open:return nr.Open;case Ir.closing:return nr.Closing;default:return nr.Closed}}isConnected(){return this.connectionState()===nr.Open}channel(e,t={config:{}}){let n=new Fn(`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(i_,"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([eP],{type:"application/javascript"});t=URL.createObjectURL(n)}return t}},dh=class{constructor(e,t,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Ir.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}};var Un=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function ge(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Ta=class extends Un{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Sr=class extends Un{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var tP=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())})},Ia=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(rr(),Er)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},c_=()=>tP(void 0,void 0,void 0,function*(){return typeof Response=="undefined"?(yield Promise.resolve().then(()=>(rr(),Er))).Response:Response}),Ea=r=>{if(Array.isArray(r))return r.map(t=>Ea(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]=Ea(n)}),e};var Rr=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())})},fh=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),rP=(r,e,t)=>Rr(void 0,void 0,void 0,function*(){let n=yield c_();r instanceof n&&!(t!=null&&t.noResolveJson)?r.json().then(s=>{e(new Ta(fh(s),r.status||500))}).catch(s=>{e(new Sr(fh(s),s))}):e(new Sr(fh(r),r))}),nP=(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 ei(r,e,t,n,s,i){return Rr(this,void 0,void 0,function*(){return new Promise((a,u)=>{r(t,nP(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 Bn(r,e,t,n){return Rr(this,void 0,void 0,function*(){return ei(r,"GET",e,t,n)})}function ct(r,e,t,n,s){return Rr(this,void 0,void 0,function*(){return ei(r,"POST",e,n,s,t)})}function l_(r,e,t,n,s){return Rr(this,void 0,void 0,function*(){return ei(r,"PUT",e,n,s,t)})}function h_(r,e,t,n){return Rr(this,void 0,void 0,function*(){return ei(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),n)})}function Aa(r,e,t,n,s){return Rr(this,void 0,void 0,function*(){return ei(r,"DELETE",e,n,s,t)})}var Me=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())})},sP={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},d_={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ti=class{constructor(e,t={},n,s){this.url=e,this.headers=t,this.bucketId=n,this.fetch=Ia(s)}uploadOrUpdate(e,t,n,s){return Me(this,void 0,void 0,function*(){try{let i,a=Object.assign(Object.assign({},d_),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(ge(i))return{data:null,error:i};throw i}})}upload(e,t,n){return Me(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,n)})}uploadToSignedUrl(e,t,n,s){return Me(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:d_.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(ge(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return Me(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 ct(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 Un("No token returned by API");return{data:{signedUrl:a.toString(),path:e,token:u},error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}})}update(e,t,n){return Me(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,n)})}move(e,t,n){return Me(this,void 0,void 0,function*(){try{return{data:yield ct(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(ge(s))return{data:null,error:s};throw s}})}copy(e,t,n){return Me(this,void 0,void 0,function*(){try{return{data:{path:(yield ct(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(ge(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,n){return Me(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=yield ct(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(ge(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,n){return Me(this,void 0,void 0,function*(){try{let s=yield ct(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(ge(s))return{data:null,error:s};throw s}})}download(e,t){return Me(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 Bn(this.fetch,`${this.url}/${s}/${u}${a}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(u){if(ge(u))return{data:null,error:u};throw u}})}info(e){return Me(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{let n=yield Bn(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:Ea(n),error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}})}exists(e){return Me(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{return yield h_(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(ge(n)&&n instanceof Sr){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 Me(this,void 0,void 0,function*(){try{return{data:yield Aa(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}list(e,t,n){return Me(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},sP),t),{prefix:e||""});return{data:yield ct(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},n),error:null}}catch(s){if(ge(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 f_="2.7.1";var p_={"X-Client-Info":`storage-js/${f_}`};var $n=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())})},ri=class{constructor(e,t={},n){this.url=e,this.headers=Object.assign(Object.assign({},p_),t),this.fetch=Ia(n)}listBuckets(){return $n(this,void 0,void 0,function*(){try{return{data:yield Bn(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(ge(e))return{data:null,error:e};throw e}})}getBucket(e){return $n(this,void 0,void 0,function*(){try{return{data:yield Bn(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return $n(this,void 0,void 0,function*(){try{return{data:yield ct(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(ge(n))return{data:null,error:n};throw n}})}updateBucket(e,t){return $n(this,void 0,void 0,function*(){try{return{data:yield l_(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(ge(n))return{data:null,error:n};throw n}})}emptyBucket(e){return $n(this,void 0,void 0,function*(){try{return{data:yield ct(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}deleteBucket(e){return $n(this,void 0,void 0,function*(){try{return{data:yield Aa(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}};var ni=class extends ri{constructor(e,t={},n){super(e,t,n)}from(e){return new ti(this.url,this.headers,e,this.fetch)}};var m_="2.48.1";var si="";typeof Deno!="undefined"?si="deno":typeof document!="undefined"?si="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?si="react-native":si="node";var iP={"X-Client-Info":`supabase-js-${si}/${m_}`},g_={headers:iP},y_={schema:"public"},__={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},v_={};rr();var oP=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())})},aP=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=Wl:e=fetch,(...t)=>e(...t)},uP=()=>typeof Headers=="undefined"?Ql:Headers,w_=(r,e,t)=>{let n=aP(t),s=uP();return(i,a)=>oP(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 cP=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 b_(r){return r.replace(/\/$/,"")}function T_(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:()=>cP(this,void 0,void 0,function*(){return""})};return r.accessToken?f.accessToken=r.accessToken:delete f.accessToken,f}var xa="2.67.3";var E_="http://localhost:9999",I_="supabase.auth.token";var A_={"X-Client-Info":`gotrue-js/${xa}`},ph=10;var ii="X-Supabase-Api-Version",mh={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function x_(r){return Math.round(Date.now()/1e3)+r}function S_(){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 Qe=()=>typeof window!="undefined"&&typeof document!="undefined",Pr={tested:!1,writable:!1},sr=()=>{if(!Qe())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Pr.tested)return Pr.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Pr.tested=!0,Pr.writable=!0}catch{Pr.tested=!0,Pr.writable=!1}return Pr.writable};function R_(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 Sa=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(rr(),Er)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},P_=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",gh=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},ai=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},ui=async(r,e)=>{await r.removeItem(e)};function lP(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",n,s,i,a,u,c,h,f=0;for(r=r.replace("-","+").replace("_","/");f<r.length;)a=e.indexOf(r.charAt(f++)),u=e.indexOf(r.charAt(f++)),c=e.indexOf(r.charAt(f++)),h=e.indexOf(r.charAt(f++)),n=a<<2|u>>4,s=(u&15)<<4|c>>2,i=(c&3)<<6|h,t=t+String.fromCharCode(n),c!=64&&s!=0&&(t=t+String.fromCharCode(s)),h!=64&&i!=0&&(t=t+String.fromCharCode(i));return t}var oi=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};oi.promiseConstructor=Promise;function yh(r){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=r.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let n=t[1];return JSON.parse(lP(n))}async function C_(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function k_(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 hP(r){return("0"+r.toString(16)).substr(-2)}function dP(){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,hP).join("")}async function fP(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("")}function pP(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function mP(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 fP(r);return pP(t)}async function Cr(r,e,t=!1){let n=dP(),s=n;t&&(s+="/PASSWORD_RECOVERY"),await gh(r,`${e}-code-verifier`,s);let i=await mP(n);return[i,n===i?"plain":"s256"]}var gP=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function D_(r){let e=r.headers.get(ii);if(!e||!e.match(gP))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var ci=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 Ra=class extends ci{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}};function O_(r){return z(r)&&r.name==="AuthApiError"}var qn=class extends ci{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},Pt=class extends ci{constructor(e,t,n,s){super(e,n,s),this.name=t,this.status=n}},ze=class extends Pt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function N_(r){return z(r)&&r.name==="AuthSessionMissingError"}var zn=class extends Pt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},kr=class extends Pt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Dr=class extends Pt{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 V_(r){return z(r)&&r.name==="AuthImplicitGrantRedirectError"}var li=class extends Pt{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}}},Gn=class extends Pt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Pa(r){return z(r)&&r.name==="AuthRetryableFetchError"}var hi=class extends Pt{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}};var yP=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},Or=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),_P=[502,503,504];async function L_(r){var e;if(!P_(r))throw new Gn(Or(r),0);if(_P.includes(r.status))throw new Gn(Or(r),r.status);let t;try{t=await r.json()}catch(i){throw new qn(Or(i),i)}let n,s=D_(r);if(s&&s.getTime()>=mh["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 hi(Or(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 hi(Or(t),r.status,t.weak_password.reasons);throw new Ra(Or(t),r.status||500,n)}var vP=(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 K(r,e,t,n){var s;let i=Object.assign({},n==null?void 0:n.headers);i[ii]||(i[ii]=mh["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=vP(e,n,s,i),u;try{u=await r(t,Object.assign({},a))}catch(c){throw console.error(c),new Gn(Or(c),0)}if(u.ok||await L_(u),n!=null&&n.noResolveJson)return u;try{return await u.json()}catch(c){await L_(c)}}function Ct(r){var e;let t=null;bP(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=x_(r.expires_in)));let n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:n},error:null}}function _h(r){let e=Ct(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 lt(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function M_(r){return{data:r,error:null}}function F_(r){let{action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i}=r,a=yP(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 j_(r){return r}function bP(r){return r.access_token&&r.refresh_token&&r.expires_in}var TP=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},Nr=class{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=Sa(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await K(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 K(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:lt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:t}=e,n=TP(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 K(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:F_,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 K(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:lt})}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 K(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:j_});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,E=(c=(u=f.headers.get("link"))===null||u===void 0?void 0:u.split(","))!==null&&c!==void 0?c:[];return E.length>0&&(E.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 K(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:lt})}catch(t){if(z(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await K(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:lt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,t=!1){try{return await K(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:lt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{let{data:t,error:n}=await K(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 K(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 U_={getItem:r=>sr()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{sr()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{sr()&&globalThis.localStorage.removeItem(r)}};function vh(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function B_(){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 Vr={debug:!!(globalThis&&sr()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},di=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Ca=class extends di{};async function wh(r,e,t){Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),Vr.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){Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,s.name);try{return await t()}finally{Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,s.name)}}else{if(e===0)throw Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Ca(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Vr.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()}}))}B_();var EP={url:E_,storageKey:I_,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:A_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},fi=30*1e3,$_=3;async function q_(r,e,t){return await t()}var Lr=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&&Qe()&&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({},EP),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 Nr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Sa(s.fetch),this.lock=s.lock||q_,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:Qe()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=wh:this.lock=q_,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:sr()?this.storage=U_:(this.memoryStorage={},this.storage=vh(this.memoryStorage)):(this.memoryStorage={},this.storage=vh(this.memoryStorage)),Qe()&&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} (${xa}) ${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=R_(window.location.href),n="none";if(this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce"),Qe()&&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),V_(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 qn("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,s;try{let i=await K(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:Ct}),{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,E=null,P=null;this.flowType==="pkce"&&([E,P]=await Cr(this.storage,this.storageKey)),i=await K(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:E,code_challenge_method:P},xform:Ct})}else if("phone"in e){let{phone:f,password:m,options:g}=e;i=await K(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:Ct})}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 K(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:_h})}else if("phone"in e){let{phone:i,password:a,options:u}=e;t=await K(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:_h})}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 zn}:(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 ai(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{let{data:i,error:a}=await K(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Ct});if(await ui(this.storage,`${this.storageKey}-code-verifier`),a)throw a;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new zn}:(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 K(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:Ct}),{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 zn}:(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 Cr(this.storage,this.storageKey));let{error:m}=await K(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 K(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 K(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Ct});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 Cr(this.storage,this.storageKey)),await K(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:M_})}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 K(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 K(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 K(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 ai(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<=Date.now()/1e3:!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 K(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:lt}):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 K(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:lt})})}catch(t){if(z(t))return N_(t)&&(await this._removeSession(),await ui(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 Cr(this.storage,this.storageKey));let{data:h,error:f}=await K(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:lt});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}}_decodeJWT(e){return yh(e)}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,a=yh(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(!Qe())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 li("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 li("No code detected.");let{data:M,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:M.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 E=g-f;E*1e3<=fi&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${E}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 ai(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&&!(O_(u)&&(u.status===404||u.status===401||u.status===403)))return{error:u}}return e!=="others"&&(await this._removeSession(),await ui(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t=S_(),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 Cr(this.storage,this.storageKey,!0));try{return await K(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 E=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 K(this.fetch,"GET",E,{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 Qe()&&!(!((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 K(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 k_(async s=>(s>0&&await C_(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await K(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ct})),(s,i)=>{let a=200*Math.pow(2,s);return i&&Pa(i)&&Date.now()+a-n<fi})}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),Qe()&&!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 ai(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=Math.round(Date.now()/1e3),i=((e=n.expires_at)!==null&&e!==void 0?e:1/0)<s+ph;if(this._debug(t,`session has${i?"":" not"} expired with margin of ${ph}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),Pa(a)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",a),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 oi;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 Pa(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 gh(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await ui(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Qe()&&(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(),fi);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)/fi);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${fi}ms, refresh threshold is ${$_} ticks`),s<=$_&&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 di)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Qe()||!(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 Cr(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 K(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 K(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 K(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 K(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 a=this._decodeJWT(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}}))}};Lr.nextInstanceID=0;var IP=Lr,bh=IP;var ka=class extends bh{constructor(e){super(e)}};var AP=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())})},pi=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=b_(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:y_,realtime:v_,auth:Object.assign(Object.assign({},__),{storageKey:c}),global:g_},f=T_(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=w_(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 t_(`${u}/rest/v1`,{headers:this.headers,schema:f.db.schema,fetch:this.fetch}),f.accessToken||this._listenForAuthEvents()}get functions(){return new Ks(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ni(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 AP(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 ka({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 jn(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 z_=(r,e,t)=>new pi(r,e,t);function xP(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function Da(r,e){return Array.isArray(r)?r.map(t=>Da(t,e)):typeof r=="object"?Object.fromEntries(Object.entries(xP(r,e)).map(([t,n])=>[t,Da(n,e)])):r}var G_={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var K_={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var H_={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 W_={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var Q_={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 J_={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var Y_={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var Kn={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[G_,K_,H_,W_,Q_,J_,Y_],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 Kn.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=so(e,Kn.settings),n=Kn.loadModules(t.modules),s=t.symetric?Da(r):t.clone?Kt(r):r,i=new Map,a=(u,c)=>{let h=Z(u);if(h&&t.circular){let g=i.get(u);if(g)return Ht(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 E=Se(u);t.symetric&&E.sort(),Ht(s,c,g),E.forEach(P=>a(u[P],c.concat(P)))}else c.length?Ht(s,c,g):s=g}else if(m){let g=Se(u);t.symetric&&g.sort(),g.forEach(E=>a(u[E],c.concat(E)))}};return a(s,[]),t.stringify?JSON.stringify(s):s},deserialize(r,e){let t=so(e,Kn.settings),n=Kn.loadModules(t.modules),s=du(n,"id"),i=t.destringify?JSON.parse(r):t.clone?Kt(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)?(Ht(i,c,h),Se(h).forEach(f=>a(u[f],[...c,f]))):Ht(i,c,h):i=h}else t.circular&&Z(u)&&u._&&u._=="~circular"?Ht(i,c,ms(i,u.p)):(!t.depth||c.length<t.depth)&&Z(u)&&Se(u).forEach(h=>a(u[h],c.concat(h)))};return a(i,[]),i}},mi=Kn;var X_="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Z_=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=X_[t[r]&63];return e};var re=class re{constructor(e,t){de(this,"path");de(this,"docRef");de(this,"value");de(this,"throttle",250);de(this,"config",{heartbeatInterval:5e4,syncroRegistryUrl:"https://tera-tools.com/api/sync",context:{}});de(this,"isDirty",!1);de(this,"_destroyActions",[]);de(this,"_heartbeatTimer");this.path=e,Object.assign(this,{...t,config:{...this.config,...t==null?void 0:t.config}}),re.session||(re.session=`syncro_${Z_()}`)}debug(...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 Kt(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)throw new Error(`Invalid session path syntax "${e}"`);if(re.SyncroEntities&&!(i.entity in SyncroEntities))throw new Error(`Unsupported entity "${e}" -> Entity="${i.entity}"`);return{...i,fsCollection:i.entity,fsId:i.relation?`${i.id}::${i.relation}`:i.id}}static toFirestore(e={}){return mi.serialize(e,{circular:!1,clone:!0,modules:[ev,...mi.settings.modules],stringify:!1})}static fromFirestore(e={}){return mi.deserialize(e,{circular:!1,clone:!0,modules:[ev,...mi.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=>re.toFirestoreFields({item:a}).item)}}:i==="object"&&(t[n]={mapValue:{fields:re.toFirestoreFields(s)}})}return t}static fromFirestoreFields(e={}){let t={};for(let n in e){let s=e[n];if(["stringValue","booleanValue","doubleValue","integerValue","timestampValue","mapValue","arrayValue"].find(a=>a===n)){if(["stringValue","booleanValue","doubleValue","integerValue","timestampValue"].find(u=>u===n))return s;if(n=="mapValue")return re.fromFirestoreFields(s.fields||{});if(n=="arrayValue"){let u=s.values;return u?u.map(c=>re.fromFirestoreFields(c)):[]}}else t[n]=re.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=re.pathSplit(e);return Promise.resolve().then(async()=>Hl(la(re.firestore,t,n))).then(s=>s?re.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:i,fsId:a}=re.pathSplit(e);return Promise.resolve().then(()=>(s.method=="merge"?"FirestoreUpdateDoc":"FirestoreSetDoc")(la(re.firestore,i,a),re.toFirestore(t))).then(()=>t)}static wrapSupabase(e){return Promise.resolve(e).then(t=>{var n,s;if(t!=null&&t.error)throw/JSON object requested, multiple \(or no\) rows returned$/.test(t.error.message)?(console.warn("Supabase query threw record not found against query",e.url.search),console.warn("Supabase raw error",t),new Error("NOT-FOUND")):(console.warn("Supabase query threw",t.error.message),new Error(`${((n=t.error)==null?void 0:n.code)||"UnknownError"}: ${((s=t.error)==null?void 0:s.message)||"Unknown Supabase error"}`));if(t.data)return t.data})}mount(e){let t={initialState:null,...e},{fsCollection:n,fsId:s,entity:i,id:a,relation:u}=re.pathSplit(this.path),c,h;return Promise.resolve().then(()=>this.setHeartbeat(!1)).then(async()=>{this.docRef=la(re.firestore,n,s);let f=await this.getFirestoreState();if(c=this.getReactive(f),!c.doc||!c.setState||!c.getState||!c.watch)throw new Error("Syncro.getReactive() requires a returned `doc`, `setState()`, `getState()` + `watch()`");this.value=h=c.doc,this.debug("Initial state",{doc:h}),this._destroyActions.push(Fy(this.docRef,m=>{let g=re.fromFirestore(m.data());this.debug("Incoming snapshot",{snapshotData:g}),c.setState(g)}))}).then(()=>{if(lu(h))return t.initialState?(this.debug("Populate initial Syncro state (from provided initialState)"),this.setFirestoreState(t.initialState,{method:"set"})):(this.debug(`Populate initial Syncro state (from "${i}" Syncro worker)`),fetch(`${this.config.syncroRegistryUrl}/${this.path}`).then(f=>f.ok||Promise.reject(`Failed to check Syncro "${n}::${s}" status - ${f.statusText}`)))}).then(()=>{c.watch(fu(f=>{this.debug("Local change",{newState:f}),this.markDirty(),this.setFirestoreState(f,{method:"merge"})},this.throttle))}).then(()=>this.setHeartbeat(!0,{immediate:!0})).then(()=>this)}setHeartbeat(e=!0,t){let n={immediate:!0,...t};clearTimeout(this._heartbeatTimer),e&&(this._heartbeatTimer=setTimeout(async()=>{await this.heartbeat(),e&&this.setHeartbeat(!0)},this.config.heartbeatInterval),n.immediate&&this.heartbeat())}async heartbeat(){this.debug("heartbeat!"),await fetch(`${this.config.syncroRegistryUrl}/${this.path}/heartbeat`,{method:"post",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:re.session,...this.isDirty&&{dirty:!0}})}).then(e=>e.ok?null:console.warn(this.path,`Heartbeat failed - ${e.statusText}`,{response:e})).then(()=>this.isDirty=!1)}setFirestoreState(e,t){let n={method:"merge",...t};if(!this.docRef)throw new Error("mount() must be called before setting Firestore state");return(n.method=="set"?Ly:My)(this.docRef,re.toFirestore(e))}getFirestoreState(){if(!this.docRef)throw new Error("mount() must be called before getting Firestore state");return Hl(this.docRef).then(e=>re.fromFirestore(e.data()))}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"))}};de(re,"firebase"),de(re,"firestore"),de(re,"supabase"),de(re,"session"),de(re,"SyncroEntities");var ir=re;var ev={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 gi=class{init(){}constructor(e,t){}};var yi=class extends gi{constructor(){super(...arguments);de(this,"syncros",{})}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(", "));ir.firebase=Du({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),ir.firestore=Py(this.firebase),ir.supabase=z_(n.supabaseUrl,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 ir(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.destroy()}};var Th=class extends yi{constructor(){super(...arguments);de(this,"Vue");de(this,"project",null);de(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])=>!hu(n[a],i[a])).forEach(([a,u])=>n[a]=u)},getState(){return Kt(n)},watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Th as default};
|
|
27
|
+
});`,Bn=class{constructor(e,t){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=u_,this.params={},this.timeout=Ta,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=lP,this.conn=null,this.sendBuffer=[],this.serializer=new ti,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(()=>(nr(),Ir)).then(({default:c})=>c(...u)):a=fetch,(...u)=>a(...u)},this.endPoint=`${e}/${ba.websocket}`,this.httpEndpoint=Ea(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 Ar(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(hP){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new mh(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>ou(f_())).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:c_}))}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 xr.connecting:return sr.Connecting;case xr.open:return sr.Open;case xr.closing:return sr.Closing;default:return sr.Closed}}isConnected(){return this.connectionState()===sr.Open}channel(e,t={config:{}}){let n=new Un(`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($e.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(l_,"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($e.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([dP],{type:"application/javascript"});t=URL.createObjectURL(n)}return t}},mh=class{constructor(e,t,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=xr.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}};var $n=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function ge(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Ia=class extends $n{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 $n{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var fP=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())})},Aa=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(nr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},p_=()=>fP(void 0,void 0,void 0,function*(){return typeof Response=="undefined"?(yield Promise.resolve().then(()=>(nr(),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())})},gh=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),pP=(r,e,t)=>Pr(void 0,void 0,void 0,function*(){let n=yield p_();r instanceof n&&!(t!=null&&t.noResolveJson)?r.json().then(s=>{e(new Ia(gh(s),r.status||500))}).catch(s=>{e(new Rr(gh(s),s))}):e(new Rr(gh(r),r))}),mP=(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 ri(r,e,t,n,s,i){return Pr(this,void 0,void 0,function*(){return new Promise((a,u)=>{r(t,mP(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=>pP(c,u,n))})})}function qn(r,e,t,n){return Pr(this,void 0,void 0,function*(){return ri(r,"GET",e,t,n)})}function lt(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return ri(r,"POST",e,n,s,t)})}function m_(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return ri(r,"PUT",e,n,s,t)})}function g_(r,e,t,n){return Pr(this,void 0,void 0,function*(){return ri(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),n)})}function Sa(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return ri(r,"DELETE",e,n,s,t)})}var Me=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())})},gP={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},y_={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ni=class{constructor(e,t={},n,s){this.url=e,this.headers=t,this.bucketId=n,this.fetch=Aa(s)}uploadOrUpdate(e,t,n,s){return Me(this,void 0,void 0,function*(){try{let i,a=Object.assign(Object.assign({},y_),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(ge(i))return{data:null,error:i};throw i}})}upload(e,t,n){return Me(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,n)})}uploadToSignedUrl(e,t,n,s){return Me(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:y_.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(ge(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return Me(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 $n("No token returned by API");return{data:{signedUrl:a.toString(),path:e,token:u},error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}})}update(e,t,n){return Me(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,n)})}move(e,t,n){return Me(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(ge(s))return{data:null,error:s};throw s}})}copy(e,t,n){return Me(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(ge(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,n){return Me(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(ge(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,n){return Me(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(ge(s))return{data:null,error:s};throw s}})}download(e,t){return Me(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 qn(this.fetch,`${this.url}/${s}/${u}${a}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(u){if(ge(u))return{data:null,error:u};throw u}})}info(e){return Me(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{let n=yield qn(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:xa(n),error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}})}exists(e){return Me(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{return yield g_(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(ge(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 Me(this,void 0,void 0,function*(){try{return{data:yield Sa(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}list(e,t,n){return Me(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},gP),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(ge(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 __="2.7.1";var v_={"X-Client-Info":`storage-js/${__}`};var zn=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())})},si=class{constructor(e,t={},n){this.url=e,this.headers=Object.assign(Object.assign({},v_),t),this.fetch=Aa(n)}listBuckets(){return zn(this,void 0,void 0,function*(){try{return{data:yield qn(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(ge(e))return{data:null,error:e};throw e}})}getBucket(e){return zn(this,void 0,void 0,function*(){try{return{data:yield qn(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return zn(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(ge(n))return{data:null,error:n};throw n}})}updateBucket(e,t){return zn(this,void 0,void 0,function*(){try{return{data:yield m_(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(ge(n))return{data:null,error:n};throw n}})}emptyBucket(e){return zn(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(ge(t))return{data:null,error:t};throw t}})}deleteBucket(e){return zn(this,void 0,void 0,function*(){try{return{data:yield Sa(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}};var ii=class extends si{constructor(e,t={},n){super(e,t,n)}from(e){return new ni(this.url,this.headers,e,this.fetch)}};var w_="2.48.1";var oi="";typeof Deno!="undefined"?oi="deno":typeof document!="undefined"?oi="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?oi="react-native":oi="node";var yP={"X-Client-Info":`supabase-js-${oi}/${w_}`},b_={headers:yP},T_={schema:"public"},E_={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},I_={};nr();var _P=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())})},vP=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=Yl:e=fetch,(...t)=>e(...t)},wP=()=>typeof Headers=="undefined"?Xl:Headers,x_=(r,e,t)=>{let n=vP(t),s=wP();return(i,a)=>_P(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 bP=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 A_(r){return r.replace(/\/$/,"")}function S_(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:()=>bP(this,void 0,void 0,function*(){return""})};return r.accessToken?f.accessToken=r.accessToken:delete f.accessToken,f}var Ra="2.67.3";var R_="http://localhost:9999",P_="supabase.auth.token";var C_={"X-Client-Info":`gotrue-js/${Ra}`},yh=10;var ai="X-Supabase-Api-Version",_h={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function k_(r){return Math.round(Date.now()/1e3)+r}function D_(){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",Cr={tested:!1,writable:!1},ir=()=>{if(!Ye())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Cr.tested)return Cr.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Cr.tested=!0,Cr.writable=!0}catch{Cr.tested=!0,Cr.writable=!1}return Cr.writable};function O_(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 Pa=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(nr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},N_=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",vh=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},ci=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},li=async(r,e)=>{await r.removeItem(e)};function TP(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",n,s,i,a,u,c,h,f=0;for(r=r.replace("-","+").replace("_","/");f<r.length;)a=e.indexOf(r.charAt(f++)),u=e.indexOf(r.charAt(f++)),c=e.indexOf(r.charAt(f++)),h=e.indexOf(r.charAt(f++)),n=a<<2|u>>4,s=(u&15)<<4|c>>2,i=(c&3)<<6|h,t=t+String.fromCharCode(n),c!=64&&s!=0&&(t=t+String.fromCharCode(s)),h!=64&&i!=0&&(t=t+String.fromCharCode(i));return t}var ui=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};ui.promiseConstructor=Promise;function wh(r){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=r.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let n=t[1];return JSON.parse(TP(n))}async function V_(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function L_(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 EP(r){return("0"+r.toString(16)).substr(-2)}function IP(){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,EP).join("")}async function xP(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("")}function AP(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function SP(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 xP(r);return AP(t)}async function kr(r,e,t=!1){let n=IP(),s=n;t&&(s+="/PASSWORD_RECOVERY"),await vh(r,`${e}-code-verifier`,s);let i=await SP(n);return[i,n===i?"plain":"s256"]}var RP=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function M_(r){let e=r.headers.get(ai);if(!e||!e.match(RP))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var hi=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 Ca=class extends hi{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}};function F_(r){return z(r)&&r.name==="AuthApiError"}var Gn=class extends hi{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},Ct=class extends hi{constructor(e,t,n,s){super(e,n,s),this.name=t,this.status=n}},Ge=class extends Ct{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function j_(r){return z(r)&&r.name==="AuthSessionMissingError"}var Kn=class extends Ct{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Dr=class extends Ct{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Or=class extends Ct{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 U_(r){return z(r)&&r.name==="AuthImplicitGrantRedirectError"}var di=class extends Ct{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}}},Hn=class extends Ct{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function ka(r){return z(r)&&r.name==="AuthRetryableFetchError"}var fi=class extends Ct{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}};var PP=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},Nr=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),CP=[502,503,504];async function B_(r){var e;if(!N_(r))throw new Hn(Nr(r),0);if(CP.includes(r.status))throw new Hn(Nr(r),r.status);let t;try{t=await r.json()}catch(i){throw new Gn(Nr(i),i)}let n,s=M_(r);if(s&&s.getTime()>=_h["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 fi(Nr(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Ge}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 fi(Nr(t),r.status,t.weak_password.reasons);throw new Ca(Nr(t),r.status||500,n)}var kP=(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 K(r,e,t,n){var s;let i=Object.assign({},n==null?void 0:n.headers);i[ai]||(i[ai]=_h["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 DP(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 DP(r,e,t,n,s,i){let a=kP(e,n,s,i),u;try{u=await r(t,Object.assign({},a))}catch(c){throw console.error(c),new Hn(Nr(c),0)}if(u.ok||await B_(u),n!=null&&n.noResolveJson)return u;try{return await u.json()}catch(c){await B_(c)}}function kt(r){var e;let t=null;OP(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=k_(r.expires_in)));let n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:n},error:null}}function bh(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 ht(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function $_(r){return{data:r,error:null}}function q_(r){let{action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i}=r,a=PP(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 z_(r){return r}function OP(r){return r.access_token&&r.refresh_token&&r.expires_in}var NP=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=class{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=Pa(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await K(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 K(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ht})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:t}=e,n=NP(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 K(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:q_,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 K(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ht})}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 K(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:z_});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,E=(c=(u=f.headers.get("link"))===null||u===void 0?void 0:u.split(","))!==null&&c!==void 0?c:[];return E.length>0&&(E.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 K(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ht})}catch(t){if(z(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await K(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ht})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,t=!1){try{return await K(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ht})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{let{data:t,error:n}=await K(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 K(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 G_={getItem:r=>ir()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{ir()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{ir()&&globalThis.localStorage.removeItem(r)}};function Th(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function K_(){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 Lr={debug:!!(globalThis&&ir()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},pi=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Da=class extends pi{};async function Eh(r,e,t){Lr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),Lr.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){Lr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,s.name);try{return await t()}finally{Lr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,s.name)}}else{if(e===0)throw Lr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Da(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Lr.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()}}))}K_();var VP={url:R_,storageKey:P_,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:C_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},mi=30*1e3,H_=3;async function W_(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({},VP),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 Vr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Pa(s.fetch),this.lock=s.lock||W_,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=Eh:this.lock=W_,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:ir()?this.storage=G_:(this.memoryStorage={},this.storage=Th(this.memoryStorage)):(this.memoryStorage={},this.storage=Th(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} (${Ra}) ${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=O_(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),U_(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 Gn("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,s;try{let i=await K(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,E=null,P=null;this.flowType==="pkce"&&([E,P]=await kr(this.storage,this.storageKey)),i=await K(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:E,code_challenge_method:P},xform:kt})}else if("phone"in e){let{phone:f,password:m,options:g}=e;i=await K(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 Dr("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 K(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:bh})}else if("phone"in e){let{phone:i,password:a,options:u}=e;t=await K(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:bh})}else throw new Dr("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 Kn}:(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 ci(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{let{data:i,error:a}=await K(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:kt});if(await li(this.storage,`${this.storageKey}-code-verifier`),a)throw a;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Kn}:(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 K(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 Kn}:(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 kr(this.storage,this.storageKey));let{error:m}=await K(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 K(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 Dr("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 K(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 kr(this.storage,this.storageKey)),await K(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:$_})}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 Ge;let{error:s}=await K(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 K(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 K(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 Dr("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 ci(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<=Date.now()/1e3:!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 K(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ht}):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 Ge}:await K(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:ht})})}catch(t){if(z(t))return j_(t)&&(await this._removeSession(),await li(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 Ge;let a=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await kr(this.storage,this.storageKey));let{data:h,error:f}=await K(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:ht});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}}_decodeJWT(e){return wh(e)}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 Ge;let t=Date.now()/1e3,n=t,s=!0,i=null,a=wh(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 Ge;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 Or("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Or(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 di("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Or("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 di("No code detected.");let{data:M,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:M.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 Or("No session defined in URL");let f=Math.round(Date.now()/1e3),m=parseInt(u),g=f+m;c&&(g=parseInt(c));let E=g-f;E*1e3<=mi&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${E}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 ci(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&&!(F_(u)&&(u.status===404||u.status===401||u.status===403)))return{error:u}}return e!=="others"&&(await this._removeSession(),await li(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t=D_(),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 kr(this.storage,this.storageKey,!0));try{return await K(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 E=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 K(this.fetch,"GET",E,{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 K(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 L_(async s=>(s>0&&await V_(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await K(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&&ka(i)&&Date.now()+a-n<mi})}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 ci(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=Math.round(Date.now()/1e3),i=((e=n.expires_at)!==null&&e!==void 0?e:1/0)<s+yh;if(this._debug(t,`session has${i?"":" not"} expired with margin of ${yh}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),ka(a)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",a),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 Ge;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new ui;let{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new Ge;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 ka(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 vh(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await li(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(),mi);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)/mi);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${mi}ms, refresh threshold is ${H_} ticks`),s<=H_&&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 pi)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 kr(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 K(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 K(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 K(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 K(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 a=this._decodeJWT(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}}))}};Mr.nextInstanceID=0;var LP=Mr,Ih=LP;var Oa=class extends Ih{constructor(e){super(e)}};var MP=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())})},gi=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=A_(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:T_,realtime:I_,auth:Object.assign(Object.assign({},E_),{storageKey:c}),global:b_},f=S_(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=x_(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 o_(`${u}/rest/v1`,{headers:this.headers,schema:f.db.schema,fetch:this.fetch}),f.accessToken||this._listenForAuthEvents()}get functions(){return new Ws(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ii(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 MP(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 Oa({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 Bn(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 Q_=(r,e,t)=>new gi(r,e,t);function FP(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function Na(r,e){return Array.isArray(r)?r.map(t=>Na(t,e)):typeof r=="object"?Object.fromEntries(Object.entries(FP(r,e)).map(([t,n])=>[t,Na(n,e)])):r}var J_={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var Y_={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var X_={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 Z_={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var ev={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 tv={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var rv={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var Wn={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[J_,Y_,X_,Z_,ev,tv,rv],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 Wn.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=oo(e,Wn.settings),n=Wn.loadModules(t.modules),s=t.symetric?Na(r):t.clone?Ht(r):r,i=new Map,a=(u,c)=>{let h=Z(u);if(h&&t.circular){let g=i.get(u);if(g)return Wt(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 E=Se(u);t.symetric&&E.sort(),Wt(s,c,g),E.forEach(P=>a(u[P],c.concat(P)))}else c.length?Wt(s,c,g):s=g}else if(m){let g=Se(u);t.symetric&&g.sort(),g.forEach(E=>a(u[E],c.concat(E)))}};return a(s,[]),t.stringify?JSON.stringify(s):s},deserialize(r,e){let t=oo(e,Wn.settings),n=Wn.loadModules(t.modules),s=mu(n,"id"),i=t.destringify?JSON.parse(r):t.clone?Ht(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)?(Wt(i,c,h),Se(h).forEach(f=>a(u[f],[...c,f]))):Wt(i,c,h):i=h}else t.circular&&Z(u)&&u._&&u._=="~circular"?Wt(i,c,ys(i,u.p)):(!t.depth||c.length<t.depth)&&Z(u)&&Se(u).forEach(h=>a(u[h],c.concat(h)))};return a(i,[]),i}},yi=Wn;var nv="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var sv=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=nv[t[r]&63];return e};var hv=ou(cv(),1);var UP=Object.prototype.toString,BP=r=>UP.call(r)==="[object Error]",$P=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 xh(r){return r&&BP(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:$P.has(r.message):!1}var Ah=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}},lv=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Sh(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=hv.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 Ah)throw m.originalError;if(m instanceof TypeError&&!xh(m))throw m;if(lv(m,f,e),await e.shouldRetry(m)||(s.stop(),n(m)),await e.onFailedAttempt(m),!s.retry(m))throw s.mainError()}catch(g){lv(g,f,e),a(),n(g)}}})})}var re=class re{constructor(e,t){de(this,"path");de(this,"docRef");de(this,"value");de(this,"throttle",250);de(this,"config",{heartbeatInterval:5e4,syncroRegistryUrl:"https://tera-tools.com/api/sync",context:{}});de(this,"isDirty",!1);de(this,"_destroyActions",[]);de(this,"_heartbeatTimer");this.path=e,Object.assign(this,{...t,config:{...this.config,...t==null?void 0:t.config}}),re.session||(re.session=`syncro_${sv()}`)}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 Ht(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)throw new Error(`Invalid session path syntax "${e}"`);if(re.SyncroEntities&&!(i.entity in SyncroEntities))throw new Error(`Unsupported entity "${e}" -> Entity="${i.entity}"`);return{...i,fsCollection:i.entity,fsId:i.relation?`${i.id}::${i.relation}`:i.id}}static toFirestore(e={}){return yi.serialize(e,{circular:!1,clone:!0,modules:[dv,...yi.settings.modules],stringify:!1})}static fromFirestore(e={}){return yi.deserialize(e,{circular:!1,clone:!0,modules:[dv,...yi.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=>re.toFirestoreFields({item:a}).item)}}:i==="object"&&(t[n]={mapValue:{fields:re.toFirestoreFields(s)}})}return t}static fromFirestoreFields(e={}){let t={};for(let n in e){let s=e[n];if(["stringValue","booleanValue","doubleValue","integerValue","timestampValue","mapValue","arrayValue"].find(a=>a===n)){if(["stringValue","booleanValue","doubleValue","integerValue","timestampValue"].find(u=>u===n))return s;if(n=="mapValue")return re.fromFirestoreFields(s.fields||{});if(n=="arrayValue"){let u=s.values;return u?u.map(c=>re.fromFirestoreFields(c)):[]}}else t[n]=re.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=re.pathSplit(e);return Promise.resolve().then(async()=>Jl(da(re.firestore,t,n))).then(s=>s?re.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:i,fsId:a}=re.pathSplit(e);return Promise.resolve().then(()=>(s.method=="merge"?"FirestoreUpdateDoc":"FirestoreSetDoc")(da(re.firestore,i,a),re.toFirestore(t))).then(()=>t)}static wrapSupabase(e){return Promise.resolve(e).then(t=>{var n,s;if(t!=null&&t.error)throw/JSON object requested, multiple \(or no\) rows returned$/.test(t.error.message)?(console.warn("Supabase query threw record not found against query",e.url.search),console.warn("Supabase raw error",t),new Error("NOT-FOUND")):(console.warn("Supabase query threw",t.error.message),new Error(`${((n=t.error)==null?void 0:n.code)||"UnknownError"}: ${((s=t.error)==null?void 0:s.message)||"Unknown Supabase error"}`));if(t.data)return t.data})}mount(e){let t={initialState:null,retries:5,retryMinTime:250,...e},{fsCollection:n,fsId:s,entity:i,id:a,relation:u}=re.pathSplit(this.path),c,h;return Sh(()=>Promise.resolve().then(()=>this.setHeartbeat(!1)).then(async()=>{this.docRef=da(re.firestore,n,s);let f=await this.getFirestoreState();if(c=this.getReactive(f),!c.doc||!c.setState||!c.getState||!c.watch)throw new Error("Syncro.getReactive() requires a returned `doc`, `setState()`, `getState()` + `watch()`");this.value=h=c.doc,this.debug("Initial state",{doc:h}),this._destroyActions.push(qy(this.docRef,m=>{let g=re.fromFirestore(m.data());this.debug("Incoming snapshot",{snapshotData:g}),c.setState(g)}))}).then(()=>{if(fu(h))return t.initialState?(this.debug("Populate initial Syncro state (from provided initialState)"),this.setFirestoreState(t.initialState,{method:"set"})):(this.debug(`Populate initial Syncro state (from "${i}" Syncro worker)`),fetch(`${this.config.syncroRegistryUrl}/${this.path}`).then(f=>f.ok||Promise.reject(`Failed to check Syncro "${n}::${s}" status - ${f.statusText}`)))}).then(()=>{c.watch(gu(f=>{this.debug("Local change",{newState:f}),this.markDirty(),this.setFirestoreState(f,{method:"merge"})},this.throttle))}).then(()=>this.setHeartbeat(!0,{immediate:!0})).then(()=>this).catch(async f=>{throw await this.destroy(),f}),{retries:t.retries,minTimeout:t.retryMinTime,randomize:!0,factor:3,onFailedAttempt:f=>this.debugError(`[Attempt ${f.attemptNumber}/${f.attemptNumber+f.retriesLeft-1}] to mount syncro`,f)})}setHeartbeat(e=!0,t){let n={immediate:!0,...t};clearTimeout(this._heartbeatTimer),e&&(this._heartbeatTimer=setTimeout(async()=>{await this.heartbeat(),e&&this.setHeartbeat(!0)},this.config.heartbeatInterval),n.immediate&&this.heartbeat())}async heartbeat(){this.debug("heartbeat!"),await fetch(`${this.config.syncroRegistryUrl}/${this.path}/heartbeat`,{method:"post",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:re.session,...this.isDirty&&{dirty:!0}})}).then(e=>e.ok?null:console.warn(this.path,`Heartbeat failed - ${e.statusText}`,{response:e})).then(()=>this.isDirty=!1)}setFirestoreState(e,t){let n={method:"merge",...t};if(!this.docRef)throw new Error("mount() must be called before setting Firestore state");return(n.method=="set"?By:$y)(this.docRef,re.toFirestore(e))}getFirestoreState(){if(!this.docRef)throw new Error("mount() must be called before getting Firestore state");return Jl(this.docRef).then(e=>re.fromFirestore(e.data()))}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"))}};de(re,"firebase"),de(re,"firestore"),de(re,"supabase"),de(re,"session"),de(re,"SyncroEntities");var or=re;var dv={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 _i=class{init(){}constructor(e,t){}};var vi=class extends _i{constructor(){super(...arguments);de(this,"syncros",{})}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(", "));or.firebase=Vu({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),or.firestore=Ny(this.firebase),or.supabase=Q_(n.supabaseUrl,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 or(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.destroy()}};var Rh=class extends vi{constructor(){super(...arguments);de(this,"Vue");de(this,"project",null);de(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])=>!pu(n[a],i[a])).forEach(([a,u])=>n[a]=u)},getState(){return Ht(n)},watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Rh as default};
|
|
28
28
|
/*! Bundled license information:
|
|
29
29
|
|
|
30
30
|
lodash-es/lodash.js:
|