@iebh/tera-fy 2.3.5 → 2.3.6
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 +7 -0
- package/dist/plugin.vue2.es2019.js +166 -176
- package/dist/terafy.es2019.js +5 -5
- package/dist/terafy.js +5 -5
- package/package.json +4 -4
|
@@ -1,51 +1,37 @@
|
|
|
1
|
-
var hw=Object.create;var jd=Object.defineProperty;var dw=Object.getOwnPropertyDescriptor;var fw=Object.getOwnPropertyNames;var pw=Object.getPrototypeOf,mw=Object.prototype.hasOwnProperty;var vu=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var gw=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fw(e))!mw.call(r,s)&&s!==t&&jd(r,s,{get:()=>e[s],enumerable:!(n=dw(e,s))||n.enumerable});return r};var yw=(r,e,t)=>(t=r!=null?hw(pw(r)):{},gw(e||!r||!r.__esModule?jd(t,"default",{value:r,enumerable:!0}):t,r));var pv=vu((hB,fv)=>{function Je(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))}fv.exports=Je;Je.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Je.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Je.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};Je.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)};Je.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Je.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Je.prototype.start=Je.prototype.try;Je.prototype.errors=function(){return this._errors};Je.prototype.attempts=function(){return this._attempts};Je.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,o=(r[i]||0)+1;r[i]=o,o>=t&&(e=s,t=o)}return e}});var mv=vu(Jr=>{var NC=pv();Jr.operation=function(r){var e=Jr.timeouts(r);return new NC(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Jr.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<e.retries;s++)n.push(this.createTimeout(s,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(s,e)),n.sort(function(i,o){return i-o}),n};Jr.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};Jr.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var s=0;s<t.length;s++){var i=t[s],o=r[i];r[i]=function(c){var h=Jr.operation(e),f=Array.prototype.slice.call(arguments,1),p=f.pop();f.push(function(m){h.retry(m)||(m&&(arguments[0]=h.mainError()),p.apply(this,arguments))}),h.attempt(function(){c.apply(r,f)})}.bind(r,o),r[i].options=e}}});var yv=vu((fB,gv)=>{gv.exports=mv()});var _w=typeof global=="object"&&global&&global.Object===Object&&global,Gi=_w;var vw=typeof self=="object"&&self&&self.Object===Object&&self,ww=Gi||vw||Function("return this")(),le=ww;var bw=le.Symbol,je=bw;var Md=Object.prototype,Ew=Md.hasOwnProperty,Tw=Md.toString,Rs=je?je.toStringTag:void 0;function Iw(r){var e=Ew.call(r,Rs),t=r[Rs];try{r[Rs]=void 0;var n=!0}catch{}var s=Tw.call(r);return n&&(e?r[Rs]=t:delete r[Rs]),s}var Ud=Iw;var Sw=Object.prototype,Aw=Sw.toString;function xw(r){return Aw.call(r)}var Bd=xw;var Rw="[object Null]",Pw="[object Undefined]",$d=je?je.toStringTag:void 0;function Cw(r){return r==null?r===void 0?Pw:Rw:$d&&$d in Object(r)?Ud(r):Bd(r)}var Ye=Cw;function kw(r){return r!=null&&typeof r=="object"}var Me=kw;var Ow="[object Symbol]";function Dw(r){return typeof r=="symbol"||Me(r)&&Ye(r)==Ow}var $t=Dw;function Nw(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 qd=Nw;var Vw=Array.isArray,fe=Vw;var Lw=1/0,zd=je?je.prototype:void 0,Kd=zd?zd.toString:void 0;function Gd(r){if(typeof r=="string")return r;if(fe(r))return qd(r,Gd)+"";if($t(r))return Kd?Kd.call(r):"";var e=r+"";return e=="0"&&1/r==-Lw?"-0":e}var Wd=Gd;var Fw=/\s/;function jw(r){for(var e=r.length;e--&&Fw.test(r.charAt(e)););return e}var Hd=jw;var Mw=/^\s+/;function Uw(r){return r&&r.slice(0,Hd(r)+1).replace(Mw,"")}var Qd=Uw;function Bw(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var ee=Bw;var Jd=NaN,$w=/^[-+]0x[0-9a-f]+$/i,qw=/^0b[01]+$/i,zw=/^0o[0-7]+$/i,Kw=parseInt;function Gw(r){if(typeof r=="number")return r;if($t(r))return Jd;if(ee(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=ee(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=Qd(r);var t=qw.test(r);return t||zw.test(r)?Kw(r.slice(2),t?2:8):$w.test(r)?Jd:+r}var wu=Gw;function Ww(r){return r}var tn=Ww;var Hw="[object AsyncFunction]",Qw="[object Function]",Jw="[object GeneratorFunction]",Xw="[object Proxy]";function Yw(r){if(!ee(r))return!1;var e=Ye(r);return e==Qw||e==Jw||e==Hw||e==Xw}var Wi=Yw;var Zw=le["__core-js_shared__"],Hi=Zw;var Xd=(function(){var r=/[^.]+$/.exec(Hi&&Hi.keys&&Hi.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function eb(r){return!!Xd&&Xd in r}var Yd=eb;var tb=Function.prototype,rb=tb.toString;function nb(r){if(r!=null){try{return rb.call(r)}catch{}try{return r+""}catch{}}return""}var wt=nb;var sb=/[\\^$.*+?()[\]{}|]/g,ib=/^\[object .+?Constructor\]$/,ob=Function.prototype,ab=Object.prototype,ub=ob.toString,cb=ab.hasOwnProperty,lb=RegExp("^"+ub.call(cb).replace(sb,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function hb(r){if(!ee(r)||Yd(r))return!1;var e=Wi(r)?lb:ib;return e.test(wt(r))}var Zd=hb;function db(r,e){return r==null?void 0:r[e]}var ef=db;function fb(r,e){var t=ef(r,e);return Zd(t)?t:void 0}var Ue=fb;var pb=Ue(le,"WeakMap"),Qi=pb;var tf=Object.create,mb=(function(){function r(){}return function(e){if(!ee(e))return{};if(tf)return tf(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})(),rf=mb;function gb(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 nf=gb;function yb(r,e){var t=-1,n=r.length;for(e||(e=Array(n));++t<n;)e[t]=r[t];return e}var sf=yb;var _b=800,vb=16,wb=Date.now;function bb(r){var e=0,t=0;return function(){var n=wb(),s=vb-(n-t);if(t=n,s>0){if(++e>=_b)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}var of=bb;function Eb(r){return function(){return r}}var af=Eb;var Tb=(function(){try{var r=Ue(Object,"defineProperty");return r({},"",{}),r}catch{}})(),rn=Tb;var Ib=rn?function(r,e){return rn(r,"toString",{configurable:!0,enumerable:!1,value:af(e),writable:!0})}:tn,uf=Ib;var Sb=of(uf),cf=Sb;function Ab(r,e){for(var t=-1,n=r==null?0:r.length;++t<n&&e(r[t],t,r)!==!1;);return r}var lf=Ab;var xb=9007199254740991,Rb=/^(?:0|[1-9]\d*)$/;function Pb(r,e){var t=typeof r;return e=e==null?xb:e,!!e&&(t=="number"||t!="symbol"&&Rb.test(r))&&r>-1&&r%1==0&&r<e}var qt=Pb;function Cb(r,e,t){e=="__proto__"&&rn?rn(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}var nn=Cb;function kb(r,e){return r===e||r!==r&&e!==e}var st=kb;var Ob=Object.prototype,Db=Ob.hasOwnProperty;function Nb(r,e,t){var n=r[e];(!(Db.call(r,e)&&st(n,t))||t===void 0&&!(e in r))&&nn(r,e,t)}var sn=Nb;function Vb(r,e,t,n){var s=!t;t||(t={});for(var i=-1,o=e.length;++i<o;){var u=e[i],c=n?n(t[u],r[u],u,t,r):void 0;c===void 0&&(c=r[u]),s?nn(t,u,c):sn(t,u,c)}return t}var zt=Vb;var hf=Math.max;function Lb(r,e,t){return e=hf(e===void 0?r.length-1:e,0),function(){for(var n=arguments,s=-1,i=hf(n.length-e,0),o=Array(i);++s<i;)o[s]=n[e+s];s=-1;for(var u=Array(e+1);++s<e;)u[s]=n[s];return u[e]=t(o),nf(r,this,u)}}var df=Lb;function Fb(r,e){return cf(df(r,e,tn),r+"")}var ff=Fb;var jb=9007199254740991;function Mb(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=jb}var on=Mb;function Ub(r){return r!=null&&on(r.length)&&!Wi(r)}var Kt=Ub;function Bb(r,e,t){if(!ee(t))return!1;var n=typeof e;return(n=="number"?Kt(t)&&qt(e,t.length):n=="string"&&e in t)?st(t[e],r):!1}var pf=Bb;var $b=Object.prototype;function qb(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||$b;return r===t}var Gt=qb;function zb(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}var mf=zb;var Kb="[object Arguments]";function Gb(r){return Me(r)&&Ye(r)==Kb}var bu=Gb;var gf=Object.prototype,Wb=gf.hasOwnProperty,Hb=gf.propertyIsEnumerable,Qb=bu((function(){return arguments})())?bu:function(r){return Me(r)&&Wb.call(r,"callee")&&!Hb.call(r,"callee")},an=Qb;function Jb(){return!1}var yf=Jb;var wf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,_f=wf&&typeof module=="object"&&module&&!module.nodeType&&module,Xb=_f&&_f.exports===wf,vf=Xb?le.Buffer:void 0,Yb=vf?vf.isBuffer:void 0,Zb=Yb||yf,bt=Zb;var e0="[object Arguments]",t0="[object Array]",r0="[object Boolean]",n0="[object Date]",s0="[object Error]",i0="[object Function]",o0="[object Map]",a0="[object Number]",u0="[object Object]",c0="[object RegExp]",l0="[object Set]",h0="[object String]",d0="[object WeakMap]",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]",E0="[object Uint16Array]",T0="[object Uint32Array]",oe={};oe[m0]=oe[g0]=oe[y0]=oe[_0]=oe[v0]=oe[w0]=oe[b0]=oe[E0]=oe[T0]=!0;oe[e0]=oe[t0]=oe[f0]=oe[r0]=oe[p0]=oe[n0]=oe[s0]=oe[i0]=oe[o0]=oe[a0]=oe[u0]=oe[c0]=oe[l0]=oe[h0]=oe[d0]=!1;function I0(r){return Me(r)&&on(r.length)&&!!oe[Ye(r)]}var bf=I0;function S0(r){return function(e){return r(e)}}var un=S0;var Ef=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ps=Ef&&typeof module=="object"&&module&&!module.nodeType&&module,A0=Ps&&Ps.exports===Ef,Eu=A0&&Gi.process,x0=(function(){try{var r=Ps&&Ps.require&&Ps.require("util").types;return r||Eu&&Eu.binding&&Eu.binding("util")}catch{}})(),Et=x0;var Tf=Et&&Et.isTypedArray,R0=Tf?un(Tf):bf,cn=R0;var P0=Object.prototype,C0=P0.hasOwnProperty;function k0(r,e){var t=fe(r),n=!t&&an(r),s=!t&&!n&&bt(r),i=!t&&!n&&!s&&cn(r),o=t||n||s||i,u=o?mf(r.length,String):[],c=u.length;for(var h in r)(e||C0.call(r,h))&&!(o&&(h=="length"||s&&(h=="offset"||h=="parent")||i&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||qt(h,c)))&&u.push(h);return u}var Ji=k0;function O0(r,e){return function(t){return r(e(t))}}var Xi=O0;var D0=Xi(Object.keys,Object),If=D0;var N0=Object.prototype,V0=N0.hasOwnProperty;function L0(r){if(!Gt(r))return If(r);var e=[];for(var t in Object(r))V0.call(r,t)&&t!="constructor"&&e.push(t);return e}var Yi=L0;function F0(r){return Kt(r)?Ji(r):Yi(r)}var De=F0;function j0(r){var e=[];if(r!=null)for(var t in Object(r))e.push(t);return e}var Sf=j0;var M0=Object.prototype,U0=M0.hasOwnProperty;function B0(r){if(!ee(r))return Sf(r);var e=Gt(r),t=[];for(var n in r)n=="constructor"&&(e||!U0.call(r,n))||t.push(n);return t}var Af=B0;function $0(r){return Kt(r)?Ji(r,!0):Af(r)}var Wt=$0;var q0=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,z0=/^\w*$/;function K0(r,e){if(fe(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||$t(r)?!0:z0.test(r)||!q0.test(r)||e!=null&&r in Object(e)}var ln=K0;var G0=Ue(Object,"create"),Tt=G0;function W0(){this.__data__=Tt?Tt(null):{},this.size=0}var xf=W0;function H0(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Rf=H0;var Q0="__lodash_hash_undefined__",J0=Object.prototype,X0=J0.hasOwnProperty;function Y0(r){var e=this.__data__;if(Tt){var t=e[r];return t===Q0?void 0:t}return X0.call(e,r)?e[r]:void 0}var Pf=Y0;var Z0=Object.prototype,eE=Z0.hasOwnProperty;function tE(r){var e=this.__data__;return Tt?e[r]!==void 0:eE.call(e,r)}var Cf=tE;var rE="__lodash_hash_undefined__";function nE(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Tt&&e===void 0?rE:e,this}var kf=nE;function hn(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])}}hn.prototype.clear=xf;hn.prototype.delete=Rf;hn.prototype.get=Pf;hn.prototype.has=Cf;hn.prototype.set=kf;var Tu=hn;function sE(){this.__data__=[],this.size=0}var Of=sE;function iE(r,e){for(var t=r.length;t--;)if(st(r[t][0],e))return t;return-1}var Ht=iE;var oE=Array.prototype,aE=oE.splice;function uE(r){var e=this.__data__,t=Ht(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():aE.call(e,t,1),--this.size,!0}var Df=uE;function cE(r){var e=this.__data__,t=Ht(e,r);return t<0?void 0:e[t][1]}var Nf=cE;function lE(r){return Ht(this.__data__,r)>-1}var Vf=lE;function hE(r,e){var t=this.__data__,n=Ht(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}var Lf=hE;function dn(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])}}dn.prototype.clear=Of;dn.prototype.delete=Df;dn.prototype.get=Nf;dn.prototype.has=Vf;dn.prototype.set=Lf;var Qt=dn;var dE=Ue(le,"Map"),Jt=dE;function fE(){this.size=0,this.__data__={hash:new Tu,map:new(Jt||Qt),string:new Tu}}var Ff=fE;function pE(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var jf=pE;function mE(r,e){var t=r.__data__;return jf(e)?t[typeof e=="string"?"string":"hash"]:t.map}var Xt=mE;function gE(r){var e=Xt(this,r).delete(r);return this.size-=e?1:0,e}var Mf=gE;function yE(r){return Xt(this,r).get(r)}var Uf=yE;function _E(r){return Xt(this,r).has(r)}var Bf=_E;function vE(r,e){var t=Xt(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}var $f=vE;function fn(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])}}fn.prototype.clear=Ff;fn.prototype.delete=Mf;fn.prototype.get=Uf;fn.prototype.has=Bf;fn.prototype.set=$f;var br=fn;var wE="Expected a function";function Iu(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(wE);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 o=r.apply(this,n);return t.cache=i.set(s,o)||i,o};return t.cache=new(Iu.Cache||br),t}Iu.Cache=br;var qf=Iu;var bE=500;function EE(r){var e=qf(r,function(n){return t.size===bE&&t.clear(),n}),t=e.cache;return e}var zf=EE;var TE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,IE=/\\(\\)?/g,SE=zf(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(TE,function(t,n,s,i){e.push(s?i.replace(IE,"$1"):n||t)}),e}),Kf=SE;function AE(r){return r==null?"":Wd(r)}var Gf=AE;function xE(r,e){return fe(r)?r:ln(r,e)?[r]:Kf(Gf(r))}var pn=xE;var RE=1/0;function PE(r){if(typeof r=="string"||$t(r))return r;var e=r+"";return e=="0"&&1/r==-RE?"-0":e}var it=PE;function CE(r,e){e=pn(e,r);for(var t=0,n=e.length;r!=null&&t<n;)r=r[it(e[t++])];return t&&t==n?r:void 0}var Zi=CE;function kE(r,e,t){var n=r==null?void 0:Zi(r,e);return n===void 0?t:n}var Cs=kE;function OE(r,e){for(var t=-1,n=e.length,s=r.length;++t<n;)r[s+t]=e[t];return r}var eo=OE;var DE=Xi(Object.getPrototypeOf,Object),to=DE;function NE(){this.__data__=new Qt,this.size=0}var Wf=NE;function VE(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}var Hf=VE;function LE(r){return this.__data__.get(r)}var Qf=LE;function FE(r){return this.__data__.has(r)}var Jf=FE;var jE=200;function ME(r,e){var t=this.__data__;if(t instanceof Qt){var n=t.__data__;if(!Jt||n.length<jE-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new br(n)}return t.set(r,e),this.size=t.size,this}var Xf=ME;function mn(r){var e=this.__data__=new Qt(r);this.size=e.size}mn.prototype.clear=Wf;mn.prototype.delete=Hf;mn.prototype.get=Qf;mn.prototype.has=Jf;mn.prototype.set=Xf;var Yt=mn;function UE(r,e){return r&&zt(e,De(e),r)}var Yf=UE;function BE(r,e){return r&&zt(e,Wt(e),r)}var Zf=BE;var np=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ep=np&&typeof module=="object"&&module&&!module.nodeType&&module,$E=ep&&ep.exports===np,tp=$E?le.Buffer:void 0,rp=tp?tp.allocUnsafe:void 0;function qE(r,e){if(e)return r.slice();var t=r.length,n=rp?rp(t):new r.constructor(t);return r.copy(n),n}var sp=qE;function zE(r,e){for(var t=-1,n=r==null?0:r.length,s=0,i=[];++t<n;){var o=r[t];e(o,t,r)&&(i[s++]=o)}return i}var ip=zE;function KE(){return[]}var ro=KE;var GE=Object.prototype,WE=GE.propertyIsEnumerable,op=Object.getOwnPropertySymbols,HE=op?function(r){return r==null?[]:(r=Object(r),ip(op(r),function(e){return WE.call(r,e)}))}:ro,gn=HE;function QE(r,e){return zt(r,gn(r),e)}var ap=QE;var JE=Object.getOwnPropertySymbols,XE=JE?function(r){for(var e=[];r;)eo(e,gn(r)),r=to(r);return e}:ro,no=XE;function YE(r,e){return zt(r,no(r),e)}var up=YE;function ZE(r,e,t){var n=e(r);return fe(r)?n:eo(n,t(r))}var so=ZE;function eT(r){return so(r,De,gn)}var ks=eT;function tT(r){return so(r,Wt,no)}var cp=tT;var rT=Ue(le,"DataView"),io=rT;var nT=Ue(le,"Promise"),oo=nT;var sT=Ue(le,"Set"),ao=sT;var lp="[object Map]",iT="[object Object]",hp="[object Promise]",dp="[object Set]",fp="[object WeakMap]",pp="[object DataView]",oT=wt(io),aT=wt(Jt),uT=wt(oo),cT=wt(ao),lT=wt(Qi),Er=Ye;(io&&Er(new io(new ArrayBuffer(1)))!=pp||Jt&&Er(new Jt)!=lp||oo&&Er(oo.resolve())!=hp||ao&&Er(new ao)!=dp||Qi&&Er(new Qi)!=fp)&&(Er=function(r){var e=Ye(r),t=e==iT?r.constructor:void 0,n=t?wt(t):"";if(n)switch(n){case oT:return pp;case aT:return lp;case uT:return hp;case cT:return dp;case lT:return fp}return e});var Ze=Er;var hT=Object.prototype,dT=hT.hasOwnProperty;function fT(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&dT.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var mp=fT;var pT=le.Uint8Array,yn=pT;function mT(r){var e=new r.constructor(r.byteLength);return new yn(e).set(new yn(r)),e}var _n=mT;function gT(r,e){var t=e?_n(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.byteLength)}var gp=gT;var yT=/\w*$/;function _T(r){var e=new r.constructor(r.source,yT.exec(r));return e.lastIndex=r.lastIndex,e}var yp=_T;var _p=je?je.prototype:void 0,vp=_p?_p.valueOf:void 0;function vT(r){return vp?Object(vp.call(r)):{}}var wp=vT;function wT(r,e){var t=e?_n(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.length)}var bp=wT;var bT="[object Boolean]",ET="[object Date]",TT="[object Map]",IT="[object Number]",ST="[object RegExp]",AT="[object Set]",xT="[object String]",RT="[object Symbol]",PT="[object ArrayBuffer]",CT="[object DataView]",kT="[object Float32Array]",OT="[object Float64Array]",DT="[object Int8Array]",NT="[object Int16Array]",VT="[object Int32Array]",LT="[object Uint8Array]",FT="[object Uint8ClampedArray]",jT="[object Uint16Array]",MT="[object Uint32Array]";function UT(r,e,t){var n=r.constructor;switch(e){case PT:return _n(r);case bT:case ET:return new n(+r);case CT:return gp(r,t);case kT:case OT:case DT:case NT:case VT:case LT:case FT:case jT:case MT:return bp(r,t);case TT:return new n;case IT:case xT:return new n(r);case ST:return yp(r);case AT:return new n;case RT:return wp(r)}}var Ep=UT;function BT(r){return typeof r.constructor=="function"&&!Gt(r)?rf(to(r)):{}}var Tp=BT;var $T="[object Map]";function qT(r){return Me(r)&&Ze(r)==$T}var Ip=qT;var Sp=Et&&Et.isMap,zT=Sp?un(Sp):Ip,Ap=zT;var KT="[object Set]";function GT(r){return Me(r)&&Ze(r)==KT}var xp=GT;var Rp=Et&&Et.isSet,WT=Rp?un(Rp):xp,Pp=WT;var HT=1,QT=2,JT=4,Cp="[object Arguments]",XT="[object Array]",YT="[object Boolean]",ZT="[object Date]",eI="[object Error]",kp="[object Function]",tI="[object GeneratorFunction]",rI="[object Map]",nI="[object Number]",Op="[object Object]",sI="[object RegExp]",iI="[object Set]",oI="[object String]",aI="[object Symbol]",uI="[object WeakMap]",cI="[object ArrayBuffer]",lI="[object DataView]",hI="[object Float32Array]",dI="[object Float64Array]",fI="[object Int8Array]",pI="[object Int16Array]",mI="[object Int32Array]",gI="[object Uint8Array]",yI="[object Uint8ClampedArray]",_I="[object Uint16Array]",vI="[object Uint32Array]",ne={};ne[Cp]=ne[XT]=ne[cI]=ne[lI]=ne[YT]=ne[ZT]=ne[hI]=ne[dI]=ne[fI]=ne[pI]=ne[mI]=ne[rI]=ne[nI]=ne[Op]=ne[sI]=ne[iI]=ne[oI]=ne[aI]=ne[gI]=ne[yI]=ne[_I]=ne[vI]=!0;ne[eI]=ne[kp]=ne[uI]=!1;function uo(r,e,t,n,s,i){var o,u=e&HT,c=e&QT,h=e&JT;if(t&&(o=s?t(r,n,s,i):t(r)),o!==void 0)return o;if(!ee(r))return r;var f=fe(r);if(f){if(o=mp(r),!u)return sf(r,o)}else{var p=Ze(r),m=p==kp||p==tI;if(bt(r))return sp(r,u);if(p==Op||p==Cp||m&&!s){if(o=c||m?{}:Tp(r),!u)return c?up(r,Zf(o,r)):ap(r,Yf(o,r))}else{if(!ne[p])return s?r:{};o=Ep(r,p,u)}}i||(i=new Yt);var y=i.get(r);if(y)return y;i.set(r,o),Pp(r)?r.forEach(function(I){o.add(uo(I,e,t,I,r,i))}):Ap(r)&&r.forEach(function(I,k){o.set(k,uo(I,e,t,k,r,i))});var T=h?c?cp:ks:c?Wt:De,R=f?void 0:T(r);return lf(R||r,function(I,k){R&&(k=I,I=r[k]),sn(o,k,uo(I,e,t,k,r,i))}),o}var Dp=uo;var wI=1,bI=4;function EI(r){return Dp(r,wI|bI)}var Zt=EI;var TI="__lodash_hash_undefined__";function II(r){return this.__data__.set(r,TI),this}var Np=II;function SI(r){return this.__data__.has(r)}var Vp=SI;function co(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new br;++e<t;)this.add(r[e])}co.prototype.add=co.prototype.push=Np;co.prototype.has=Vp;var Lp=co;function AI(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 Fp=AI;function xI(r,e){return r.has(e)}var jp=xI;var RI=1,PI=2;function CI(r,e,t,n,s,i){var o=t&RI,u=r.length,c=e.length;if(u!=c&&!(o&&c>u))return!1;var h=i.get(r),f=i.get(e);if(h&&f)return h==e&&f==r;var p=-1,m=!0,y=t&PI?new Lp:void 0;for(i.set(r,e),i.set(e,r);++p<u;){var T=r[p],R=e[p];if(n)var I=o?n(R,T,p,e,r,i):n(T,R,p,r,e,i);if(I!==void 0){if(I)continue;m=!1;break}if(y){if(!Fp(e,function(k,O){if(!jp(y,O)&&(T===k||s(T,k,t,n,i)))return y.push(O)})){m=!1;break}}else if(!(T===R||s(T,R,t,n,i))){m=!1;break}}return i.delete(r),i.delete(e),m}var lo=CI;function kI(r){var e=-1,t=Array(r.size);return r.forEach(function(n,s){t[++e]=[s,n]}),t}var Mp=kI;function OI(r){var e=-1,t=Array(r.size);return r.forEach(function(n){t[++e]=n}),t}var Up=OI;var DI=1,NI=2,VI="[object Boolean]",LI="[object Date]",FI="[object Error]",jI="[object Map]",MI="[object Number]",UI="[object RegExp]",BI="[object Set]",$I="[object String]",qI="[object Symbol]",zI="[object ArrayBuffer]",KI="[object DataView]",Bp=je?je.prototype:void 0,Su=Bp?Bp.valueOf:void 0;function GI(r,e,t,n,s,i,o){switch(t){case KI:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case zI:return!(r.byteLength!=e.byteLength||!i(new yn(r),new yn(e)));case VI:case LI:case MI:return st(+r,+e);case FI:return r.name==e.name&&r.message==e.message;case UI:case $I:return r==e+"";case jI:var u=Mp;case BI:var c=n&DI;if(u||(u=Up),r.size!=e.size&&!c)return!1;var h=o.get(r);if(h)return h==e;n|=NI,o.set(r,e);var f=lo(u(r),u(e),n,s,i,o);return o.delete(r),f;case qI:if(Su)return Su.call(r)==Su.call(e)}return!1}var $p=GI;var WI=1,HI=Object.prototype,QI=HI.hasOwnProperty;function JI(r,e,t,n,s,i){var o=t&WI,u=ks(r),c=u.length,h=ks(e),f=h.length;if(c!=f&&!o)return!1;for(var p=c;p--;){var m=u[p];if(!(o?m in e:QI.call(e,m)))return!1}var y=i.get(r),T=i.get(e);if(y&&T)return y==e&&T==r;var R=!0;i.set(r,e),i.set(e,r);for(var I=o;++p<c;){m=u[p];var k=r[m],O=e[m];if(n)var D=o?n(O,k,m,e,r,i):n(k,O,m,r,e,i);if(!(D===void 0?k===O||s(k,O,t,n,i):D)){R=!1;break}I||(I=m=="constructor")}if(R&&!I){var j=r.constructor,H=e.constructor;j!=H&&"constructor"in r&&"constructor"in e&&!(typeof j=="function"&&j instanceof j&&typeof H=="function"&&H instanceof H)&&(R=!1)}return i.delete(r),i.delete(e),R}var qp=JI;var XI=1,zp="[object Arguments]",Kp="[object Array]",ho="[object Object]",YI=Object.prototype,Gp=YI.hasOwnProperty;function ZI(r,e,t,n,s,i){var o=fe(r),u=fe(e),c=o?Kp:Ze(r),h=u?Kp:Ze(e);c=c==zp?ho:c,h=h==zp?ho:h;var f=c==ho,p=h==ho,m=c==h;if(m&&bt(r)){if(!bt(e))return!1;o=!0,f=!1}if(m&&!f)return i||(i=new Yt),o||cn(r)?lo(r,e,t,n,s,i):$p(r,e,c,t,n,s,i);if(!(t&XI)){var y=f&&Gp.call(r,"__wrapped__"),T=p&&Gp.call(e,"__wrapped__");if(y||T){var R=y?r.value():r,I=T?e.value():e;return i||(i=new Yt),s(R,I,t,n,i)}}return m?(i||(i=new Yt),qp(r,e,t,n,s,i)):!1}var Wp=ZI;function Hp(r,e,t,n,s){return r===e?!0:r==null||e==null||!Me(r)&&!Me(e)?r!==r&&e!==e:Wp(r,e,t,n,Hp,s)}var vn=Hp;var eS=1,tS=2;function rS(r,e,t,n){var s=t.length,i=s,o=!n;if(r==null)return!i;for(r=Object(r);s--;){var u=t[s];if(o&&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(o&&u[2]){if(h===void 0&&!(c in r))return!1}else{var p=new Yt;if(n)var m=n(h,f,c,r,e,p);if(!(m===void 0?vn(f,h,eS|tS,n,p):m))return!1}}return!0}var Qp=rS;function nS(r){return r===r&&!ee(r)}var fo=nS;function sS(r){for(var e=De(r),t=e.length;t--;){var n=e[t],s=r[n];e[t]=[n,s,fo(s)]}return e}var Jp=sS;function iS(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}var po=iS;function oS(r){var e=Jp(r);return e.length==1&&e[0][2]?po(e[0][0],e[0][1]):function(t){return t===r||Qp(t,r,e)}}var Xp=oS;function aS(r,e){return r!=null&&e in Object(r)}var Yp=aS;function uS(r,e,t){e=pn(e,r);for(var n=-1,s=e.length,i=!1;++n<s;){var o=it(e[n]);if(!(i=r!=null&&t(r,o)))break;r=r[o]}return i||++n!=s?i:(s=r==null?0:r.length,!!s&&on(s)&&qt(o,s)&&(fe(r)||an(r)))}var Zp=uS;function cS(r,e){return r!=null&&Zp(r,e,Yp)}var em=cS;var lS=1,hS=2;function dS(r,e){return ln(r)&&fo(e)?po(it(r),e):function(t){var n=Cs(t,r);return n===void 0&&n===e?em(t,r):vn(e,n,lS|hS)}}var tm=dS;function fS(r){return function(e){return e==null?void 0:e[r]}}var rm=fS;function pS(r){return function(e){return Zi(e,r)}}var nm=pS;function mS(r){return ln(r)?rm(it(r)):nm(r)}var sm=mS;function gS(r){return typeof r=="function"?r:r==null?tn:typeof r=="object"?fe(r)?tm(r[0],r[1]):Xp(r):sm(r)}var im=gS;function yS(r){return function(e,t,n){for(var s=-1,i=Object(e),o=n(e),u=o.length;u--;){var c=o[r?u:++s];if(t(i[c],c,i)===!1)break}return e}}var om=yS;var _S=om(),am=_S;function vS(r,e){return r&&am(r,e,De)}var um=vS;var wS=function(){return le.Date.now()},mo=wS;var bS="Expected a function",ES=Math.max,TS=Math.min;function IS(r,e,t){var n,s,i,o,u,c,h=0,f=!1,p=!1,m=!0;if(typeof r!="function")throw new TypeError(bS);e=wu(e)||0,ee(t)&&(f=!!t.leading,p="maxWait"in t,i=p?ES(wu(t.maxWait)||0,e):i,m="trailing"in t?!!t.trailing:m);function y(F){var E=n,_=s;return n=s=void 0,h=F,o=r.apply(_,E),o}function T(F){return h=F,u=setTimeout(k,e),f?y(F):o}function R(F){var E=F-c,_=F-h,w=e-E;return p?TS(w,i-_):w}function I(F){var E=F-c,_=F-h;return c===void 0||E>=e||E<0||p&&_>=i}function k(){var F=mo();if(I(F))return O(F);u=setTimeout(k,R(F))}function O(F){return u=void 0,m&&n?y(F):(n=s=void 0,o)}function D(){u!==void 0&&clearTimeout(u),h=0,n=c=s=u=void 0}function j(){return u===void 0?o:O(mo())}function H(){var F=mo(),E=I(F);if(n=arguments,s=this,c=F,E){if(u===void 0)return T(c);if(p)return clearTimeout(u),u=setTimeout(k,e),y(c)}return u===void 0&&(u=setTimeout(k,e)),o}return H.cancel=D,H.flush=j,H}var cm=IS;var lm=Object.prototype,SS=lm.hasOwnProperty,AS=ff(function(r,e){r=Object(r);var t=-1,n=e.length,s=n>2?e[2]:void 0;for(s&&pf(e[0],e[1],s)&&(n=1);++t<n;)for(var i=e[t],o=Wt(i),u=-1,c=o.length;++u<c;){var h=o[u],f=r[h];(f===void 0||st(f,lm[h])&&!SS.call(r,h))&&(r[h]=i[h])}return r}),go=AS;var xS="[object Map]",RS="[object Set]",PS=Object.prototype,CS=PS.hasOwnProperty;function kS(r){if(r==null)return!0;if(Kt(r)&&(fe(r)||typeof r=="string"||typeof r.splice=="function"||bt(r)||cn(r)||an(r)))return!r.length;var e=Ze(r);if(e==xS||e==RS)return!r.size;if(Gt(r))return!Yi(r).length;for(var t in r)if(CS.call(r,t))return!1;return!0}var yo=kS;function OS(r,e){return vn(r,e)}var Os=OS;function DS(r,e){var t={};return e=im(e,3),um(r,function(n,s,i){nn(t,e(n,s,i),n)}),t}var Au=DS;function NS(r,e,t,n){if(!ee(r))return r;e=pn(e,r);for(var s=-1,i=e.length,o=i-1,u=r;u!=null&&++s<i;){var c=it(e[s]),h=t;if(c==="__proto__"||c==="constructor"||c==="prototype")return r;if(s!=o){var f=u[c];h=n?n(f,c,u):void 0,h===void 0&&(h=ee(f)?f:qt(e[s+1])?[]:{})}sn(u,c,h),u=u[c]}return r}var hm=NS;function VS(r,e,t){return r==null?r:hm(r,e,t)}var er=VS;var LS="Expected a function";function FS(r,e,t){var n=!0,s=!0;if(typeof r!="function")throw new TypeError(LS);return ee(t)&&(n="leading"in t?!!t.leading:n,s="trailing"in t?!!t.trailing:s),cm(r,e,{leading:n,maxWait:e,trailing:s})}var xu=FS;var dm=()=>{};var mm=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},jS=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++],o=r[t++],u=r[t++],c=((s&7)<<18|(i&63)<<12|(o&63)<<6|u&63)-65536;e[n++]=String.fromCharCode(55296+(c>>10)),e[n++]=String.fromCharCode(56320+(c&1023))}else{let i=r[t++],o=r[t++];e[n++]=String.fromCharCode((s&15)<<12|(i&63)<<6|o&63)}}return e.join("")},gm={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],o=s+1<r.length,u=o?r[s+1]:0,c=s+2<r.length,h=c?r[s+2]:0,f=i>>2,p=(i&3)<<4|u>>4,m=(u&15)<<2|h>>6,y=h&63;c||(y=64,o||(m=64)),n.push(t[f],t[p],t[m],t[y])}return n.join("")},encodeString(r,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(r):this.encodeByteArray(mm(r),e)},decodeString(r,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(r):jS(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 p=s<r.length?t[r.charAt(s)]:64;if(++s,i==null||u==null||h==null||p==null)throw new Ru;let m=i<<2|u>>4;if(n.push(m),h!==64){let y=u<<4&240|h>>2;if(n.push(y),p!==64){let T=h<<6&192|p;n.push(T)}}}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)}}},Ru=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},MS=function(r){let e=mm(r);return gm.encodeByteArray(e,!0)},Ns=function(r){return MS(r).replace(/\./g,"")},ym=function(r){try{return gm.decodeString(r,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function _m(){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 US=()=>_m().__FIREBASE_DEFAULTS__,BS=()=>{if(typeof process=="undefined"||typeof process.env=="undefined")return;let r=process.env.__FIREBASE_DEFAULTS__;if(r)return JSON.parse(r)},$S=()=>{if(typeof document=="undefined")return;let r;try{r=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}let e=r&&ym(r[1]);return e&&JSON.parse(e)},Pu=()=>{try{return dm()||US()||BS()||$S()}catch(r){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${r}`);return}},qS=r=>{var e,t;return(t=(e=Pu())===null||e===void 0?void 0:e.emulatorHosts)===null||t===void 0?void 0:t[r]},vm=r=>{let e=qS(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]},Cu=()=>{var r;return(r=Pu())===null||r===void 0?void 0:r.config};var _o=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 vo(r){try{return(r.startsWith("http://")||r.startsWith("https://")?new URL(r).hostname:r).endsWith(".cloudworkstations.dev")}catch{return!1}}async function wm(r){return(await fetch(r,{credentials:"include"})).ok}function bm(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 o=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[Ns(JSON.stringify(t)),Ns(JSON.stringify(o)),""].join(".")}var Ds={};function zS(){let r={prod:[],emulator:[]};for(let e of Object.keys(Ds))Ds[e]?r.emulator.push(e):r.prod.push(e);return r}function KS(r){let e=document.getElementById(r),t=!1;return e||(e=document.createElement("div"),e.setAttribute("id",r),t=!0),{created:t,element:e}}var fm=!1;function Em(r,e){if(typeof window=="undefined"||typeof document=="undefined"||!vo(window.location.host)||Ds[r]===e||Ds[r]||fm)return;Ds[r]=e;function t(m){return`__firebase__banner__${m}`}let n="__firebase__banner",i=zS().prod.length>0;function o(){let m=document.getElementById(n);m&&m.remove()}function u(m){m.style.display="flex",m.style.background="#7faaf0",m.style.position="fixed",m.style.bottom="5px",m.style.left="5px",m.style.padding=".5em",m.style.borderRadius="5px",m.style.alignItems="center"}function c(m,y){m.setAttribute("width","24"),m.setAttribute("id",y),m.setAttribute("height","24"),m.setAttribute("viewBox","0 0 24 24"),m.setAttribute("fill","none"),m.style.marginLeft="-6px"}function h(){let m=document.createElement("span");return m.style.cursor="pointer",m.style.marginLeft="16px",m.style.fontSize="24px",m.innerHTML=" ×",m.onclick=()=>{fm=!0,o()},m}function f(m,y){m.setAttribute("id",y),m.innerText="Learn more",m.href="https://firebase.google.com/docs/studio/preview-apps#preview-backend",m.setAttribute("target","__blank"),m.style.paddingLeft="5px",m.style.textDecoration="underline"}function p(){let m=KS(n),y=t("text"),T=document.getElementById(y)||document.createElement("span"),R=t("learnmore"),I=document.getElementById(R)||document.createElement("a"),k=t("preprendIcon"),O=document.getElementById(k)||document.createElementNS("http://www.w3.org/2000/svg","svg");if(m.created){let D=m.element;u(D),f(I,R);let j=h();c(O,k),D.append(O,T,I,j),document.body.appendChild(D)}i?(T.innerText="Preview backend disconnected.",O.innerHTML=`<g clip-path="url(#clip0_6013_33858)">
|
|
2
|
-
<path d="M4.8 17.6L12 5.6L19.2 17.6H4.8ZM6.91667 16.4H17.0833L12 7.93333L6.91667 16.4ZM12 15.6C12.1667 15.6 12.3056 15.5444 12.4167 15.4333C12.5389 15.3111 12.6 15.1667 12.6 15C12.6 14.8333 12.5389 14.6944 12.4167 14.5833C12.3056 14.4611 12.1667 14.4 12 14.4C11.8333 14.4 11.6889 14.4611 11.5667 14.5833C11.4556 14.6944 11.4 14.8333 11.4 15C11.4 15.1667 11.4556 15.3111 11.5667 15.4333C11.6889 15.5444 11.8333 15.6 12 15.6ZM11.4 13.6H12.6V10.4H11.4V13.6Z" fill="#212121"/>
|
|
3
|
-
</g>
|
|
4
|
-
<defs>
|
|
5
|
-
<clipPath id="clip0_6013_33858">
|
|
6
|
-
<rect width="24" height="24" fill="white"/>
|
|
7
|
-
</clipPath>
|
|
8
|
-
</defs>`):(O.innerHTML=`<g clip-path="url(#clip0_6083_34804)">
|
|
9
|
-
<path d="M11.4 15.2H12.6V11.2H11.4V15.2ZM12 10C12.1667 10 12.3056 9.94444 12.4167 9.83333C12.5389 9.71111 12.6 9.56667 12.6 9.4C12.6 9.23333 12.5389 9.09444 12.4167 8.98333C12.3056 8.86111 12.1667 8.8 12 8.8C11.8333 8.8 11.6889 8.86111 11.5667 8.98333C11.4556 9.09444 11.4 9.23333 11.4 9.4C11.4 9.56667 11.4556 9.71111 11.5667 9.83333C11.6889 9.94444 11.8333 10 12 10ZM12 18.4C11.1222 18.4 10.2944 18.2333 9.51667 17.9C8.73889 17.5667 8.05556 17.1111 7.46667 16.5333C6.88889 15.9444 6.43333 15.2611 6.1 14.4833C5.76667 13.7056 5.6 12.8778 5.6 12C5.6 11.1111 5.76667 10.2833 6.1 9.51667C6.43333 8.73889 6.88889 8.06111 7.46667 7.48333C8.05556 6.89444 8.73889 6.43333 9.51667 6.1C10.2944 5.76667 11.1222 5.6 12 5.6C12.8889 5.6 13.7167 5.76667 14.4833 6.1C15.2611 6.43333 15.9389 6.89444 16.5167 7.48333C17.1056 8.06111 17.5667 8.73889 17.9 9.51667C18.2333 10.2833 18.4 11.1111 18.4 12C18.4 12.8778 18.2333 13.7056 17.9 14.4833C17.5667 15.2611 17.1056 15.9444 16.5167 16.5333C15.9389 17.1111 15.2611 17.5667 14.4833 17.9C13.7167 18.2333 12.8889 18.4 12 18.4ZM12 17.2C13.4444 17.2 14.6722 16.6944 15.6833 15.6833C16.6944 14.6722 17.2 13.4444 17.2 12C17.2 10.5556 16.6944 9.32778 15.6833 8.31667C14.6722 7.30555 13.4444 6.8 12 6.8C10.5556 6.8 9.32778 7.30555 8.31667 8.31667C7.30556 9.32778 6.8 10.5556 6.8 12C6.8 13.4444 7.30556 14.6722 8.31667 15.6833C9.32778 16.6944 10.5556 17.2 12 17.2Z" fill="#212121"/>
|
|
10
|
-
</g>
|
|
11
|
-
<defs>
|
|
12
|
-
<clipPath id="clip0_6083_34804">
|
|
13
|
-
<rect width="24" height="24" fill="white"/>
|
|
14
|
-
</clipPath>
|
|
15
|
-
</defs>`,T.innerText="Preview backend running in this workspace."),T.setAttribute("id",y)}document.readyState==="loading"?window.addEventListener("DOMContentLoaded",p):p()}function Tm(){return typeof navigator!="undefined"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function GS(){var r;let e=(r=Pu())===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 Im(){return!GS()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function ku(){try{return typeof indexedDB=="object"}catch{return!1}}function Sm(){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 WS="FirebaseError",et=class r extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name=WS,Object.setPrototypeOf(this,r.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Vs.prototype.create)}},Vs=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],o=i?HS(i,n):"Error",u=`${this.serviceName}: ${o} (${s}).`;return new et(s,u,n)}};function HS(r,e){return r.replace(QS,(t,n)=>{let s=e[n];return s!=null?String(s):`<${n}?>`})}var QS=/\{\$([^}]+)}/g;function wn(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],o=e[s];if(pm(i)&&pm(o)){if(!wn(i,o))return!1}else if(i!==o)return!1}for(let s of n)if(!t.includes(s))return!1;return!0}function pm(r){return r!==null&&typeof r=="object"}var WF=14400*1e3;function It(r){return r&&r._delegate?r._delegate:r}var St=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 Tr="[DEFAULT]";var Ou=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 _o;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(XS(e))try{this.getOrInitializeService({instanceIdentifier:Tr})}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=Tr){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=Tr){return this.instances.has(e)}getOptions(e=Tr){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,o]of this.instancesDeferred.entries()){let u=this.normalizeInstanceIdentifier(i);n===u&&o.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 o=this.instances.get(s);return o&&e(o,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:JS(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=Tr){return this.component?this.component.multipleInstances?e:Tr:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}};function JS(r){return r===Tr?void 0:r}function XS(r){return r.instantiationMode==="EAGER"}var wo=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 Ou(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}};var YS=[],X;(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"})(X||(X={}));var ZS={debug:X.DEBUG,verbose:X.VERBOSE,info:X.INFO,warn:X.WARN,error:X.ERROR,silent:X.SILENT},eA=X.INFO,tA={[X.DEBUG]:"log",[X.VERBOSE]:"log",[X.INFO]:"info",[X.WARN]:"warn",[X.ERROR]:"error"},rA=(r,e,...t)=>{if(e<r.logLevel)return;let n=new Date().toISOString(),s=tA[e];if(s)console[s](`[${n}] ${r.name}:`,...t);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},bn=class{constructor(e){this.name=e,this._logLevel=eA,this._logHandler=rA,this._userLogHandler=null,YS.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in X))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?ZS[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,X.DEBUG,...e),this._logHandler(this,X.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,X.VERBOSE,...e),this._logHandler(this,X.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,X.INFO,...e),this._logHandler(this,X.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,X.WARN,...e),this._logHandler(this,X.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,X.ERROR,...e),this._logHandler(this,X.ERROR,...e)}};var nA=(r,e)=>e.some(t=>r instanceof t),Am,xm;function sA(){return Am||(Am=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function iA(){return xm||(xm=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Rm=new WeakMap,Nu=new WeakMap,Pm=new WeakMap,Du=new WeakMap,Lu=new WeakMap;function oA(r){let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("success",i),r.removeEventListener("error",o)},i=()=>{t(ot(r.result)),s()},o=()=>{n(r.error),s()};r.addEventListener("success",i),r.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&Rm.set(t,r)}).catch(()=>{}),Lu.set(e,r),e}function aA(r){if(Nu.has(r))return;let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("complete",i),r.removeEventListener("error",o),r.removeEventListener("abort",o)},i=()=>{t(),s()},o=()=>{n(r.error||new DOMException("AbortError","AbortError")),s()};r.addEventListener("complete",i),r.addEventListener("error",o),r.addEventListener("abort",o)});Nu.set(r,e)}var Vu={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return Nu.get(r);if(e==="objectStoreNames")return r.objectStoreNames||Pm.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return ot(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 Cm(r){Vu=r(Vu)}function uA(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let n=r.call(bo(this),e,...t);return Pm.set(n,e.sort?e.sort():[e]),ot(n)}:iA().includes(r)?function(...e){return r.apply(bo(this),e),ot(Rm.get(this))}:function(...e){return ot(r.apply(bo(this),e))}}function cA(r){return typeof r=="function"?uA(r):(r instanceof IDBTransaction&&aA(r),nA(r,sA())?new Proxy(r,Vu):r)}function ot(r){if(r instanceof IDBRequest)return oA(r);if(Du.has(r))return Du.get(r);let e=cA(r);return e!==r&&(Du.set(r,e),Lu.set(e,r)),e}var bo=r=>Lu.get(r);function Om(r,e,{blocked:t,upgrade:n,blocking:s,terminated:i}={}){let o=indexedDB.open(r,e),u=ot(o);return n&&o.addEventListener("upgradeneeded",c=>{n(ot(o.result),c.oldVersion,c.newVersion,ot(o.transaction),c)}),t&&o.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 lA=["get","getKey","getAll","getAllKeys","count"],hA=["put","add","delete","clear"],Fu=new Map;function km(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(Fu.get(e))return Fu.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,s=hA.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(s||lA.includes(t)))return;let i=async function(o,...u){let c=this.transaction(o,s?"readwrite":"readonly"),h=c.store;return n&&(h=h.index(u.shift())),(await Promise.all([h[t](...u),s&&c.done]))[0]};return Fu.set(e,i),i}Cm(r=>({...r,get:(e,t,n)=>km(e,t)||r.get(e,t,n),has:(e,t)=>!!km(e,t)||r.has(e,t)}));var Mu=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(t=>{if(dA(t)){let n=t.getImmediate();return`${n.library}/${n.version}`}else return null}).filter(t=>t).join(" ")}};function dA(r){let e=r.getComponent();return(e==null?void 0:e.type)==="VERSION"}var Uu="@firebase/app",Dm="0.13.2";var At=new bn("@firebase/app"),fA="@firebase/app-compat",pA="@firebase/analytics-compat",mA="@firebase/analytics",gA="@firebase/app-check-compat",yA="@firebase/app-check",_A="@firebase/auth",vA="@firebase/auth-compat",wA="@firebase/database",bA="@firebase/data-connect",EA="@firebase/database-compat",TA="@firebase/functions",IA="@firebase/functions-compat",SA="@firebase/installations",AA="@firebase/installations-compat",xA="@firebase/messaging",RA="@firebase/messaging-compat",PA="@firebase/performance",CA="@firebase/performance-compat",kA="@firebase/remote-config",OA="@firebase/remote-config-compat",DA="@firebase/storage",NA="@firebase/storage-compat",VA="@firebase/firestore",LA="@firebase/ai",FA="@firebase/firestore-compat",jA="firebase",MA="11.10.0";var Bu="[DEFAULT]",UA={[Uu]:"fire-core",[fA]:"fire-core-compat",[mA]:"fire-analytics",[pA]:"fire-analytics-compat",[yA]:"fire-app-check",[gA]:"fire-app-check-compat",[_A]:"fire-auth",[vA]:"fire-auth-compat",[wA]:"fire-rtdb",[bA]:"fire-data-connect",[EA]:"fire-rtdb-compat",[TA]:"fire-fn",[IA]:"fire-fn-compat",[SA]:"fire-iid",[AA]:"fire-iid-compat",[xA]:"fire-fcm",[RA]:"fire-fcm-compat",[PA]:"fire-perf",[CA]:"fire-perf-compat",[kA]:"fire-rc",[OA]:"fire-rc-compat",[DA]:"fire-gcs",[NA]:"fire-gcs-compat",[VA]:"fire-fst",[FA]:"fire-fst-compat",[LA]:"fire-vertex","fire-js":"fire-js",[jA]:"fire-js-all"};var Eo=new Map,BA=new Map,$u=new Map;function Nm(r,e){try{r.container.addComponent(e)}catch(t){At.debug(`Component ${e.name} failed to register with FirebaseApp ${r.name}`,t)}}function Ls(r){let e=r.name;if($u.has(e))return At.debug(`There were multiple attempts to register component ${e}.`),!1;$u.set(e,r);for(let t of Eo.values())Nm(t,r);for(let t of BA.values())Nm(t,r);return!0}function jm(r,e){let t=r.container.getProvider("heartbeat").getImmediate({optional:!0});return t&&t.triggerHeartbeat(),r.container.getProvider(e)}function Mm(r){return r==null?!1:r.settings!==void 0}var $A={"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."},tr=new Vs("app","Firebase",$A);var qu=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 St("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 tr.create("app-deleted",{appName:this._name})}};var Um=MA;function Gu(r,e={}){let t=r;typeof e!="object"&&(e={name:e});let n=Object.assign({name:Bu,automaticDataCollectionEnabled:!0},e),s=n.name;if(typeof s!="string"||!s)throw tr.create("bad-app-name",{appName:String(s)});if(t||(t=Cu()),!t)throw tr.create("no-options");let i=Eo.get(s);if(i){if(wn(t,i.options)&&wn(n,i.config))return i;throw tr.create("duplicate-app",{appName:s})}let o=new wo(s);for(let c of $u.values())o.addComponent(c);let u=new qu(t,n,o);return Eo.set(s,u),u}function Bm(r=Bu){let e=Eo.get(r);if(!e&&r===Bu&&Cu())return Gu();if(!e)throw tr.create("no-app",{appName:r});return e}function rr(r,e,t){var n;let s=(n=UA[r])!==null&&n!==void 0?n:r;t&&(s+=`-${t}`);let i=s.match(/\s|\//),o=e.match(/\s|\//);if(i||o){let u=[`Unable to register library "${s}" with version "${e}":`];i&&u.push(`library name "${s}" contains illegal characters (whitespace or "/")`),i&&o&&u.push("and"),o&&u.push(`version name "${e}" contains illegal characters (whitespace or "/")`),At.warn(u.join(" "));return}Ls(new St(`${s}-version`,()=>({library:s,version:e}),"VERSION"))}var qA="firebase-heartbeat-database",zA=1,Fs="firebase-heartbeat-store",ju=null;function $m(){return ju||(ju=Om(qA,zA,{upgrade:(r,e)=>{switch(e){case 0:try{r.createObjectStore(Fs)}catch(t){console.warn(t)}}}}).catch(r=>{throw tr.create("idb-open",{originalErrorMessage:r.message})})),ju}async function KA(r){try{let t=(await $m()).transaction(Fs),n=await t.objectStore(Fs).get(qm(r));return await t.done,n}catch(e){if(e instanceof et)At.warn(e.message);else{let t=tr.create("idb-get",{originalErrorMessage:e==null?void 0:e.message});At.warn(t.message)}}}async function Vm(r,e){try{let n=(await $m()).transaction(Fs,"readwrite");await n.objectStore(Fs).put(e,qm(r)),await n.done}catch(t){if(t instanceof et)At.warn(t.message);else{let n=tr.create("idb-set",{originalErrorMessage:t==null?void 0:t.message});At.warn(n.message)}}}function qm(r){return`${r.name}!${r.options.appId}`}var GA=1024,WA=30,zu=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=Lm();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(o=>o.date===i))return;if(this._heartbeatsCache.heartbeats.push({date:i,agent:s}),this._heartbeatsCache.heartbeats.length>WA){let o=QA(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(o,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(n){At.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=Lm(),{heartbeatsToSend:n,unsentEntries:s}=HA(this._heartbeatsCache.heartbeats),i=Ns(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 At.warn(t),""}}};function Lm(){return new Date().toISOString().substring(0,10)}function HA(r,e=GA){let t=[],n=r.slice();for(let s of r){let i=t.find(o=>o.agent===s.agent);if(i){if(i.dates.push(s.date),Fm(t)>e){i.dates.pop();break}}else if(t.push({agent:s.agent,dates:[s.date]}),Fm(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 ku()?Sm().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let t=await KA(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 Vm(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 Vm(this.app,{lastSentHeartbeatDate:(t=e.lastSentHeartbeatDate)!==null&&t!==void 0?t:s.lastSentHeartbeatDate,heartbeats:[...s.heartbeats,...e.heartbeats]})}else return}};function Fm(r){return Ns(JSON.stringify({version:2,heartbeats:r})).length}function QA(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 JA(r){Ls(new St("platform-logger",e=>new Mu(e),"PRIVATE")),Ls(new St("heartbeat",e=>new zu(e),"PRIVATE")),rr(Uu,Dm,r),rr(Uu,Dm,"esm2017"),rr("fire-js","")}JA("");var XA="firebase",YA="11.10.0";rr(XA,YA,"app");var zm=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Km={};var xt,Wu;(function(){var r;function e(E,_){function w(){}w.prototype=_.prototype,E.D=_.prototype,E.prototype=new w,E.prototype.constructor=E,E.C=function(S,A,P){for(var b=Array(arguments.length-2),yt=2;yt<arguments.length;yt++)b[yt-2]=arguments[yt];return _.prototype[A].apply(S,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(E,_,w){w||(w=0);var S=Array(16);if(typeof _=="string")for(var A=0;16>A;++A)S[A]=_.charCodeAt(w++)|_.charCodeAt(w++)<<8|_.charCodeAt(w++)<<16|_.charCodeAt(w++)<<24;else for(A=0;16>A;++A)S[A]=_[w++]|_[w++]<<8|_[w++]<<16|_[w++]<<24;_=E.g[0],w=E.g[1],A=E.g[2];var P=E.g[3],b=_+(P^w&(A^P))+S[0]+3614090360&4294967295;_=w+(b<<7&4294967295|b>>>25),b=P+(A^_&(w^A))+S[1]+3905402710&4294967295,P=_+(b<<12&4294967295|b>>>20),b=A+(w^P&(_^w))+S[2]+606105819&4294967295,A=P+(b<<17&4294967295|b>>>15),b=w+(_^A&(P^_))+S[3]+3250441966&4294967295,w=A+(b<<22&4294967295|b>>>10),b=_+(P^w&(A^P))+S[4]+4118548399&4294967295,_=w+(b<<7&4294967295|b>>>25),b=P+(A^_&(w^A))+S[5]+1200080426&4294967295,P=_+(b<<12&4294967295|b>>>20),b=A+(w^P&(_^w))+S[6]+2821735955&4294967295,A=P+(b<<17&4294967295|b>>>15),b=w+(_^A&(P^_))+S[7]+4249261313&4294967295,w=A+(b<<22&4294967295|b>>>10),b=_+(P^w&(A^P))+S[8]+1770035416&4294967295,_=w+(b<<7&4294967295|b>>>25),b=P+(A^_&(w^A))+S[9]+2336552879&4294967295,P=_+(b<<12&4294967295|b>>>20),b=A+(w^P&(_^w))+S[10]+4294925233&4294967295,A=P+(b<<17&4294967295|b>>>15),b=w+(_^A&(P^_))+S[11]+2304563134&4294967295,w=A+(b<<22&4294967295|b>>>10),b=_+(P^w&(A^P))+S[12]+1804603682&4294967295,_=w+(b<<7&4294967295|b>>>25),b=P+(A^_&(w^A))+S[13]+4254626195&4294967295,P=_+(b<<12&4294967295|b>>>20),b=A+(w^P&(_^w))+S[14]+2792965006&4294967295,A=P+(b<<17&4294967295|b>>>15),b=w+(_^A&(P^_))+S[15]+1236535329&4294967295,w=A+(b<<22&4294967295|b>>>10),b=_+(A^P&(w^A))+S[1]+4129170786&4294967295,_=w+(b<<5&4294967295|b>>>27),b=P+(w^A&(_^w))+S[6]+3225465664&4294967295,P=_+(b<<9&4294967295|b>>>23),b=A+(_^w&(P^_))+S[11]+643717713&4294967295,A=P+(b<<14&4294967295|b>>>18),b=w+(P^_&(A^P))+S[0]+3921069994&4294967295,w=A+(b<<20&4294967295|b>>>12),b=_+(A^P&(w^A))+S[5]+3593408605&4294967295,_=w+(b<<5&4294967295|b>>>27),b=P+(w^A&(_^w))+S[10]+38016083&4294967295,P=_+(b<<9&4294967295|b>>>23),b=A+(_^w&(P^_))+S[15]+3634488961&4294967295,A=P+(b<<14&4294967295|b>>>18),b=w+(P^_&(A^P))+S[4]+3889429448&4294967295,w=A+(b<<20&4294967295|b>>>12),b=_+(A^P&(w^A))+S[9]+568446438&4294967295,_=w+(b<<5&4294967295|b>>>27),b=P+(w^A&(_^w))+S[14]+3275163606&4294967295,P=_+(b<<9&4294967295|b>>>23),b=A+(_^w&(P^_))+S[3]+4107603335&4294967295,A=P+(b<<14&4294967295|b>>>18),b=w+(P^_&(A^P))+S[8]+1163531501&4294967295,w=A+(b<<20&4294967295|b>>>12),b=_+(A^P&(w^A))+S[13]+2850285829&4294967295,_=w+(b<<5&4294967295|b>>>27),b=P+(w^A&(_^w))+S[2]+4243563512&4294967295,P=_+(b<<9&4294967295|b>>>23),b=A+(_^w&(P^_))+S[7]+1735328473&4294967295,A=P+(b<<14&4294967295|b>>>18),b=w+(P^_&(A^P))+S[12]+2368359562&4294967295,w=A+(b<<20&4294967295|b>>>12),b=_+(w^A^P)+S[5]+4294588738&4294967295,_=w+(b<<4&4294967295|b>>>28),b=P+(_^w^A)+S[8]+2272392833&4294967295,P=_+(b<<11&4294967295|b>>>21),b=A+(P^_^w)+S[11]+1839030562&4294967295,A=P+(b<<16&4294967295|b>>>16),b=w+(A^P^_)+S[14]+4259657740&4294967295,w=A+(b<<23&4294967295|b>>>9),b=_+(w^A^P)+S[1]+2763975236&4294967295,_=w+(b<<4&4294967295|b>>>28),b=P+(_^w^A)+S[4]+1272893353&4294967295,P=_+(b<<11&4294967295|b>>>21),b=A+(P^_^w)+S[7]+4139469664&4294967295,A=P+(b<<16&4294967295|b>>>16),b=w+(A^P^_)+S[10]+3200236656&4294967295,w=A+(b<<23&4294967295|b>>>9),b=_+(w^A^P)+S[13]+681279174&4294967295,_=w+(b<<4&4294967295|b>>>28),b=P+(_^w^A)+S[0]+3936430074&4294967295,P=_+(b<<11&4294967295|b>>>21),b=A+(P^_^w)+S[3]+3572445317&4294967295,A=P+(b<<16&4294967295|b>>>16),b=w+(A^P^_)+S[6]+76029189&4294967295,w=A+(b<<23&4294967295|b>>>9),b=_+(w^A^P)+S[9]+3654602809&4294967295,_=w+(b<<4&4294967295|b>>>28),b=P+(_^w^A)+S[12]+3873151461&4294967295,P=_+(b<<11&4294967295|b>>>21),b=A+(P^_^w)+S[15]+530742520&4294967295,A=P+(b<<16&4294967295|b>>>16),b=w+(A^P^_)+S[2]+3299628645&4294967295,w=A+(b<<23&4294967295|b>>>9),b=_+(A^(w|~P))+S[0]+4096336452&4294967295,_=w+(b<<6&4294967295|b>>>26),b=P+(w^(_|~A))+S[7]+1126891415&4294967295,P=_+(b<<10&4294967295|b>>>22),b=A+(_^(P|~w))+S[14]+2878612391&4294967295,A=P+(b<<15&4294967295|b>>>17),b=w+(P^(A|~_))+S[5]+4237533241&4294967295,w=A+(b<<21&4294967295|b>>>11),b=_+(A^(w|~P))+S[12]+1700485571&4294967295,_=w+(b<<6&4294967295|b>>>26),b=P+(w^(_|~A))+S[3]+2399980690&4294967295,P=_+(b<<10&4294967295|b>>>22),b=A+(_^(P|~w))+S[10]+4293915773&4294967295,A=P+(b<<15&4294967295|b>>>17),b=w+(P^(A|~_))+S[1]+2240044497&4294967295,w=A+(b<<21&4294967295|b>>>11),b=_+(A^(w|~P))+S[8]+1873313359&4294967295,_=w+(b<<6&4294967295|b>>>26),b=P+(w^(_|~A))+S[15]+4264355552&4294967295,P=_+(b<<10&4294967295|b>>>22),b=A+(_^(P|~w))+S[6]+2734768916&4294967295,A=P+(b<<15&4294967295|b>>>17),b=w+(P^(A|~_))+S[13]+1309151649&4294967295,w=A+(b<<21&4294967295|b>>>11),b=_+(A^(w|~P))+S[4]+4149444226&4294967295,_=w+(b<<6&4294967295|b>>>26),b=P+(w^(_|~A))+S[11]+3174756917&4294967295,P=_+(b<<10&4294967295|b>>>22),b=A+(_^(P|~w))+S[2]+718787259&4294967295,A=P+(b<<15&4294967295|b>>>17),b=w+(P^(A|~_))+S[9]+3951481745&4294967295,E.g[0]=E.g[0]+_&4294967295,E.g[1]=E.g[1]+(A+(b<<21&4294967295|b>>>11))&4294967295,E.g[2]=E.g[2]+A&4294967295,E.g[3]=E.g[3]+P&4294967295}n.prototype.u=function(E,_){_===void 0&&(_=E.length);for(var w=_-this.blockSize,S=this.B,A=this.h,P=0;P<_;){if(A==0)for(;P<=w;)s(this,E,P),P+=this.blockSize;if(typeof E=="string"){for(;P<_;)if(S[A++]=E.charCodeAt(P++),A==this.blockSize){s(this,S),A=0;break}}else for(;P<_;)if(S[A++]=E[P++],A==this.blockSize){s(this,S),A=0;break}}this.h=A,this.o+=_},n.prototype.v=function(){var E=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);E[0]=128;for(var _=1;_<E.length-8;++_)E[_]=0;var w=8*this.o;for(_=E.length-8;_<E.length;++_)E[_]=w&255,w/=256;for(this.u(E),E=Array(16),_=w=0;4>_;++_)for(var S=0;32>S;S+=8)E[w++]=this.g[_]>>>S&255;return E};function i(E,_){var w=u;return Object.prototype.hasOwnProperty.call(w,E)?w[E]:w[E]=_(E)}function o(E,_){this.h=_;for(var w=[],S=!0,A=E.length-1;0<=A;A--){var P=E[A]|0;S&&P==_||(w[A]=P,S=!1)}this.g=w}var u={};function c(E){return-128<=E&&128>E?i(E,function(_){return new o([_|0],0>_?-1:0)}):new o([E|0],0>E?-1:0)}function h(E){if(isNaN(E)||!isFinite(E))return p;if(0>E)return I(h(-E));for(var _=[],w=1,S=0;E>=w;S++)_[S]=E/w|0,w*=4294967296;return new o(_,0)}function f(E,_){if(E.length==0)throw Error("number format error: empty string");if(_=_||10,2>_||36<_)throw Error("radix out of range: "+_);if(E.charAt(0)=="-")return I(f(E.substring(1),_));if(0<=E.indexOf("-"))throw Error('number format error: interior "-" character');for(var w=h(Math.pow(_,8)),S=p,A=0;A<E.length;A+=8){var P=Math.min(8,E.length-A),b=parseInt(E.substring(A,A+P),_);8>P?(P=h(Math.pow(_,P)),S=S.j(P).add(h(b))):(S=S.j(w),S=S.add(h(b)))}return S}var p=c(0),m=c(1),y=c(16777216);r=o.prototype,r.m=function(){if(R(this))return-I(this).m();for(var E=0,_=1,w=0;w<this.g.length;w++){var S=this.i(w);E+=(0<=S?S:4294967296+S)*_,_*=4294967296}return E},r.toString=function(E){if(E=E||10,2>E||36<E)throw Error("radix out of range: "+E);if(T(this))return"0";if(R(this))return"-"+I(this).toString(E);for(var _=h(Math.pow(E,6)),w=this,S="";;){var A=j(w,_).g;w=k(w,A.j(_));var P=((0<w.g.length?w.g[0]:w.h)>>>0).toString(E);if(w=A,T(w))return P+S;for(;6>P.length;)P="0"+P;S=P+S}},r.i=function(E){return 0>E?0:E<this.g.length?this.g[E]:this.h};function T(E){if(E.h!=0)return!1;for(var _=0;_<E.g.length;_++)if(E.g[_]!=0)return!1;return!0}function R(E){return E.h==-1}r.l=function(E){return E=k(this,E),R(E)?-1:T(E)?0:1};function I(E){for(var _=E.g.length,w=[],S=0;S<_;S++)w[S]=~E.g[S];return new o(w,~E.h).add(m)}r.abs=function(){return R(this)?I(this):this},r.add=function(E){for(var _=Math.max(this.g.length,E.g.length),w=[],S=0,A=0;A<=_;A++){var P=S+(this.i(A)&65535)+(E.i(A)&65535),b=(P>>>16)+(this.i(A)>>>16)+(E.i(A)>>>16);S=b>>>16,P&=65535,b&=65535,w[A]=b<<16|P}return new o(w,w[w.length-1]&-2147483648?-1:0)};function k(E,_){return E.add(I(_))}r.j=function(E){if(T(this)||T(E))return p;if(R(this))return R(E)?I(this).j(I(E)):I(I(this).j(E));if(R(E))return I(this.j(I(E)));if(0>this.l(y)&&0>E.l(y))return h(this.m()*E.m());for(var _=this.g.length+E.g.length,w=[],S=0;S<2*_;S++)w[S]=0;for(S=0;S<this.g.length;S++)for(var A=0;A<E.g.length;A++){var P=this.i(S)>>>16,b=this.i(S)&65535,yt=E.i(A)>>>16,cs=E.i(A)&65535;w[2*S+2*A]+=b*cs,O(w,2*S+2*A),w[2*S+2*A+1]+=P*cs,O(w,2*S+2*A+1),w[2*S+2*A+1]+=b*yt,O(w,2*S+2*A+1),w[2*S+2*A+2]+=P*yt,O(w,2*S+2*A+2)}for(S=0;S<_;S++)w[S]=w[2*S+1]<<16|w[2*S];for(S=_;S<2*_;S++)w[S]=0;return new o(w,0)};function O(E,_){for(;(E[_]&65535)!=E[_];)E[_+1]+=E[_]>>>16,E[_]&=65535,_++}function D(E,_){this.g=E,this.h=_}function j(E,_){if(T(_))throw Error("division by zero");if(T(E))return new D(p,p);if(R(E))return _=j(I(E),_),new D(I(_.g),I(_.h));if(R(_))return _=j(E,I(_)),new D(I(_.g),_.h);if(30<E.g.length){if(R(E)||R(_))throw Error("slowDivide_ only works with positive integers.");for(var w=m,S=_;0>=S.l(E);)w=H(w),S=H(S);var A=F(w,1),P=F(S,1);for(S=F(S,2),w=F(w,2);!T(S);){var b=P.add(S);0>=b.l(E)&&(A=A.add(w),P=b),S=F(S,1),w=F(w,1)}return _=k(E,A.j(_)),new D(A,_)}for(A=p;0<=E.l(_);){for(w=Math.max(1,Math.floor(E.m()/_.m())),S=Math.ceil(Math.log(w)/Math.LN2),S=48>=S?1:Math.pow(2,S-48),P=h(w),b=P.j(_);R(b)||0<b.l(E);)w-=S,P=h(w),b=P.j(_);T(P)&&(P=m),A=A.add(P),E=k(E,b)}return new D(A,E)}r.A=function(E){return j(this,E).h},r.and=function(E){for(var _=Math.max(this.g.length,E.g.length),w=[],S=0;S<_;S++)w[S]=this.i(S)&E.i(S);return new o(w,this.h&E.h)},r.or=function(E){for(var _=Math.max(this.g.length,E.g.length),w=[],S=0;S<_;S++)w[S]=this.i(S)|E.i(S);return new o(w,this.h|E.h)},r.xor=function(E){for(var _=Math.max(this.g.length,E.g.length),w=[],S=0;S<_;S++)w[S]=this.i(S)^E.i(S);return new o(w,this.h^E.h)};function H(E){for(var _=E.g.length+1,w=[],S=0;S<_;S++)w[S]=E.i(S)<<1|E.i(S-1)>>>31;return new o(w,E.h)}function F(E,_){var w=_>>5;_%=32;for(var S=E.g.length-w,A=[],P=0;P<S;P++)A[P]=0<_?E.i(P+w)>>>_|E.i(P+w+1)<<32-_:E.i(P+w);return new o(A,E.h)}n.prototype.digest=n.prototype.v,n.prototype.reset=n.prototype.s,n.prototype.update=n.prototype.u,Wu=Km.Md5=n,o.prototype.add=o.prototype.add,o.prototype.multiply=o.prototype.j,o.prototype.modulo=o.prototype.A,o.prototype.compare=o.prototype.l,o.prototype.toNumber=o.prototype.m,o.prototype.toString=o.prototype.toString,o.prototype.getBits=o.prototype.i,o.fromNumber=h,o.fromString=f,xt=Km.Integer=o}).apply(typeof zm!="undefined"?zm:typeof self!="undefined"?self:typeof window!="undefined"?window:{});var To=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Rt={};var Hu,ZA,En,Qu,js,Io,Ju,Xu,Yu;(function(){var r,e=typeof Object.defineProperties=="function"?Object.defineProperty:function(a,l,d){return a==Array.prototype||a==Object.prototype||(a[l]=d.value),a};function t(a){a=[typeof globalThis=="object"&&globalThis,a,typeof window=="object"&&window,typeof self=="object"&&self,typeof To=="object"&&To];for(var l=0;l<a.length;++l){var d=a[l];if(d&&d.Math==Math)return d}throw Error("Cannot find global object")}var n=t(this);function s(a,l){if(l)e:{var d=n;a=a.split(".");for(var g=0;g<a.length-1;g++){var x=a[g];if(!(x in d))break e;d=d[x]}a=a[a.length-1],g=d[a],l=l(g),l!=g&&l!=null&&e(d,a,{configurable:!0,writable:!0,value:l})}}function i(a,l){a instanceof String&&(a+="");var d=0,g=!1,x={next:function(){if(!g&&d<a.length){var C=d++;return{value:l(C,a[C]),done:!1}}return g=!0,{done:!0,value:void 0}}};return x[Symbol.iterator]=function(){return x},x}s("Array.prototype.values",function(a){return a||function(){return i(this,function(l,d){return d})}});var o=o||{},u=this||self;function c(a){var l=typeof a;return l=l!="object"?l:a?Array.isArray(a)?"array":l:"null",l=="array"||l=="object"&&typeof a.length=="number"}function h(a){var l=typeof a;return l=="object"&&a!=null||l=="function"}function f(a,l,d){return a.call.apply(a.bind,arguments)}function p(a,l,d){if(!a)throw Error();if(2<arguments.length){var g=Array.prototype.slice.call(arguments,2);return function(){var x=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(x,g),a.apply(l,x)}}return function(){return a.apply(l,arguments)}}function m(a,l,d){return m=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!=-1?f:p,m.apply(null,arguments)}function y(a,l){var d=Array.prototype.slice.call(arguments,1);return function(){var g=d.slice();return g.push.apply(g,arguments),a.apply(this,g)}}function T(a,l){function d(){}d.prototype=l.prototype,a.aa=l.prototype,a.prototype=new d,a.prototype.constructor=a,a.Qb=function(g,x,C){for(var L=Array(arguments.length-2),re=2;re<arguments.length;re++)L[re-2]=arguments[re];return l.prototype[x].apply(g,L)}}function R(a){let l=a.length;if(0<l){let d=Array(l);for(let g=0;g<l;g++)d[g]=a[g];return d}return[]}function I(a,l){for(let d=1;d<arguments.length;d++){let g=arguments[d];if(c(g)){let x=a.length||0,C=g.length||0;a.length=x+C;for(let L=0;L<C;L++)a[x+L]=g[L]}else a.push(g)}}class k{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 O(a){return/^[\s\xa0]*$/.test(a)}function D(){var a=u.navigator;return a&&(a=a.userAgent)?a:""}function j(a){return j[" "](a),a}j[" "]=function(){};var H=D().indexOf("Gecko")!=-1&&!(D().toLowerCase().indexOf("webkit")!=-1&&D().indexOf("Edge")==-1)&&!(D().indexOf("Trident")!=-1||D().indexOf("MSIE")!=-1)&&D().indexOf("Edge")==-1;function F(a,l,d){for(let g in a)l.call(d,a[g],g,a)}function E(a,l){for(let d in a)l.call(void 0,a[d],d,a)}function _(a){let l={};for(let d in a)l[d]=a[d];return l}let w="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function S(a,l){let d,g;for(let x=1;x<arguments.length;x++){g=arguments[x];for(d in g)a[d]=g[d];for(let C=0;C<w.length;C++)d=w[C],Object.prototype.hasOwnProperty.call(g,d)&&(a[d]=g[d])}}function A(a){var l=1;a=a.split(":");let d=[];for(;0<l&&a.length;)d.push(a.shift()),l--;return a.length&&d.push(a.join(":")),d}function P(a){u.setTimeout(()=>{throw a},0)}function b(){var a=Ha;let l=null;return a.g&&(l=a.g,a.g=a.g.next,a.g||(a.h=null),l.next=null),l}class yt{constructor(){this.h=this.g=null}add(l,d){let g=cs.get();g.set(l,d),this.h?this.h.next=g:this.g=g,this.h=g}}var cs=new k(()=>new kv,a=>a.reset());class kv{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 ls,hs=!1,Ha=new yt,Fh=()=>{let a=u.Promise.resolve(void 0);ls=()=>{a.then(Ov)}};var Ov=()=>{for(var a;a=b();){try{a.h.call(a.g)}catch(d){P(d)}var l=cs;l.j(a),100>l.h&&(l.h++,a.next=l.g,l.g=a)}hs=!1};function jt(){this.s=this.s,this.C=this.C}jt.prototype.s=!1,jt.prototype.ma=function(){this.s||(this.s=!0,this.N())},jt.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function Pe(a,l){this.type=a,this.g=this.target=l,this.defaultPrevented=!1}Pe.prototype.h=function(){this.defaultPrevented=!0};var Dv=(function(){if(!u.addEventListener||!Object.defineProperty)return!1;var a=!1,l=Object.defineProperty({},"passive",{get:function(){a=!0}});try{let d=()=>{};u.addEventListener("test",d,l),u.removeEventListener("test",d,l)}catch{}return a})();function ds(a,l){if(Pe.call(this,a?a.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,a){var d=this.type=a.type,g=a.changedTouches&&a.changedTouches.length?a.changedTouches[0]:null;if(this.target=a.target||a.srcElement,this.g=l,l=a.relatedTarget){if(H){e:{try{j(l.nodeName);var x=!0;break e}catch{}x=!1}x||(l=null)}}else d=="mouseover"?l=a.fromElement:d=="mouseout"&&(l=a.toElement);this.relatedTarget=l,g?(this.clientX=g.clientX!==void 0?g.clientX:g.pageX,this.clientY=g.clientY!==void 0?g.clientY:g.pageY,this.screenX=g.screenX||0,this.screenY=g.screenY||0):(this.clientX=a.clientX!==void 0?a.clientX:a.pageX,this.clientY=a.clientY!==void 0?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0),this.button=a.button,this.key=a.key||"",this.ctrlKey=a.ctrlKey,this.altKey=a.altKey,this.shiftKey=a.shiftKey,this.metaKey=a.metaKey,this.pointerId=a.pointerId||0,this.pointerType=typeof a.pointerType=="string"?a.pointerType:Nv[a.pointerType]||"",this.state=a.state,this.i=a,a.defaultPrevented&&ds.aa.h.call(this)}}T(ds,Pe);var Nv={2:"touch",3:"pen",4:"mouse"};ds.prototype.h=function(){ds.aa.h.call(this);var a=this.i;a.preventDefault?a.preventDefault():a.returnValue=!1};var fs="closure_listenable_"+(1e6*Math.random()|0),Vv=0;function Lv(a,l,d,g,x){this.listener=a,this.proxy=null,this.src=l,this.type=d,this.capture=!!g,this.ha=x,this.key=++Vv,this.da=this.fa=!1}function Pi(a){a.da=!0,a.listener=null,a.proxy=null,a.src=null,a.ha=null}function Ci(a){this.src=a,this.g={},this.h=0}Ci.prototype.add=function(a,l,d,g,x){var C=a.toString();a=this.g[C],a||(a=this.g[C]=[],this.h++);var L=Ja(a,l,g,x);return-1<L?(l=a[L],d||(l.fa=!1)):(l=new Lv(l,this.src,C,!!g,x),l.fa=d,a.push(l)),l};function Qa(a,l){var d=l.type;if(d in a.g){var g=a.g[d],x=Array.prototype.indexOf.call(g,l,void 0),C;(C=0<=x)&&Array.prototype.splice.call(g,x,1),C&&(Pi(l),a.g[d].length==0&&(delete a.g[d],a.h--))}}function Ja(a,l,d,g){for(var x=0;x<a.length;++x){var C=a[x];if(!C.da&&C.listener==l&&C.capture==!!d&&C.ha==g)return x}return-1}var Xa="closure_lm_"+(1e6*Math.random()|0),Ya={};function jh(a,l,d,g,x){if(g&&g.once)return Uh(a,l,d,g,x);if(Array.isArray(l)){for(var C=0;C<l.length;C++)jh(a,l[C],d,g,x);return null}return d=ru(d),a&&a[fs]?a.K(l,d,h(g)?!!g.capture:!!g,x):Mh(a,l,d,!1,g,x)}function Mh(a,l,d,g,x,C){if(!l)throw Error("Invalid event type");var L=h(x)?!!x.capture:!!x,re=eu(a);if(re||(a[Xa]=re=new Ci(a)),d=re.add(l,d,g,L,C),d.proxy)return d;if(g=Fv(),d.proxy=g,g.src=a,g.listener=d,a.addEventListener)Dv||(x=L),x===void 0&&(x=!1),a.addEventListener(l.toString(),g,x);else if(a.attachEvent)a.attachEvent($h(l.toString()),g);else if(a.addListener&&a.removeListener)a.addListener(g);else throw Error("addEventListener and attachEvent are unavailable.");return d}function Fv(){function a(d){return l.call(a.src,a.listener,d)}let l=jv;return a}function Uh(a,l,d,g,x){if(Array.isArray(l)){for(var C=0;C<l.length;C++)Uh(a,l[C],d,g,x);return null}return d=ru(d),a&&a[fs]?a.L(l,d,h(g)?!!g.capture:!!g,x):Mh(a,l,d,!0,g,x)}function Bh(a,l,d,g,x){if(Array.isArray(l))for(var C=0;C<l.length;C++)Bh(a,l[C],d,g,x);else g=h(g)?!!g.capture:!!g,d=ru(d),a&&a[fs]?(a=a.i,l=String(l).toString(),l in a.g&&(C=a.g[l],d=Ja(C,d,g,x),-1<d&&(Pi(C[d]),Array.prototype.splice.call(C,d,1),C.length==0&&(delete a.g[l],a.h--)))):a&&(a=eu(a))&&(l=a.g[l.toString()],a=-1,l&&(a=Ja(l,d,g,x)),(d=-1<a?l[a]:null)&&Za(d))}function Za(a){if(typeof a!="number"&&a&&!a.da){var l=a.src;if(l&&l[fs])Qa(l.i,a);else{var d=a.type,g=a.proxy;l.removeEventListener?l.removeEventListener(d,g,a.capture):l.detachEvent?l.detachEvent($h(d),g):l.addListener&&l.removeListener&&l.removeListener(g),(d=eu(l))?(Qa(d,a),d.h==0&&(d.src=null,l[Xa]=null)):Pi(a)}}}function $h(a){return a in Ya?Ya[a]:Ya[a]="on"+a}function jv(a,l){if(a.da)a=!0;else{l=new ds(l,this);var d=a.listener,g=a.ha||a.src;a.fa&&Za(a),a=d.call(g,l)}return a}function eu(a){return a=a[Xa],a instanceof Ci?a:null}var tu="__closure_events_fn_"+(1e9*Math.random()>>>0);function ru(a){return typeof a=="function"?a:(a[tu]||(a[tu]=function(l){return a.handleEvent(l)}),a[tu])}function Ce(){jt.call(this),this.i=new Ci(this),this.M=this,this.F=null}T(Ce,jt),Ce.prototype[fs]=!0,Ce.prototype.removeEventListener=function(a,l,d,g){Bh(this,a,l,d,g)};function Le(a,l){var d,g=a.F;if(g)for(d=[];g;g=g.F)d.push(g);if(a=a.M,g=l.type||l,typeof l=="string")l=new Pe(l,a);else if(l instanceof Pe)l.target=l.target||a;else{var x=l;l=new Pe(g,a),S(l,x)}if(x=!0,d)for(var C=d.length-1;0<=C;C--){var L=l.g=d[C];x=ki(L,g,!0,l)&&x}if(L=l.g=a,x=ki(L,g,!0,l)&&x,x=ki(L,g,!1,l)&&x,d)for(C=0;C<d.length;C++)L=l.g=d[C],x=ki(L,g,!1,l)&&x}Ce.prototype.N=function(){if(Ce.aa.N.call(this),this.i){var a=this.i,l;for(l in a.g){for(var d=a.g[l],g=0;g<d.length;g++)Pi(d[g]);delete a.g[l],a.h--}}this.F=null},Ce.prototype.K=function(a,l,d,g){return this.i.add(String(a),l,!1,d,g)},Ce.prototype.L=function(a,l,d,g){return this.i.add(String(a),l,!0,d,g)};function ki(a,l,d,g){if(l=a.i.g[String(l)],!l)return!0;l=l.concat();for(var x=!0,C=0;C<l.length;++C){var L=l[C];if(L&&!L.da&&L.capture==d){var re=L.listener,Ae=L.ha||L.src;L.fa&&Qa(a.i,L),x=re.call(Ae,g)!==!1&&x}}return x&&!g.defaultPrevented}function qh(a,l,d){if(typeof a=="function")d&&(a=m(a,d));else if(a&&typeof a.handleEvent=="function")a=m(a.handleEvent,a);else throw Error("Invalid listener argument");return 2147483647<Number(l)?-1:u.setTimeout(a,l||0)}function zh(a){a.g=qh(()=>{a.g=null,a.i&&(a.i=!1,zh(a))},a.l);let l=a.h;a.h=null,a.m.apply(null,l)}class Mv extends jt{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:zh(this)}N(){super.N(),this.g&&(u.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function ps(a){jt.call(this),this.h=a,this.g={}}T(ps,jt);var Kh=[];function Gh(a){F(a.g,function(l,d){this.g.hasOwnProperty(d)&&Za(l)},a),a.g={}}ps.prototype.N=function(){ps.aa.N.call(this),Gh(this)},ps.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var nu=u.JSON.stringify,Uv=u.JSON.parse,Bv=class{stringify(a){return u.JSON.stringify(a,void 0)}parse(a){return u.JSON.parse(a,void 0)}};function su(){}su.prototype.h=null;function Wh(a){return a.h||(a.h=a.i())}function Hh(){}var ms={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function iu(){Pe.call(this,"d")}T(iu,Pe);function ou(){Pe.call(this,"c")}T(ou,Pe);var yr={},Qh=null;function Oi(){return Qh=Qh||new Ce}yr.La="serverreachability";function Jh(a){Pe.call(this,yr.La,a)}T(Jh,Pe);function gs(a){let l=Oi();Le(l,new Jh(l))}yr.STAT_EVENT="statevent";function Xh(a,l){Pe.call(this,yr.STAT_EVENT,a),this.stat=l}T(Xh,Pe);function Fe(a){let l=Oi();Le(l,new Xh(l,a))}yr.Ma="timingevent";function Yh(a,l){Pe.call(this,yr.Ma,a),this.size=l}T(Yh,Pe);function ys(a,l){if(typeof a!="function")throw Error("Fn must not be null and must be a function");return u.setTimeout(function(){a()},l)}function _s(){this.g=!0}_s.prototype.xa=function(){this.g=!1};function $v(a,l,d,g,x,C){a.info(function(){if(a.g)if(C)for(var L="",re=C.split("&"),Ae=0;Ae<re.length;Ae++){var Z=re[Ae].split("=");if(1<Z.length){var ke=Z[0];Z=Z[1];var Oe=ke.split("_");L=2<=Oe.length&&Oe[1]=="type"?L+(ke+"="+Z+"&"):L+(ke+"=redacted&")}}else L=null;else L=C;return"XMLHTTP REQ ("+g+") [attempt "+x+"]: "+l+`
|
|
1
|
+
var sv=typeof global=="object"&&global&&global.Object===Object&&global,Yi=sv;var iv=typeof self=="object"&&self&&self.Object===Object&&self,ov=Yi||iv||Function("return this")(),le=ov;var av=le.Symbol,Le=av;var Ld=Object.prototype,uv=Ld.hasOwnProperty,cv=Ld.toString,Os=Le?Le.toStringTag:void 0;function lv(r){var e=uv.call(r,Os),t=r[Os];try{r[Os]=void 0;var n=!0}catch{}var s=cv.call(r);return n&&(e?r[Os]=t:delete r[Os]),s}var Fd=lv;var hv=Object.prototype,dv=hv.toString;function fv(r){return dv.call(r)}var Md=fv;var pv="[object Null]",mv="[object Undefined]",jd=Le?Le.toStringTag:void 0;function gv(r){return r==null?r===void 0?mv:pv:jd&&jd in Object(r)?Fd(r):Md(r)}var Qe=gv;function yv(r){return r!=null&&typeof r=="object"}var Fe=yv;var _v="[object Symbol]";function wv(r){return typeof r=="symbol"||Fe(r)&&Qe(r)==_v}var Ht=wv;function vv(r,e){for(var t=-1,n=r==null?0:r.length,s=Array(n);++t<n;)s[t]=e(r[t],t,r);return s}var Ud=vv;var bv=Array.isArray,pe=bv;var Ev=1/0,Bd=Le?Le.prototype:void 0,$d=Bd?Bd.toString:void 0;function qd(r){if(typeof r=="string")return r;if(pe(r))return Ud(r,qd)+"";if(Ht(r))return $d?$d.call(r):"";var e=r+"";return e=="0"&&1/r==-Ev?"-0":e}var zd=qd;var Tv=/\s/;function Iv(r){for(var e=r.length;e--&&Tv.test(r.charAt(e)););return e}var Kd=Iv;var Av=/^\s+/;function Sv(r){return r&&r.slice(0,Kd(r)+1).replace(Av,"")}var Gd=Sv;function xv(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var ee=xv;var Wd=NaN,Rv=/^[-+]0x[0-9a-f]+$/i,Pv=/^0b[01]+$/i,Cv=/^0o[0-7]+$/i,kv=parseInt;function Ov(r){if(typeof r=="number")return r;if(Ht(r))return Wd;if(ee(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=ee(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=Gd(r);var t=Pv.test(r);return t||Cv.test(r)?kv(r.slice(2),t?2:8):Rv.test(r)?Wd:+r}var Iu=Ov;function Dv(r){return r}var an=Dv;var Nv="[object AsyncFunction]",Vv="[object Function]",Lv="[object GeneratorFunction]",Fv="[object Proxy]";function Mv(r){if(!ee(r))return!1;var e=Qe(r);return e==Vv||e==Lv||e==Nv||e==Fv}var Xi=Mv;var jv=le["__core-js_shared__"],Zi=jv;var Hd=(function(){var r=/[^.]+$/.exec(Zi&&Zi.keys&&Zi.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function Uv(r){return!!Hd&&Hd in r}var Jd=Uv;var Bv=Function.prototype,$v=Bv.toString;function qv(r){if(r!=null){try{return $v.call(r)}catch{}try{return r+""}catch{}}return""}var bt=qv;var zv=/[\\^$.*+?()[\]{}|]/g,Kv=/^\[object .+?Constructor\]$/,Gv=Function.prototype,Wv=Object.prototype,Hv=Gv.toString,Jv=Wv.hasOwnProperty,Qv=RegExp("^"+Hv.call(Jv).replace(zv,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Yv(r){if(!ee(r)||Jd(r))return!1;var e=Xi(r)?Qv:Kv;return e.test(bt(r))}var Qd=Yv;function Xv(r,e){return r==null?void 0:r[e]}var Yd=Xv;function Zv(r,e){var t=Yd(r,e);return Qd(t)?t:void 0}var je=Zv;var eb=je(le,"WeakMap"),eo=eb;var Xd=Object.create,tb=(function(){function r(){}return function(e){if(!ee(e))return{};if(Xd)return Xd(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})(),Zd=tb;function rb(r,e,t){switch(t.length){case 0:return r.call(e);case 1:return r.call(e,t[0]);case 2:return r.call(e,t[0],t[1]);case 3:return r.call(e,t[0],t[1],t[2])}return r.apply(e,t)}var ef=rb;function nb(r,e){var t=-1,n=r.length;for(e||(e=Array(n));++t<n;)e[t]=r[t];return e}var tf=nb;var sb=800,ib=16,ob=Date.now;function ab(r){var e=0,t=0;return function(){var n=ob(),s=ib-(n-t);if(t=n,s>0){if(++e>=sb)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}var rf=ab;function ub(r){return function(){return r}}var nf=ub;var cb=(function(){try{var r=je(Object,"defineProperty");return r({},"",{}),r}catch{}})(),un=cb;var lb=un?function(r,e){return un(r,"toString",{configurable:!0,enumerable:!1,value:nf(e),writable:!0})}:an,sf=lb;var hb=rf(sf),of=hb;function db(r,e){for(var t=-1,n=r==null?0:r.length;++t<n&&e(r[t],t,r)!==!1;);return r}var af=db;var fb=9007199254740991,pb=/^(?:0|[1-9]\d*)$/;function mb(r,e){var t=typeof r;return e=e==null?fb:e,!!e&&(t=="number"||t!="symbol"&&pb.test(r))&&r>-1&&r%1==0&&r<e}var Jt=mb;function gb(r,e,t){e=="__proto__"&&un?un(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}var cn=gb;function yb(r,e){return r===e||r!==r&&e!==e}var it=yb;var _b=Object.prototype,wb=_b.hasOwnProperty;function vb(r,e,t){var n=r[e];(!(wb.call(r,e)&&it(n,t))||t===void 0&&!(e in r))&&cn(r,e,t)}var ln=vb;function bb(r,e,t,n){var s=!t;t||(t={});for(var i=-1,o=e.length;++i<o;){var u=e[i],c=n?n(t[u],r[u],u,t,r):void 0;c===void 0&&(c=r[u]),s?cn(t,u,c):ln(t,u,c)}return t}var Qt=bb;var uf=Math.max;function Eb(r,e,t){return e=uf(e===void 0?r.length-1:e,0),function(){for(var n=arguments,s=-1,i=uf(n.length-e,0),o=Array(i);++s<i;)o[s]=n[e+s];s=-1;for(var u=Array(e+1);++s<e;)u[s]=n[s];return u[e]=t(o),ef(r,this,u)}}var cf=Eb;function Tb(r,e){return of(cf(r,e,an),r+"")}var lf=Tb;var Ib=9007199254740991;function Ab(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ib}var hn=Ab;function Sb(r){return r!=null&&hn(r.length)&&!Xi(r)}var Yt=Sb;function xb(r,e,t){if(!ee(t))return!1;var n=typeof e;return(n=="number"?Yt(t)&&Jt(e,t.length):n=="string"&&e in t)?it(t[e],r):!1}var hf=xb;var Rb=Object.prototype;function Pb(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Rb;return r===t}var Xt=Pb;function Cb(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}var df=Cb;var kb="[object Arguments]";function Ob(r){return Fe(r)&&Qe(r)==kb}var Au=Ob;var ff=Object.prototype,Db=ff.hasOwnProperty,Nb=ff.propertyIsEnumerable,Vb=Au((function(){return arguments})())?Au:function(r){return Fe(r)&&Db.call(r,"callee")&&!Nb.call(r,"callee")},dn=Vb;function Lb(){return!1}var pf=Lb;var yf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,mf=yf&&typeof module=="object"&&module&&!module.nodeType&&module,Fb=mf&&mf.exports===yf,gf=Fb?le.Buffer:void 0,Mb=gf?gf.isBuffer:void 0,jb=Mb||pf,Et=jb;var Ub="[object Arguments]",Bb="[object Array]",$b="[object Boolean]",qb="[object Date]",zb="[object Error]",Kb="[object Function]",Gb="[object Map]",Wb="[object Number]",Hb="[object Object]",Jb="[object RegExp]",Qb="[object Set]",Yb="[object String]",Xb="[object WeakMap]",Zb="[object ArrayBuffer]",eE="[object DataView]",tE="[object Float32Array]",rE="[object Float64Array]",nE="[object Int8Array]",sE="[object Int16Array]",iE="[object Int32Array]",oE="[object Uint8Array]",aE="[object Uint8ClampedArray]",uE="[object Uint16Array]",cE="[object Uint32Array]",oe={};oe[tE]=oe[rE]=oe[nE]=oe[sE]=oe[iE]=oe[oE]=oe[aE]=oe[uE]=oe[cE]=!0;oe[Ub]=oe[Bb]=oe[Zb]=oe[$b]=oe[eE]=oe[qb]=oe[zb]=oe[Kb]=oe[Gb]=oe[Wb]=oe[Hb]=oe[Jb]=oe[Qb]=oe[Yb]=oe[Xb]=!1;function lE(r){return Fe(r)&&hn(r.length)&&!!oe[Qe(r)]}var _f=lE;function hE(r){return function(e){return r(e)}}var fn=hE;var wf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ds=wf&&typeof module=="object"&&module&&!module.nodeType&&module,dE=Ds&&Ds.exports===wf,Su=dE&&Yi.process,fE=(function(){try{var r=Ds&&Ds.require&&Ds.require("util").types;return r||Su&&Su.binding&&Su.binding("util")}catch{}})(),Tt=fE;var vf=Tt&&Tt.isTypedArray,pE=vf?fn(vf):_f,pn=pE;var mE=Object.prototype,gE=mE.hasOwnProperty;function yE(r,e){var t=pe(r),n=!t&&dn(r),s=!t&&!n&&Et(r),i=!t&&!n&&!s&&pn(r),o=t||n||s||i,u=o?df(r.length,String):[],c=u.length;for(var l in r)(e||gE.call(r,l))&&!(o&&(l=="length"||s&&(l=="offset"||l=="parent")||i&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||Jt(l,c)))&&u.push(l);return u}var to=yE;function _E(r,e){return function(t){return r(e(t))}}var ro=_E;var wE=ro(Object.keys,Object),bf=wE;var vE=Object.prototype,bE=vE.hasOwnProperty;function EE(r){if(!Xt(r))return bf(r);var e=[];for(var t in Object(r))bE.call(r,t)&&t!="constructor"&&e.push(t);return e}var no=EE;function TE(r){return Yt(r)?to(r):no(r)}var Oe=TE;function IE(r){var e=[];if(r!=null)for(var t in Object(r))e.push(t);return e}var Ef=IE;var AE=Object.prototype,SE=AE.hasOwnProperty;function xE(r){if(!ee(r))return Ef(r);var e=Xt(r),t=[];for(var n in r)n=="constructor"&&(e||!SE.call(r,n))||t.push(n);return t}var Tf=xE;function RE(r){return Yt(r)?to(r,!0):Tf(r)}var Zt=RE;var PE=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,CE=/^\w*$/;function kE(r,e){if(pe(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Ht(r)?!0:CE.test(r)||!PE.test(r)||e!=null&&r in Object(e)}var mn=kE;var OE=je(Object,"create"),It=OE;function DE(){this.__data__=It?It(null):{},this.size=0}var If=DE;function NE(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Af=NE;var VE="__lodash_hash_undefined__",LE=Object.prototype,FE=LE.hasOwnProperty;function ME(r){var e=this.__data__;if(It){var t=e[r];return t===VE?void 0:t}return FE.call(e,r)?e[r]:void 0}var Sf=ME;var jE=Object.prototype,UE=jE.hasOwnProperty;function BE(r){var e=this.__data__;return It?e[r]!==void 0:UE.call(e,r)}var xf=BE;var $E="__lodash_hash_undefined__";function qE(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=It&&e===void 0?$E:e,this}var Rf=qE;function gn(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])}}gn.prototype.clear=If;gn.prototype.delete=Af;gn.prototype.get=Sf;gn.prototype.has=xf;gn.prototype.set=Rf;var xu=gn;function zE(){this.__data__=[],this.size=0}var Pf=zE;function KE(r,e){for(var t=r.length;t--;)if(it(r[t][0],e))return t;return-1}var er=KE;var GE=Array.prototype,WE=GE.splice;function HE(r){var e=this.__data__,t=er(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():WE.call(e,t,1),--this.size,!0}var Cf=HE;function JE(r){var e=this.__data__,t=er(e,r);return t<0?void 0:e[t][1]}var kf=JE;function QE(r){return er(this.__data__,r)>-1}var Of=QE;function YE(r,e){var t=this.__data__,n=er(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}var Df=YE;function yn(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])}}yn.prototype.clear=Pf;yn.prototype.delete=Cf;yn.prototype.get=kf;yn.prototype.has=Of;yn.prototype.set=Df;var tr=yn;var XE=je(le,"Map"),rr=XE;function ZE(){this.size=0,this.__data__={hash:new xu,map:new(rr||tr),string:new xu}}var Nf=ZE;function eT(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var Vf=eT;function tT(r,e){var t=r.__data__;return Vf(e)?t[typeof e=="string"?"string":"hash"]:t.map}var nr=tT;function rT(r){var e=nr(this,r).delete(r);return this.size-=e?1:0,e}var Lf=rT;function nT(r){return nr(this,r).get(r)}var Ff=nT;function sT(r){return nr(this,r).has(r)}var Mf=sT;function iT(r,e){var t=nr(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}var jf=iT;function _n(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])}}_n.prototype.clear=Nf;_n.prototype.delete=Lf;_n.prototype.get=Ff;_n.prototype.has=Mf;_n.prototype.set=jf;var Er=_n;var oT="Expected a function";function Ru(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(oT);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 o=r.apply(this,n);return t.cache=i.set(s,o)||i,o};return t.cache=new(Ru.Cache||Er),t}Ru.Cache=Er;var Uf=Ru;var aT=500;function uT(r){var e=Uf(r,function(n){return t.size===aT&&t.clear(),n}),t=e.cache;return e}var Bf=uT;var cT=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,lT=/\\(\\)?/g,hT=Bf(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(cT,function(t,n,s,i){e.push(s?i.replace(lT,"$1"):n||t)}),e}),$f=hT;function dT(r){return r==null?"":zd(r)}var qf=dT;function fT(r,e){return pe(r)?r:mn(r,e)?[r]:$f(qf(r))}var wn=fT;var pT=1/0;function mT(r){if(typeof r=="string"||Ht(r))return r;var e=r+"";return e=="0"&&1/r==-pT?"-0":e}var ot=mT;function gT(r,e){e=wn(e,r);for(var t=0,n=e.length;r!=null&&t<n;)r=r[ot(e[t++])];return t&&t==n?r:void 0}var so=gT;function yT(r,e,t){var n=r==null?void 0:so(r,e);return n===void 0?t:n}var Ns=yT;function _T(r,e){for(var t=-1,n=e.length,s=r.length;++t<n;)r[s+t]=e[t];return r}var io=_T;var wT=ro(Object.getPrototypeOf,Object),oo=wT;function vT(){this.__data__=new tr,this.size=0}var zf=vT;function bT(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}var Kf=bT;function ET(r){return this.__data__.get(r)}var Gf=ET;function TT(r){return this.__data__.has(r)}var Wf=TT;var IT=200;function AT(r,e){var t=this.__data__;if(t instanceof tr){var n=t.__data__;if(!rr||n.length<IT-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new Er(n)}return t.set(r,e),this.size=t.size,this}var Hf=AT;function vn(r){var e=this.__data__=new tr(r);this.size=e.size}vn.prototype.clear=zf;vn.prototype.delete=Kf;vn.prototype.get=Gf;vn.prototype.has=Wf;vn.prototype.set=Hf;var sr=vn;function ST(r,e){return r&&Qt(e,Oe(e),r)}var Jf=ST;function xT(r,e){return r&&Qt(e,Zt(e),r)}var Qf=xT;var ep=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Yf=ep&&typeof module=="object"&&module&&!module.nodeType&&module,RT=Yf&&Yf.exports===ep,Xf=RT?le.Buffer:void 0,Zf=Xf?Xf.allocUnsafe:void 0;function PT(r,e){if(e)return r.slice();var t=r.length,n=Zf?Zf(t):new r.constructor(t);return r.copy(n),n}var tp=PT;function CT(r,e){for(var t=-1,n=r==null?0:r.length,s=0,i=[];++t<n;){var o=r[t];e(o,t,r)&&(i[s++]=o)}return i}var rp=CT;function kT(){return[]}var ao=kT;var OT=Object.prototype,DT=OT.propertyIsEnumerable,np=Object.getOwnPropertySymbols,NT=np?function(r){return r==null?[]:(r=Object(r),rp(np(r),function(e){return DT.call(r,e)}))}:ao,bn=NT;function VT(r,e){return Qt(r,bn(r),e)}var sp=VT;var LT=Object.getOwnPropertySymbols,FT=LT?function(r){for(var e=[];r;)io(e,bn(r)),r=oo(r);return e}:ao,uo=FT;function MT(r,e){return Qt(r,uo(r),e)}var ip=MT;function jT(r,e,t){var n=e(r);return pe(r)?n:io(n,t(r))}var co=jT;function UT(r){return co(r,Oe,bn)}var Vs=UT;function BT(r){return co(r,Zt,uo)}var op=BT;var $T=je(le,"DataView"),lo=$T;var qT=je(le,"Promise"),ho=qT;var zT=je(le,"Set"),fo=zT;var ap="[object Map]",KT="[object Object]",up="[object Promise]",cp="[object Set]",lp="[object WeakMap]",hp="[object DataView]",GT=bt(lo),WT=bt(rr),HT=bt(ho),JT=bt(fo),QT=bt(eo),Tr=Qe;(lo&&Tr(new lo(new ArrayBuffer(1)))!=hp||rr&&Tr(new rr)!=ap||ho&&Tr(ho.resolve())!=up||fo&&Tr(new fo)!=cp||eo&&Tr(new eo)!=lp)&&(Tr=function(r){var e=Qe(r),t=e==KT?r.constructor:void 0,n=t?bt(t):"";if(n)switch(n){case GT:return hp;case WT:return ap;case HT:return up;case JT:return cp;case QT:return lp}return e});var Ye=Tr;var YT=Object.prototype,XT=YT.hasOwnProperty;function ZT(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&XT.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var dp=ZT;var e0=le.Uint8Array,En=e0;function t0(r){var e=new r.constructor(r.byteLength);return new En(e).set(new En(r)),e}var Tn=t0;function r0(r,e){var t=e?Tn(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.byteLength)}var fp=r0;var n0=/\w*$/;function s0(r){var e=new r.constructor(r.source,n0.exec(r));return e.lastIndex=r.lastIndex,e}var pp=s0;var mp=Le?Le.prototype:void 0,gp=mp?mp.valueOf:void 0;function i0(r){return gp?Object(gp.call(r)):{}}var yp=i0;function o0(r,e){var t=e?Tn(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.length)}var _p=o0;var a0="[object Boolean]",u0="[object Date]",c0="[object Map]",l0="[object Number]",h0="[object RegExp]",d0="[object Set]",f0="[object String]",p0="[object Symbol]",m0="[object ArrayBuffer]",g0="[object DataView]",y0="[object Float32Array]",_0="[object Float64Array]",w0="[object Int8Array]",v0="[object Int16Array]",b0="[object Int32Array]",E0="[object Uint8Array]",T0="[object Uint8ClampedArray]",I0="[object Uint16Array]",A0="[object Uint32Array]";function S0(r,e,t){var n=r.constructor;switch(e){case m0:return Tn(r);case a0:case u0:return new n(+r);case g0:return fp(r,t);case y0:case _0:case w0:case v0:case b0:case E0:case T0:case I0:case A0:return _p(r,t);case c0:return new n;case l0:case f0:return new n(r);case h0:return pp(r);case d0:return new n;case p0:return yp(r)}}var wp=S0;function x0(r){return typeof r.constructor=="function"&&!Xt(r)?Zd(oo(r)):{}}var vp=x0;var R0="[object Map]";function P0(r){return Fe(r)&&Ye(r)==R0}var bp=P0;var Ep=Tt&&Tt.isMap,C0=Ep?fn(Ep):bp,Tp=C0;var k0="[object Set]";function O0(r){return Fe(r)&&Ye(r)==k0}var Ip=O0;var Ap=Tt&&Tt.isSet,D0=Ap?fn(Ap):Ip,Sp=D0;var N0=1,V0=2,L0=4,xp="[object Arguments]",F0="[object Array]",M0="[object Boolean]",j0="[object Date]",U0="[object Error]",Rp="[object Function]",B0="[object GeneratorFunction]",$0="[object Map]",q0="[object Number]",Pp="[object Object]",z0="[object RegExp]",K0="[object Set]",G0="[object String]",W0="[object Symbol]",H0="[object WeakMap]",J0="[object ArrayBuffer]",Q0="[object DataView]",Y0="[object Float32Array]",X0="[object Float64Array]",Z0="[object Int8Array]",eI="[object Int16Array]",tI="[object Int32Array]",rI="[object Uint8Array]",nI="[object Uint8ClampedArray]",sI="[object Uint16Array]",iI="[object Uint32Array]",ne={};ne[xp]=ne[F0]=ne[J0]=ne[Q0]=ne[M0]=ne[j0]=ne[Y0]=ne[X0]=ne[Z0]=ne[eI]=ne[tI]=ne[$0]=ne[q0]=ne[Pp]=ne[z0]=ne[K0]=ne[G0]=ne[W0]=ne[rI]=ne[nI]=ne[sI]=ne[iI]=!0;ne[U0]=ne[Rp]=ne[H0]=!1;function po(r,e,t,n,s,i){var o,u=e&N0,c=e&V0,l=e&L0;if(t&&(o=s?t(r,n,s,i):t(r)),o!==void 0)return o;if(!ee(r))return r;var f=pe(r);if(f){if(o=dp(r),!u)return tf(r,o)}else{var p=Ye(r),g=p==Rp||p==B0;if(Et(r))return tp(r,u);if(p==Pp||p==xp||g&&!s){if(o=c||g?{}:vp(r),!u)return c?ip(r,Qf(o,r)):sp(r,Jf(o,r))}else{if(!ne[p])return s?r:{};o=wp(r,p,u)}}i||(i=new sr);var y=i.get(r);if(y)return y;i.set(r,o),Sp(r)?r.forEach(function(A){o.add(po(A,e,t,A,r,i))}):Tp(r)&&r.forEach(function(A,k){o.set(k,po(A,e,t,k,r,i))});var I=l?c?op:Vs:c?Zt:Oe,R=f?void 0:I(r);return af(R||r,function(A,k){R&&(k=A,A=r[k]),ln(o,k,po(A,e,t,k,r,i))}),o}var Cp=po;var oI=1,aI=4;function uI(r){return Cp(r,oI|aI)}var ir=uI;var cI="__lodash_hash_undefined__";function lI(r){return this.__data__.set(r,cI),this}var kp=lI;function hI(r){return this.__data__.has(r)}var Op=hI;function mo(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new Er;++e<t;)this.add(r[e])}mo.prototype.add=mo.prototype.push=kp;mo.prototype.has=Op;var Dp=mo;function dI(r,e){for(var t=-1,n=r==null?0:r.length;++t<n;)if(e(r[t],t,r))return!0;return!1}var Np=dI;function fI(r,e){return r.has(e)}var Vp=fI;var pI=1,mI=2;function gI(r,e,t,n,s,i){var o=t&pI,u=r.length,c=e.length;if(u!=c&&!(o&&c>u))return!1;var l=i.get(r),f=i.get(e);if(l&&f)return l==e&&f==r;var p=-1,g=!0,y=t&mI?new Dp:void 0;for(i.set(r,e),i.set(e,r);++p<u;){var I=r[p],R=e[p];if(n)var A=o?n(R,I,p,e,r,i):n(I,R,p,r,e,i);if(A!==void 0){if(A)continue;g=!1;break}if(y){if(!Np(e,function(k,D){if(!Vp(y,D)&&(I===k||s(I,k,t,n,i)))return y.push(D)})){g=!1;break}}else if(!(I===R||s(I,R,t,n,i))){g=!1;break}}return i.delete(r),i.delete(e),g}var go=gI;function yI(r){var e=-1,t=Array(r.size);return r.forEach(function(n,s){t[++e]=[s,n]}),t}var Lp=yI;function _I(r){var e=-1,t=Array(r.size);return r.forEach(function(n){t[++e]=n}),t}var Fp=_I;var wI=1,vI=2,bI="[object Boolean]",EI="[object Date]",TI="[object Error]",II="[object Map]",AI="[object Number]",SI="[object RegExp]",xI="[object Set]",RI="[object String]",PI="[object Symbol]",CI="[object ArrayBuffer]",kI="[object DataView]",Mp=Le?Le.prototype:void 0,Pu=Mp?Mp.valueOf:void 0;function OI(r,e,t,n,s,i,o){switch(t){case kI:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case CI:return!(r.byteLength!=e.byteLength||!i(new En(r),new En(e)));case bI:case EI:case AI:return it(+r,+e);case TI:return r.name==e.name&&r.message==e.message;case SI:case RI:return r==e+"";case II:var u=Lp;case xI:var c=n&wI;if(u||(u=Fp),r.size!=e.size&&!c)return!1;var l=o.get(r);if(l)return l==e;n|=vI,o.set(r,e);var f=go(u(r),u(e),n,s,i,o);return o.delete(r),f;case PI:if(Pu)return Pu.call(r)==Pu.call(e)}return!1}var jp=OI;var DI=1,NI=Object.prototype,VI=NI.hasOwnProperty;function LI(r,e,t,n,s,i){var o=t&DI,u=Vs(r),c=u.length,l=Vs(e),f=l.length;if(c!=f&&!o)return!1;for(var p=c;p--;){var g=u[p];if(!(o?g in e:VI.call(e,g)))return!1}var y=i.get(r),I=i.get(e);if(y&&I)return y==e&&I==r;var R=!0;i.set(r,e),i.set(e,r);for(var A=o;++p<c;){g=u[p];var k=r[g],D=e[g];if(n)var N=o?n(D,k,g,e,r,i):n(k,D,g,r,e,i);if(!(N===void 0?k===D||s(k,D,t,n,i):N)){R=!1;break}A||(A=g=="constructor")}if(R&&!A){var U=r.constructor,z=e.constructor;U!=z&&"constructor"in r&&"constructor"in e&&!(typeof U=="function"&&U instanceof U&&typeof z=="function"&&z instanceof z)&&(R=!1)}return i.delete(r),i.delete(e),R}var Up=LI;var FI=1,Bp="[object Arguments]",$p="[object Array]",yo="[object Object]",MI=Object.prototype,qp=MI.hasOwnProperty;function jI(r,e,t,n,s,i){var o=pe(r),u=pe(e),c=o?$p:Ye(r),l=u?$p:Ye(e);c=c==Bp?yo:c,l=l==Bp?yo:l;var f=c==yo,p=l==yo,g=c==l;if(g&&Et(r)){if(!Et(e))return!1;o=!0,f=!1}if(g&&!f)return i||(i=new sr),o||pn(r)?go(r,e,t,n,s,i):jp(r,e,c,t,n,s,i);if(!(t&FI)){var y=f&&qp.call(r,"__wrapped__"),I=p&&qp.call(e,"__wrapped__");if(y||I){var R=y?r.value():r,A=I?e.value():e;return i||(i=new sr),s(R,A,t,n,i)}}return g?(i||(i=new sr),Up(r,e,t,n,s,i)):!1}var zp=jI;function Kp(r,e,t,n,s){return r===e?!0:r==null||e==null||!Fe(r)&&!Fe(e)?r!==r&&e!==e:zp(r,e,t,n,Kp,s)}var In=Kp;var UI=1,BI=2;function $I(r,e,t,n){var s=t.length,i=s,o=!n;if(r==null)return!i;for(r=Object(r);s--;){var u=t[s];if(o&&u[2]?u[1]!==r[u[0]]:!(u[0]in r))return!1}for(;++s<i;){u=t[s];var c=u[0],l=r[c],f=u[1];if(o&&u[2]){if(l===void 0&&!(c in r))return!1}else{var p=new sr;if(n)var g=n(l,f,c,r,e,p);if(!(g===void 0?In(f,l,UI|BI,n,p):g))return!1}}return!0}var Gp=$I;function qI(r){return r===r&&!ee(r)}var _o=qI;function zI(r){for(var e=Oe(r),t=e.length;t--;){var n=e[t],s=r[n];e[t]=[n,s,_o(s)]}return e}var Wp=zI;function KI(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}var wo=KI;function GI(r){var e=Wp(r);return e.length==1&&e[0][2]?wo(e[0][0],e[0][1]):function(t){return t===r||Gp(t,r,e)}}var Hp=GI;function WI(r,e){return r!=null&&e in Object(r)}var Jp=WI;function HI(r,e,t){e=wn(e,r);for(var n=-1,s=e.length,i=!1;++n<s;){var o=ot(e[n]);if(!(i=r!=null&&t(r,o)))break;r=r[o]}return i||++n!=s?i:(s=r==null?0:r.length,!!s&&hn(s)&&Jt(o,s)&&(pe(r)||dn(r)))}var Qp=HI;function JI(r,e){return r!=null&&Qp(r,e,Jp)}var Yp=JI;var QI=1,YI=2;function XI(r,e){return mn(r)&&_o(e)?wo(ot(r),e):function(t){var n=Ns(t,r);return n===void 0&&n===e?Yp(t,r):In(e,n,QI|YI)}}var Xp=XI;function ZI(r){return function(e){return e==null?void 0:e[r]}}var Zp=ZI;function eA(r){return function(e){return so(e,r)}}var em=eA;function tA(r){return mn(r)?Zp(ot(r)):em(r)}var tm=tA;function rA(r){return typeof r=="function"?r:r==null?an:typeof r=="object"?pe(r)?Xp(r[0],r[1]):Hp(r):tm(r)}var rm=rA;function nA(r){return function(e,t,n){for(var s=-1,i=Object(e),o=n(e),u=o.length;u--;){var c=o[r?u:++s];if(t(i[c],c,i)===!1)break}return e}}var nm=nA;var sA=nm(),sm=sA;function iA(r,e){return r&&sm(r,e,Oe)}var im=iA;var oA=function(){return le.Date.now()},vo=oA;var aA="Expected a function",uA=Math.max,cA=Math.min;function lA(r,e,t){var n,s,i,o,u,c,l=0,f=!1,p=!1,g=!0;if(typeof r!="function")throw new TypeError(aA);e=Iu(e)||0,ee(t)&&(f=!!t.leading,p="maxWait"in t,i=p?uA(Iu(t.maxWait)||0,e):i,g="trailing"in t?!!t.trailing:g);function y(F){var E=n,_=s;return n=s=void 0,l=F,o=r.apply(_,E),o}function I(F){return l=F,u=setTimeout(k,e),f?y(F):o}function R(F){var E=F-c,_=F-l,w=e-E;return p?cA(w,i-_):w}function A(F){var E=F-c,_=F-l;return c===void 0||E>=e||E<0||p&&_>=i}function k(){var F=vo();if(A(F))return D(F);u=setTimeout(k,R(F))}function D(F){return u=void 0,g&&n?y(F):(n=s=void 0,o)}function N(){u!==void 0&&clearTimeout(u),l=0,n=c=s=u=void 0}function U(){return u===void 0?o:D(vo())}function z(){var F=vo(),E=A(F);if(n=arguments,s=this,c=F,E){if(u===void 0)return I(c);if(p)return clearTimeout(u),u=setTimeout(k,e),y(c)}return u===void 0&&(u=setTimeout(k,e)),o}return z.cancel=N,z.flush=U,z}var om=lA;var am=Object.prototype,hA=am.hasOwnProperty,dA=lf(function(r,e){r=Object(r);var t=-1,n=e.length,s=n>2?e[2]:void 0;for(s&&hf(e[0],e[1],s)&&(n=1);++t<n;)for(var i=e[t],o=Zt(i),u=-1,c=o.length;++u<c;){var l=o[u],f=r[l];(f===void 0||it(f,am[l])&&!hA.call(r,l))&&(r[l]=i[l])}return r}),bo=dA;var fA="[object Map]",pA="[object Set]",mA=Object.prototype,gA=mA.hasOwnProperty;function yA(r){if(r==null)return!0;if(Yt(r)&&(pe(r)||typeof r=="string"||typeof r.splice=="function"||Et(r)||pn(r)||dn(r)))return!r.length;var e=Ye(r);if(e==fA||e==pA)return!r.size;if(Xt(r))return!no(r).length;for(var t in r)if(gA.call(r,t))return!1;return!0}var Eo=yA;function _A(r,e){return In(r,e)}var Ls=_A;function wA(r,e){var t={};return e=rm(e,3),im(r,function(n,s,i){cn(t,e(n,s,i),n)}),t}var Cu=wA;function vA(r,e,t,n){if(!ee(r))return r;e=wn(e,r);for(var s=-1,i=e.length,o=i-1,u=r;u!=null&&++s<i;){var c=ot(e[s]),l=t;if(c==="__proto__"||c==="constructor"||c==="prototype")return r;if(s!=o){var f=u[c];l=n?n(f,c,u):void 0,l===void 0&&(l=ee(f)?f:Jt(e[s+1])?[]:{})}ln(u,c,l),u=u[c]}return r}var um=vA;function bA(r,e,t){return r==null?r:um(r,e,t)}var or=bA;var EA="Expected a function";function TA(r,e,t){var n=!0,s=!0;if(typeof r!="function")throw new TypeError(EA);return ee(t)&&(n="leading"in t?!!t.leading:n,s="trailing"in t?!!t.trailing:s),om(r,e,{leading:n,maxWait:e,trailing:s})}var ku=TA;var cm=()=>{};var hm=function(r){let e=[],t=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(s=65536+((s&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128)}return e},IA=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++],o=r[t++],u=r[t++],c=((s&7)<<18|(i&63)<<12|(o&63)<<6|u&63)-65536;e[n++]=String.fromCharCode(55296+(c>>10)),e[n++]=String.fromCharCode(56320+(c&1023))}else{let i=r[t++],o=r[t++];e[n++]=String.fromCharCode((s&15)<<12|(i&63)<<6|o&63)}}return e.join("")},dm={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:typeof atob=="function",encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();let t=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let s=0;s<r.length;s+=3){let i=r[s],o=s+1<r.length,u=o?r[s+1]:0,c=s+2<r.length,l=c?r[s+2]:0,f=i>>2,p=(i&3)<<4|u>>4,g=(u&15)<<2|l>>6,y=l&63;c||(y=64,o||(g=64)),n.push(t[f],t[p],t[g],t[y])}return n.join("")},encodeString(r,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(r):this.encodeByteArray(hm(r),e)},decodeString(r,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(r):IA(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 l=s<r.length?t[r.charAt(s)]:64;++s;let p=s<r.length?t[r.charAt(s)]:64;if(++s,i==null||u==null||l==null||p==null)throw new Ou;let g=i<<2|u>>4;if(n.push(g),l!==64){let y=u<<4&240|l>>2;if(n.push(y),p!==64){let I=l<<6&192|p;n.push(I)}}}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)}}},Ou=class extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}},AA=function(r){let e=hm(r);return dm.encodeByteArray(e,!0)},Fs=function(r){return AA(r).replace(/\./g,"")},fm=function(r){try{return dm.decodeString(r,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function pm(){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 SA=()=>pm().__FIREBASE_DEFAULTS__,xA=()=>{if(typeof process=="undefined"||typeof process.env=="undefined")return;let r=process.env.__FIREBASE_DEFAULTS__;if(r)return JSON.parse(r)},RA=()=>{if(typeof document=="undefined")return;let r;try{r=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}let e=r&&fm(r[1]);return e&&JSON.parse(e)},Du=()=>{try{return cm()||SA()||xA()||RA()}catch(r){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${r}`);return}},PA=r=>{var e,t;return(t=(e=Du())==null?void 0:e.emulatorHosts)==null?void 0:t[r]},mm=r=>{let e=PA(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]},Nu=()=>{var r;return(r=Du())==null?void 0:r.config};var To=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 gm(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 o={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[Fs(JSON.stringify(t)),Fs(JSON.stringify(o)),""].join(".")}function ym(){return typeof navigator!="undefined"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function CA(){var e;let r=(e=Du())==null?void 0:e.forceEnvironment;if(r==="node")return!0;if(r==="browser")return!1;try{return Object.prototype.toString.call(global.process)==="[object process]"}catch{return!1}}function _m(){return!CA()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function Vu(){try{return typeof indexedDB=="object"}catch{return!1}}function wm(){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?void 0:i.message)||"")}}catch(t){e(t)}})}var kA="FirebaseError",Xe=class r extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name=kA,Object.setPrototypeOf(this,r.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Ms.prototype.create)}},Ms=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],o=i?OA(i,n):"Error",u=`${this.serviceName}: ${o} (${s}).`;return new Xe(s,u,n)}};function OA(r,e){return r.replace(DA,(t,n)=>{let s=e[n];return s!=null?String(s):`<${n}?>`})}var DA=/\{\$([^}]+)}/g;function Ir(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],o=e[s];if(lm(i)&&lm(o)){if(!Ir(i,o))return!1}else if(i!==o)return!1}for(let s of n)if(!t.includes(s))return!1;return!0}function lm(r){return r!==null&&typeof r=="object"}var NM=14400*1e3;function at(r){return r&&r._delegate?r._delegate:r}function Lu(r){try{return(r.startsWith("http://")||r.startsWith("https://")?new URL(r).hostname:r).endsWith(".cloudworkstations.dev")}catch{return!1}}async function vm(r){return(await fetch(r,{credentials:"include"})).ok}var At=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 Ar="[DEFAULT]";var Fu=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 To;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 s;let t=this.normalizeInstanceIdentifier(e==null?void 0:e.identifier),n=(s=e==null?void 0:e.optional)!=null?s:!1;if(this.isInitialized(t)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:t})}catch(i){if(n)return null;throw i}else{if(n)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(VA(e))try{this.getOrInitializeService({instanceIdentifier:Ar})}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=Ar){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=Ar){return this.instances.has(e)}getOptions(e=Ar){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,o]of this.instancesDeferred.entries()){let u=this.normalizeInstanceIdentifier(i);n===u&&o.resolve(s)}return s}onInit(e,t){var o;let n=this.normalizeInstanceIdentifier(t),s=(o=this.onInitCallbacks.get(n))!=null?o:new Set;s.add(e),this.onInitCallbacks.set(n,s);let i=this.instances.get(n);return i&&e(i,n),()=>{s.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:NA(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=Ar){return this.component?this.component.multipleInstances?e:Ar:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}};function NA(r){return r===Ar?void 0:r}function VA(r){return r.instantiationMode==="EAGER"}var Io=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 Fu(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}};var LA=[],X;(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"})(X||(X={}));var FA={debug:X.DEBUG,verbose:X.VERBOSE,info:X.INFO,warn:X.WARN,error:X.ERROR,silent:X.SILENT},MA=X.INFO,jA={[X.DEBUG]:"log",[X.VERBOSE]:"log",[X.INFO]:"info",[X.WARN]:"warn",[X.ERROR]:"error"},UA=(r,e,...t)=>{if(e<r.logLevel)return;let n=new Date().toISOString(),s=jA[e];if(s)console[s](`[${n}] ${r.name}:`,...t);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)},An=class{constructor(e){this.name=e,this._logLevel=MA,this._logHandler=UA,this._userLogHandler=null,LA.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in X))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?FA[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,X.DEBUG,...e),this._logHandler(this,X.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,X.VERBOSE,...e),this._logHandler(this,X.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,X.INFO,...e),this._logHandler(this,X.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,X.WARN,...e),this._logHandler(this,X.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,X.ERROR,...e),this._logHandler(this,X.ERROR,...e)}};var BA=(r,e)=>e.some(t=>r instanceof t),bm,Em;function $A(){return bm||(bm=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function qA(){return Em||(Em=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Tm=new WeakMap,ju=new WeakMap,Im=new WeakMap,Mu=new WeakMap,Bu=new WeakMap;function zA(r){let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("success",i),r.removeEventListener("error",o)},i=()=>{t(ut(r.result)),s()},o=()=>{n(r.error),s()};r.addEventListener("success",i),r.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&Tm.set(t,r)}).catch(()=>{}),Bu.set(e,r),e}function KA(r){if(ju.has(r))return;let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("complete",i),r.removeEventListener("error",o),r.removeEventListener("abort",o)},i=()=>{t(),s()},o=()=>{n(r.error||new DOMException("AbortError","AbortError")),s()};r.addEventListener("complete",i),r.addEventListener("error",o),r.addEventListener("abort",o)});ju.set(r,e)}var Uu={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return ju.get(r);if(e==="objectStoreNames")return r.objectStoreNames||Im.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return ut(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 Am(r){Uu=r(Uu)}function GA(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let n=r.call(Ao(this),e,...t);return Im.set(n,e.sort?e.sort():[e]),ut(n)}:qA().includes(r)?function(...e){return r.apply(Ao(this),e),ut(Tm.get(this))}:function(...e){return ut(r.apply(Ao(this),e))}}function WA(r){return typeof r=="function"?GA(r):(r instanceof IDBTransaction&&KA(r),BA(r,$A())?new Proxy(r,Uu):r)}function ut(r){if(r instanceof IDBRequest)return zA(r);if(Mu.has(r))return Mu.get(r);let e=WA(r);return e!==r&&(Mu.set(r,e),Bu.set(e,r)),e}var Ao=r=>Bu.get(r);function xm(r,e,{blocked:t,upgrade:n,blocking:s,terminated:i}={}){let o=indexedDB.open(r,e),u=ut(o);return n&&o.addEventListener("upgradeneeded",c=>{n(ut(o.result),c.oldVersion,c.newVersion,ut(o.transaction),c)}),t&&o.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),u.then(c=>{i&&c.addEventListener("close",()=>i()),s&&c.addEventListener("versionchange",l=>s(l.oldVersion,l.newVersion,l))}).catch(()=>{}),u}var HA=["get","getKey","getAll","getAllKeys","count"],JA=["put","add","delete","clear"],$u=new Map;function Sm(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if($u.get(e))return $u.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,s=JA.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(s||HA.includes(t)))return;let i=async function(o,...u){let c=this.transaction(o,s?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(u.shift())),(await Promise.all([l[t](...u),s&&c.done]))[0]};return $u.set(e,i),i}Am(r=>({...r,get:(e,t,n)=>Sm(e,t)||r.get(e,t,n),has:(e,t)=>!!Sm(e,t)||r.has(e,t)}));var zu=class{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(t=>{if(QA(t)){let n=t.getImmediate();return`${n.library}/${n.version}`}else return null}).filter(t=>t).join(" ")}};function QA(r){let e=r.getComponent();return(e==null?void 0:e.type)==="VERSION"}var Ku="@firebase/app",Rm="0.14.10";var St=new An("@firebase/app"),YA="@firebase/app-compat",XA="@firebase/analytics-compat",ZA="@firebase/analytics",eS="@firebase/app-check-compat",tS="@firebase/app-check",rS="@firebase/auth",nS="@firebase/auth-compat",sS="@firebase/database",iS="@firebase/data-connect",oS="@firebase/database-compat",aS="@firebase/functions",uS="@firebase/functions-compat",cS="@firebase/installations",lS="@firebase/installations-compat",hS="@firebase/messaging",dS="@firebase/messaging-compat",fS="@firebase/performance",pS="@firebase/performance-compat",mS="@firebase/remote-config",gS="@firebase/remote-config-compat",yS="@firebase/storage",_S="@firebase/storage-compat",wS="@firebase/firestore",vS="@firebase/ai",bS="@firebase/firestore-compat",ES="firebase",TS="12.11.0";var Gu="[DEFAULT]",IS={[Ku]:"fire-core",[YA]:"fire-core-compat",[ZA]:"fire-analytics",[XA]:"fire-analytics-compat",[tS]:"fire-app-check",[eS]:"fire-app-check-compat",[rS]:"fire-auth",[nS]:"fire-auth-compat",[sS]:"fire-rtdb",[iS]:"fire-data-connect",[oS]:"fire-rtdb-compat",[aS]:"fire-fn",[uS]:"fire-fn-compat",[cS]:"fire-iid",[lS]:"fire-iid-compat",[hS]:"fire-fcm",[dS]:"fire-fcm-compat",[fS]:"fire-perf",[pS]:"fire-perf-compat",[mS]:"fire-rc",[gS]:"fire-rc-compat",[yS]:"fire-gcs",[_S]:"fire-gcs-compat",[wS]:"fire-fst",[bS]:"fire-fst-compat",[vS]:"fire-vertex","fire-js":"fire-js",[ES]:"fire-js-all"};var So=new Map,AS=new Map,Wu=new Map;function Pm(r,e){try{r.container.addComponent(e)}catch(t){St.debug(`Component ${e.name} failed to register with FirebaseApp ${r.name}`,t)}}function js(r){let e=r.name;if(Wu.has(e))return St.debug(`There were multiple attempts to register component ${e}.`),!1;Wu.set(e,r);for(let t of So.values())Pm(t,r);for(let t of AS.values())Pm(t,r);return!0}function Dm(r,e){let t=r.container.getProvider("heartbeat").getImmediate({optional:!0});return t&&t.triggerHeartbeat(),r.container.getProvider(e)}function Nm(r){return r==null?!1:r.settings!==void 0}var SS={"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."},ar=new Ms("app","Firebase",SS);var Hu=class{constructor(e,t,n){this._isDeleted=!1,this._options={...e},this._config={...t},this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new At("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 ar.create("app-deleted",{appName:this._name})}};var Vm=TS;function Yu(r,e={}){let t=r;typeof e!="object"&&(e={name:e});let n={name:Gu,automaticDataCollectionEnabled:!0,...e},s=n.name;if(typeof s!="string"||!s)throw ar.create("bad-app-name",{appName:String(s)});if(t||(t=Nu()),!t)throw ar.create("no-options");let i=So.get(s);if(i){if(Ir(t,i.options)&&Ir(n,i.config))return i;throw ar.create("duplicate-app",{appName:s})}let o=new Io(s);for(let c of Wu.values())o.addComponent(c);let u=new Hu(t,n,o);return So.set(s,u),u}function Lm(r=Gu){let e=So.get(r);if(!e&&r===Gu&&Nu())return Yu();if(!e)throw ar.create("no-app",{appName:r});return e}function ur(r,e,t){var o;let n=(o=IS[r])!=null?o:r;t&&(n+=`-${t}`);let s=n.match(/\s|\//),i=e.match(/\s|\//);if(s||i){let u=[`Unable to register library "${n}" with version "${e}":`];s&&u.push(`library name "${n}" contains illegal characters (whitespace or "/")`),s&&i&&u.push("and"),i&&u.push(`version name "${e}" contains illegal characters (whitespace or "/")`),St.warn(u.join(" "));return}js(new At(`${n}-version`,()=>({library:n,version:e}),"VERSION"))}var xS="firebase-heartbeat-database",RS=1,Us="firebase-heartbeat-store",qu=null;function Fm(){return qu||(qu=xm(xS,RS,{upgrade:(r,e)=>{switch(e){case 0:try{r.createObjectStore(Us)}catch(t){console.warn(t)}}}}).catch(r=>{throw ar.create("idb-open",{originalErrorMessage:r.message})})),qu}async function PS(r){try{let t=(await Fm()).transaction(Us),n=await t.objectStore(Us).get(Mm(r));return await t.done,n}catch(e){if(e instanceof Xe)St.warn(e.message);else{let t=ar.create("idb-get",{originalErrorMessage:e==null?void 0:e.message});St.warn(t.message)}}}async function Cm(r,e){try{let n=(await Fm()).transaction(Us,"readwrite");await n.objectStore(Us).put(e,Mm(r)),await n.done}catch(t){if(t instanceof Xe)St.warn(t.message);else{let n=ar.create("idb-set",{originalErrorMessage:t==null?void 0:t.message});St.warn(n.message)}}}function Mm(r){return`${r.name}!${r.options.appId}`}var CS=1024,kS=30,Ju=class{constructor(e){this.container=e,this._heartbeatsCache=null;let t=this.container.getProvider("app").getImmediate();this._storage=new Qu(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=km();if(((e=this._heartbeatsCache)==null?void 0:e.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,((t=this._heartbeatsCache)==null?void 0:t.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===i||this._heartbeatsCache.heartbeats.some(o=>o.date===i))return;if(this._heartbeatsCache.heartbeats.push({date:i,agent:s}),this._heartbeatsCache.heartbeats.length>kS){let o=DS(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(o,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(n){St.warn(n)}}async getHeartbeatsHeader(){var e;try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,((e=this._heartbeatsCache)==null?void 0:e.heartbeats)==null||this._heartbeatsCache.heartbeats.length===0)return"";let t=km(),{heartbeatsToSend:n,unsentEntries:s}=OS(this._heartbeatsCache.heartbeats),i=Fs(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 St.warn(t),""}}};function km(){return new Date().toISOString().substring(0,10)}function OS(r,e=CS){let t=[],n=r.slice();for(let s of r){let i=t.find(o=>o.agent===s.agent);if(i){if(i.dates.push(s.date),Om(t)>e){i.dates.pop();break}}else if(t.push({agent:s.agent,dates:[s.date]}),Om(t)>e){t.pop();break}n=n.slice(1)}return{heartbeatsToSend:t,unsentEntries:n}}var Qu=class{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return Vu()?wm().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){let t=await PS(this.app);return t!=null&&t.heartbeats?t:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){var n;if(await this._canUseIndexedDBPromise){let s=await this.read();return Cm(this.app,{lastSentHeartbeatDate:(n=e.lastSentHeartbeatDate)!=null?n:s.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){var n;if(await this._canUseIndexedDBPromise){let s=await this.read();return Cm(this.app,{lastSentHeartbeatDate:(n=e.lastSentHeartbeatDate)!=null?n:s.lastSentHeartbeatDate,heartbeats:[...s.heartbeats,...e.heartbeats]})}else return}};function Om(r){return Fs(JSON.stringify({version:2,heartbeats:r})).length}function DS(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 NS(r){js(new At("platform-logger",e=>new zu(e),"PRIVATE")),js(new At("heartbeat",e=>new Ju(e),"PRIVATE")),ur(Ku,Rm,r),ur(Ku,Rm,"esm2020"),ur("fire-js","")}NS("");var VS="firebase",LS="12.11.0";ur(VS,LS,"app");var jm=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Um={};var xt,Xu;(function(){var r;function e(E,_){function w(){}w.prototype=_.prototype,E.F=_.prototype,E.prototype=new w,E.prototype.constructor=E,E.D=function(S,T,P){for(var b=Array(arguments.length-2),Me=2;Me<arguments.length;Me++)b[Me-2]=arguments[Me];return _.prototype[T].apply(S,b)}}function t(){this.blockSize=-1}function n(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.C=Array(this.blockSize),this.o=this.h=0,this.u()}e(n,t),n.prototype.u=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0};function s(E,_,w){w||(w=0);let S=Array(16);if(typeof _=="string")for(var T=0;T<16;++T)S[T]=_.charCodeAt(w++)|_.charCodeAt(w++)<<8|_.charCodeAt(w++)<<16|_.charCodeAt(w++)<<24;else for(T=0;T<16;++T)S[T]=_[w++]|_[w++]<<8|_[w++]<<16|_[w++]<<24;_=E.g[0],w=E.g[1],T=E.g[2];let P=E.g[3],b;b=_+(P^w&(T^P))+S[0]+3614090360&4294967295,_=w+(b<<7&4294967295|b>>>25),b=P+(T^_&(w^T))+S[1]+3905402710&4294967295,P=_+(b<<12&4294967295|b>>>20),b=T+(w^P&(_^w))+S[2]+606105819&4294967295,T=P+(b<<17&4294967295|b>>>15),b=w+(_^T&(P^_))+S[3]+3250441966&4294967295,w=T+(b<<22&4294967295|b>>>10),b=_+(P^w&(T^P))+S[4]+4118548399&4294967295,_=w+(b<<7&4294967295|b>>>25),b=P+(T^_&(w^T))+S[5]+1200080426&4294967295,P=_+(b<<12&4294967295|b>>>20),b=T+(w^P&(_^w))+S[6]+2821735955&4294967295,T=P+(b<<17&4294967295|b>>>15),b=w+(_^T&(P^_))+S[7]+4249261313&4294967295,w=T+(b<<22&4294967295|b>>>10),b=_+(P^w&(T^P))+S[8]+1770035416&4294967295,_=w+(b<<7&4294967295|b>>>25),b=P+(T^_&(w^T))+S[9]+2336552879&4294967295,P=_+(b<<12&4294967295|b>>>20),b=T+(w^P&(_^w))+S[10]+4294925233&4294967295,T=P+(b<<17&4294967295|b>>>15),b=w+(_^T&(P^_))+S[11]+2304563134&4294967295,w=T+(b<<22&4294967295|b>>>10),b=_+(P^w&(T^P))+S[12]+1804603682&4294967295,_=w+(b<<7&4294967295|b>>>25),b=P+(T^_&(w^T))+S[13]+4254626195&4294967295,P=_+(b<<12&4294967295|b>>>20),b=T+(w^P&(_^w))+S[14]+2792965006&4294967295,T=P+(b<<17&4294967295|b>>>15),b=w+(_^T&(P^_))+S[15]+1236535329&4294967295,w=T+(b<<22&4294967295|b>>>10),b=_+(T^P&(w^T))+S[1]+4129170786&4294967295,_=w+(b<<5&4294967295|b>>>27),b=P+(w^T&(_^w))+S[6]+3225465664&4294967295,P=_+(b<<9&4294967295|b>>>23),b=T+(_^w&(P^_))+S[11]+643717713&4294967295,T=P+(b<<14&4294967295|b>>>18),b=w+(P^_&(T^P))+S[0]+3921069994&4294967295,w=T+(b<<20&4294967295|b>>>12),b=_+(T^P&(w^T))+S[5]+3593408605&4294967295,_=w+(b<<5&4294967295|b>>>27),b=P+(w^T&(_^w))+S[10]+38016083&4294967295,P=_+(b<<9&4294967295|b>>>23),b=T+(_^w&(P^_))+S[15]+3634488961&4294967295,T=P+(b<<14&4294967295|b>>>18),b=w+(P^_&(T^P))+S[4]+3889429448&4294967295,w=T+(b<<20&4294967295|b>>>12),b=_+(T^P&(w^T))+S[9]+568446438&4294967295,_=w+(b<<5&4294967295|b>>>27),b=P+(w^T&(_^w))+S[14]+3275163606&4294967295,P=_+(b<<9&4294967295|b>>>23),b=T+(_^w&(P^_))+S[3]+4107603335&4294967295,T=P+(b<<14&4294967295|b>>>18),b=w+(P^_&(T^P))+S[8]+1163531501&4294967295,w=T+(b<<20&4294967295|b>>>12),b=_+(T^P&(w^T))+S[13]+2850285829&4294967295,_=w+(b<<5&4294967295|b>>>27),b=P+(w^T&(_^w))+S[2]+4243563512&4294967295,P=_+(b<<9&4294967295|b>>>23),b=T+(_^w&(P^_))+S[7]+1735328473&4294967295,T=P+(b<<14&4294967295|b>>>18),b=w+(P^_&(T^P))+S[12]+2368359562&4294967295,w=T+(b<<20&4294967295|b>>>12),b=_+(w^T^P)+S[5]+4294588738&4294967295,_=w+(b<<4&4294967295|b>>>28),b=P+(_^w^T)+S[8]+2272392833&4294967295,P=_+(b<<11&4294967295|b>>>21),b=T+(P^_^w)+S[11]+1839030562&4294967295,T=P+(b<<16&4294967295|b>>>16),b=w+(T^P^_)+S[14]+4259657740&4294967295,w=T+(b<<23&4294967295|b>>>9),b=_+(w^T^P)+S[1]+2763975236&4294967295,_=w+(b<<4&4294967295|b>>>28),b=P+(_^w^T)+S[4]+1272893353&4294967295,P=_+(b<<11&4294967295|b>>>21),b=T+(P^_^w)+S[7]+4139469664&4294967295,T=P+(b<<16&4294967295|b>>>16),b=w+(T^P^_)+S[10]+3200236656&4294967295,w=T+(b<<23&4294967295|b>>>9),b=_+(w^T^P)+S[13]+681279174&4294967295,_=w+(b<<4&4294967295|b>>>28),b=P+(_^w^T)+S[0]+3936430074&4294967295,P=_+(b<<11&4294967295|b>>>21),b=T+(P^_^w)+S[3]+3572445317&4294967295,T=P+(b<<16&4294967295|b>>>16),b=w+(T^P^_)+S[6]+76029189&4294967295,w=T+(b<<23&4294967295|b>>>9),b=_+(w^T^P)+S[9]+3654602809&4294967295,_=w+(b<<4&4294967295|b>>>28),b=P+(_^w^T)+S[12]+3873151461&4294967295,P=_+(b<<11&4294967295|b>>>21),b=T+(P^_^w)+S[15]+530742520&4294967295,T=P+(b<<16&4294967295|b>>>16),b=w+(T^P^_)+S[2]+3299628645&4294967295,w=T+(b<<23&4294967295|b>>>9),b=_+(T^(w|~P))+S[0]+4096336452&4294967295,_=w+(b<<6&4294967295|b>>>26),b=P+(w^(_|~T))+S[7]+1126891415&4294967295,P=_+(b<<10&4294967295|b>>>22),b=T+(_^(P|~w))+S[14]+2878612391&4294967295,T=P+(b<<15&4294967295|b>>>17),b=w+(P^(T|~_))+S[5]+4237533241&4294967295,w=T+(b<<21&4294967295|b>>>11),b=_+(T^(w|~P))+S[12]+1700485571&4294967295,_=w+(b<<6&4294967295|b>>>26),b=P+(w^(_|~T))+S[3]+2399980690&4294967295,P=_+(b<<10&4294967295|b>>>22),b=T+(_^(P|~w))+S[10]+4293915773&4294967295,T=P+(b<<15&4294967295|b>>>17),b=w+(P^(T|~_))+S[1]+2240044497&4294967295,w=T+(b<<21&4294967295|b>>>11),b=_+(T^(w|~P))+S[8]+1873313359&4294967295,_=w+(b<<6&4294967295|b>>>26),b=P+(w^(_|~T))+S[15]+4264355552&4294967295,P=_+(b<<10&4294967295|b>>>22),b=T+(_^(P|~w))+S[6]+2734768916&4294967295,T=P+(b<<15&4294967295|b>>>17),b=w+(P^(T|~_))+S[13]+1309151649&4294967295,w=T+(b<<21&4294967295|b>>>11),b=_+(T^(w|~P))+S[4]+4149444226&4294967295,_=w+(b<<6&4294967295|b>>>26),b=P+(w^(_|~T))+S[11]+3174756917&4294967295,P=_+(b<<10&4294967295|b>>>22),b=T+(_^(P|~w))+S[2]+718787259&4294967295,T=P+(b<<15&4294967295|b>>>17),b=w+(P^(T|~_))+S[9]+3951481745&4294967295,E.g[0]=E.g[0]+_&4294967295,E.g[1]=E.g[1]+(T+(b<<21&4294967295|b>>>11))&4294967295,E.g[2]=E.g[2]+T&4294967295,E.g[3]=E.g[3]+P&4294967295}n.prototype.v=function(E,_){_===void 0&&(_=E.length);let w=_-this.blockSize,S=this.C,T=this.h,P=0;for(;P<_;){if(T==0)for(;P<=w;)s(this,E,P),P+=this.blockSize;if(typeof E=="string"){for(;P<_;)if(S[T++]=E.charCodeAt(P++),T==this.blockSize){s(this,S),T=0;break}}else for(;P<_;)if(S[T++]=E[P++],T==this.blockSize){s(this,S),T=0;break}}this.h=T,this.o+=_},n.prototype.A=function(){var E=Array((this.h<56?this.blockSize:this.blockSize*2)-this.h);E[0]=128;for(var _=1;_<E.length-8;++_)E[_]=0;_=this.o*8;for(var w=E.length-8;w<E.length;++w)E[w]=_&255,_/=256;for(this.v(E),E=Array(16),_=0,w=0;w<4;++w)for(let S=0;S<32;S+=8)E[_++]=this.g[w]>>>S&255;return E};function i(E,_){var w=u;return Object.prototype.hasOwnProperty.call(w,E)?w[E]:w[E]=_(E)}function o(E,_){this.h=_;let w=[],S=!0;for(let T=E.length-1;T>=0;T--){let P=E[T]|0;S&&P==_||(w[T]=P,S=!1)}this.g=w}var u={};function c(E){return-128<=E&&E<128?i(E,function(_){return new o([_|0],_<0?-1:0)}):new o([E|0],E<0?-1:0)}function l(E){if(isNaN(E)||!isFinite(E))return p;if(E<0)return A(l(-E));let _=[],w=1;for(let S=0;E>=w;S++)_[S]=E/w|0,w*=4294967296;return new o(_,0)}function f(E,_){if(E.length==0)throw Error("number format error: empty string");if(_=_||10,_<2||36<_)throw Error("radix out of range: "+_);if(E.charAt(0)=="-")return A(f(E.substring(1),_));if(E.indexOf("-")>=0)throw Error('number format error: interior "-" character');let w=l(Math.pow(_,8)),S=p;for(let P=0;P<E.length;P+=8){var T=Math.min(8,E.length-P);let b=parseInt(E.substring(P,P+T),_);T<8?(T=l(Math.pow(_,T)),S=S.j(T).add(l(b))):(S=S.j(w),S=S.add(l(b)))}return S}var p=c(0),g=c(1),y=c(16777216);r=o.prototype,r.m=function(){if(R(this))return-A(this).m();let E=0,_=1;for(let w=0;w<this.g.length;w++){let S=this.i(w);E+=(S>=0?S:4294967296+S)*_,_*=4294967296}return E},r.toString=function(E){if(E=E||10,E<2||36<E)throw Error("radix out of range: "+E);if(I(this))return"0";if(R(this))return"-"+A(this).toString(E);let _=l(Math.pow(E,6));var w=this;let S="";for(;;){let T=U(w,_).g;w=k(w,T.j(_));let P=((w.g.length>0?w.g[0]:w.h)>>>0).toString(E);if(w=T,I(w))return P+S;for(;P.length<6;)P="0"+P;S=P+S}},r.i=function(E){return E<0?0:E<this.g.length?this.g[E]:this.h};function I(E){if(E.h!=0)return!1;for(let _=0;_<E.g.length;_++)if(E.g[_]!=0)return!1;return!0}function R(E){return E.h==-1}r.l=function(E){return E=k(this,E),R(E)?-1:I(E)?0:1};function A(E){let _=E.g.length,w=[];for(let S=0;S<_;S++)w[S]=~E.g[S];return new o(w,~E.h).add(g)}r.abs=function(){return R(this)?A(this):this},r.add=function(E){let _=Math.max(this.g.length,E.g.length),w=[],S=0;for(let T=0;T<=_;T++){let P=S+(this.i(T)&65535)+(E.i(T)&65535),b=(P>>>16)+(this.i(T)>>>16)+(E.i(T)>>>16);S=b>>>16,P&=65535,b&=65535,w[T]=b<<16|P}return new o(w,w[w.length-1]&-2147483648?-1:0)};function k(E,_){return E.add(A(_))}r.j=function(E){if(I(this)||I(E))return p;if(R(this))return R(E)?A(this).j(A(E)):A(A(this).j(E));if(R(E))return A(this.j(A(E)));if(this.l(y)<0&&E.l(y)<0)return l(this.m()*E.m());let _=this.g.length+E.g.length,w=[];for(var S=0;S<2*_;S++)w[S]=0;for(S=0;S<this.g.length;S++)for(let T=0;T<E.g.length;T++){let P=this.i(S)>>>16,b=this.i(S)&65535,Me=E.i(T)>>>16,Bt=E.i(T)&65535;w[2*S+2*T]+=b*Bt,D(w,2*S+2*T),w[2*S+2*T+1]+=P*Bt,D(w,2*S+2*T+1),w[2*S+2*T+1]+=b*Me,D(w,2*S+2*T+1),w[2*S+2*T+2]+=P*Me,D(w,2*S+2*T+2)}for(E=0;E<_;E++)w[E]=w[2*E+1]<<16|w[2*E];for(E=_;E<2*_;E++)w[E]=0;return new o(w,0)};function D(E,_){for(;(E[_]&65535)!=E[_];)E[_+1]+=E[_]>>>16,E[_]&=65535,_++}function N(E,_){this.g=E,this.h=_}function U(E,_){if(I(_))throw Error("division by zero");if(I(E))return new N(p,p);if(R(E))return _=U(A(E),_),new N(A(_.g),A(_.h));if(R(_))return _=U(E,A(_)),new N(A(_.g),_.h);if(E.g.length>30){if(R(E)||R(_))throw Error("slowDivide_ only works with positive integers.");for(var w=g,S=_;S.l(E)<=0;)w=z(w),S=z(S);var T=F(w,1),P=F(S,1);for(S=F(S,2),w=F(w,2);!I(S);){var b=P.add(S);b.l(E)<=0&&(T=T.add(w),P=b),S=F(S,1),w=F(w,1)}return _=k(E,T.j(_)),new N(T,_)}for(T=p;E.l(_)>=0;){for(w=Math.max(1,Math.floor(E.m()/_.m())),S=Math.ceil(Math.log(w)/Math.LN2),S=S<=48?1:Math.pow(2,S-48),P=l(w),b=P.j(_);R(b)||b.l(E)>0;)w-=S,P=l(w),b=P.j(_);I(P)&&(P=g),T=T.add(P),E=k(E,b)}return new N(T,E)}r.B=function(E){return U(this,E).h},r.and=function(E){let _=Math.max(this.g.length,E.g.length),w=[];for(let S=0;S<_;S++)w[S]=this.i(S)&E.i(S);return new o(w,this.h&E.h)},r.or=function(E){let _=Math.max(this.g.length,E.g.length),w=[];for(let S=0;S<_;S++)w[S]=this.i(S)|E.i(S);return new o(w,this.h|E.h)},r.xor=function(E){let _=Math.max(this.g.length,E.g.length),w=[];for(let S=0;S<_;S++)w[S]=this.i(S)^E.i(S);return new o(w,this.h^E.h)};function z(E){let _=E.g.length+1,w=[];for(let S=0;S<_;S++)w[S]=E.i(S)<<1|E.i(S-1)>>>31;return new o(w,E.h)}function F(E,_){let w=_>>5;_%=32;let S=E.g.length-w,T=[];for(let P=0;P<S;P++)T[P]=_>0?E.i(P+w)>>>_|E.i(P+w+1)<<32-_:E.i(P+w);return new o(T,E.h)}n.prototype.digest=n.prototype.A,n.prototype.reset=n.prototype.u,n.prototype.update=n.prototype.v,Xu=Um.Md5=n,o.prototype.add=o.prototype.add,o.prototype.multiply=o.prototype.j,o.prototype.modulo=o.prototype.B,o.prototype.compare=o.prototype.l,o.prototype.toNumber=o.prototype.m,o.prototype.toString=o.prototype.toString,o.prototype.getBits=o.prototype.i,o.fromNumber=l,o.fromString=f,xt=Um.Integer=o}).apply(typeof jm!="undefined"?jm:typeof self!="undefined"?self:typeof window!="undefined"?window:{});var xo=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Rt={};var Zu,FS,Sn,ec,Bs,Ro,tc,rc,nc;(function(){var r,e=Object.defineProperty;function t(a){a=[typeof globalThis=="object"&&globalThis,a,typeof window=="object"&&window,typeof self=="object"&&self,typeof xo=="object"&&xo];for(var h=0;h<a.length;++h){var d=a[h];if(d&&d.Math==Math)return d}throw Error("Cannot find global object")}var n=t(this);function s(a,h){if(h)e:{var d=n;a=a.split(".");for(var m=0;m<a.length-1;m++){var x=a[m];if(!(x in d))break e;d=d[x]}a=a[a.length-1],m=d[a],h=h(m),h!=m&&h!=null&&e(d,a,{configurable:!0,writable:!0,value:h})}}s("Symbol.dispose",function(a){return a||Symbol("Symbol.dispose")}),s("Array.prototype.values",function(a){return a||function(){return this[Symbol.iterator]()}}),s("Object.entries",function(a){return a||function(h){var d=[],m;for(m in h)Object.prototype.hasOwnProperty.call(h,m)&&d.push([m,h[m]]);return d}});var i=i||{},o=this||self;function u(a){var h=typeof a;return h=="object"&&a!=null||h=="function"}function c(a,h,d){return a.call.apply(a.bind,arguments)}function l(a,h,d){return l=c,l.apply(null,arguments)}function f(a,h){var d=Array.prototype.slice.call(arguments,1);return function(){var m=d.slice();return m.push.apply(m,arguments),a.apply(this,m)}}function p(a,h){function d(){}d.prototype=h.prototype,a.Z=h.prototype,a.prototype=new d,a.prototype.constructor=a,a.Ob=function(m,x,C){for(var L=Array(arguments.length-2),J=2;J<arguments.length;J++)L[J-2]=arguments[J];return h.prototype[x].apply(m,L)}}var g=typeof AsyncContext!="undefined"&&typeof AsyncContext.Snapshot=="function"?a=>a&&AsyncContext.Snapshot.wrap(a):a=>a;function y(a){let h=a.length;if(h>0){let d=Array(h);for(let m=0;m<h;m++)d[m]=a[m];return d}return[]}function I(a,h){for(let m=1;m<arguments.length;m++){let x=arguments[m];var d=typeof x;if(d=d!="object"?d:x?Array.isArray(x)?"array":d:"null",d=="array"||d=="object"&&typeof x.length=="number"){d=a.length||0;let C=x.length||0;a.length=d+C;for(let L=0;L<C;L++)a[d+L]=x[L]}else a.push(x)}}class R{constructor(h,d){this.i=h,this.j=d,this.h=0,this.g=null}get(){let h;return this.h>0?(this.h--,h=this.g,this.g=h.next,h.next=null):h=this.i(),h}}function A(a){o.setTimeout(()=>{throw a},0)}function k(){var a=E;let h=null;return a.g&&(h=a.g,a.g=a.g.next,a.g||(a.h=null),h.next=null),h}class D{constructor(){this.h=this.g=null}add(h,d){let m=N.get();m.set(h,d),this.h?this.h.next=m:this.g=m,this.h=m}}var N=new R(()=>new U,a=>a.reset());class U{constructor(){this.next=this.g=this.h=null}set(h,d){this.h=h,this.g=d,this.next=null}reset(){this.next=this.g=this.h=null}}let z,F=!1,E=new D,_=()=>{let a=Promise.resolve(void 0);z=()=>{a.then(w)}};function w(){for(var a;a=k();){try{a.h.call(a.g)}catch(d){A(d)}var h=N;h.j(a),h.h<100&&(h.h++,a.next=h.g,h.g=a)}F=!1}function S(){this.u=this.u,this.C=this.C}S.prototype.u=!1,S.prototype.dispose=function(){this.u||(this.u=!0,this.N())},S.prototype[Symbol.dispose]=function(){this.dispose()},S.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function T(a,h){this.type=a,this.g=this.target=h,this.defaultPrevented=!1}T.prototype.h=function(){this.defaultPrevented=!0};var P=(function(){if(!o.addEventListener||!Object.defineProperty)return!1;var a=!1,h=Object.defineProperty({},"passive",{get:function(){a=!0}});try{let d=()=>{};o.addEventListener("test",d,h),o.removeEventListener("test",d,h)}catch{}return a})();function b(a){return/^[\s\xa0]*$/.test(a)}function Me(a,h){T.call(this,a?a.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,a&&this.init(a,h)}p(Me,T),Me.prototype.init=function(a,h){let d=this.type=a.type,m=a.changedTouches&&a.changedTouches.length?a.changedTouches[0]:null;this.target=a.target||a.srcElement,this.g=h,h=a.relatedTarget,h||(d=="mouseover"?h=a.fromElement:d=="mouseout"&&(h=a.toElement)),this.relatedTarget=h,m?(this.clientX=m.clientX!==void 0?m.clientX:m.pageX,this.clientY=m.clientY!==void 0?m.clientY:m.pageY,this.screenX=m.screenX||0,this.screenY=m.screenY||0):(this.clientX=a.clientX!==void 0?a.clientX:a.pageX,this.clientY=a.clientY!==void 0?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0),this.button=a.button,this.key=a.key||"",this.ctrlKey=a.ctrlKey,this.altKey=a.altKey,this.shiftKey=a.shiftKey,this.metaKey=a.metaKey,this.pointerId=a.pointerId||0,this.pointerType=a.pointerType,this.state=a.state,this.i=a,a.defaultPrevented&&Me.Z.h.call(this)},Me.prototype.h=function(){Me.Z.h.call(this);let a=this.i;a.preventDefault?a.preventDefault():a.returnValue=!1};var Bt="closure_listenable_"+(Math.random()*1e6|0),xw=0;function Rw(a,h,d,m,x){this.listener=a,this.proxy=null,this.src=h,this.type=d,this.capture=!!m,this.ha=x,this.key=++xw,this.da=this.fa=!1}function Vi(a){a.da=!0,a.listener=null,a.proxy=null,a.src=null,a.ha=null}function Li(a,h,d){for(let m in a)h.call(d,a[m],m,a)}function Pw(a,h){for(let d in a)h.call(void 0,a[d],d,a)}function Nh(a){let h={};for(let d in a)h[d]=a[d];return h}let Vh="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Lh(a,h){let d,m;for(let x=1;x<arguments.length;x++){m=arguments[x];for(d in m)a[d]=m[d];for(let C=0;C<Vh.length;C++)d=Vh[C],Object.prototype.hasOwnProperty.call(m,d)&&(a[d]=m[d])}}function Fi(a){this.src=a,this.g={},this.h=0}Fi.prototype.add=function(a,h,d,m,x){let C=a.toString();a=this.g[C],a||(a=this.g[C]=[],this.h++);let L=tu(a,h,m,x);return L>-1?(h=a[L],d||(h.fa=!1)):(h=new Rw(h,this.src,C,!!m,x),h.fa=d,a.push(h)),h};function eu(a,h){let d=h.type;if(d in a.g){var m=a.g[d],x=Array.prototype.indexOf.call(m,h,void 0),C;(C=x>=0)&&Array.prototype.splice.call(m,x,1),C&&(Vi(h),a.g[d].length==0&&(delete a.g[d],a.h--))}}function tu(a,h,d,m){for(let x=0;x<a.length;++x){let C=a[x];if(!C.da&&C.listener==h&&C.capture==!!d&&C.ha==m)return x}return-1}var ru="closure_lm_"+(Math.random()*1e6|0),nu={};function Fh(a,h,d,m,x){if(m&&m.once)return jh(a,h,d,m,x);if(Array.isArray(h)){for(let C=0;C<h.length;C++)Fh(a,h[C],d,m,x);return null}return d=au(d),a&&a[Bt]?a.J(h,d,u(m)?!!m.capture:!!m,x):Mh(a,h,d,!1,m,x)}function Mh(a,h,d,m,x,C){if(!h)throw Error("Invalid event type");let L=u(x)?!!x.capture:!!x,J=iu(a);if(J||(a[ru]=J=new Fi(a)),d=J.add(h,d,m,L,C),d.proxy)return d;if(m=Cw(),d.proxy=m,m.src=a,m.listener=d,a.addEventListener)P||(x=L),x===void 0&&(x=!1),a.addEventListener(h.toString(),m,x);else if(a.attachEvent)a.attachEvent(Bh(h.toString()),m);else if(a.addListener&&a.removeListener)a.addListener(m);else throw Error("addEventListener and attachEvent are unavailable.");return d}function Cw(){function a(d){return h.call(a.src,a.listener,d)}let h=kw;return a}function jh(a,h,d,m,x){if(Array.isArray(h)){for(let C=0;C<h.length;C++)jh(a,h[C],d,m,x);return null}return d=au(d),a&&a[Bt]?a.K(h,d,u(m)?!!m.capture:!!m,x):Mh(a,h,d,!0,m,x)}function Uh(a,h,d,m,x){if(Array.isArray(h))for(var C=0;C<h.length;C++)Uh(a,h[C],d,m,x);else m=u(m)?!!m.capture:!!m,d=au(d),a&&a[Bt]?(a=a.i,C=String(h).toString(),C in a.g&&(h=a.g[C],d=tu(h,d,m,x),d>-1&&(Vi(h[d]),Array.prototype.splice.call(h,d,1),h.length==0&&(delete a.g[C],a.h--)))):a&&(a=iu(a))&&(h=a.g[h.toString()],a=-1,h&&(a=tu(h,d,m,x)),(d=a>-1?h[a]:null)&&su(d))}function su(a){if(typeof a!="number"&&a&&!a.da){var h=a.src;if(h&&h[Bt])eu(h.i,a);else{var d=a.type,m=a.proxy;h.removeEventListener?h.removeEventListener(d,m,a.capture):h.detachEvent?h.detachEvent(Bh(d),m):h.addListener&&h.removeListener&&h.removeListener(m),(d=iu(h))?(eu(d,a),d.h==0&&(d.src=null,h[ru]=null)):Vi(a)}}}function Bh(a){return a in nu?nu[a]:nu[a]="on"+a}function kw(a,h){if(a.da)a=!0;else{h=new Me(h,this);let d=a.listener,m=a.ha||a.src;a.fa&&su(a),a=d.call(m,h)}return a}function iu(a){return a=a[ru],a instanceof Fi?a:null}var ou="__closure_events_fn_"+(Math.random()*1e9>>>0);function au(a){return typeof a=="function"?a:(a[ou]||(a[ou]=function(h){return a.handleEvent(h)}),a[ou])}function ke(){S.call(this),this.i=new Fi(this),this.M=this,this.G=null}p(ke,S),ke.prototype[Bt]=!0,ke.prototype.removeEventListener=function(a,h,d,m){Uh(this,a,h,d,m)};function Ne(a,h){var d,m=a.G;if(m)for(d=[];m;m=m.G)d.push(m);if(a=a.M,m=h.type||h,typeof h=="string")h=new T(h,a);else if(h instanceof T)h.target=h.target||a;else{var x=h;h=new T(m,a),Lh(h,x)}x=!0;let C,L;if(d)for(L=d.length-1;L>=0;L--)C=h.g=d[L],x=Mi(C,m,!0,h)&&x;if(C=h.g=a,x=Mi(C,m,!0,h)&&x,x=Mi(C,m,!1,h)&&x,d)for(L=0;L<d.length;L++)C=h.g=d[L],x=Mi(C,m,!1,h)&&x}ke.prototype.N=function(){if(ke.Z.N.call(this),this.i){var a=this.i;for(let h in a.g){let d=a.g[h];for(let m=0;m<d.length;m++)Vi(d[m]);delete a.g[h],a.h--}}this.G=null},ke.prototype.J=function(a,h,d,m){return this.i.add(String(a),h,!1,d,m)},ke.prototype.K=function(a,h,d,m){return this.i.add(String(a),h,!0,d,m)};function Mi(a,h,d,m){if(h=a.i.g[String(h)],!h)return!0;h=h.concat();let x=!0;for(let C=0;C<h.length;++C){let L=h[C];if(L&&!L.da&&L.capture==d){let J=L.listener,be=L.ha||L.src;L.fa&&eu(a.i,L),x=J.call(be,m)!==!1&&x}}return x&&!m.defaultPrevented}function Ow(a,h){if(typeof a!="function")if(a&&typeof a.handleEvent=="function")a=l(a.handleEvent,a);else throw Error("Invalid listener argument");return Number(h)>2147483647?-1:o.setTimeout(a,h||0)}function $h(a){a.g=Ow(()=>{a.g=null,a.i&&(a.i=!1,$h(a))},a.l);let h=a.h;a.h=null,a.m.apply(null,h)}class Dw extends S{constructor(h,d){super(),this.m=h,this.l=d,this.h=null,this.i=!1,this.g=null}j(h){this.h=arguments,this.g?this.i=!0:$h(this)}N(){super.N(),this.g&&(o.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function gs(a){S.call(this),this.h=a,this.g={}}p(gs,S);var qh=[];function zh(a){Li(a.g,function(h,d){this.g.hasOwnProperty(d)&&su(h)},a),a.g={}}gs.prototype.N=function(){gs.Z.N.call(this),zh(this)},gs.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var uu=o.JSON.stringify,Nw=o.JSON.parse,Vw=class{stringify(a){return o.JSON.stringify(a,void 0)}parse(a){return o.JSON.parse(a,void 0)}};function Kh(){}function Gh(){}var ys={OPEN:"a",hb:"b",ERROR:"c",tb:"d"};function cu(){T.call(this,"d")}p(cu,T);function lu(){T.call(this,"c")}p(lu,T);var yr={},Wh=null;function ji(){return Wh=Wh||new ke}yr.Ia="serverreachability";function Hh(a){T.call(this,yr.Ia,a)}p(Hh,T);function _s(a){let h=ji();Ne(h,new Hh(h))}yr.STAT_EVENT="statevent";function Jh(a,h){T.call(this,yr.STAT_EVENT,a),this.stat=h}p(Jh,T);function Ve(a){let h=ji();Ne(h,new Jh(h,a))}yr.Ja="timingevent";function Qh(a,h){T.call(this,yr.Ja,a),this.size=h}p(Qh,T);function ws(a,h){if(typeof a!="function")throw Error("Fn must not be null and must be a function");return o.setTimeout(function(){a()},h)}function vs(){this.g=!0}vs.prototype.ua=function(){this.g=!1};function Lw(a,h,d,m,x,C){a.info(function(){if(a.g)if(C){var L="",J=C.split("&");for(let re=0;re<J.length;re++){var be=J[re].split("=");if(be.length>1){let Ae=be[0];be=be[1];let st=Ae.split("_");L=st.length>=2&&st[1]=="type"?L+(Ae+"="+be+"&"):L+(Ae+"=redacted&")}}}else L=null;else L=C;return"XMLHTTP REQ ("+m+") [attempt "+x+"]: "+h+`
|
|
16
2
|
`+d+`
|
|
17
|
-
`+L})}function
|
|
3
|
+
`+L})}function Fw(a,h,d,m,x,C,L){a.info(function(){return"XMLHTTP RESP ("+m+") [ attempt "+x+"]: "+h+`
|
|
18
4
|
`+d+`
|
|
19
|
-
`+C+" "+L})}function
|
|
20
|
-
`,d);return g==-1?uu:(d=Number(l.substring(d,g)),isNaN(d)?td:(g+=1,g+d>l.length?uu:(l=l.slice(g,g+d),a.C=g+d,l)))}Mt.prototype.cancel=function(){this.J=!0,_r(this)};function Vi(a){a.S=Date.now()+a.I,sd(a,a.I)}function sd(a,l){if(a.B!=null)throw Error("WatchDog timer not null");a.B=ys(m(a.ba,a),l)}function lu(a){a.B&&(u.clearTimeout(a.B),a.B=null)}Mt.prototype.ba=function(){this.B=null;let a=Date.now();0<=a-this.S?(zv(this.i,this.A),this.L!=2&&(gs(),Fe(17)),_r(this),this.s=2,vs(this)):sd(this,this.S-a)};function vs(a){a.j.G==0||a.J||Cd(a.j,a)}function _r(a){lu(a);var l=a.M;l&&typeof l.ma=="function"&&l.ma(),a.M=null,Gh(a.U),a.g&&(l=a.g,a.g=null,l.abort(),l.ma())}function hu(a,l){try{var d=a.j;if(d.G!=0&&(d.g==a||du(d.h,a))){if(!a.K&&du(d.h,a)&&d.G==3){try{var g=d.Da.g.parse(l)}catch{g=null}if(Array.isArray(g)&&g.length==3){var x=g;if(x[0]==0){e:if(!d.u){if(d.g)if(d.g.F+3e3<a.F)qi(d),Bi(d);else break e;gu(d),Fe(18)}}else d.za=x[1],0<d.za-d.T&&37500>x[2]&&d.F&&d.v==0&&!d.C&&(d.C=ys(m(d.Za,d),6e3));if(1>=ad(d.h)&&d.ca){try{d.ca()}catch{}d.ca=void 0}}else wr(d,11)}else if((a.K||d.g==a)&&qi(d),!O(l))for(x=d.Da.g.parse(l),l=0;l<x.length;l++){let Z=x[l];if(d.T=Z[0],Z=Z[1],d.G==2)if(Z[0]=="c"){d.K=Z[1],d.ia=Z[2];let ke=Z[3];ke!=null&&(d.la=ke,d.j.info("VER="+d.la));let Oe=Z[4];Oe!=null&&(d.Aa=Oe,d.j.info("SVER="+d.Aa));let en=Z[5];en!=null&&typeof en=="number"&&0<en&&(g=1.5*en,d.L=g,d.j.info("backChannelRequestTimeoutMs_="+g)),g=d;let Xe=a.g;if(Xe){let Ki=Xe.g?Xe.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(Ki){var C=g.h;C.g||Ki.indexOf("spdy")==-1&&Ki.indexOf("quic")==-1&&Ki.indexOf("h2")==-1||(C.j=C.l,C.g=new Set,C.h&&(fu(C,C.h),C.h=null))}if(g.D){let _u=Xe.g?Xe.g.getResponseHeader("X-HTTP-Session-Id"):null;_u&&(g.ya=_u,ie(g.I,g.D,_u))}}d.G=3,d.l&&d.l.ua(),d.ba&&(d.R=Date.now()-a.F,d.j.info("Handshake RTT: "+d.R+"ms")),g=d;var L=a;if(g.qa=Dd(g,g.J?g.ia:null,g.W),L.K){ud(g.h,L);var re=L,Ae=g.L;Ae&&(re.I=Ae),re.B&&(lu(re),Vi(re)),g.g=L}else Rd(g);0<d.i.length&&$i(d)}else Z[0]!="stop"&&Z[0]!="close"||wr(d,7);else d.G==3&&(Z[0]=="stop"||Z[0]=="close"?Z[0]=="stop"?wr(d,7):mu(d):Z[0]!="noop"&&d.l&&d.l.ta(Z),d.v=0)}}gs(4)}catch{}}var Wv=class{constructor(a,l){this.g=a,this.map=l}};function id(a){this.l=a||10,u.PerformanceNavigationTiming?(a=u.performance.getEntriesByType("navigation"),a=0<a.length&&(a[0].nextHopProtocol=="hq"||a[0].nextHopProtocol=="h2")):a=!!(u.chrome&&u.chrome.loadTimes&&u.chrome.loadTimes()&&u.chrome.loadTimes().wasFetchedViaSpdy),this.j=a?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function od(a){return a.h?!0:a.g?a.g.size>=a.j:!1}function ad(a){return a.h?1:a.g?a.g.size:0}function du(a,l){return a.h?a.h==l:a.g?a.g.has(l):!1}function fu(a,l){a.g?a.g.add(l):a.h=l}function ud(a,l){a.h&&a.h==l?a.h=null:a.g&&a.g.has(l)&&a.g.delete(l)}id.prototype.cancel=function(){if(this.i=cd(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&this.g.size!==0){for(let a of this.g.values())a.cancel();this.g.clear()}};function cd(a){if(a.h!=null)return a.i.concat(a.h.D);if(a.g!=null&&a.g.size!==0){let l=a.i;for(let d of a.g.values())l=l.concat(d.D);return l}return R(a.i)}function Hv(a){if(a.V&&typeof a.V=="function")return a.V();if(typeof Map!="undefined"&&a instanceof Map||typeof Set!="undefined"&&a instanceof Set)return Array.from(a.values());if(typeof a=="string")return a.split("");if(c(a)){for(var l=[],d=a.length,g=0;g<d;g++)l.push(a[g]);return l}l=[],d=0;for(g in a)l[d++]=a[g];return l}function Qv(a){if(a.na&&typeof a.na=="function")return a.na();if(!a.V||typeof a.V!="function"){if(typeof Map!="undefined"&&a instanceof Map)return Array.from(a.keys());if(!(typeof Set!="undefined"&&a instanceof Set)){if(c(a)||typeof a=="string"){var l=[];a=a.length;for(var d=0;d<a;d++)l.push(d);return l}l=[],d=0;for(let g in a)l[d++]=g;return l}}}function ld(a,l){if(a.forEach&&typeof a.forEach=="function")a.forEach(l,void 0);else if(c(a)||typeof a=="string")Array.prototype.forEach.call(a,l,void 0);else for(var d=Qv(a),g=Hv(a),x=g.length,C=0;C<x;C++)l.call(void 0,g[C],d&&d[C],a)}var hd=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function Jv(a,l){if(a){a=a.split("&");for(var d=0;d<a.length;d++){var g=a[d].indexOf("="),x=null;if(0<=g){var C=a[d].substring(0,g);x=a[d].substring(g+1)}else C=a[d];l(C,x?decodeURIComponent(x.replace(/\+/g," ")):"")}}}function vr(a){if(this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,a instanceof vr){this.h=a.h,Li(this,a.j),this.o=a.o,this.g=a.g,Fi(this,a.s),this.l=a.l;var l=a.i,d=new Es;d.i=l.i,l.g&&(d.g=new Map(l.g),d.h=l.h),dd(this,d),this.m=a.m}else a&&(l=String(a).match(hd))?(this.h=!1,Li(this,l[1]||"",!0),this.o=ws(l[2]||""),this.g=ws(l[3]||"",!0),Fi(this,l[4]),this.l=ws(l[5]||"",!0),dd(this,l[6]||"",!0),this.m=ws(l[7]||"")):(this.h=!1,this.i=new Es(null,this.h))}vr.prototype.toString=function(){var a=[],l=this.j;l&&a.push(bs(l,fd,!0),":");var d=this.g;return(d||l=="file")&&(a.push("//"),(l=this.o)&&a.push(bs(l,fd,!0),"@"),a.push(encodeURIComponent(String(d)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),d=this.s,d!=null&&a.push(":",String(d))),(d=this.l)&&(this.g&&d.charAt(0)!="/"&&a.push("/"),a.push(bs(d,d.charAt(0)=="/"?Zv:Yv,!0))),(d=this.i.toString())&&a.push("?",d),(d=this.m)&&a.push("#",bs(d,tw)),a.join("")};function _t(a){return new vr(a)}function Li(a,l,d){a.j=d?ws(l,!0):l,a.j&&(a.j=a.j.replace(/:$/,""))}function Fi(a,l){if(l){if(l=Number(l),isNaN(l)||0>l)throw Error("Bad port number "+l);a.s=l}else a.s=null}function dd(a,l,d){l instanceof Es?(a.i=l,rw(a.i,a.h)):(d||(l=bs(l,ew)),a.i=new Es(l,a.h))}function ie(a,l,d){a.i.set(l,d)}function ji(a){return ie(a,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),a}function ws(a,l){return a?l?decodeURI(a.replace(/%25/g,"%2525")):decodeURIComponent(a):""}function bs(a,l,d){return typeof a=="string"?(a=encodeURI(a).replace(l,Xv),d&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),a):null}function Xv(a){return a=a.charCodeAt(0),"%"+(a>>4&15).toString(16)+(a&15).toString(16)}var fd=/[#\/\?@]/g,Yv=/[#\?:]/g,Zv=/[#\?]/g,ew=/[#\?@]/g,tw=/#/g;function Es(a,l){this.h=this.g=null,this.i=a||null,this.j=!!l}function Ut(a){a.g||(a.g=new Map,a.h=0,a.i&&Jv(a.i,function(l,d){a.add(decodeURIComponent(l.replace(/\+/g," ")),d)}))}r=Es.prototype,r.add=function(a,l){Ut(this),this.i=null,a=Yr(this,a);var d=this.g.get(a);return d||this.g.set(a,d=[]),d.push(l),this.h+=1,this};function pd(a,l){Ut(a),l=Yr(a,l),a.g.has(l)&&(a.i=null,a.h-=a.g.get(l).length,a.g.delete(l))}function md(a,l){return Ut(a),l=Yr(a,l),a.g.has(l)}r.forEach=function(a,l){Ut(this),this.g.forEach(function(d,g){d.forEach(function(x){a.call(l,x,g,this)},this)},this)},r.na=function(){Ut(this);let a=Array.from(this.g.values()),l=Array.from(this.g.keys()),d=[];for(let g=0;g<l.length;g++){let x=a[g];for(let C=0;C<x.length;C++)d.push(l[g])}return d},r.V=function(a){Ut(this);let l=[];if(typeof a=="string")md(this,a)&&(l=l.concat(this.g.get(Yr(this,a))));else{a=Array.from(this.g.values());for(let d=0;d<a.length;d++)l=l.concat(a[d])}return l},r.set=function(a,l){return Ut(this),this.i=null,a=Yr(this,a),md(this,a)&&(this.h-=this.g.get(a).length),this.g.set(a,[l]),this.h+=1,this},r.get=function(a,l){return a?(a=this.V(a),0<a.length?String(a[0]):l):l};function gd(a,l,d){pd(a,l),0<d.length&&(a.i=null,a.g.set(Yr(a,l),R(d)),a.h+=d.length)}r.toString=function(){if(this.i)return this.i;if(!this.g)return"";let a=[],l=Array.from(this.g.keys());for(var d=0;d<l.length;d++){var g=l[d];let C=encodeURIComponent(String(g)),L=this.V(g);for(g=0;g<L.length;g++){var x=C;L[g]!==""&&(x+="="+encodeURIComponent(String(L[g]))),a.push(x)}}return this.i=a.join("&")};function Yr(a,l){return l=String(l),a.j&&(l=l.toLowerCase()),l}function rw(a,l){l&&!a.j&&(Ut(a),a.i=null,a.g.forEach(function(d,g){var x=g.toLowerCase();g!=x&&(pd(this,g),gd(this,x,d))},a)),a.j=l}function nw(a,l){let d=new _s;if(u.Image){let g=new Image;g.onload=y(Bt,d,"TestLoadImage: loaded",!0,l,g),g.onerror=y(Bt,d,"TestLoadImage: error",!1,l,g),g.onabort=y(Bt,d,"TestLoadImage: abort",!1,l,g),g.ontimeout=y(Bt,d,"TestLoadImage: timeout",!1,l,g),u.setTimeout(function(){g.ontimeout&&g.ontimeout()},1e4),g.src=a}else l(!1)}function sw(a,l){let d=new _s,g=new AbortController,x=setTimeout(()=>{g.abort(),Bt(d,"TestPingServer: timeout",!1,l)},1e4);fetch(a,{signal:g.signal}).then(C=>{clearTimeout(x),C.ok?Bt(d,"TestPingServer: ok",!0,l):Bt(d,"TestPingServer: server error",!1,l)}).catch(()=>{clearTimeout(x),Bt(d,"TestPingServer: error",!1,l)})}function Bt(a,l,d,g,x){try{x&&(x.onload=null,x.onerror=null,x.onabort=null,x.ontimeout=null),g(d)}catch{}}function iw(){this.g=new Bv}function ow(a,l,d){let g=d||"";try{ld(a,function(x,C){let L=x;h(x)&&(L=nu(x)),l.push(g+C+"="+encodeURIComponent(L))})}catch(x){throw l.push(g+"type="+encodeURIComponent("_badmap")),x}}function Ts(a){this.l=a.Ub||null,this.j=a.eb||!1}T(Ts,su),Ts.prototype.g=function(){return new Mi(this.l,this.j)},Ts.prototype.i=(function(a){return function(){return a}})({});function Mi(a,l){Ce.call(this),this.D=a,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}T(Mi,Ce),r=Mi.prototype,r.open=function(a,l){if(this.readyState!=0)throw this.abort(),Error("Error reopening a connection");this.B=a,this.A=l,this.readyState=1,Ss(this)},r.send=function(a){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};a&&(l.body=a),(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,Is(this)),this.readyState=0},r.Sa=function(a){if(this.g&&(this.l=a,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=a.headers,this.readyState=2,Ss(this)),this.g&&(this.readyState=3,Ss(this),this.g)))if(this.responseType==="arraybuffer")a.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(typeof u.ReadableStream!="undefined"&&"body"in a){if(this.j=a.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;yd(this)}else a.text().then(this.Ra.bind(this),this.ga.bind(this))};function yd(a){a.j.read().then(a.Pa.bind(a)).catch(a.ga.bind(a))}r.Pa=function(a){if(this.g){if(this.o&&a.value)this.response.push(a.value);else if(!this.o){var l=a.value?a.value:new Uint8Array(0);(l=this.v.decode(l,{stream:!a.done}))&&(this.response=this.responseText+=l)}a.done?Is(this):Ss(this),this.readyState==3&&yd(this)}},r.Ra=function(a){this.g&&(this.response=this.responseText=a,Is(this))},r.Qa=function(a){this.g&&(this.response=a,Is(this))},r.ga=function(){this.g&&Is(this)};function Is(a){a.readyState=4,a.l=null,a.j=null,a.v=null,Ss(a)}r.setRequestHeader=function(a,l){this.u.append(a,l)},r.getResponseHeader=function(a){return this.h&&this.h.get(a.toLowerCase())||""},r.getAllResponseHeaders=function(){if(!this.h)return"";let a=[],l=this.h.entries();for(var d=l.next();!d.done;)d=d.value,a.push(d[0]+": "+d[1]),d=l.next();return a.join(`\r
|
|
21
|
-
`)};function
|
|
22
|
-
`}),
|
|
23
|
-
`);for(let g=0;g<a.length;g++){if(O(a[g]))continue;var d=A(a[g]);let x=d[0];if(d=d[1],typeof d!="string")continue;d=d.trim();let C=l[x]||[];l[x]=C,C.push(d)}E(l,function(g){return g.join(", ")})}r.Ba=function(){return this.m},r.Ka=function(){return typeof this.l=="string"?this.l:String(this.l)};function As(a,l,d){return d&&d.internalChannelParams&&d.internalChannelParams[a]||l}function Id(a){this.Aa=0,this.i=[],this.j=new _s,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=As("failFast",!1,a),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=As("baseRetryDelayMs",5e3,a),this.cb=As("retryDelaySeedMs",1e4,a),this.Wa=As("forwardChannelMaxRetries",2,a),this.wa=As("forwardChannelRequestTimeoutMs",2e4,a),this.pa=a&&a.xmlHttpFactory||void 0,this.Xa=a&&a.Tb||void 0,this.Ca=a&&a.useFetchStreams||!1,this.L=void 0,this.J=a&&a.supportsCrossDomainXhr||!1,this.K="",this.h=new id(a&&a.concurrentRequestLimit),this.Da=new iw,this.P=a&&a.fastHandshake||!1,this.O=a&&a.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=a&&a.Rb||!1,a&&a.xa&&this.j.xa(),a&&a.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&a&&a.detectBufferingProxy||!1,this.ja=void 0,a&&a.longPollingTimeout&&0<a.longPollingTimeout&&(this.ja=a.longPollingTimeout),this.ca=void 0,this.R=0,this.M=!1,this.ka=this.A=null}r=Id.prototype,r.la=8,r.G=1,r.connect=function(a,l,d,g){Fe(0),this.W=a,this.H=l||{},d&&g!==void 0&&(this.H.OSID=d,this.H.OAID=g),this.F=this.X,this.I=Dd(this,null,this.W),$i(this)};function mu(a){if(Sd(a),a.G==3){var l=a.U++,d=_t(a.I);if(ie(d,"SID",a.K),ie(d,"RID",l),ie(d,"TYPE","terminate"),xs(a,d),l=new Mt(a,a.j,l),l.L=2,l.v=ji(_t(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=Nd(l.j,null),l.g.ea(l.v)),l.F=Date.now(),Vi(l)}Od(a)}function Bi(a){a.g&&(yu(a),a.g.cancel(),a.g=null)}function Sd(a){Bi(a),a.u&&(u.clearTimeout(a.u),a.u=null),qi(a),a.h.cancel(),a.s&&(typeof a.s=="number"&&u.clearTimeout(a.s),a.s=null)}function $i(a){if(!od(a.h)&&!a.s){a.s=!0;var l=a.Ga;ls||Fh(),hs||(ls(),hs=!0),Ha.add(l,a),a.B=0}}function lw(a,l){return ad(a.h)>=a.h.j-(a.s?1:0)?!1:a.s?(a.i=l.D.concat(a.i),!0):a.G==1||a.G==2||a.B>=(a.Va?0:a.Wa)?!1:(a.s=ys(m(a.Ga,a,l),kd(a,a.B)),a.B++,!0)}r.Ga=function(a){if(this.s)if(this.s=null,this.G==1){if(!a){this.U=Math.floor(1e5*Math.random()),a=this.U++;let x=new Mt(this,this.j,a),C=this.o;if(this.S&&(C?(C=_(C),S(C,this.S)):C=this.S),this.m!==null||this.O||(x.H=C,C=null),this.P)e:{for(var l=0,d=0;d<this.i.length;d++){t:{var g=this.i[d];if("__data__"in g.map&&(g=g.map.__data__,typeof g=="string")){g=g.length;break t}g=void 0}if(g===void 0)break;if(l+=g,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=xd(this,x,l),d=_t(this.I),ie(d,"RID",a),ie(d,"CVER",22),this.D&&ie(d,"X-HTTP-Session-Id",this.D),xs(this,d),C&&(this.O?l="headers="+encodeURIComponent(String(_d(C)))+"&"+l:this.m&&pu(d,this.m,C)),fu(this.h,x),this.Ua&&ie(d,"TYPE","init"),this.P?(ie(d,"$req",l),ie(d,"SID","null"),x.T=!0,cu(x,d,null)):cu(x,d,l),this.G=2}}else this.G==3&&(a?Ad(this,a):this.i.length==0||od(this.h)||Ad(this))};function Ad(a,l){var d;l?d=l.l:d=a.U++;let g=_t(a.I);ie(g,"SID",a.K),ie(g,"RID",d),ie(g,"AID",a.T),xs(a,g),a.m&&a.o&&pu(g,a.m,a.o),d=new Mt(a,a.j,d,a.B+1),a.m===null&&(d.H=a.o),l&&(a.i=l.D.concat(a.i)),l=xd(a,d,1e3),d.I=Math.round(.5*a.wa)+Math.round(.5*a.wa*Math.random()),fu(a.h,d),cu(d,g,l)}function xs(a,l){a.H&&F(a.H,function(d,g){ie(l,g,d)}),a.l&&ld({},function(d,g){ie(l,g,d)})}function xd(a,l,d){d=Math.min(a.i.length,d);var g=a.l?m(a.l.Na,a.l,a):null;e:{var x=a.i;let C=-1;for(;;){let L=["count="+d];C==-1?0<d?(C=x[0].g,L.push("ofs="+C)):C=0:L.push("ofs="+C);let re=!0;for(let Ae=0;Ae<d;Ae++){let Z=x[Ae].g,ke=x[Ae].map;if(Z-=C,0>Z)C=Math.max(0,x[Ae].g-100),re=!1;else try{ow(ke,L,"req"+Z+"_")}catch{g&&g(ke)}}if(re){g=L.join("&");break e}}}return a=a.i.splice(0,d),l.D=a,g}function Rd(a){if(!a.g&&!a.u){a.Y=1;var l=a.Fa;ls||Fh(),hs||(ls(),hs=!0),Ha.add(l,a),a.v=0}}function gu(a){return a.g||a.u||3<=a.v?!1:(a.Y++,a.u=ys(m(a.Fa,a),kd(a,a.v)),a.v++,!0)}r.Fa=function(){if(this.u=null,Pd(this),this.ba&&!(this.M||this.g==null||0>=this.R)){var a=2*this.R;this.j.info("BP detection timer enabled: "+a),this.A=ys(m(this.ab,this),a)}},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,Fe(10),Bi(this),Pd(this))};function yu(a){a.A!=null&&(u.clearTimeout(a.A),a.A=null)}function Pd(a){a.g=new Mt(a,a.j,"rpc",a.Y),a.m===null&&(a.g.H=a.o),a.g.O=0;var l=_t(a.qa);ie(l,"RID","rpc"),ie(l,"SID",a.K),ie(l,"AID",a.T),ie(l,"CI",a.F?"0":"1"),!a.F&&a.ja&&ie(l,"TO",a.ja),ie(l,"TYPE","xmlhttp"),xs(a,l),a.m&&a.o&&pu(l,a.m,a.o),a.L&&(a.g.I=a.L);var d=a.g;a=a.ia,d.L=1,d.v=ji(_t(l)),d.m=null,d.P=!0,rd(d,a)}r.Za=function(){this.C!=null&&(this.C=null,Bi(this),gu(this),Fe(19))};function qi(a){a.C!=null&&(u.clearTimeout(a.C),a.C=null)}function Cd(a,l){var d=null;if(a.g==l){qi(a),yu(a),a.g=null;var g=2}else if(du(a.h,l))d=l.D,ud(a.h,l),g=1;else return;if(a.G!=0){if(l.o)if(g==1){d=l.m?l.m.length:0,l=Date.now()-l.F;var x=a.B;g=Oi(),Le(g,new Yh(g,d)),$i(a)}else Rd(a);else if(x=l.s,x==3||x==0&&0<l.X||!(g==1&&lw(a,l)||g==2&&gu(a)))switch(d&&0<d.length&&(l=a.h,l.i=l.i.concat(d)),x){case 1:wr(a,5);break;case 4:wr(a,10);break;case 3:wr(a,6);break;default:wr(a,2)}}}function kd(a,l){let d=a.Ta+Math.floor(Math.random()*a.cb);return a.isActive()||(d*=2),d*l}function wr(a,l){if(a.j.info("Error code "+l),l==2){var d=m(a.fb,a),g=a.Xa;let x=!g;g=new vr(g||"//www.google.com/images/cleardot.gif"),u.location&&u.location.protocol=="http"||Li(g,"https"),ji(g),x?nw(g.toString(),d):sw(g.toString(),d)}else Fe(2);a.G=0,a.l&&a.l.sa(l),Od(a),Sd(a)}r.fb=function(a){a?(this.j.info("Successfully pinged google.com"),Fe(2)):(this.j.info("Failed to ping google.com"),Fe(1))};function Od(a){if(a.G=0,a.ka=[],a.l){let l=cd(a.h);(l.length!=0||a.i.length!=0)&&(I(a.ka,l),I(a.ka,a.i),a.h.i.length=0,R(a.i),a.i.length=0),a.l.ra()}}function Dd(a,l,d){var g=d instanceof vr?_t(d):new vr(d);if(g.g!="")l&&(g.g=l+"."+g.g),Fi(g,g.s);else{var x=u.location;g=x.protocol,l=l?l+"."+x.hostname:x.hostname,x=+x.port;var C=new vr(null);g&&Li(C,g),l&&(C.g=l),x&&Fi(C,x),d&&(C.l=d),g=C}return d=a.D,l=a.ya,d&&l&&ie(g,d,l),ie(g,"VER",a.la),xs(a,g),g}function Nd(a,l,d){if(l&&!a.J)throw Error("Can't create secondary domain capable XhrIo object.");return l=a.Ca&&!a.pa?new ce(new Ts({eb:d})):new ce(a.pa),l.Ha(a.J),l}r.isActive=function(){return!!this.l&&this.l.isActive(this)};function Vd(){}r=Vd.prototype,r.ua=function(){},r.ta=function(){},r.sa=function(){},r.ra=function(){},r.isActive=function(){return!0},r.Na=function(){};function zi(){}zi.prototype.g=function(a,l){return new Be(a,l)};function Be(a,l){Ce.call(this),this.g=new Id(l),this.l=a,this.h=l&&l.messageUrlParams||null,a=l&&l.messageHeaders||null,l&&l.clientProtocolHeaderRequired&&(a?a["X-Client-Protocol"]="webchannel":a={"X-Client-Protocol":"webchannel"}),this.g.o=a,a=l&&l.initMessageHeaders||null,l&&l.messageContentType&&(a?a["X-WebChannel-Content-Type"]=l.messageContentType:a={"X-WebChannel-Content-Type":l.messageContentType}),l&&l.va&&(a?a["X-WebChannel-Client-Profile"]=l.va:a={"X-WebChannel-Client-Profile":l.va}),this.g.S=a,(a=l&&l.Sb)&&!O(a)&&(this.g.m=a),this.v=l&&l.supportsCrossDomainXhr||!1,this.u=l&&l.sendRawJson||!1,(l=l&&l.httpSessionIdParam)&&!O(l)&&(this.g.D=l,a=this.h,a!==null&&l in a&&(a=this.h,l in a&&delete a[l])),this.j=new Zr(this)}T(Be,Ce),Be.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},Be.prototype.close=function(){mu(this.g)},Be.prototype.o=function(a){var l=this.g;if(typeof a=="string"){var d={};d.__data__=a,a=d}else this.u&&(d={},d.__data__=nu(a),a=d);l.i.push(new Wv(l.Ya++,a)),l.G==3&&$i(l)},Be.prototype.N=function(){this.g.l=null,delete this.j,mu(this.g),delete this.g,Be.aa.N.call(this)};function Ld(a){iu.call(this),a.__headers__&&(this.headers=a.__headers__,this.statusCode=a.__status__,delete a.__headers__,delete a.__status__);var l=a.__sm__;if(l){e:{for(let d in l){a=d;break e}a=void 0}(this.i=a)&&(a=this.i,l=l!==null&&a in l?l[a]:void 0),this.data=l}else this.data=a}T(Ld,iu);function Fd(){ou.call(this),this.status=1}T(Fd,ou);function Zr(a){this.g=a}T(Zr,Vd),Zr.prototype.ua=function(){Le(this.g,"a")},Zr.prototype.ta=function(a){Le(this.g,new Ld(a))},Zr.prototype.sa=function(a){Le(this.g,new Fd)},Zr.prototype.ra=function(){Le(this.g,"b")},zi.prototype.createWebChannel=zi.prototype.g,Be.prototype.send=Be.prototype.o,Be.prototype.open=Be.prototype.m,Be.prototype.close=Be.prototype.close,Yu=Rt.createWebChannelTransport=function(){return new zi},Xu=Rt.getStatEventTarget=function(){return Oi()},Ju=Rt.Event=yr,Io=Rt.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},Di.NO_ERROR=0,Di.TIMEOUT=8,Di.HTTP_ERROR=6,js=Rt.ErrorCode=Di,Zh.COMPLETE="complete",Qu=Rt.EventType=Zh,Hh.EventType=ms,ms.OPEN="a",ms.CLOSE="b",ms.ERROR="c",ms.MESSAGE="d",Ce.prototype.listen=Ce.prototype.K,En=Rt.WebChannel=Hh,ZA=Rt.FetchXmlHttpFactory=Ts,ce.prototype.listenOnce=ce.prototype.L,ce.prototype.getLastError=ce.prototype.Ka,ce.prototype.getLastErrorCode=ce.prototype.Ba,ce.prototype.getStatus=ce.prototype.Z,ce.prototype.getResponseJson=ce.prototype.Oa,ce.prototype.getResponseText=ce.prototype.oa,ce.prototype.send=ce.prototype.ea,ce.prototype.setWithCredentials=ce.prototype.Ha,Hu=Rt.XhrIo=ce}).apply(typeof To!="undefined"?To:typeof self!="undefined"?self:typeof window!="undefined"?window:{});var Gm="@firebase/firestore",Wm="4.8.0";var Te=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}};Te.UNAUTHENTICATED=new Te(null),Te.GOOGLE_CREDENTIALS=new Te("google-credentials-uid"),Te.FIRST_PARTY=new Te("first-party-uid"),Te.MOCK_USER=new Te("mock-user");var Gn="11.10.0";var Rr=new bn("@firebase/firestore");function Tn(){return Rr.logLevel}function M(r,...e){if(Rr.logLevel<=X.DEBUG){let t=e.map(jl);Rr.debug(`Firestore (${Gn}): ${r}`,...t)}}function Pt(r,...e){if(Rr.logLevel<=X.ERROR){let t=e.map(jl);Rr.error(`Firestore (${Gn}): ${r}`,...t)}}function ar(r,...e){if(Rr.logLevel<=X.WARN){let t=e.map(jl);Rr.warn(`Firestore (${Gn}): ${r}`,...t)}}function jl(r){if(typeof r=="string")return r;try{return(function(t){return JSON.stringify(t)})(r)}catch{return r}}function z(r,e,t){let n="Unexpected state";typeof e=="string"?n=e:t=e,Vg(r,n,t)}function Vg(r,e,t){let n=`FIRESTORE (${Gn}) INTERNAL ASSERTION FAILED: ${e} (ID: ${r.toString(16)})`;if(t!==void 0)try{n+=" CONTEXT: "+JSON.stringify(t)}catch{n+=" CONTEXT: "+t}throw Pt(n),new Error(n)}function te(r,e,t,n){let s="Unexpected state";typeof t=="string"?s=t:n=t,r||Vg(e,s,n)}function G(r,e){return r}var N={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"},B=class extends et{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}};var at=class{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}};var ko=class{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}},nc=class{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(Te.UNAUTHENTICATED)))}shutdown(){}},sc=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}},ic=class{constructor(e){this.t=e,this.currentUser=Te.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){te(this.o===void 0,42304);let n=this.i,s=c=>this.i!==n?(n=this.i,t(c)):Promise.resolve(),i=new at;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new at,e.enqueueRetryable((()=>s(this.currentUser)))};let o=()=>{let c=i;e.enqueueRetryable((async()=>{await c.promise,await s(this.currentUser)}))},u=c=>{M("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=c,this.o&&(this.auth.addAuthTokenListener(this.o),o())};this.t.onInit((c=>u(c))),setTimeout((()=>{if(!this.auth){let c=this.t.getImmediate({optional:!0});c?u(c):(M("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new at)}}),0),o()}getToken(){let e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((n=>this.i!==e?(M("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):n?(te(typeof n.accessToken=="string",31837,{l:n}),new ko(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 te(e===null||typeof e=="string",2055,{h:e}),new Te(e)}},oc=class{constructor(e,t,n){this.P=e,this.T=t,this.I=n,this.type="FirstParty",this.user=Te.FIRST_PARTY,this.A=new Map}R(){return this.I?this.I():null}get headers(){this.A.set("X-Goog-AuthUser",this.P);let e=this.R();return e&&this.A.set("Authorization",e),this.T&&this.A.set("X-Goog-Iam-Authorization-Token",this.T),this.A}},ac=class{constructor(e,t,n){this.P=e,this.T=t,this.I=n}getToken(){return Promise.resolve(new oc(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable((()=>t(Te.FIRST_PARTY)))}shutdown(){}invalidateToken(){}},Oo=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)}},uc=class{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,Mm(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,t){te(this.o===void 0,3512);let n=i=>{i.error!=null&&M("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${i.error.message}`);let o=i.token!==this.m;return this.m=i.token,M("FirebaseAppCheckTokenProvider",`Received ${o?"new":"existing"} token.`),o?t(i.token):Promise.resolve()};this.o=i=>{e.enqueueRetryable((()=>n(i)))};let s=i=>{M("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=i,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit((i=>s(i))),setTimeout((()=>{if(!this.appCheck){let i=this.V.getImmediate({optional:!0});i?s(i):M("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){if(this.p)return Promise.resolve(new Oo(this.p));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((t=>t?(te(typeof t.token=="string",44558,{tokenResult:t}),this.m=t.token,new Oo(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 ex(r){let e=typeof self!="undefined"&&(self.crypto||self.msCrypto),t=new Uint8Array(r);if(e&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let n=0;n<r;n++)t[n]=Math.floor(256*Math.random());return t}function Lg(){return new TextEncoder}var zs=class{static newId(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(4.129032258064516),n="";for(;n.length<20;){let s=ex(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 cc(r,e){let t=0;for(;t<r.length&&t<e.length;){let n=r.codePointAt(t),s=e.codePointAt(t);if(n!==s){if(n<128&&s<128)return Q(n,s);{let i=Lg(),o=tx(i.encode(Hm(r,t)),i.encode(Hm(e,t)));return o!==0?o:Q(n,s)}}t+=n>65535?2:1}return Q(r.length,e.length)}function Hm(r,e){return r.codePointAt(e)>65535?r.substring(e,e+2):r.substring(e,e+1)}function tx(r,e){for(let t=0;t<r.length&&t<e.length;++t)if(r[t]!==e[t])return Q(r[t],e[t]);return Q(r.length,e.length)}function kn(r,e,t){return r.length===e.length&&r.every(((n,s)=>t(n,e[s])))}var Qm="__name__",Do=class r{constructor(e,t,n){t===void 0?t=0:t>e.length&&z(637,{offset:t,range:e.length}),n===void 0?n=e.length-t:n>e.length-t&&z(1746,{length:n,range:e.length-t}),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 Q(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)):cc(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return xt.fromString(e.substring(4,e.length-2))}},pe=class r extends Do{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 B(N.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([])}},rx=/^[_a-zA-Z][_a-zA-Z0-9]*$/,qe=class r extends Do{construct(e,t,n){return new r(e,t,n)}static isValidIdentifier(e){return rx.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)===Qm}static keyField(){return new r([Qm])}static fromServerFormat(e){let t=[],n="",s=0,i=()=>{if(n.length===0)throw new B(N.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""},o=!1;for(;s<e.length;){let u=e[s];if(u==="\\"){if(s+1===e.length)throw new B(N.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let c=e[s+1];if(c!=="\\"&&c!=="."&&c!=="`")throw new B(N.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=c,s+=2}else u==="`"?(o=!o,s++):u!=="."||o?(n+=u,s++):(i(),s++)}if(i(),o)throw new B(N.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new r(t)}static emptyPath(){return new r([])}};var K=class r{constructor(e){this.path=e}static fromPath(e){return new r(pe.fromString(e))}static fromName(e){return new r(pe.fromString(e).popFirst(5))}static empty(){return new r(pe.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&&pe.comparator(this.path,e.path)===0}toString(){return this.path.toString()}static comparator(e,t){return pe.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new r(new pe(e.slice()))}};function nx(r,e,t){if(!t)throw new B(N.INVALID_ARGUMENT,`Function ${r}() cannot be called with an empty ${e}.`)}function sx(r,e,t,n){if(e===!0&&n===!0)throw new B(N.INVALID_ARGUMENT,`${r} and ${t} cannot be used together.`)}function Jm(r){if(!K.isDocumentKey(r))throw new B(N.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${r} has ${r.length}.`)}function Fg(r){return typeof r=="object"&&r!==null&&(Object.getPrototypeOf(r)===Object.prototype||Object.getPrototypeOf(r)===null)}function Ml(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":z(12329,{type:typeof r})}function ut(r,e){if("_delegate"in r&&(r=r._delegate),!(r instanceof e)){if(e.name===r.constructor.name)throw new B(N.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let t=Ml(r);throw new B(N.INVALID_ARGUMENT,`Expected type '${e.name}', but it was: ${t}`)}}return r}function ye(r,e){let t={typeString:r};return e&&(t.value=e),t}function ni(r,e){if(!Fg(r))throw new B(N.INVALID_ARGUMENT,"JSON must be an object");let t;for(let n in e)if(e[n]){let s=e[n].typeString,i="value"in e[n]?{value:e[n].value}:void 0;if(!(n in r)){t=`JSON missing required field: '${n}'`;break}let o=r[n];if(s&&typeof o!==s){t=`JSON field '${n}' must be a ${s}.`;break}if(i!==void 0&&o!==i.value){t=`Expected '${n}' field to equal '${i.value}'`;break}}if(t)throw new B(N.INVALID_ARGUMENT,t);return!0}var Xm=-62135596800,Ym=1e6,_e=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)*Ym);return new r(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new B(N.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new B(N.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<Xm)throw new B(N.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new B(N.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/Ym}_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{type:r._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(ni(e,r._jsonSchema))return new r(e.seconds,e.nanoseconds)}valueOf(){let e=this.seconds-Xm;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}};_e._jsonSchemaVersion="firestore/timestamp/1.0",_e._jsonSchema={type:ye("string",_e._jsonSchemaVersion),seconds:ye("number"),nanoseconds:ye("number")};var W=class r{static fromTimestamp(e){return new r(e)}static min(){return new r(new _e(0,0))}static max(){return new r(new _e(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 Ks=-1,lc=class{constructor(e,t,n,s){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=s}};lc.UNKNOWN_ID=-1;function ix(r,e){let t=r.toTimestamp().seconds,n=r.toTimestamp().nanoseconds+1,s=W.fromTimestamp(n===1e9?new _e(t+1,0):new _e(t,n));return new Pr(s,K.empty(),e)}function ox(r){return new Pr(r.readTime,r.key,Ks)}var Pr=class r{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new r(W.min(),K.empty(),Ks)}static max(){return new r(W.max(),K.empty(),Ks)}};function ax(r,e){let t=r.readTime.compareTo(e.readTime);return t!==0?t:(t=K.comparator(r.documentKey,e.documentKey),t!==0?t:Q(r.largestBatchId,e.largestBatchId))}var ux="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",hc=class{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}};async function Wn(r){if(r.code!==N.FAILED_PRECONDITION||r.message!==ux)throw r;M("LocalStore","Unexpectedly lost primary lease")}var V=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&&z(59440),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,o=!1;e.forEach((u=>{++s,u.next((()=>{++i,o&&i===s&&t()}),(c=>n(c)))})),o=!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,o=new Array(i),u=0;for(let c=0;c<i;c++){let h=c;t(e[h]).next((f=>{o[h]=f,++u,u===i&&n(o)}),(f=>s(f)))}}))}static doWhile(e,t){return new r(((n,s)=>{let i=()=>{e()===!0?t().next((()=>{i()}),s):n()};i()}))}};function cx(r){let e=r.match(/Android ([\d.]+)/i),t=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(t)}function Hn(r){return r.name==="IndexedDbTransactionError"}var On=class{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=n=>this._e(n),this.ae=n=>t.writeSequenceNumber(n))}_e(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this.ae&&this.ae(e),e}};On.ue=-1;var Ul=-1;function fa(r){return r==null}function Gs(r){return r===0&&1/r==-1/0}function lx(r){return typeof r=="number"&&Number.isInteger(r)&&!Gs(r)&&r<=Number.MAX_SAFE_INTEGER&&r>=Number.MIN_SAFE_INTEGER}var jg="";function hx(r){let e="";for(let t=0;t<r.length;t++)e.length>0&&(e=Zm(e)),e=dx(r.get(t),e);return Zm(e)}function dx(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 jg:t+="";break;default:t+=i}}return t}function Zm(r){return r+jg+""}var fx="remoteDocuments",Mg="owner";var Ug="mutationQueues";var Bg="mutations";var $g="documentMutations",px="remoteDocumentsV14";var qg="remoteDocumentGlobal";var zg="targets";var Kg="targetDocuments";var Gg="targetGlobal",Wg="collectionParents";var Hg="clientMetadata";var Qg="bundles";var Jg="namedQueries";var mx="indexConfiguration";var gx="indexState";var yx="indexEntries";var Xg="documentOverlays";var _x="globals";var vx=[Ug,Bg,$g,fx,zg,Mg,Gg,Kg,Hg,qg,Wg,Qg,Jg],xj=[...vx,Xg],wx=[Ug,Bg,$g,px,zg,Mg,Gg,Kg,Hg,qg,Wg,Qg,Jg,Xg],bx=wx,Ex=[...bx,mx,gx,yx];var Rj=[...Ex,_x];function eg(r){let e=0;for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e++;return e}function dr(r,e){for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e(t,r[t])}function Yg(r){for(let e in r)if(Object.prototype.hasOwnProperty.call(r,e))return!1;return!0}var he=class r{constructor(e,t){this.comparator=e,this.root=t||ct.EMPTY}insert(e,t){return new r(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,ct.BLACK,null,null))}remove(e){return new r(this.comparator,this.root.remove(e,this.comparator).copy(null,null,ct.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 xn(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new xn(this.root,e,this.comparator,!1)}getReverseIterator(){return new xn(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new xn(this.root,e,this.comparator,!0)}},xn=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}}},ct=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())throw z(43730,{key:this.key,value:this.value});if(this.right.isRed())throw z(14113,{key:this.key,value:this.value});let e=this.left.check();if(e!==this.right.check())throw z(27949);return e+(this.isRed()?0:1)}};ct.EMPTY=null,ct.RED=!0,ct.BLACK=!1;ct.EMPTY=new class{constructor(){this.size=0}get key(){throw z(57766)}get value(){throw z(16141)}get color(){throw z(16727)}get left(){throw z(29726)}get right(){throw z(36894)}copy(e,t,n,s,i){return this}insert(e,t,n){return new ct(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 Ie=class r{constructor(e){this.comparator=e,this.data=new he(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 No(this.data.getIterator())}getIteratorFrom(e){return new No(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}},No=class{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}};var We=class r{constructor(e){this.fields=e,e.sort(qe.comparator)}static empty(){return new r([])}unionWith(e){let t=new Ie(qe.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 kn(this.fields,e.fields,((t,n)=>t.isEqual(n)))}};var Vo=class extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}};var Ve=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 Vo("Invalid base64 string: "+i):i}})(e);return new r(t)}static fromUint8Array(e){let t=(function(s){let i="";for(let o=0;o<s.length;++o)i+=String.fromCharCode(s[o]);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}};Ve.EMPTY_BYTE_STRING=new Ve("");var Tx=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Ct(r){if(te(!!r,39018),typeof r=="string"){let e=0,t=Tx.exec(r);if(te(!!t,46558,{timestamp:r}),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 kt(r){return typeof r=="string"?Ve.fromBase64String(r):Ve.fromUint8Array(r)}var Zg="server_timestamp",ey="__type__",ty="__previous_value__",ry="__local_write_time__";function Bl(r){var e,t;return((t=(((e=r==null?void 0:r.mapValue)===null||e===void 0?void 0:e.fields)||{})[ey])===null||t===void 0?void 0:t.stringValue)===Zg}function pa(r){let e=r.mapValue.fields[ty];return Bl(e)?pa(e):e}function Ws(r){let e=Ct(r.mapValue.fields[ry].timestampValue);return new _e(e.seconds,e.nanos)}var dc=class{constructor(e,t,n,s,i,o,u,c,h,f){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=s,this.ssl=i,this.forceLongPolling=o,this.autoDetectLongPolling=u,this.longPollingOptions=c,this.useFetchStreams=h,this.isUsingEmulator=f}},Lo="(default)",Fo=class r{constructor(e,t){this.projectId=e,this.database=t||Lo}static empty(){return new r("","")}get isDefaultDatabase(){return this.database===Lo}isEqual(e){return e instanceof r&&e.projectId===this.projectId&&e.database===this.database}};var $l="__type__",ny="__max__",So={mapValue:{fields:{__type__:{stringValue:ny}}}},ql="__vector__",Dn="value";function ur(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?Bl(r)?4:iy(r)?9007199254740991:sy(r)?10:11:z(28295,{value:r})}function dt(r,e){if(r===e)return!0;let t=ur(r);if(t!==ur(e))return!1;switch(t){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===e.booleanValue;case 4:return Ws(r).isEqual(Ws(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 o=Ct(s.timestampValue),u=Ct(i.timestampValue);return o.seconds===u.seconds&&o.nanos===u.nanos})(r,e);case 5:return r.stringValue===e.stringValue;case 6:return(function(s,i){return kt(s.bytesValue).isEqual(kt(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 o=ae(s.doubleValue),u=ae(i.doubleValue);return o===u?Gs(o)===Gs(u):isNaN(o)&&isNaN(u)}return!1})(r,e);case 9:return kn(r.arrayValue.values||[],e.arrayValue.values||[],dt);case 10:case 11:return(function(s,i){let o=s.mapValue.fields||{},u=i.mapValue.fields||{};if(eg(o)!==eg(u))return!1;for(let c in o)if(o.hasOwnProperty(c)&&(u[c]===void 0||!dt(o[c],u[c])))return!1;return!0})(r,e);default:return z(52216,{left:r})}}function Hs(r,e){return(r.values||[]).find((t=>dt(t,e)))!==void 0}function Nn(r,e){if(r===e)return 0;let t=ur(r),n=ur(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,o){let u=ae(i.integerValue||i.doubleValue),c=ae(o.integerValue||o.doubleValue);return u<c?-1:u>c?1:u===c?0:isNaN(u)?isNaN(c)?0:-1:1})(r,e);case 3:return tg(r.timestampValue,e.timestampValue);case 4:return tg(Ws(r),Ws(e));case 5:return cc(r.stringValue,e.stringValue);case 6:return(function(i,o){let u=kt(i),c=kt(o);return u.compareTo(c)})(r.bytesValue,e.bytesValue);case 7:return(function(i,o){let u=i.split("/"),c=o.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,o){let u=Q(ae(i.latitude),ae(o.latitude));return u!==0?u:Q(ae(i.longitude),ae(o.longitude))})(r.geoPointValue,e.geoPointValue);case 9:return rg(r.arrayValue,e.arrayValue);case 10:return(function(i,o){var u,c,h,f;let p=i.fields||{},m=o.fields||{},y=(u=p[Dn])===null||u===void 0?void 0:u.arrayValue,T=(c=m[Dn])===null||c===void 0?void 0:c.arrayValue,R=Q(((h=y==null?void 0:y.values)===null||h===void 0?void 0:h.length)||0,((f=T==null?void 0:T.values)===null||f===void 0?void 0:f.length)||0);return R!==0?R:rg(y,T)})(r.mapValue,e.mapValue);case 11:return(function(i,o){if(i===So.mapValue&&o===So.mapValue)return 0;if(i===So.mapValue)return 1;if(o===So.mapValue)return-1;let u=i.fields||{},c=Object.keys(u),h=o.fields||{},f=Object.keys(h);c.sort(),f.sort();for(let p=0;p<c.length&&p<f.length;++p){let m=cc(c[p],f[p]);if(m!==0)return m;let y=Nn(u[c[p]],h[f[p]]);if(y!==0)return y}return Q(c.length,f.length)})(r.mapValue,e.mapValue);default:throw z(23264,{le:t})}}function tg(r,e){if(typeof r=="string"&&typeof e=="string"&&r.length===e.length)return Q(r,e);let t=Ct(r),n=Ct(e),s=Q(t.seconds,n.seconds);return s!==0?s:Q(t.nanos,n.nanos)}function rg(r,e){let t=r.values||[],n=e.values||[];for(let s=0;s<t.length&&s<n.length;++s){let i=Nn(t[s],n[s]);if(i)return i}return Q(t.length,n.length)}function Vn(r){return fc(r)}function fc(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=Ct(t);return`time(${n.seconds},${n.nanos})`})(r.timestampValue):"stringValue"in r?r.stringValue:"bytesValue"in r?(function(t){return kt(t).toBase64()})(r.bytesValue):"referenceValue"in r?(function(t){return K.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+=fc(i);return n+"]"})(r.arrayValue):"mapValue"in r?(function(t){let n=Object.keys(t.fields||{}).sort(),s="{",i=!0;for(let o of n)i?i=!1:s+=",",s+=`${o}:${fc(t.fields[o])}`;return s+"}"})(r.mapValue):z(61005,{value:r})}function Ro(r){switch(ur(r)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let e=pa(r);return e?16+Ro(e):16;case 5:return 2*r.stringValue.length;case 6:return kt(r.bytesValue).approximateByteSize();case 7:return r.referenceValue.length;case 9:return(function(n){return(n.values||[]).reduce(((s,i)=>s+Ro(i)),0)})(r.arrayValue);case 10:case 11:return(function(n){let s=0;return dr(n.fields,((i,o)=>{s+=i.length+Ro(o)})),s})(r.mapValue);default:throw z(13486,{value:r})}}function pc(r){return!!r&&"integerValue"in r}function zl(r){return!!r&&"arrayValue"in r}function ng(r){return!!r&&"nullValue"in r}function sg(r){return!!r&&"doubleValue"in r&&isNaN(Number(r.doubleValue))}function Po(r){return!!r&&"mapValue"in r}function sy(r){var e,t;return((t=(((e=r==null?void 0:r.mapValue)===null||e===void 0?void 0:e.fields)||{})[$l])===null||t===void 0?void 0:t.stringValue)===ql}function Us(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 dr(r.mapValue.fields,((t,n)=>e.mapValue.fields[t]=Us(n))),e}if(r.arrayValue){let e={arrayValue:{values:[]}};for(let t=0;t<(r.arrayValue.values||[]).length;++t)e.arrayValue.values[t]=Us(r.arrayValue.values[t]);return e}return Object.assign({},r)}function iy(r){return(((r.mapValue||{}).fields||{}).__type__||{}).stringValue===ny}var Cj={mapValue:{fields:{[$l]:{stringValue:ql},[Dn]:{arrayValue:{}}}}};var $e=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)],!Po(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Us(t)}setAll(e){let t=qe.emptyPath(),n={},s=[];e.forEach(((o,u)=>{if(!t.isImmediateParentOf(u)){let c=this.getFieldsMap(t);this.applyChanges(c,n,s),n={},s=[],t=u.popLast()}o?n[u.lastSegment()]=Us(o):s.push(u.lastSegment())}));let i=this.getFieldsMap(t);this.applyChanges(i,n,s)}delete(e){let t=this.field(e.popLast());Po(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return dt(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)];Po(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=s),t=s}return t.mapValue.fields}applyChanges(e,t,n){dr(t,((s,i)=>e[s]=i));for(let s of n)delete e[s]}clone(){return new r(Us(this.value))}};function oy(r){let e=[];return dr(r.fields,((t,n)=>{let s=new qe([t]);if(Po(n)){let i=oy(n.mapValue).fields;if(i.length===0)e.push(s);else for(let o of i)e.push(s.child(o))}else e.push(s)})),new We(e)}var tt=class r{constructor(e,t,n,s,i,o,u){this.key=e,this.documentType=t,this.version=n,this.readTime=s,this.createTime=i,this.data=o,this.documentState=u}static newInvalidDocument(e){return new r(e,0,W.min(),W.min(),W.min(),$e.empty(),0)}static newFoundDocument(e,t,n,s){return new r(e,1,t,W.min(),n,s,0)}static newNoDocument(e,t){return new r(e,2,t,W.min(),W.min(),$e.empty(),0)}static newUnknownDocument(e,t){return new r(e,3,t,W.min(),W.min(),$e.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(W.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=$e.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=$e.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=W.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 Ln=class{constructor(e,t){this.position=e,this.inclusive=t}};function ig(r,e,t){let n=0;for(let s=0;s<r.position.length;s++){let i=e[s],o=r.position[s];if(i.field.isKeyField()?n=K.comparator(K.fromName(o.referenceValue),t.key):n=Nn(o,t.data.field(i.field)),i.dir==="desc"&&(n*=-1),n!==0)break}return n}function og(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(!dt(r.position[t],e.position[t]))return!1;return!0}var Fn=class{constructor(e,t="asc"){this.field=e,this.dir=t}};function Ix(r,e){return r.dir===e.dir&&r.field.isEqual(e.field)}var jo=class{},we=class r extends jo{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 gc(e,t,n):t==="array-contains"?new vc(e,n):t==="in"?new wc(e,n):t==="not-in"?new bc(e,n):t==="array-contains-any"?new Ec(e,n):new r(e,t,n)}static createKeyFieldInFilter(e,t,n){return t==="in"?new yc(e,n):new _c(e,n)}matches(e){let t=e.data.field(this.field);return this.op==="!="?t!==null&&t.nullValue===void 0&&this.matchesComparison(Nn(t,this.value)):t!==null&&ur(this.value)===ur(t)&&this.matchesComparison(Nn(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 z(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}},ft=class r extends jo{constructor(e,t){super(),this.filters=e,this.op=t,this.he=null}static create(e,t){return new r(e,t)}matches(e){return ay(this)?this.filters.find((t=>!t.matches(e)))===void 0:this.filters.find((t=>t.matches(e)))!==void 0}getFlattenedFilters(){return this.he!==null||(this.he=this.filters.reduce(((e,t)=>e.concat(t.getFlattenedFilters())),[])),this.he}getFilters(){return Object.assign([],this.filters)}};function ay(r){return r.op==="and"}function uy(r){return Sx(r)&&ay(r)}function Sx(r){for(let e of r.filters)if(e instanceof ft)return!1;return!0}function mc(r){if(r instanceof we)return r.field.canonicalString()+r.op.toString()+Vn(r.value);if(uy(r))return r.filters.map((e=>mc(e))).join(",");{let e=r.filters.map((t=>mc(t))).join(",");return`${r.op}(${e})`}}function cy(r,e){return r instanceof we?(function(n,s){return s instanceof we&&n.op===s.op&&n.field.isEqual(s.field)&&dt(n.value,s.value)})(r,e):r instanceof ft?(function(n,s){return s instanceof ft&&n.op===s.op&&n.filters.length===s.filters.length?n.filters.reduce(((i,o,u)=>i&&cy(o,s.filters[u])),!0):!1})(r,e):void z(19439)}function ly(r){return r instanceof we?(function(t){return`${t.field.canonicalString()} ${t.op} ${Vn(t.value)}`})(r):r instanceof ft?(function(t){return t.op.toString()+" {"+t.getFilters().map(ly).join(" ,")+"}"})(r):"Filter"}var gc=class extends we{constructor(e,t,n){super(e,t,n),this.key=K.fromName(n.referenceValue)}matches(e){let t=K.comparator(e.key,this.key);return this.matchesComparison(t)}},yc=class extends we{constructor(e,t){super(e,"in",t),this.keys=hy("in",t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}},_c=class extends we{constructor(e,t){super(e,"not-in",t),this.keys=hy("not-in",t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}};function hy(r,e){var t;return(((t=e.arrayValue)===null||t===void 0?void 0:t.values)||[]).map((n=>K.fromName(n.referenceValue)))}var vc=class extends we{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return zl(t)&&Hs(t.arrayValue,this.value)}},wc=class extends we{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return t!==null&&Hs(this.value.arrayValue,t)}},bc=class extends we{constructor(e,t){super(e,"not-in",t)}matches(e){if(Hs(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return t!==null&&t.nullValue===void 0&&!Hs(this.value.arrayValue,t)}},Ec=class extends we{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!zl(t)||!t.arrayValue.values)&&t.arrayValue.values.some((n=>Hs(this.value.arrayValue,n)))}};var Tc=class{constructor(e,t=null,n=[],s=[],i=null,o=null,u=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=s,this.limit=i,this.startAt=o,this.endAt=u,this.Pe=null}};function ag(r,e=null,t=[],n=[],s=null,i=null,o=null){return new Tc(r,e,t,n,s,i,o)}function Kl(r){let e=G(r);if(e.Pe===null){let t=e.path.canonicalString();e.collectionGroup!==null&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map((n=>mc(n))).join(","),t+="|ob:",t+=e.orderBy.map((n=>(function(i){return i.field.canonicalString()+i.dir})(n))).join(","),fa(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map((n=>Vn(n))).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map((n=>Vn(n))).join(",")),e.Pe=t}return e.Pe}function Gl(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(!Ix(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(!cy(r.filters[t],e.filters[t]))return!1;return r.collectionGroup===e.collectionGroup&&!!r.path.isEqual(e.path)&&!!og(r.startAt,e.startAt)&&og(r.endAt,e.endAt)}function Ic(r){return K.isDocumentKey(r.path)&&r.collectionGroup===null&&r.filters.length===0}var jn=class{constructor(e,t=null,n=[],s=[],i=null,o="F",u=null,c=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=s,this.limit=i,this.limitType=o,this.startAt=u,this.endAt=c,this.Te=null,this.Ie=null,this.de=null,this.startAt,this.endAt}};function Ax(r,e,t,n,s,i,o,u){return new jn(r,e,t,n,s,i,o,u)}function ma(r){return new jn(r)}function ug(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 xx(r){return r.collectionGroup!==null}function Bs(r){let e=G(r);if(e.Te===null){e.Te=[];let t=new Set;for(let i of e.explicitOrderBy)e.Te.push(i),t.add(i.field.canonicalString());let n=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(function(o){let u=new Ie(qe.comparator);return o.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.Te.push(new Fn(i,n))})),t.has(qe.keyField().canonicalString())||e.Te.push(new Fn(qe.keyField(),n))}return e.Te}function lt(r){let e=G(r);return e.Ie||(e.Ie=Rx(e,Bs(r))),e.Ie}function Rx(r,e){if(r.limitType==="F")return ag(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 Fn(s.field,i)}));let t=r.endAt?new Ln(r.endAt.position,r.endAt.inclusive):null,n=r.startAt?new Ln(r.startAt.position,r.startAt.inclusive):null;return ag(r.path,r.collectionGroup,e,r.filters,r.limit,t,n)}}function Sc(r,e,t){return new jn(r.path,r.collectionGroup,r.explicitOrderBy.slice(),r.filters.slice(),e,t,r.startAt,r.endAt)}function ga(r,e){return Gl(lt(r),lt(e))&&r.limitType===e.limitType}function dy(r){return`${Kl(lt(r))}|lt:${r.limitType}`}function In(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=>ly(s))).join(", ")}]`),fa(t.limit)||(n+=", limit: "+t.limit),t.orderBy.length>0&&(n+=`, orderBy: [${t.orderBy.map((s=>(function(o){return`${o.field.canonicalString()} (${o.dir})`})(s))).join(", ")}]`),t.startAt&&(n+=", startAt: ",n+=t.startAt.inclusive?"b:":"a:",n+=t.startAt.position.map((s=>Vn(s))).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map((s=>Vn(s))).join(",")),`Target(${n})`})(lt(r))}; limitType=${r.limitType})`}function ya(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):K.isDocumentKey(n.path)?n.path.isEqual(i):n.path.isImmediateParentOf(i)})(r,e)&&(function(n,s){for(let i of Bs(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(o,u,c){let h=ig(o,u,c);return o.inclusive?h<=0:h<0})(n.startAt,Bs(n),s)||n.endAt&&!(function(o,u,c){let h=ig(o,u,c);return o.inclusive?h>=0:h>0})(n.endAt,Bs(n),s))})(r,e)}function Px(r){return r.collectionGroup||(r.path.length%2==1?r.path.lastSegment():r.path.get(r.path.length-2))}function fy(r){return(e,t)=>{let n=!1;for(let s of Bs(r)){let i=Cx(s,e,t);if(i!==0)return i;n=n||s.field.isKeyField()}return 0}}function Cx(r,e,t){let n=r.field.isKeyField()?K.comparator(e.key,t.key):(function(i,o,u){let c=o.data.field(i),h=u.data.field(i);return c!==null&&h!==null?Nn(c,h):z(42886)})(r.field,e,t);switch(r.dir){case"asc":return n;case"desc":return-1*n;default:return z(19790,{direction:r.dir})}}var Ot=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){dr(this.inner,((t,n)=>{for(let[s,i]of n)e(s,i)}))}isEmpty(){return Yg(this.inner)}size(){return this.innerSize}};var kx=new he(K.comparator);function Dt(){return kx}var py=new he(K.comparator);function Ms(...r){let e=py;for(let t of r)e=e.insert(t.key,t);return e}function my(r){let e=py;return r.forEach(((t,n)=>e=e.insert(t,n.overlayedDocument))),e}function Ir(){return $s()}function gy(){return $s()}function $s(){return new Ot((r=>r.toString()),((r,e)=>r.isEqual(e)))}var Ox=new he(K.comparator),Dx=new Ie(K.comparator);function J(...r){let e=Dx;for(let t of r)e=e.add(t);return e}var Nx=new Ie(Q);function Vx(){return Nx}function Wl(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:Gs(e)?"-0":e}}function yy(r){return{integerValue:""+r}}function Lx(r,e){return lx(e)?yy(e):Wl(r,e)}var Mn=class{constructor(){this._=void 0}};function Fx(r,e,t){return r instanceof Un?(function(s,i){let o={fields:{[ey]:{stringValue:Zg},[ry]:{timestampValue:{seconds:s.seconds,nanos:s.nanoseconds}}}};return i&&Bl(i)&&(i=pa(i)),i&&(o.fields[ty]=i),{mapValue:o}})(t,e):r instanceof Cr?vy(r,e):r instanceof kr?wy(r,e):(function(s,i){let o=_y(s,i),u=cg(o)+cg(s.Ee);return pc(o)&&pc(s.Ee)?yy(u):Wl(s.serializer,u)})(r,e)}function jx(r,e,t){return r instanceof Cr?vy(r,e):r instanceof kr?wy(r,e):t}function _y(r,e){return r instanceof Bn?(function(n){return pc(n)||(function(i){return!!i&&"doubleValue"in i})(n)})(e)?e:{integerValue:0}:null}var Un=class extends Mn{},Cr=class extends Mn{constructor(e){super(),this.elements=e}};function vy(r,e){let t=by(e);for(let n of r.elements)t.some((s=>dt(s,n)))||t.push(n);return{arrayValue:{values:t}}}var kr=class extends Mn{constructor(e){super(),this.elements=e}};function wy(r,e){let t=by(e);for(let n of r.elements)t=t.filter((s=>!dt(s,n)));return{arrayValue:{values:t}}}var Bn=class extends Mn{constructor(e,t){super(),this.serializer=e,this.Ee=t}};function cg(r){return ae(r.integerValue||r.doubleValue)}function by(r){return zl(r)&&r.arrayValue.values?r.arrayValue.values.slice():[]}function Mx(r,e){return r.field.isEqual(e.field)&&(function(n,s){return n instanceof Cr&&s instanceof Cr||n instanceof kr&&s instanceof kr?kn(n.elements,s.elements,dt):n instanceof Bn&&s instanceof Bn?dt(n.Ee,s.Ee):n instanceof Un&&s instanceof Un})(r.transform,e.transform)}var Ac=class{constructor(e,t){this.version=e,this.transformResults=t}},nr=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 Co(r,e){return r.updateTime!==void 0?e.isFoundDocument()&&e.version.isEqual(r.updateTime):r.exists===void 0||r.exists===e.isFoundDocument()}var $n=class{};function Ey(r,e){if(!r.hasLocalMutations||e&&e.fields.length===0)return null;if(e===null)return r.isNoDocument()?new Mo(r.key,nr.none()):new Or(r.key,r.data,nr.none());{let t=r.data,n=$e.empty(),s=new Ie(qe.comparator);for(let i of e.fields)if(!s.has(i)){let o=t.field(i);o===null&&i.length>1&&(i=i.popLast(),o=t.field(i)),o===null?n.delete(i):n.set(i,o),s=s.add(i)}return new pt(r.key,n,new We(s.toArray()),nr.none())}}function Ux(r,e,t){r instanceof Or?(function(s,i,o){let u=s.value.clone(),c=hg(s.fieldTransforms,i,o.transformResults);u.setAll(c),i.convertToFoundDocument(o.version,u).setHasCommittedMutations()})(r,e,t):r instanceof pt?(function(s,i,o){if(!Co(s.precondition,i))return void i.convertToUnknownDocument(o.version);let u=hg(s.fieldTransforms,i,o.transformResults),c=i.data;c.setAll(Ty(s)),c.setAll(u),i.convertToFoundDocument(o.version,c).setHasCommittedMutations()})(r,e,t):(function(s,i,o){i.convertToNoDocument(o.version).setHasCommittedMutations()})(0,e,t)}function qs(r,e,t,n){return r instanceof Or?(function(i,o,u,c){if(!Co(i.precondition,o))return u;let h=i.value.clone(),f=dg(i.fieldTransforms,c,o);return h.setAll(f),o.convertToFoundDocument(o.version,h).setHasLocalMutations(),null})(r,e,t,n):r instanceof pt?(function(i,o,u,c){if(!Co(i.precondition,o))return u;let h=dg(i.fieldTransforms,c,o),f=o.data;return f.setAll(Ty(i)),f.setAll(h),o.convertToFoundDocument(o.version,f).setHasLocalMutations(),u===null?null:u.unionWith(i.fieldMask.fields).unionWith(i.fieldTransforms.map((p=>p.field)))})(r,e,t,n):(function(i,o,u){return Co(i.precondition,o)?(o.convertToNoDocument(o.version).setHasLocalMutations(),null):u})(r,e,t)}function Bx(r,e){let t=null;for(let n of r.fieldTransforms){let s=e.data.field(n.field),i=_y(n.transform,s||null);i!=null&&(t===null&&(t=$e.empty()),t.set(n.field,i))}return t||null}function lg(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)&&kn(n,s,((i,o)=>Mx(i,o)))})(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 Or=class extends $n{constructor(e,t,n,s=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}},pt=class extends $n{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 Ty(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 hg(r,e,t){let n=new Map;te(r.length===t.length,32656,{Ae:t.length,Re:r.length});for(let s=0;s<t.length;s++){let i=r[s],o=i.transform,u=e.data.field(i.field);n.set(i.field,jx(o,u,t[s]))}return n}function dg(r,e,t){let n=new Map;for(let s of r){let i=s.transform,o=t.data.field(s.field);n.set(s.field,Fx(i,o,e))}return n}var Mo=class extends $n{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}},xc=class extends $n{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}};var Rc=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)&&Ux(i,e,n[s])}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=qs(n,e,t,this.localWriteTime));for(let n of this.mutations)n.key.isEqual(e.key)&&(t=qs(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let n=gy();return this.mutations.forEach((s=>{let i=e.get(s.key),o=i.overlayedDocument,u=this.applyToLocalView(o,i.mutatedFields);u=t.has(s.key)?null:u;let c=Ey(o,u);c!==null&&n.set(s.key,c),o.isValidDocument()||o.convertToNoDocument(W.min())})),n}keys(){return this.mutations.reduce(((e,t)=>e.add(t.key)),J())}isEqual(e){return this.batchId===e.batchId&&kn(this.mutations,e.mutations,((t,n)=>lg(t,n)))&&kn(this.baseMutations,e.baseMutations,((t,n)=>lg(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){te(e.mutations.length===n.length,58842,{Ve:e.mutations.length,me:n.length});let s=(function(){return Ox})(),i=e.mutations;for(let o=0;o<i.length;o++)s=s.insert(i[o].key,n[o].version);return new r(e,t,n,s)}};var Cc=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
|
+
`+C+" "+L})}function nn(a,h,d,m){a.info(function(){return"XMLHTTP TEXT ("+h+"): "+jw(a,d)+(m?" "+m:"")})}function Mw(a,h){a.info(function(){return"TIMEOUT: "+h})}vs.prototype.info=function(){};function jw(a,h){if(!a.g)return h;if(!h)return null;try{let C=JSON.parse(h);if(C){for(a=0;a<C.length;a++)if(Array.isArray(C[a])){var d=C[a];if(!(d.length<2)){var m=d[1];if(Array.isArray(m)&&!(m.length<1)){var x=m[0];if(x!="noop"&&x!="stop"&&x!="close")for(let L=1;L<m.length;L++)m[L]=""}}}}return uu(C)}catch{return h}}var Ui={NO_ERROR:0,cb:1,qb:2,pb:3,kb:4,ob:5,rb:6,Ga:7,TIMEOUT:8,ub:9},Yh={ib:"complete",Fb:"success",ERROR:"error",Ga:"abort",xb:"ready",yb:"readystatechange",TIMEOUT:"timeout",sb:"incrementaldata",wb:"progress",lb:"downloadprogress",Nb:"uploadprogress"},Xh;function hu(){}p(hu,Kh),hu.prototype.g=function(){return new XMLHttpRequest},Xh=new hu;function bs(a){return encodeURIComponent(String(a))}function Uw(a){var h=1;a=a.split(":");let d=[];for(;h>0&&a.length;)d.push(a.shift()),h--;return a.length&&d.push(a.join(":")),d}function $t(a,h,d,m){this.j=a,this.i=h,this.l=d,this.S=m||1,this.V=new gs(this),this.H=45e3,this.J=null,this.o=!1,this.u=this.B=this.A=this.M=this.F=this.T=this.D=null,this.G=[],this.g=null,this.C=0,this.m=this.v=null,this.X=-1,this.K=!1,this.P=0,this.O=null,this.W=this.L=this.U=this.R=!1,this.h=new Zh}function Zh(){this.i=null,this.g="",this.h=!1}var ed={},du={};function fu(a,h,d){a.M=1,a.A=$i(nt(h)),a.u=d,a.R=!0,td(a,null)}function td(a,h){a.F=Date.now(),Bi(a),a.B=nt(a.A);var d=a.B,m=a.S;Array.isArray(m)||(m=[String(m)]),pd(d.i,"t",m),a.C=0,d=a.j.L,a.h=new Zh,a.g=Od(a.j,d?h:null,!a.u),a.P>0&&(a.O=new Dw(l(a.Y,a,a.g),a.P)),h=a.V,d=a.g,m=a.ba;var x="readystatechange";Array.isArray(x)||(x&&(qh[0]=x.toString()),x=qh);for(let C=0;C<x.length;C++){let L=Fh(d,x[C],m||h.handleEvent,!1,h.h||h);if(!L)break;h.g[L.key]=L}h=a.J?Nh(a.J):{},a.u?(a.v||(a.v="POST"),h["Content-Type"]="application/x-www-form-urlencoded",a.g.ea(a.B,a.v,a.u,h)):(a.v="GET",a.g.ea(a.B,a.v,null,h)),_s(),Lw(a.i,a.v,a.B,a.l,a.S,a.u)}$t.prototype.ba=function(a){a=a.target;let h=this.O;h&&Kt(a)==3?h.j():this.Y(a)},$t.prototype.Y=function(a){try{if(a==this.g)e:{let J=Kt(this.g),be=this.g.ya(),re=this.g.ca();if(!(J<3)&&(J!=3||this.g&&(this.h.h||this.g.la()||bd(this.g)))){this.K||J!=4||be==7||(be==8||re<=0?_s(3):_s(2)),pu(this);var h=this.g.ca();this.X=h;var d=Bw(this);if(this.o=h==200,Fw(this.i,this.v,this.B,this.l,this.S,J,h),this.o){if(this.U&&!this.L){t:{if(this.g){var m,x=this.g;if((m=x.g?x.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!b(m)){var C=m;break t}}C=null}if(a=C)nn(this.i,this.l,a,"Initial handshake response via X-HTTP-Initial-Response"),this.L=!0,mu(this,a);else{this.o=!1,this.m=3,Ve(12),_r(this),Es(this);break e}}if(this.R){a=!0;let Ae;for(;!this.K&&this.C<d.length;)if(Ae=$w(this,d),Ae==du){J==4&&(this.m=4,Ve(14),a=!1),nn(this.i,this.l,null,"[Incomplete Response]");break}else if(Ae==ed){this.m=4,Ve(15),nn(this.i,this.l,d,"[Invalid Chunk]"),a=!1;break}else nn(this.i,this.l,Ae,null),mu(this,Ae);if(rd(this)&&this.C!=0&&(this.h.g=this.h.g.slice(this.C),this.C=0),J!=4||d.length!=0||this.h.h||(this.m=1,Ve(16),a=!1),this.o=this.o&&a,!a)nn(this.i,this.l,d,"[Invalid Chunked Response]"),_r(this),Es(this);else if(d.length>0&&!this.W){this.W=!0;var L=this.j;L.g==this&&L.aa&&!L.P&&(L.j.info("Great, no buffering proxy detected. Bytes received: "+d.length),Eu(L),L.P=!0,Ve(11))}}else nn(this.i,this.l,d,null),mu(this,d);J==4&&_r(this),this.o&&!this.K&&(J==4?Rd(this.j,this):(this.o=!1,Bi(this)))}else rv(this.g),h==400&&d.indexOf("Unknown SID")>0?(this.m=3,Ve(12)):(this.m=0,Ve(13)),_r(this),Es(this)}}}catch{}};function Bw(a){if(!rd(a))return a.g.la();let h=bd(a.g);if(h==="")return"";let d="",m=h.length,x=Kt(a.g)==4;if(!a.h.i){if(typeof TextDecoder=="undefined")return _r(a),Es(a),"";a.h.i=new o.TextDecoder}for(let C=0;C<m;C++)a.h.h=!0,d+=a.h.i.decode(h[C],{stream:!(x&&C==m-1)});return h.length=0,a.h.g+=d,a.C=0,a.h.g}function rd(a){return a.g?a.v=="GET"&&a.M!=2&&a.j.Aa:!1}function $w(a,h){var d=a.C,m=h.indexOf(`
|
|
6
|
+
`,d);return m==-1?du:(d=Number(h.substring(d,m)),isNaN(d)?ed:(m+=1,m+d>h.length?du:(h=h.slice(m,m+d),a.C=m+d,h)))}$t.prototype.cancel=function(){this.K=!0,_r(this)};function Bi(a){a.T=Date.now()+a.H,nd(a,a.H)}function nd(a,h){if(a.D!=null)throw Error("WatchDog timer not null");a.D=ws(l(a.aa,a),h)}function pu(a){a.D&&(o.clearTimeout(a.D),a.D=null)}$t.prototype.aa=function(){this.D=null;let a=Date.now();a-this.T>=0?(Mw(this.i,this.B),this.M!=2&&(_s(),Ve(17)),_r(this),this.m=2,Es(this)):nd(this,this.T-a)};function Es(a){a.j.I==0||a.K||Rd(a.j,a)}function _r(a){pu(a);var h=a.O;h&&typeof h.dispose=="function"&&h.dispose(),a.O=null,zh(a.V),a.g&&(h=a.g,a.g=null,h.abort(),h.dispose())}function mu(a,h){try{var d=a.j;if(d.I!=0&&(d.g==a||gu(d.h,a))){if(!a.L&&gu(d.h,a)&&d.I==3){try{var m=d.Ba.g.parse(h)}catch{m=null}if(Array.isArray(m)&&m.length==3){var x=m;if(x[0]==0){e:if(!d.v){if(d.g)if(d.g.F+3e3<a.F)Hi(d),Gi(d);else break e;bu(d),Ve(18)}}else d.xa=x[1],0<d.xa-d.K&&x[2]<37500&&d.F&&d.A==0&&!d.C&&(d.C=ws(l(d.Va,d),6e3));od(d.h)<=1&&d.ta&&(d.ta=void 0)}else vr(d,11)}else if((a.L||d.g==a)&&Hi(d),!b(h))for(x=d.Ba.g.parse(h),h=0;h<x.length;h++){let re=x[h],Ae=re[0];if(!(Ae<=d.K))if(d.K=Ae,re=re[1],d.I==2)if(re[0]=="c"){d.M=re[1],d.ba=re[2];let st=re[3];st!=null&&(d.ka=st,d.j.info("VER="+d.ka));let br=re[4];br!=null&&(d.za=br,d.j.info("SVER="+d.za));let Gt=re[5];Gt!=null&&typeof Gt=="number"&&Gt>0&&(m=1.5*Gt,d.O=m,d.j.info("backChannelRequestTimeoutMs_="+m)),m=d;let Wt=a.g;if(Wt){let Qi=Wt.g?Wt.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(Qi){var C=m.h;C.g||Qi.indexOf("spdy")==-1&&Qi.indexOf("quic")==-1&&Qi.indexOf("h2")==-1||(C.j=C.l,C.g=new Set,C.h&&(yu(C,C.h),C.h=null))}if(m.G){let Tu=Wt.g?Wt.g.getResponseHeader("X-HTTP-Session-Id"):null;Tu&&(m.wa=Tu,ie(m.J,m.G,Tu))}}d.I=3,d.l&&d.l.ra(),d.aa&&(d.T=Date.now()-a.F,d.j.info("Handshake RTT: "+d.T+"ms")),m=d;var L=a;if(m.na=kd(m,m.L?m.ba:null,m.W),L.L){ad(m.h,L);var J=L,be=m.O;be&&(J.H=be),J.D&&(pu(J),Bi(J)),m.g=L}else Sd(m);d.i.length>0&&Wi(d)}else re[0]!="stop"&&re[0]!="close"||vr(d,7);else d.I==3&&(re[0]=="stop"||re[0]=="close"?re[0]=="stop"?vr(d,7):vu(d):re[0]!="noop"&&d.l&&d.l.qa(re),d.A=0)}}_s(4)}catch{}}var qw=class{constructor(a,h){this.g=a,this.map=h}};function sd(a){this.l=a||10,o.PerformanceNavigationTiming?(a=o.performance.getEntriesByType("navigation"),a=a.length>0&&(a[0].nextHopProtocol=="hq"||a[0].nextHopProtocol=="h2")):a=!!(o.chrome&&o.chrome.loadTimes&&o.chrome.loadTimes()&&o.chrome.loadTimes().wasFetchedViaSpdy),this.j=a?this.l:1,this.g=null,this.j>1&&(this.g=new Set),this.h=null,this.i=[]}function id(a){return a.h?!0:a.g?a.g.size>=a.j:!1}function od(a){return a.h?1:a.g?a.g.size:0}function gu(a,h){return a.h?a.h==h:a.g?a.g.has(h):!1}function yu(a,h){a.g?a.g.add(h):a.h=h}function ad(a,h){a.h&&a.h==h?a.h=null:a.g&&a.g.has(h)&&a.g.delete(h)}sd.prototype.cancel=function(){if(this.i=ud(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&this.g.size!==0){for(let a of this.g.values())a.cancel();this.g.clear()}};function ud(a){if(a.h!=null)return a.i.concat(a.h.G);if(a.g!=null&&a.g.size!==0){let h=a.i;for(let d of a.g.values())h=h.concat(d.G);return h}return y(a.i)}var cd=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function zw(a,h){if(a){a=a.split("&");for(let d=0;d<a.length;d++){let m=a[d].indexOf("="),x,C=null;m>=0?(x=a[d].substring(0,m),C=a[d].substring(m+1)):x=a[d],h(x,C?decodeURIComponent(C.replace(/\+/g," ")):"")}}}function qt(a){this.g=this.o=this.j="",this.u=null,this.m=this.h="",this.l=!1;let h;a instanceof qt?(this.l=a.l,Ts(this,a.j),this.o=a.o,this.g=a.g,Is(this,a.u),this.h=a.h,_u(this,md(a.i)),this.m=a.m):a&&(h=String(a).match(cd))?(this.l=!1,Ts(this,h[1]||"",!0),this.o=As(h[2]||""),this.g=As(h[3]||"",!0),Is(this,h[4]),this.h=As(h[5]||"",!0),_u(this,h[6]||"",!0),this.m=As(h[7]||"")):(this.l=!1,this.i=new xs(null,this.l))}qt.prototype.toString=function(){let a=[];var h=this.j;h&&a.push(Ss(h,ld,!0),":");var d=this.g;return(d||h=="file")&&(a.push("//"),(h=this.o)&&a.push(Ss(h,ld,!0),"@"),a.push(bs(d).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),d=this.u,d!=null&&a.push(":",String(d))),(d=this.h)&&(this.g&&d.charAt(0)!="/"&&a.push("/"),a.push(Ss(d,d.charAt(0)=="/"?Ww:Gw,!0))),(d=this.i.toString())&&a.push("?",d),(d=this.m)&&a.push("#",Ss(d,Jw)),a.join("")},qt.prototype.resolve=function(a){let h=nt(this),d=!!a.j;d?Ts(h,a.j):d=!!a.o,d?h.o=a.o:d=!!a.g,d?h.g=a.g:d=a.u!=null;var m=a.h;if(d)Is(h,a.u);else if(d=!!a.h){if(m.charAt(0)!="/")if(this.g&&!this.h)m="/"+m;else{var x=h.h.lastIndexOf("/");x!=-1&&(m=h.h.slice(0,x+1)+m)}if(x=m,x==".."||x==".")m="";else if(x.indexOf("./")!=-1||x.indexOf("/.")!=-1){m=x.lastIndexOf("/",0)==0,x=x.split("/");let C=[];for(let L=0;L<x.length;){let J=x[L++];J=="."?m&&L==x.length&&C.push(""):J==".."?((C.length>1||C.length==1&&C[0]!="")&&C.pop(),m&&L==x.length&&C.push("")):(C.push(J),m=!0)}m=C.join("/")}else m=x}return d?h.h=m:d=a.i.toString()!=="",d?_u(h,md(a.i)):d=!!a.m,d&&(h.m=a.m),h};function nt(a){return new qt(a)}function Ts(a,h,d){a.j=d?As(h,!0):h,a.j&&(a.j=a.j.replace(/:$/,""))}function Is(a,h){if(h){if(h=Number(h),isNaN(h)||h<0)throw Error("Bad port number "+h);a.u=h}else a.u=null}function _u(a,h,d){h instanceof xs?(a.i=h,Qw(a.i,a.l)):(d||(h=Ss(h,Hw)),a.i=new xs(h,a.l))}function ie(a,h,d){a.i.set(h,d)}function $i(a){return ie(a,"zx",Math.floor(Math.random()*2147483648).toString(36)+Math.abs(Math.floor(Math.random()*2147483648)^Date.now()).toString(36)),a}function As(a,h){return a?h?decodeURI(a.replace(/%25/g,"%2525")):decodeURIComponent(a):""}function Ss(a,h,d){return typeof a=="string"?(a=encodeURI(a).replace(h,Kw),d&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),a):null}function Kw(a){return a=a.charCodeAt(0),"%"+(a>>4&15).toString(16)+(a&15).toString(16)}var ld=/[#\/\?@]/g,Gw=/[#\?:]/g,Ww=/[#\?]/g,Hw=/[#\?@]/g,Jw=/#/g;function xs(a,h){this.h=this.g=null,this.i=a||null,this.j=!!h}function wr(a){a.g||(a.g=new Map,a.h=0,a.i&&zw(a.i,function(h,d){a.add(decodeURIComponent(h.replace(/\+/g," ")),d)}))}r=xs.prototype,r.add=function(a,h){wr(this),this.i=null,a=sn(this,a);let d=this.g.get(a);return d||this.g.set(a,d=[]),d.push(h),this.h+=1,this};function hd(a,h){wr(a),h=sn(a,h),a.g.has(h)&&(a.i=null,a.h-=a.g.get(h).length,a.g.delete(h))}function dd(a,h){return wr(a),h=sn(a,h),a.g.has(h)}r.forEach=function(a,h){wr(this),this.g.forEach(function(d,m){d.forEach(function(x){a.call(h,x,m,this)},this)},this)};function fd(a,h){wr(a);let d=[];if(typeof h=="string")dd(a,h)&&(d=d.concat(a.g.get(sn(a,h))));else for(a=Array.from(a.g.values()),h=0;h<a.length;h++)d=d.concat(a[h]);return d}r.set=function(a,h){return wr(this),this.i=null,a=sn(this,a),dd(this,a)&&(this.h-=this.g.get(a).length),this.g.set(a,[h]),this.h+=1,this},r.get=function(a,h){return a?(a=fd(this,a),a.length>0?String(a[0]):h):h};function pd(a,h,d){hd(a,h),d.length>0&&(a.i=null,a.g.set(sn(a,h),y(d)),a.h+=d.length)}r.toString=function(){if(this.i)return this.i;if(!this.g)return"";let a=[],h=Array.from(this.g.keys());for(let m=0;m<h.length;m++){var d=h[m];let x=bs(d);d=fd(this,d);for(let C=0;C<d.length;C++){let L=x;d[C]!==""&&(L+="="+bs(d[C])),a.push(L)}}return this.i=a.join("&")};function md(a){let h=new xs;return h.i=a.i,a.g&&(h.g=new Map(a.g),h.h=a.h),h}function sn(a,h){return h=String(h),a.j&&(h=h.toLowerCase()),h}function Qw(a,h){h&&!a.j&&(wr(a),a.i=null,a.g.forEach(function(d,m){let x=m.toLowerCase();m!=x&&(hd(this,m),pd(this,x,d))},a)),a.j=h}function Yw(a,h){let d=new vs;if(o.Image){let m=new Image;m.onload=f(zt,d,"TestLoadImage: loaded",!0,h,m),m.onerror=f(zt,d,"TestLoadImage: error",!1,h,m),m.onabort=f(zt,d,"TestLoadImage: abort",!1,h,m),m.ontimeout=f(zt,d,"TestLoadImage: timeout",!1,h,m),o.setTimeout(function(){m.ontimeout&&m.ontimeout()},1e4),m.src=a}else h(!1)}function Xw(a,h){let d=new vs,m=new AbortController,x=setTimeout(()=>{m.abort(),zt(d,"TestPingServer: timeout",!1,h)},1e4);fetch(a,{signal:m.signal}).then(C=>{clearTimeout(x),C.ok?zt(d,"TestPingServer: ok",!0,h):zt(d,"TestPingServer: server error",!1,h)}).catch(()=>{clearTimeout(x),zt(d,"TestPingServer: error",!1,h)})}function zt(a,h,d,m,x){try{x&&(x.onload=null,x.onerror=null,x.onabort=null,x.ontimeout=null),m(d)}catch{}}function Zw(){this.g=new Vw}function qi(a){this.i=a.Sb||null,this.h=a.ab||!1}p(qi,Kh),qi.prototype.g=function(){return new zi(this.i,this.h)};function zi(a,h){ke.call(this),this.H=a,this.o=h,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.A=new Headers,this.h=null,this.F="GET",this.D="",this.g=!1,this.B=this.j=this.l=null,this.v=new AbortController}p(zi,ke),r=zi.prototype,r.open=function(a,h){if(this.readyState!=0)throw this.abort(),Error("Error reopening a connection");this.F=a,this.D=h,this.readyState=1,Ps(this)},r.send=function(a){if(this.readyState!=1)throw this.abort(),Error("need to call open() first. ");if(this.v.signal.aborted)throw this.abort(),Error("Request was aborted.");this.g=!0;let h={headers:this.A,method:this.F,credentials:this.m,cache:void 0,signal:this.v.signal};a&&(h.body=a),(this.H||o).fetch(new Request(this.D,h)).then(this.Pa.bind(this),this.ga.bind(this))},r.abort=function(){this.response=this.responseText="",this.A=new Headers,this.status=0,this.v.abort(),this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),this.readyState>=1&&this.g&&this.readyState!=4&&(this.g=!1,Rs(this)),this.readyState=0},r.Pa=function(a){if(this.g&&(this.l=a,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=a.headers,this.readyState=2,Ps(this)),this.g&&(this.readyState=3,Ps(this),this.g)))if(this.responseType==="arraybuffer")a.arrayBuffer().then(this.Na.bind(this),this.ga.bind(this));else if(typeof o.ReadableStream!="undefined"&&"body"in a){if(this.j=a.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.B=new TextDecoder;gd(this)}else a.text().then(this.Oa.bind(this),this.ga.bind(this))};function gd(a){a.j.read().then(a.Ma.bind(a)).catch(a.ga.bind(a))}r.Ma=function(a){if(this.g){if(this.o&&a.value)this.response.push(a.value);else if(!this.o){var h=a.value?a.value:new Uint8Array(0);(h=this.B.decode(h,{stream:!a.done}))&&(this.response=this.responseText+=h)}a.done?Rs(this):Ps(this),this.readyState==3&&gd(this)}},r.Oa=function(a){this.g&&(this.response=this.responseText=a,Rs(this))},r.Na=function(a){this.g&&(this.response=a,Rs(this))},r.ga=function(){this.g&&Rs(this)};function Rs(a){a.readyState=4,a.l=null,a.j=null,a.B=null,Ps(a)}r.setRequestHeader=function(a,h){this.A.append(a,h)},r.getResponseHeader=function(a){return this.h&&this.h.get(a.toLowerCase())||""},r.getAllResponseHeaders=function(){if(!this.h)return"";let a=[],h=this.h.entries();for(var d=h.next();!d.done;)d=d.value,a.push(d[0]+": "+d[1]),d=h.next();return a.join(`\r
|
|
7
|
+
`)};function Ps(a){a.onreadystatechange&&a.onreadystatechange.call(a)}Object.defineProperty(zi.prototype,"withCredentials",{get:function(){return this.m==="include"},set:function(a){this.m=a?"include":"same-origin"}});function yd(a){let h="";return Li(a,function(d,m){h+=m,h+=":",h+=d,h+=`\r
|
|
8
|
+
`}),h}function wu(a,h,d){e:{for(m in d){var m=!1;break e}m=!0}m||(d=yd(d),typeof a=="string"?d!=null&&bs(d):ie(a,h,d))}function ce(a){ke.call(this),this.headers=new Map,this.L=a||null,this.h=!1,this.g=null,this.D="",this.o=0,this.l="",this.j=this.B=this.v=this.A=!1,this.m=null,this.F="",this.H=!1}p(ce,ke);var ev=/^https?$/i,tv=["POST","PUT"];r=ce.prototype,r.Fa=function(a){this.H=a},r.ea=function(a,h,d,m){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+a);h=h?h.toUpperCase():"GET",this.D=a,this.l="",this.o=0,this.A=!1,this.h=!0,this.g=this.L?this.L.g():Xh.g(),this.g.onreadystatechange=g(l(this.Ca,this));try{this.B=!0,this.g.open(h,String(a),!0),this.B=!1}catch(C){_d(this,C);return}if(a=d||"",d=new Map(this.headers),m)if(Object.getPrototypeOf(m)===Object.prototype)for(var x in m)d.set(x,m[x]);else if(typeof m.keys=="function"&&typeof m.get=="function")for(let C of m.keys())d.set(C,m.get(C));else throw Error("Unknown input type for opt_headers: "+String(m));m=Array.from(d.keys()).find(C=>C.toLowerCase()=="content-type"),x=o.FormData&&a instanceof o.FormData,!(Array.prototype.indexOf.call(tv,h,void 0)>=0)||m||x||d.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(let[C,L]of d)this.g.setRequestHeader(C,L);this.F&&(this.g.responseType=this.F),"withCredentials"in this.g&&this.g.withCredentials!==this.H&&(this.g.withCredentials=this.H);try{this.m&&(clearTimeout(this.m),this.m=null),this.v=!0,this.g.send(a),this.v=!1}catch(C){_d(this,C)}};function _d(a,h){a.h=!1,a.g&&(a.j=!0,a.g.abort(),a.j=!1),a.l=h,a.o=5,wd(a),Ki(a)}function wd(a){a.A||(a.A=!0,Ne(a,"complete"),Ne(a,"error"))}r.abort=function(a){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.o=a||7,Ne(this,"complete"),Ne(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)),ce.Z.N.call(this)},r.Ca=function(){this.u||(this.B||this.v||this.j?vd(this):this.Xa())},r.Xa=function(){vd(this)};function vd(a){if(a.h&&typeof i!="undefined"){if(a.v&&Kt(a)==4)setTimeout(a.Ca.bind(a),0);else if(Ne(a,"readystatechange"),Kt(a)==4){a.h=!1;try{let C=a.ca();e:switch(C){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var h=!0;break e;default:h=!1}var d;if(!(d=h)){var m;if(m=C===0){let L=String(a.D).match(cd)[1]||null;!L&&o.self&&o.self.location&&(L=o.self.location.protocol.slice(0,-1)),m=!ev.test(L?L.toLowerCase():"")}d=m}if(d)Ne(a,"complete"),Ne(a,"success");else{a.o=6;try{var x=Kt(a)>2?a.g.statusText:""}catch{x=""}a.l=x+" ["+a.ca()+"]",wd(a)}}finally{Ki(a)}}}}function Ki(a,h){if(a.g){a.m&&(clearTimeout(a.m),a.m=null);let d=a.g;a.g=null,h||Ne(a,"ready");try{d.onreadystatechange=null}catch{}}}r.isActive=function(){return!!this.g};function Kt(a){return a.g?a.g.readyState:0}r.ca=function(){try{return Kt(this)>2?this.g.status:-1}catch{return-1}},r.la=function(){try{return this.g?this.g.responseText:""}catch{return""}},r.La=function(a){if(this.g){var h=this.g.responseText;return a&&h.indexOf(a)==0&&(h=h.substring(a.length)),Nw(h)}};function bd(a){try{if(!a.g)return null;if("response"in a.g)return a.g.response;switch(a.F){case"":case"text":return a.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in a.g)return a.g.mozResponseArrayBuffer}return null}catch{return null}}function rv(a){let h={};a=(a.g&&Kt(a)>=2&&a.g.getAllResponseHeaders()||"").split(`\r
|
|
9
|
+
`);for(let m=0;m<a.length;m++){if(b(a[m]))continue;var d=Uw(a[m]);let x=d[0];if(d=d[1],typeof d!="string")continue;d=d.trim();let C=h[x]||[];h[x]=C,C.push(d)}Pw(h,function(m){return m.join(", ")})}r.ya=function(){return this.o},r.Ha=function(){return typeof this.l=="string"?this.l:String(this.l)};function Cs(a,h,d){return d&&d.internalChannelParams&&d.internalChannelParams[a]||h}function Ed(a){this.za=0,this.i=[],this.j=new vs,this.ba=this.na=this.J=this.W=this.g=this.wa=this.G=this.H=this.u=this.U=this.o=null,this.Ya=this.V=0,this.Sa=Cs("failFast",!1,a),this.F=this.C=this.v=this.m=this.l=null,this.X=!0,this.xa=this.K=-1,this.Y=this.A=this.D=0,this.Qa=Cs("baseRetryDelayMs",5e3,a),this.Za=Cs("retryDelaySeedMs",1e4,a),this.Ta=Cs("forwardChannelMaxRetries",2,a),this.va=Cs("forwardChannelRequestTimeoutMs",2e4,a),this.ma=a&&a.xmlHttpFactory||void 0,this.Ua=a&&a.Rb||void 0,this.Aa=a&&a.useFetchStreams||!1,this.O=void 0,this.L=a&&a.supportsCrossDomainXhr||!1,this.M="",this.h=new sd(a&&a.concurrentRequestLimit),this.Ba=new Zw,this.S=a&&a.fastHandshake||!1,this.R=a&&a.encodeInitMessageHeaders||!1,this.S&&this.R&&(this.R=!1),this.Ra=a&&a.Pb||!1,a&&a.ua&&this.j.ua(),a&&a.forceLongPolling&&(this.X=!1),this.aa=!this.S&&this.X&&a&&a.detectBufferingProxy||!1,this.ia=void 0,a&&a.longPollingTimeout&&a.longPollingTimeout>0&&(this.ia=a.longPollingTimeout),this.ta=void 0,this.T=0,this.P=!1,this.ja=this.B=null}r=Ed.prototype,r.ka=8,r.I=1,r.connect=function(a,h,d,m){Ve(0),this.W=a,this.H=h||{},d&&m!==void 0&&(this.H.OSID=d,this.H.OAID=m),this.F=this.X,this.J=kd(this,null,this.W),Wi(this)};function vu(a){if(Td(a),a.I==3){var h=a.V++,d=nt(a.J);if(ie(d,"SID",a.M),ie(d,"RID",h),ie(d,"TYPE","terminate"),ks(a,d),h=new $t(a,a.j,h),h.M=2,h.A=$i(nt(d)),d=!1,o.navigator&&o.navigator.sendBeacon)try{d=o.navigator.sendBeacon(h.A.toString(),"")}catch{}!d&&o.Image&&(new Image().src=h.A,d=!0),d||(h.g=Od(h.j,null),h.g.ea(h.A)),h.F=Date.now(),Bi(h)}Cd(a)}function Gi(a){a.g&&(Eu(a),a.g.cancel(),a.g=null)}function Td(a){Gi(a),a.v&&(o.clearTimeout(a.v),a.v=null),Hi(a),a.h.cancel(),a.m&&(typeof a.m=="number"&&o.clearTimeout(a.m),a.m=null)}function Wi(a){if(!id(a.h)&&!a.m){a.m=!0;var h=a.Ea;z||_(),F||(z(),F=!0),E.add(h,a),a.D=0}}function nv(a,h){return od(a.h)>=a.h.j-(a.m?1:0)?!1:a.m?(a.i=h.G.concat(a.i),!0):a.I==1||a.I==2||a.D>=(a.Sa?0:a.Ta)?!1:(a.m=ws(l(a.Ea,a,h),Pd(a,a.D)),a.D++,!0)}r.Ea=function(a){if(this.m)if(this.m=null,this.I==1){if(!a){this.V=Math.floor(Math.random()*1e5),a=this.V++;let x=new $t(this,this.j,a),C=this.o;if(this.U&&(C?(C=Nh(C),Lh(C,this.U)):C=this.U),this.u!==null||this.R||(x.J=C,C=null),this.S)e:{for(var h=0,d=0;d<this.i.length;d++){t:{var m=this.i[d];if("__data__"in m.map&&(m=m.map.__data__,typeof m=="string")){m=m.length;break t}m=void 0}if(m===void 0)break;if(h+=m,h>4096){h=d;break e}if(h===4096||d===this.i.length-1){h=d+1;break e}}h=1e3}else h=1e3;h=Ad(this,x,h),d=nt(this.J),ie(d,"RID",a),ie(d,"CVER",22),this.G&&ie(d,"X-HTTP-Session-Id",this.G),ks(this,d),C&&(this.R?h="headers="+bs(yd(C))+"&"+h:this.u&&wu(d,this.u,C)),yu(this.h,x),this.Ra&&ie(d,"TYPE","init"),this.S?(ie(d,"$req",h),ie(d,"SID","null"),x.U=!0,fu(x,d,null)):fu(x,d,h),this.I=2}}else this.I==3&&(a?Id(this,a):this.i.length==0||id(this.h)||Id(this))};function Id(a,h){var d;h?d=h.l:d=a.V++;let m=nt(a.J);ie(m,"SID",a.M),ie(m,"RID",d),ie(m,"AID",a.K),ks(a,m),a.u&&a.o&&wu(m,a.u,a.o),d=new $t(a,a.j,d,a.D+1),a.u===null&&(d.J=a.o),h&&(a.i=h.G.concat(a.i)),h=Ad(a,d,1e3),d.H=Math.round(a.va*.5)+Math.round(a.va*.5*Math.random()),yu(a.h,d),fu(d,m,h)}function ks(a,h){a.H&&Li(a.H,function(d,m){ie(h,m,d)}),a.l&&Li({},function(d,m){ie(h,m,d)})}function Ad(a,h,d){d=Math.min(a.i.length,d);let m=a.l?l(a.l.Ka,a.l,a):null;e:{var x=a.i;let J=-1;for(;;){let be=["count="+d];J==-1?d>0?(J=x[0].g,be.push("ofs="+J)):J=0:be.push("ofs="+J);let re=!0;for(let Ae=0;Ae<d;Ae++){var C=x[Ae].g;let st=x[Ae].map;if(C-=J,C<0)J=Math.max(0,x[Ae].g-100),re=!1;else try{C="req"+C+"_"||"";try{var L=st instanceof Map?st:Object.entries(st);for(let[br,Gt]of L){let Wt=Gt;u(Gt)&&(Wt=uu(Gt)),be.push(C+br+"="+encodeURIComponent(Wt))}}catch(br){throw be.push(C+"type="+encodeURIComponent("_badmap")),br}}catch{m&&m(st)}}if(re){L=be.join("&");break e}}L=void 0}return a=a.i.splice(0,d),h.G=a,L}function Sd(a){if(!a.g&&!a.v){a.Y=1;var h=a.Da;z||_(),F||(z(),F=!0),E.add(h,a),a.A=0}}function bu(a){return a.g||a.v||a.A>=3?!1:(a.Y++,a.v=ws(l(a.Da,a),Pd(a,a.A)),a.A++,!0)}r.Da=function(){if(this.v=null,xd(this),this.aa&&!(this.P||this.g==null||this.T<=0)){var a=4*this.T;this.j.info("BP detection timer enabled: "+a),this.B=ws(l(this.Wa,this),a)}},r.Wa=function(){this.B&&(this.B=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.P=!0,Ve(10),Gi(this),xd(this))};function Eu(a){a.B!=null&&(o.clearTimeout(a.B),a.B=null)}function xd(a){a.g=new $t(a,a.j,"rpc",a.Y),a.u===null&&(a.g.J=a.o),a.g.P=0;var h=nt(a.na);ie(h,"RID","rpc"),ie(h,"SID",a.M),ie(h,"AID",a.K),ie(h,"CI",a.F?"0":"1"),!a.F&&a.ia&&ie(h,"TO",a.ia),ie(h,"TYPE","xmlhttp"),ks(a,h),a.u&&a.o&&wu(h,a.u,a.o),a.O&&(a.g.H=a.O);var d=a.g;a=a.ba,d.M=1,d.A=$i(nt(h)),d.u=null,d.R=!0,td(d,a)}r.Va=function(){this.C!=null&&(this.C=null,Gi(this),bu(this),Ve(19))};function Hi(a){a.C!=null&&(o.clearTimeout(a.C),a.C=null)}function Rd(a,h){var d=null;if(a.g==h){Hi(a),Eu(a),a.g=null;var m=2}else if(gu(a.h,h))d=h.G,ad(a.h,h),m=1;else return;if(a.I!=0){if(h.o)if(m==1){d=h.u?h.u.length:0,h=Date.now()-h.F;var x=a.D;m=ji(),Ne(m,new Qh(m,d)),Wi(a)}else Sd(a);else if(x=h.m,x==3||x==0&&h.X>0||!(m==1&&nv(a,h)||m==2&&bu(a)))switch(d&&d.length>0&&(h=a.h,h.i=h.i.concat(d)),x){case 1:vr(a,5);break;case 4:vr(a,10);break;case 3:vr(a,6);break;default:vr(a,2)}}}function Pd(a,h){let d=a.Qa+Math.floor(Math.random()*a.Za);return a.isActive()||(d*=2),d*h}function vr(a,h){if(a.j.info("Error code "+h),h==2){var d=l(a.bb,a),m=a.Ua;let x=!m;m=new qt(m||"//www.google.com/images/cleardot.gif"),o.location&&o.location.protocol=="http"||Ts(m,"https"),$i(m),x?Yw(m.toString(),d):Xw(m.toString(),d)}else Ve(2);a.I=0,a.l&&a.l.pa(h),Cd(a),Td(a)}r.bb=function(a){a?(this.j.info("Successfully pinged google.com"),Ve(2)):(this.j.info("Failed to ping google.com"),Ve(1))};function Cd(a){if(a.I=0,a.ja=[],a.l){let h=ud(a.h);(h.length!=0||a.i.length!=0)&&(I(a.ja,h),I(a.ja,a.i),a.h.i.length=0,y(a.i),a.i.length=0),a.l.oa()}}function kd(a,h,d){var m=d instanceof qt?nt(d):new qt(d);if(m.g!="")h&&(m.g=h+"."+m.g),Is(m,m.u);else{var x=o.location;m=x.protocol,h=h?h+"."+x.hostname:x.hostname,x=+x.port;let C=new qt(null);m&&Ts(C,m),h&&(C.g=h),x&&Is(C,x),d&&(C.h=d),m=C}return d=a.G,h=a.wa,d&&h&&ie(m,d,h),ie(m,"VER",a.ka),ks(a,m),m}function Od(a,h,d){if(h&&!a.L)throw Error("Can't create secondary domain capable XhrIo object.");return h=a.Aa&&!a.ma?new ce(new qi({ab:d})):new ce(a.ma),h.Fa(a.L),h}r.isActive=function(){return!!this.l&&this.l.isActive(this)};function Dd(){}r=Dd.prototype,r.ra=function(){},r.qa=function(){},r.pa=function(){},r.oa=function(){},r.isActive=function(){return!0},r.Ka=function(){};function Ji(){}Ji.prototype.g=function(a,h){return new $e(a,h)};function $e(a,h){ke.call(this),this.g=new Ed(h),this.l=a,this.h=h&&h.messageUrlParams||null,a=h&&h.messageHeaders||null,h&&h.clientProtocolHeaderRequired&&(a?a["X-Client-Protocol"]="webchannel":a={"X-Client-Protocol":"webchannel"}),this.g.o=a,a=h&&h.initMessageHeaders||null,h&&h.messageContentType&&(a?a["X-WebChannel-Content-Type"]=h.messageContentType:a={"X-WebChannel-Content-Type":h.messageContentType}),h&&h.sa&&(a?a["X-WebChannel-Client-Profile"]=h.sa:a={"X-WebChannel-Client-Profile":h.sa}),this.g.U=a,(a=h&&h.Qb)&&!b(a)&&(this.g.u=a),this.A=h&&h.supportsCrossDomainXhr||!1,this.v=h&&h.sendRawJson||!1,(h=h&&h.httpSessionIdParam)&&!b(h)&&(this.g.G=h,a=this.h,a!==null&&h in a&&(a=this.h,h in a&&delete a[h])),this.j=new on(this)}p($e,ke),$e.prototype.m=function(){this.g.l=this.j,this.A&&(this.g.L=!0),this.g.connect(this.l,this.h||void 0)},$e.prototype.close=function(){vu(this.g)},$e.prototype.o=function(a){var h=this.g;if(typeof a=="string"){var d={};d.__data__=a,a=d}else this.v&&(d={},d.__data__=uu(a),a=d);h.i.push(new qw(h.Ya++,a)),h.I==3&&Wi(h)},$e.prototype.N=function(){this.g.l=null,delete this.j,vu(this.g),delete this.g,$e.Z.N.call(this)};function Nd(a){cu.call(this),a.__headers__&&(this.headers=a.__headers__,this.statusCode=a.__status__,delete a.__headers__,delete a.__status__);var h=a.__sm__;if(h){e:{for(let d in h){a=d;break e}a=void 0}(this.i=a)&&(a=this.i,h=h!==null&&a in h?h[a]:void 0),this.data=h}else this.data=a}p(Nd,cu);function Vd(){lu.call(this),this.status=1}p(Vd,lu);function on(a){this.g=a}p(on,Dd),on.prototype.ra=function(){Ne(this.g,"a")},on.prototype.qa=function(a){Ne(this.g,new Nd(a))},on.prototype.pa=function(a){Ne(this.g,new Vd)},on.prototype.oa=function(){Ne(this.g,"b")},Ji.prototype.createWebChannel=Ji.prototype.g,$e.prototype.send=$e.prototype.o,$e.prototype.open=$e.prototype.m,$e.prototype.close=$e.prototype.close,nc=Rt.createWebChannelTransport=function(){return new Ji},rc=Rt.getStatEventTarget=function(){return ji()},tc=Rt.Event=yr,Ro=Rt.Stat={jb:0,mb:1,nb:2,Hb:3,Mb:4,Jb:5,Kb:6,Ib:7,Gb:8,Lb:9,PROXY:10,NOPROXY:11,Eb:12,Ab:13,Bb:14,zb:15,Cb:16,Db:17,fb:18,eb:19,gb:20},Ui.NO_ERROR=0,Ui.TIMEOUT=8,Ui.HTTP_ERROR=6,Bs=Rt.ErrorCode=Ui,Yh.COMPLETE="complete",ec=Rt.EventType=Yh,Gh.EventType=ys,ys.OPEN="a",ys.CLOSE="b",ys.ERROR="c",ys.MESSAGE="d",ke.prototype.listen=ke.prototype.J,Sn=Rt.WebChannel=Gh,FS=Rt.FetchXmlHttpFactory=qi,ce.prototype.listenOnce=ce.prototype.K,ce.prototype.getLastError=ce.prototype.Ha,ce.prototype.getLastErrorCode=ce.prototype.ya,ce.prototype.getStatus=ce.prototype.ca,ce.prototype.getResponseJson=ce.prototype.La,ce.prototype.getResponseText=ce.prototype.la,ce.prototype.send=ce.prototype.ea,ce.prototype.setWithCredentials=ce.prototype.Fa,Zu=Rt.XhrIo=ce}).apply(typeof xo!="undefined"?xo:typeof self!="undefined"?self:typeof window!="undefined"?window:{});var Se=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}};Se.UNAUTHENTICATED=new Se(null),Se.GOOGLE_CREDENTIALS=new Se("google-credentials-uid"),Se.FIRST_PARTY=new Se("first-party-uid"),Se.MOCK_USER=new Se("mock-user");var Jn="12.11.0";function Ag(r){Jn=r}var Rr=new An("@firebase/firestore");function xn(){return Rr.logLevel}function M(r,...e){if(Rr.logLevel<=X.DEBUG){let t=e.map(Vl);Rr.debug(`Firestore (${Jn}): ${r}`,...t)}}function kt(r,...e){if(Rr.logLevel<=X.ERROR){let t=e.map(Vl);Rr.error(`Firestore (${Jn}): ${r}`,...t)}}function Ot(r,...e){if(Rr.logLevel<=X.WARN){let t=e.map(Vl);Rr.warn(`Firestore (${Jn}): ${r}`,...t)}}function Vl(r){if(typeof r=="string")return r;try{return(function(t){return JSON.stringify(t)})(r)}catch{return r}}function K(r,e,t){let n="Unexpected state";typeof e=="string"?n=e:t=e,Sg(r,n,t)}function Sg(r,e,t){let n=`FIRESTORE (${Jn}) INTERNAL ASSERTION FAILED: ${e} (ID: ${r.toString(16)})`;if(t!==void 0)try{n+=" CONTEXT: "+JSON.stringify(t)}catch{n+=" CONTEXT: "+t}throw kt(n),new Error(n)}function te(r,e,t,n){let s="Unexpected state";typeof t=="string"?s=t:n=t,r||Sg(e,s,n)}function W(r,e){return r}var O={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"},B=class extends Xe{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}};var ct=class{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}};var Vo=class{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}},Lo=class{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(Se.UNAUTHENTICATED)))}shutdown(){}},lc=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}},Fo=class{constructor(e){this.t=e,this.currentUser=Se.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){te(this.o===void 0,42304);let n=this.i,s=c=>this.i!==n?(n=this.i,t(c)):Promise.resolve(),i=new ct;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new ct,e.enqueueRetryable((()=>s(this.currentUser)))};let o=()=>{let c=i;e.enqueueRetryable((async()=>{await c.promise,await s(this.currentUser)}))},u=c=>{M("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=c,this.o&&(this.auth.addAuthTokenListener(this.o),o())};this.t.onInit((c=>u(c))),setTimeout((()=>{if(!this.auth){let c=this.t.getImmediate({optional:!0});c?u(c):(M("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new ct)}}),0),o()}getToken(){let e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((n=>this.i!==e?(M("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):n?(te(typeof n.accessToken=="string",31837,{l:n}),new Vo(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 te(e===null||typeof e=="string",2055,{h:e}),new Se(e)}},hc=class{constructor(e,t,n){this.P=e,this.T=t,this.I=n,this.type="FirstParty",this.user=Se.FIRST_PARTY,this.R=new Map}A(){return this.I?this.I():null}get headers(){this.R.set("X-Goog-AuthUser",this.P);let e=this.A();return e&&this.R.set("Authorization",e),this.T&&this.R.set("X-Goog-Iam-Authorization-Token",this.T),this.R}},dc=class{constructor(e,t,n){this.P=e,this.T=t,this.I=n}getToken(){return Promise.resolve(new hc(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable((()=>t(Se.FIRST_PARTY)))}shutdown(){}invalidateToken(){}},Mo=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)}},jo=class{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,Nm(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,t){te(this.o===void 0,3512);let n=i=>{i.error!=null&&M("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${i.error.message}`);let o=i.token!==this.m;return this.m=i.token,M("FirebaseAppCheckTokenProvider",`Received ${o?"new":"existing"} token.`),o?t(i.token):Promise.resolve()};this.o=i=>{e.enqueueRetryable((()=>n(i)))};let s=i=>{M("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=i,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit((i=>s(i))),setTimeout((()=>{if(!this.appCheck){let i=this.V.getImmediate({optional:!0});i?s(i):M("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){if(this.p)return Promise.resolve(new Mo(this.p));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((t=>t?(te(typeof t.token=="string",44558,{tokenResult:t}),this.m=t.token,new Mo(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 MS(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 Pr=class{static newId(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(4.129032258064516),n="";for(;n.length<20;){let s=MS(40);for(let i=0;i<s.length;++i)n.length<20&&s[i]<t&&(n+=e.charAt(s[i]%62))}return n}};function Y(r,e){return r<e?-1:r>e?1:0}function fc(r,e){let t=Math.min(r.length,e.length);for(let n=0;n<t;n++){let s=r.charAt(n),i=e.charAt(n);if(s!==i)return sc(s)===sc(i)?Y(s,i):sc(s)?1:-1}return Y(r.length,e.length)}var jS=55296,US=57343;function sc(r){let e=r.charCodeAt(0);return e>=jS&&e<=US}function Nn(r,e,t){return r.length===e.length&&r.every(((n,s)=>t(n,e[s])))}var Bm="__name__",Uo=class r{constructor(e,t,n){t===void 0?t=0:t>e.length&&K(637,{offset:t,range:e.length}),n===void 0?n=e.length-t:n>e.length-t&&K(1746,{length:n,range:e.length-t}),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 Y(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)):fc(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return xt.fromString(e.substring(4,e.length-2))}},he=class r extends Uo{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 B(O.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([])}},BS=/^[_a-zA-Z][_a-zA-Z0-9]*$/,Be=class r extends Uo{construct(e,t,n){return new r(e,t,n)}static isValidIdentifier(e){return BS.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)===Bm}static keyField(){return new r([Bm])}static fromServerFormat(e){let t=[],n="",s=0,i=()=>{if(n.length===0)throw new B(O.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""},o=!1;for(;s<e.length;){let u=e[s];if(u==="\\"){if(s+1===e.length)throw new B(O.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let c=e[s+1];if(c!=="\\"&&c!=="."&&c!=="`")throw new B(O.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=c,s+=2}else u==="`"?(o=!o,s++):u!=="."||o?(n+=u,s++):(i(),s++)}if(i(),o)throw new B(O.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new r(t)}static emptyPath(){return new r([])}};var q=class r{constructor(e){this.path=e}static fromPath(e){return new r(he.fromString(e))}static fromName(e){return new r(he.fromString(e).popFirst(5))}static empty(){return new r(he.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&&he.comparator(this.path,e.path)===0}toString(){return this.path.toString()}static comparator(e,t){return he.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new r(new he(e.slice()))}};function $S(r,e,t){if(!t)throw new B(O.INVALID_ARGUMENT,`Function ${r}() cannot be called with an empty ${e}.`)}function xg(r,e,t,n){if(e===!0&&n===!0)throw new B(O.INVALID_ARGUMENT,`${r} and ${t} cannot be used together.`)}function $m(r){if(!q.isDocumentKey(r))throw new B(O.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${r} has ${r.length}.`)}function Rg(r){return typeof r=="object"&&r!==null&&(Object.getPrototypeOf(r)===Object.prototype||Object.getPrototypeOf(r)===null)}function _a(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":K(12329,{type:typeof r})}function We(r,e){if("_delegate"in r&&(r=r._delegate),!(r instanceof e)){if(e.name===r.constructor.name)throw new B(O.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let t=_a(r);throw new B(O.INVALID_ARGUMENT,`Expected type '${e.name}', but it was: ${t}`)}}return r}function me(r,e){let t={typeString:r};return e&&(t.value=e),t}function Qn(r,e){if(!Rg(r))throw new B(O.INVALID_ARGUMENT,"JSON must be an object");let t;for(let n in e)if(e[n]){let s=e[n].typeString,i="value"in e[n]?{value:e[n].value}:void 0;if(!(n in r)){t=`JSON missing required field: '${n}'`;break}let o=r[n];if(s&&typeof o!==s){t=`JSON field '${n}' must be a ${s}.`;break}if(i!==void 0&&o!==i.value){t=`Expected '${n}' field to equal '${i.value}'`;break}}if(t)throw new B(O.INVALID_ARGUMENT,t);return!0}var qm=-62135596800,zm=1e6,ge=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)*zm);return new r(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new B(O.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new B(O.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<qm)throw new B(O.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new B(O.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/zm}_compareTo(e){return this.seconds===e.seconds?Y(this.nanoseconds,e.nanoseconds):Y(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{type:r._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(Qn(e,r._jsonSchema))return new r(e.seconds,e.nanoseconds)}valueOf(){let e=this.seconds-qm;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}};ge._jsonSchemaVersion="firestore/timestamp/1.0",ge._jsonSchema={type:me("string",ge._jsonSchemaVersion),seconds:me("number"),nanoseconds:me("number")};var H=class r{static fromTimestamp(e){return new r(e)}static min(){return new r(new ge(0,0))}static max(){return new r(new ge(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 Ws=-1,Bo=class{constructor(e,t,n,s){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=s}};Bo.UNKNOWN_ID=-1;function qS(r,e){let t=r.toTimestamp().seconds,n=r.toTimestamp().nanoseconds+1,s=H.fromTimestamp(n===1e9?new ge(t+1,0):new ge(t,n));return new Cr(s,q.empty(),e)}function zS(r){return new Cr(r.readTime,r.key,Ws)}var Cr=class r{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new r(H.min(),q.empty(),Ws)}static max(){return new r(H.max(),q.empty(),Ws)}};function KS(r,e){let t=r.readTime.compareTo(e.readTime);return t!==0?t:(t=q.comparator(r.documentKey,e.documentKey),t!==0?t:Y(r.largestBatchId,e.largestBatchId))}var GS="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",pc=class{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}};async function Yn(r){if(r.code!==O.FAILED_PRECONDITION||r.message!==GS)throw r;M("LocalStore","Unexpectedly lost primary lease")}var V=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&&K(59440),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,o=!1;e.forEach((u=>{++s,u.next((()=>{++i,o&&i===s&&t()}),(c=>n(c)))})),o=!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,o=new Array(i),u=0;for(let c=0;c<i;c++){let l=c;t(e[l]).next((f=>{o[l]=f,++u,u===i&&n(o)}),(f=>s(f)))}}))}static doWhile(e,t){return new r(((n,s)=>{let i=()=>{e()===!0?t().next((()=>{i()}),s):n()};i()}))}};function WS(r){let e=r.match(/Android ([\d.]+)/i),t=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(t)}function Xn(r){return r.name==="IndexedDbTransactionError"}var Vn=class{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=n=>this.ae(n),this.ue=n=>t.writeSequenceNumber(n))}ae(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this.ue&&this.ue(e),e}};Vn.ce=-1;var Ll=-1;function wa(r){return r==null}function Hs(r){return r===0&&1/r==-1/0}function HS(r){return typeof r=="number"&&Number.isInteger(r)&&!Hs(r)&&r<=Number.MAX_SAFE_INTEGER&&r>=Number.MIN_SAFE_INTEGER}var Pg="";function JS(r){let e="";for(let t=0;t<r.length;t++)e.length>0&&(e=Km(e)),e=QS(r.get(t),e);return Km(e)}function QS(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 Pg:t+="";break;default:t+=i}}return t}function Km(r){return r+Pg+""}var YS="remoteDocuments",Cg="owner";var kg="mutationQueues";var Og="mutations";var Dg="documentMutations",XS="remoteDocumentsV14";var Ng="remoteDocumentGlobal";var Vg="targets";var Lg="targetDocuments";var Fg="targetGlobal",Mg="collectionParents";var jg="clientMetadata";var Ug="bundles";var Bg="namedQueries";var ZS="indexConfiguration";var ex="indexState";var tx="indexEntries";var $g="documentOverlays";var rx="globals";var nx=[kg,Og,Dg,YS,Vg,Cg,Fg,Lg,jg,Ng,Mg,Ug,Bg],fj=[...nx,$g],sx=[kg,Og,Dg,XS,Vg,Cg,Fg,Lg,jg,Ng,Mg,Ug,Bg,$g],ix=sx,ox=[...ix,ZS,ex,tx];var pj=[...ox,rx];function Gm(r){let e=0;for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e++;return e}function dr(r,e){for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e(t,r[t])}function qg(r){for(let e in r)if(Object.prototype.hasOwnProperty.call(r,e))return!1;return!0}var de=class r{constructor(e,t){this.comparator=e,this.root=t||lt.EMPTY}insert(e,t){return new r(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,lt.BLACK,null,null))}remove(e){return new r(this.comparator,this.root.remove(e,this.comparator).copy(null,null,lt.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 kn(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new kn(this.root,e,this.comparator,!1)}getReverseIterator(){return new kn(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new kn(this.root,e,this.comparator,!0)}},kn=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}}},lt=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())throw K(43730,{key:this.key,value:this.value});if(this.right.isRed())throw K(14113,{key:this.key,value:this.value});let e=this.left.check();if(e!==this.right.check())throw K(27949);return e+(this.isRed()?0:1)}};lt.EMPTY=null,lt.RED=!0,lt.BLACK=!1;lt.EMPTY=new class{constructor(){this.size=0}get key(){throw K(57766)}get value(){throw K(16141)}get color(){throw K(16727)}get left(){throw K(29726)}get right(){throw K(36894)}copy(e,t,n,s,i){return this}insert(e,t,n){return new lt(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 xe=class r{constructor(e){this.comparator=e,this.data=new de(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 $o(this.data.getIterator())}getIteratorFrom(e){return new $o(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}},$o=class{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}};var Ge=class r{constructor(e){this.fields=e,e.sort(Be.comparator)}static empty(){return new r([])}unionWith(e){let t=new xe(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 Nn(this.fields,e.fields,((t,n)=>t.isEqual(n)))}};var qo=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 qo("Invalid base64 string: "+i):i}})(e);return new r(t)}static fromUint8Array(e){let t=(function(s){let i="";for(let o=0;o<s.length;++o)i+=String.fromCharCode(s[o]);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 Y(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}};Pe.EMPTY_BYTE_STRING=new Pe("");var ax=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Dt(r){if(te(!!r,39018),typeof r=="string"){let e=0,t=ax.exec(r);if(te(!!t,46558,{timestamp:r}),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 Nt(r){return typeof r=="string"?Pe.fromBase64String(r):Pe.fromUint8Array(r)}var zg="server_timestamp",Kg="__type__",Gg="__previous_value__",Wg="__local_write_time__";function va(r){var t,n;return((n=(((t=r==null?void 0:r.mapValue)==null?void 0:t.fields)||{})[Kg])==null?void 0:n.stringValue)===zg}function ba(r){let e=r.mapValue.fields[Gg];return va(e)?ba(e):e}function Js(r){let e=Dt(r.mapValue.fields[Wg].timestampValue);return new ge(e.seconds,e.nanos)}var mc=class{constructor(e,t,n,s,i,o,u,c,l,f,p){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=s,this.ssl=i,this.forceLongPolling=o,this.autoDetectLongPolling=u,this.longPollingOptions=c,this.useFetchStreams=l,this.isUsingEmulator=f,this.apiKey=p}},zo="(default)",Qs=class r{constructor(e,t){this.projectId=e,this.database=t||zo}static empty(){return new r("","")}get isDefaultDatabase(){return this.database===zo}isEqual(e){return e instanceof r&&e.projectId===this.projectId&&e.database===this.database}};function Hg(r,e){if(!Object.prototype.hasOwnProperty.apply(r.options,["projectId"]))throw new B(O.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Qs(r.options.projectId,e)}var Fl="__type__",Jg="__max__",Po={mapValue:{fields:{__type__:{stringValue:Jg}}}},Ml="__vector__",Ln="value";function cr(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?va(r)?4:Yg(r)?9007199254740991:Qg(r)?10:11:K(28295,{value:r})}function mt(r,e){if(r===e)return!0;let t=cr(r);if(t!==cr(e))return!1;switch(t){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===e.booleanValue;case 4:return Js(r).isEqual(Js(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 o=Dt(s.timestampValue),u=Dt(i.timestampValue);return o.seconds===u.seconds&&o.nanos===u.nanos})(r,e);case 5:return r.stringValue===e.stringValue;case 6:return(function(s,i){return Nt(s.bytesValue).isEqual(Nt(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 o=ae(s.doubleValue),u=ae(i.doubleValue);return o===u?Hs(o)===Hs(u):isNaN(o)&&isNaN(u)}return!1})(r,e);case 9:return Nn(r.arrayValue.values||[],e.arrayValue.values||[],mt);case 10:case 11:return(function(s,i){let o=s.mapValue.fields||{},u=i.mapValue.fields||{};if(Gm(o)!==Gm(u))return!1;for(let c in o)if(o.hasOwnProperty(c)&&(u[c]===void 0||!mt(o[c],u[c])))return!1;return!0})(r,e);default:return K(52216,{left:r})}}function Ys(r,e){return(r.values||[]).find((t=>mt(t,e)))!==void 0}function Fn(r,e){if(r===e)return 0;let t=cr(r),n=cr(e);if(t!==n)return Y(t,n);switch(t){case 0:case 9007199254740991:return 0;case 1:return Y(r.booleanValue,e.booleanValue);case 2:return(function(i,o){let u=ae(i.integerValue||i.doubleValue),c=ae(o.integerValue||o.doubleValue);return u<c?-1:u>c?1:u===c?0:isNaN(u)?isNaN(c)?0:-1:1})(r,e);case 3:return Wm(r.timestampValue,e.timestampValue);case 4:return Wm(Js(r),Js(e));case 5:return fc(r.stringValue,e.stringValue);case 6:return(function(i,o){let u=Nt(i),c=Nt(o);return u.compareTo(c)})(r.bytesValue,e.bytesValue);case 7:return(function(i,o){let u=i.split("/"),c=o.split("/");for(let l=0;l<u.length&&l<c.length;l++){let f=Y(u[l],c[l]);if(f!==0)return f}return Y(u.length,c.length)})(r.referenceValue,e.referenceValue);case 8:return(function(i,o){let u=Y(ae(i.latitude),ae(o.latitude));return u!==0?u:Y(ae(i.longitude),ae(o.longitude))})(r.geoPointValue,e.geoPointValue);case 9:return Hm(r.arrayValue,e.arrayValue);case 10:return(function(i,o){var g,y,I,R;let u=i.fields||{},c=o.fields||{},l=(g=u[Ln])==null?void 0:g.arrayValue,f=(y=c[Ln])==null?void 0:y.arrayValue,p=Y(((I=l==null?void 0:l.values)==null?void 0:I.length)||0,((R=f==null?void 0:f.values)==null?void 0:R.length)||0);return p!==0?p:Hm(l,f)})(r.mapValue,e.mapValue);case 11:return(function(i,o){if(i===Po.mapValue&&o===Po.mapValue)return 0;if(i===Po.mapValue)return 1;if(o===Po.mapValue)return-1;let u=i.fields||{},c=Object.keys(u),l=o.fields||{},f=Object.keys(l);c.sort(),f.sort();for(let p=0;p<c.length&&p<f.length;++p){let g=fc(c[p],f[p]);if(g!==0)return g;let y=Fn(u[c[p]],l[f[p]]);if(y!==0)return y}return Y(c.length,f.length)})(r.mapValue,e.mapValue);default:throw K(23264,{he:t})}}function Wm(r,e){if(typeof r=="string"&&typeof e=="string"&&r.length===e.length)return Y(r,e);let t=Dt(r),n=Dt(e),s=Y(t.seconds,n.seconds);return s!==0?s:Y(t.nanos,n.nanos)}function Hm(r,e){let t=r.values||[],n=e.values||[];for(let s=0;s<t.length&&s<n.length;++s){let i=Fn(t[s],n[s]);if(i)return i}return Y(t.length,n.length)}function Mn(r){return gc(r)}function gc(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=Dt(t);return`time(${n.seconds},${n.nanos})`})(r.timestampValue):"stringValue"in r?r.stringValue:"bytesValue"in r?(function(t){return Nt(t).toBase64()})(r.bytesValue):"referenceValue"in r?(function(t){return q.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+=gc(i);return n+"]"})(r.arrayValue):"mapValue"in r?(function(t){let n=Object.keys(t.fields||{}).sort(),s="{",i=!0;for(let o of n)i?i=!1:s+=",",s+=`${o}:${gc(t.fields[o])}`;return s+"}"})(r.mapValue):K(61005,{value:r})}function Oo(r){switch(cr(r)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let e=ba(r);return e?16+Oo(e):16;case 5:return 2*r.stringValue.length;case 6:return Nt(r.bytesValue).approximateByteSize();case 7:return r.referenceValue.length;case 9:return(function(n){return(n.values||[]).reduce(((s,i)=>s+Oo(i)),0)})(r.arrayValue);case 10:case 11:return(function(n){let s=0;return dr(n.fields,((i,o)=>{s+=i.length+Oo(o)})),s})(r.mapValue);default:throw K(13486,{value:r})}}function yc(r){return!!r&&"integerValue"in r}function jl(r){return!!r&&"arrayValue"in r}function Jm(r){return!!r&&"nullValue"in r}function Qm(r){return!!r&&"doubleValue"in r&&isNaN(Number(r.doubleValue))}function Do(r){return!!r&&"mapValue"in r}function Qg(r){var t,n;return((n=(((t=r==null?void 0:r.mapValue)==null?void 0:t.fields)||{})[Fl])==null?void 0:n.stringValue)===Ml}function zs(r){if(r.geoPointValue)return{geoPointValue:{...r.geoPointValue}};if(r.timestampValue&&typeof r.timestampValue=="object")return{timestampValue:{...r.timestampValue}};if(r.mapValue){let e={mapValue:{fields:{}}};return dr(r.mapValue.fields,((t,n)=>e.mapValue.fields[t]=zs(n))),e}if(r.arrayValue){let e={arrayValue:{values:[]}};for(let t=0;t<(r.arrayValue.values||[]).length;++t)e.arrayValue.values[t]=zs(r.arrayValue.values[t]);return e}return{...r}}function Yg(r){return(((r.mapValue||{}).fields||{}).__type__||{}).stringValue===Jg}var gj={mapValue:{fields:{[Fl]:{stringValue:Ml},[Ln]:{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)],!Do(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=zs(t)}setAll(e){let t=Be.emptyPath(),n={},s=[];e.forEach(((o,u)=>{if(!t.isImmediateParentOf(u)){let c=this.getFieldsMap(t);this.applyChanges(c,n,s),n={},s=[],t=u.popLast()}o?n[u.lastSegment()]=zs(o):s.push(u.lastSegment())}));let i=this.getFieldsMap(t);this.applyChanges(i,n,s)}delete(e){let t=this.field(e.popLast());Do(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return mt(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)];Do(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=s),t=s}return t.mapValue.fields}applyChanges(e,t,n){dr(t,((s,i)=>e[s]=i));for(let s of n)delete e[s]}clone(){return new r(zs(this.value))}};function Xg(r){let e=[];return dr(r.fields,((t,n)=>{let s=new Be([t]);if(Do(n)){let i=Xg(n.mapValue).fields;if(i.length===0)e.push(s);else for(let o of i)e.push(s.child(o))}else e.push(s)})),new Ge(e)}var Ze=class r{constructor(e,t,n,s,i,o,u){this.key=e,this.documentType=t,this.version=n,this.readTime=s,this.createTime=i,this.data=o,this.documentState=u}static newInvalidDocument(e){return new r(e,0,H.min(),H.min(),H.min(),Ue.empty(),0)}static newFoundDocument(e,t,n,s){return new r(e,1,t,H.min(),n,s,0)}static newNoDocument(e,t){return new r(e,2,t,H.min(),H.min(),Ue.empty(),0)}static newUnknownDocument(e,t){return new r(e,3,t,H.min(),H.min(),Ue.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(H.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=H.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 kr=class{constructor(e,t){this.position=e,this.inclusive=t}};function Ym(r,e,t){let n=0;for(let s=0;s<r.position.length;s++){let i=e[s],o=r.position[s];if(i.field.isKeyField()?n=q.comparator(q.fromName(o.referenceValue),t.key):n=Fn(o,t.data.field(i.field)),i.dir==="desc"&&(n*=-1),n!==0)break}return n}function Xm(r,e){if(r===null)return e===null;if(e===null||r.inclusive!==e.inclusive||r.position.length!==e.position.length)return!1;for(let t=0;t<r.position.length;t++)if(!mt(r.position[t],e.position[t]))return!1;return!0}var Or=class{constructor(e,t="asc"){this.field=e,this.dir=t}};function ux(r,e){return r.dir===e.dir&&r.field.isEqual(e.field)}var Ko=class{},we=class r extends Ko{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 wc(e,t,n):t==="array-contains"?new Ec(e,n):t==="in"?new Tc(e,n):t==="not-in"?new Ic(e,n):t==="array-contains-any"?new Ac(e,n):new r(e,t,n)}static createKeyFieldInFilter(e,t,n){return t==="in"?new vc(e,n):new bc(e,n)}matches(e){let t=e.data.field(this.field);return this.op==="!="?t!==null&&t.nullValue===void 0&&this.matchesComparison(Fn(t,this.value)):t!==null&&cr(this.value)===cr(t)&&this.matchesComparison(Fn(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 K(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}},et=class r extends Ko{constructor(e,t){super(),this.filters=e,this.op=t,this.Pe=null}static create(e,t){return new r(e,t)}matches(e){return Zg(this)?this.filters.find((t=>!t.matches(e)))===void 0:this.filters.find((t=>t.matches(e)))!==void 0}getFlattenedFilters(){return this.Pe!==null||(this.Pe=this.filters.reduce(((e,t)=>e.concat(t.getFlattenedFilters())),[])),this.Pe}getFilters(){return Object.assign([],this.filters)}};function Zg(r){return r.op==="and"}function ey(r){return cx(r)&&Zg(r)}function cx(r){for(let e of r.filters)if(e instanceof et)return!1;return!0}function _c(r){if(r instanceof we)return r.field.canonicalString()+r.op.toString()+Mn(r.value);if(ey(r))return r.filters.map((e=>_c(e))).join(",");{let e=r.filters.map((t=>_c(t))).join(",");return`${r.op}(${e})`}}function ty(r,e){return r instanceof we?(function(n,s){return s instanceof we&&n.op===s.op&&n.field.isEqual(s.field)&&mt(n.value,s.value)})(r,e):r instanceof et?(function(n,s){return s instanceof et&&n.op===s.op&&n.filters.length===s.filters.length?n.filters.reduce(((i,o,u)=>i&&ty(o,s.filters[u])),!0):!1})(r,e):void K(19439)}function ry(r){return r instanceof we?(function(t){return`${t.field.canonicalString()} ${t.op} ${Mn(t.value)}`})(r):r instanceof et?(function(t){return t.op.toString()+" {"+t.getFilters().map(ry).join(" ,")+"}"})(r):"Filter"}var wc=class extends we{constructor(e,t,n){super(e,t,n),this.key=q.fromName(n.referenceValue)}matches(e){let t=q.comparator(e.key,this.key);return this.matchesComparison(t)}},vc=class extends we{constructor(e,t){super(e,"in",t),this.keys=ny("in",t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}},bc=class extends we{constructor(e,t){super(e,"not-in",t),this.keys=ny("not-in",t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}};function ny(r,e){var t;return(((t=e.arrayValue)==null?void 0:t.values)||[]).map((n=>q.fromName(n.referenceValue)))}var Ec=class extends we{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return jl(t)&&Ys(t.arrayValue,this.value)}},Tc=class extends we{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return t!==null&&Ys(this.value.arrayValue,t)}},Ic=class extends we{constructor(e,t){super(e,"not-in",t)}matches(e){if(Ys(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return t!==null&&t.nullValue===void 0&&!Ys(this.value.arrayValue,t)}},Ac=class extends we{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!jl(t)||!t.arrayValue.values)&&t.arrayValue.values.some((n=>Ys(this.value.arrayValue,n)))}};var Sc=class{constructor(e,t=null,n=[],s=[],i=null,o=null,u=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=s,this.limit=i,this.startAt=o,this.endAt=u,this.Te=null}};function Zm(r,e=null,t=[],n=[],s=null,i=null,o=null){return new Sc(r,e,t,n,s,i,o)}function Ul(r){let e=W(r);if(e.Te===null){let t=e.path.canonicalString();e.collectionGroup!==null&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map((n=>_c(n))).join(","),t+="|ob:",t+=e.orderBy.map((n=>(function(i){return i.field.canonicalString()+i.dir})(n))).join(","),wa(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map((n=>Mn(n))).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map((n=>Mn(n))).join(",")),e.Te=t}return e.Te}function Bl(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(!ux(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(!ty(r.filters[t],e.filters[t]))return!1;return r.collectionGroup===e.collectionGroup&&!!r.path.isEqual(e.path)&&!!Xm(r.startAt,e.startAt)&&Xm(r.endAt,e.endAt)}function xc(r){return q.isDocumentKey(r.path)&&r.collectionGroup===null&&r.filters.length===0}var jn=class{constructor(e,t=null,n=[],s=[],i=null,o="F",u=null,c=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=s,this.limit=i,this.limitType=o,this.startAt=u,this.endAt=c,this.Ee=null,this.Ie=null,this.Re=null,this.startAt,this.endAt}};function lx(r,e,t,n,s,i,o,u){return new jn(r,e,t,n,s,i,o,u)}function ai(r){return new jn(r)}function eg(r){return r.filters.length===0&&r.limit===null&&r.startAt==null&&r.endAt==null&&(r.explicitOrderBy.length===0||r.explicitOrderBy.length===1&&r.explicitOrderBy[0].field.isKeyField())}function hx(r){return q.isDocumentKey(r.path)&&r.collectionGroup===null&&r.filters.length===0}function sy(r){return r.collectionGroup!==null}function On(r){let e=W(r);if(e.Ee===null){e.Ee=[];let t=new Set;for(let i of e.explicitOrderBy)e.Ee.push(i),t.add(i.field.canonicalString());let n=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(function(o){let u=new xe(Be.comparator);return o.filters.forEach((c=>{c.getFlattenedFilters().forEach((l=>{l.isInequality()&&(u=u.add(l.field))}))})),u})(e).forEach((i=>{t.has(i.canonicalString())||i.isKeyField()||e.Ee.push(new Or(i,n))})),t.has(Be.keyField().canonicalString())||e.Ee.push(new Or(Be.keyField(),n))}return e.Ee}function ht(r){let e=W(r);return e.Ie||(e.Ie=dx(e,On(r))),e.Ie}function dx(r,e){if(r.limitType==="F")return Zm(r.path,r.collectionGroup,e,r.filters,r.limit,r.startAt,r.endAt);{e=e.map((s=>{let i=s.dir==="desc"?"asc":"desc";return new Or(s.field,i)}));let t=r.endAt?new kr(r.endAt.position,r.endAt.inclusive):null,n=r.startAt?new kr(r.startAt.position,r.startAt.inclusive):null;return Zm(r.path,r.collectionGroup,e,r.filters,r.limit,t,n)}}function Go(r,e,t){return new jn(r.path,r.collectionGroup,r.explicitOrderBy.slice(),r.filters.slice(),e,t,r.startAt,r.endAt)}function Ea(r,e){return Bl(ht(r),ht(e))&&r.limitType===e.limitType}function iy(r){return`${Ul(ht(r))}|lt:${r.limitType}`}function Rn(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=>ry(s))).join(", ")}]`),wa(t.limit)||(n+=", limit: "+t.limit),t.orderBy.length>0&&(n+=`, orderBy: [${t.orderBy.map((s=>(function(o){return`${o.field.canonicalString()} (${o.dir})`})(s))).join(", ")}]`),t.startAt&&(n+=", startAt: ",n+=t.startAt.inclusive?"b:":"a:",n+=t.startAt.position.map((s=>Mn(s))).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map((s=>Mn(s))).join(",")),`Target(${n})`})(ht(r))}; limitType=${r.limitType})`}function Ta(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):q.isDocumentKey(n.path)?n.path.isEqual(i):n.path.isImmediateParentOf(i)})(r,e)&&(function(n,s){for(let i of On(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(o,u,c){let l=Ym(o,u,c);return o.inclusive?l<=0:l<0})(n.startAt,On(n),s)||n.endAt&&!(function(o,u,c){let l=Ym(o,u,c);return o.inclusive?l>=0:l>0})(n.endAt,On(n),s))})(r,e)}function fx(r){return r.collectionGroup||(r.path.length%2==1?r.path.lastSegment():r.path.get(r.path.length-2))}function oy(r){return(e,t)=>{let n=!1;for(let s of On(r)){let i=px(s,e,t);if(i!==0)return i;n=n||s.field.isKeyField()}return 0}}function px(r,e,t){let n=r.field.isKeyField()?q.comparator(e.key,t.key):(function(i,o,u){let c=o.data.field(i),l=u.data.field(i);return c!==null&&l!==null?Fn(c,l):K(42886)})(r.field,e,t);switch(r.dir){case"asc":return n;case"desc":return-1*n;default:return K(19790,{direction:r.dir})}}var Vt=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){dr(this.inner,((t,n)=>{for(let[s,i]of n)e(s,i)}))}isEmpty(){return qg(this.inner)}size(){return this.innerSize}};var mx=new de(q.comparator);function Lt(){return mx}var ay=new de(q.comparator);function qs(...r){let e=ay;for(let t of r)e=e.insert(t.key,t);return e}function uy(r){let e=ay;return r.forEach(((t,n)=>e=e.insert(t,n.overlayedDocument))),e}function Sr(){return Ks()}function cy(){return Ks()}function Ks(){return new Vt((r=>r.toString()),((r,e)=>r.isEqual(e)))}var gx=new de(q.comparator),yx=new xe(q.comparator);function Q(...r){let e=yx;for(let t of r)e=e.add(t);return e}var _x=new xe(Y);function wx(){return _x}function $l(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:Hs(e)?"-0":e}}function ly(r){return{integerValue:""+r}}function vx(r,e){return HS(e)?ly(e):$l(r,e)}var Un=class{constructor(){this._=void 0}};function bx(r,e,t){return r instanceof Bn?(function(s,i){let o={fields:{[Kg]:{stringValue:zg},[Wg]:{timestampValue:{seconds:s.seconds,nanos:s.nanoseconds}}}};return i&&va(i)&&(i=ba(i)),i&&(o.fields[Gg]=i),{mapValue:o}})(t,e):r instanceof Dr?dy(r,e):r instanceof Nr?fy(r,e):(function(s,i){let o=hy(s,i),u=tg(o)+tg(s.Ae);return yc(o)&&yc(s.Ae)?ly(u):$l(s.serializer,u)})(r,e)}function Ex(r,e,t){return r instanceof Dr?dy(r,e):r instanceof Nr?fy(r,e):t}function hy(r,e){return r instanceof $n?(function(n){return yc(n)||(function(i){return!!i&&"doubleValue"in i})(n)})(e)?e:{integerValue:0}:null}var Bn=class extends Un{},Dr=class extends Un{constructor(e){super(),this.elements=e}};function dy(r,e){let t=py(e);for(let n of r.elements)t.some((s=>mt(s,n)))||t.push(n);return{arrayValue:{values:t}}}var Nr=class extends Un{constructor(e){super(),this.elements=e}};function fy(r,e){let t=py(e);for(let n of r.elements)t=t.filter((s=>!mt(s,n)));return{arrayValue:{values:t}}}var $n=class extends Un{constructor(e,t){super(),this.serializer=e,this.Ae=t}};function tg(r){return ae(r.integerValue||r.doubleValue)}function py(r){return jl(r)&&r.arrayValue.values?r.arrayValue.values.slice():[]}function Tx(r,e){return r.field.isEqual(e.field)&&(function(n,s){return n instanceof Dr&&s instanceof Dr||n instanceof Nr&&s instanceof Nr?Nn(n.elements,s.elements,mt):n instanceof $n&&s instanceof $n?mt(n.Ae,s.Ae):n instanceof Bn&&s instanceof Bn})(r.transform,e.transform)}var Rc=class{constructor(e,t){this.version=e,this.transformResults=t}},Pt=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 No(r,e){return r.updateTime!==void 0?e.isFoundDocument()&&e.version.isEqual(r.updateTime):r.exists===void 0||r.exists===e.isFoundDocument()}var qn=class{};function my(r,e){if(!r.hasLocalMutations||e&&e.fields.length===0)return null;if(e===null)return r.isNoDocument()?new Xs(r.key,Pt.none()):new Vr(r.key,r.data,Pt.none());{let t=r.data,n=Ue.empty(),s=new xe(Be.comparator);for(let i of e.fields)if(!s.has(i)){let o=t.field(i);o===null&&i.length>1&&(i=i.popLast(),o=t.field(i)),o===null?n.delete(i):n.set(i,o),s=s.add(i)}return new gt(r.key,n,new Ge(s.toArray()),Pt.none())}}function Ix(r,e,t){r instanceof Vr?(function(s,i,o){let u=s.value.clone(),c=ng(s.fieldTransforms,i,o.transformResults);u.setAll(c),i.convertToFoundDocument(o.version,u).setHasCommittedMutations()})(r,e,t):r instanceof gt?(function(s,i,o){if(!No(s.precondition,i))return void i.convertToUnknownDocument(o.version);let u=ng(s.fieldTransforms,i,o.transformResults),c=i.data;c.setAll(gy(s)),c.setAll(u),i.convertToFoundDocument(o.version,c).setHasCommittedMutations()})(r,e,t):(function(s,i,o){i.convertToNoDocument(o.version).setHasCommittedMutations()})(0,e,t)}function Gs(r,e,t,n){return r instanceof Vr?(function(i,o,u,c){if(!No(i.precondition,o))return u;let l=i.value.clone(),f=sg(i.fieldTransforms,c,o);return l.setAll(f),o.convertToFoundDocument(o.version,l).setHasLocalMutations(),null})(r,e,t,n):r instanceof gt?(function(i,o,u,c){if(!No(i.precondition,o))return u;let l=sg(i.fieldTransforms,c,o),f=o.data;return f.setAll(gy(i)),f.setAll(l),o.convertToFoundDocument(o.version,f).setHasLocalMutations(),u===null?null:u.unionWith(i.fieldMask.fields).unionWith(i.fieldTransforms.map((p=>p.field)))})(r,e,t,n):(function(i,o,u){return No(i.precondition,o)?(o.convertToNoDocument(o.version).setHasLocalMutations(),null):u})(r,e,t)}function Ax(r,e){let t=null;for(let n of r.fieldTransforms){let s=e.data.field(n.field),i=hy(n.transform,s||null);i!=null&&(t===null&&(t=Ue.empty()),t.set(n.field,i))}return t||null}function rg(r,e){return r.type===e.type&&!!r.key.isEqual(e.key)&&!!r.precondition.isEqual(e.precondition)&&!!(function(n,s){return n===void 0&&s===void 0||!(!n||!s)&&Nn(n,s,((i,o)=>Tx(i,o)))})(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 Vr=class extends qn{constructor(e,t,n,s=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}},gt=class extends qn{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 gy(r){let e=new Map;return r.fieldMask.fields.forEach((t=>{if(!t.isEmpty()){let n=r.data.field(t);e.set(t,n)}})),e}function ng(r,e,t){let n=new Map;te(r.length===t.length,32656,{Ve:t.length,de:r.length});for(let s=0;s<t.length;s++){let i=r[s],o=i.transform,u=e.data.field(i.field);n.set(i.field,Ex(o,u,t[s]))}return n}function sg(r,e,t){let n=new Map;for(let s of r){let i=s.transform,o=t.data.field(s.field);n.set(s.field,bx(i,o,e))}return n}var Xs=class extends qn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}},Pc=class extends qn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}};var Cc=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)&&Ix(i,e,n[s])}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=Gs(n,e,t,this.localWriteTime));for(let n of this.mutations)n.key.isEqual(e.key)&&(t=Gs(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let n=cy();return this.mutations.forEach((s=>{let i=e.get(s.key),o=i.overlayedDocument,u=this.applyToLocalView(o,i.mutatedFields);u=t.has(s.key)?null:u;let c=my(o,u);c!==null&&n.set(s.key,c),o.isValidDocument()||o.convertToNoDocument(H.min())})),n}keys(){return this.mutations.reduce(((e,t)=>e.add(t.key)),Q())}isEqual(e){return this.batchId===e.batchId&&Nn(this.mutations,e.mutations,((t,n)=>rg(t,n)))&&Nn(this.baseMutations,e.baseMutations,((t,n)=>rg(t,n)))}},kc=class r{constructor(e,t,n,s){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=s}static from(e,t,n){te(e.mutations.length===n.length,58842,{me:e.mutations.length,fe:n.length});let s=(function(){return gx})(),i=e.mutations;for(let o=0;o<i.length;o++)s=s.insert(i[o].key,n[o].version);return new r(e,t,n,s)}};var Oc=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{
|
|
24
10
|
largestBatchId: ${this.largestBatchId},
|
|
25
11
|
mutation: ${this.mutation.toString()}
|
|
26
|
-
}`}};var kc=class{constructor(e,t){this.count=e,this.unchangedNames=t}};var me,Y;function $x(r){switch(r){case N.OK:return z(64938);case N.CANCELLED:case N.UNKNOWN:case N.DEADLINE_EXCEEDED:case N.RESOURCE_EXHAUSTED:case N.INTERNAL:case N.UNAVAILABLE:case N.UNAUTHENTICATED:return!1;case N.INVALID_ARGUMENT:case N.NOT_FOUND:case N.ALREADY_EXISTS:case N.PERMISSION_DENIED:case N.FAILED_PRECONDITION:case N.ABORTED:case N.OUT_OF_RANGE:case N.UNIMPLEMENTED:case N.DATA_LOSS:return!0;default:return z(15467,{code:r})}}function Iy(r){if(r===void 0)return Pt("GRPC error has no .code"),N.UNKNOWN;switch(r){case me.OK:return N.OK;case me.CANCELLED:return N.CANCELLED;case me.UNKNOWN:return N.UNKNOWN;case me.DEADLINE_EXCEEDED:return N.DEADLINE_EXCEEDED;case me.RESOURCE_EXHAUSTED:return N.RESOURCE_EXHAUSTED;case me.INTERNAL:return N.INTERNAL;case me.UNAVAILABLE:return N.UNAVAILABLE;case me.UNAUTHENTICATED:return N.UNAUTHENTICATED;case me.INVALID_ARGUMENT:return N.INVALID_ARGUMENT;case me.NOT_FOUND:return N.NOT_FOUND;case me.ALREADY_EXISTS:return N.ALREADY_EXISTS;case me.PERMISSION_DENIED:return N.PERMISSION_DENIED;case me.FAILED_PRECONDITION:return N.FAILED_PRECONDITION;case me.ABORTED:return N.ABORTED;case me.OUT_OF_RANGE:return N.OUT_OF_RANGE;case me.UNIMPLEMENTED:return N.UNIMPLEMENTED;case me.DATA_LOSS:return N.DATA_LOSS;default:return z(39323,{code:r})}}(Y=me||(me={}))[Y.OK=0]="OK",Y[Y.CANCELLED=1]="CANCELLED",Y[Y.UNKNOWN=2]="UNKNOWN",Y[Y.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",Y[Y.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",Y[Y.NOT_FOUND=5]="NOT_FOUND",Y[Y.ALREADY_EXISTS=6]="ALREADY_EXISTS",Y[Y.PERMISSION_DENIED=7]="PERMISSION_DENIED",Y[Y.UNAUTHENTICATED=16]="UNAUTHENTICATED",Y[Y.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",Y[Y.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",Y[Y.ABORTED=10]="ABORTED",Y[Y.OUT_OF_RANGE=11]="OUT_OF_RANGE",Y[Y.UNIMPLEMENTED=12]="UNIMPLEMENTED",Y[Y.INTERNAL=13]="INTERNAL",Y[Y.UNAVAILABLE=14]="UNAVAILABLE",Y[Y.DATA_LOSS=15]="DATA_LOSS";var fg=null;var qx=new xt([4294967295,4294967295],0);function pg(r){let e=Lg().encode(r),t=new Wu;return t.update(e),new Uint8Array(t.digest())}function mg(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 xt([t,n],0),new xt([s,i],0)]}var Oc=class r{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new Sr(`Invalid padding: ${t}`);if(n<0)throw new Sr(`Invalid hash count: ${n}`);if(e.length>0&&this.hashCount===0)throw new Sr(`Invalid hash count: ${n}`);if(e.length===0&&t!==0)throw new Sr(`Invalid padding when bitmap length is 0: ${t}`);this.fe=8*e.length-t,this.ge=xt.fromNumber(this.fe)}pe(e,t,n){let s=e.add(t.multiply(xt.fromNumber(n)));return s.compare(qx)===1&&(s=new xt([s.getBits(0),s.getBits(1)],0)),s.modulo(this.ge).toNumber()}ye(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(this.fe===0)return!1;let t=pg(e),[n,s]=mg(t);for(let i=0;i<this.hashCount;i++){let o=this.pe(n,s,i);if(!this.ye(o))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)),o=new r(i,s,t);return n.forEach((u=>o.insert(u))),o}insert(e){if(this.fe===0)return;let t=pg(e),[n,s]=mg(t);for(let i=0;i<this.hashCount;i++){let o=this.pe(n,s,i);this.we(o)}}we(e){let t=Math.floor(e/8),n=e%8;this.bitmap[t]|=1<<n}},Sr=class extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}};var Uo=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,Qs.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new r(W.min(),s,new he(Q),Dt(),J())}},Qs=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,J(),J(),J())}};var Rn=class{constructor(e,t,n,s){this.Se=e,this.removedTargetIds=t,this.key=n,this.be=s}},Bo=class{constructor(e,t){this.targetId=e,this.De=t}},$o=class{constructor(e,t,n=Ve.EMPTY_BYTE_STRING,s=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=s}},qo=class{constructor(){this.ve=0,this.Ce=gg(),this.Fe=Ve.EMPTY_BYTE_STRING,this.Me=!1,this.xe=!0}get current(){return this.Me}get resumeToken(){return this.Fe}get Oe(){return this.ve!==0}get Ne(){return this.xe}Be(e){e.approximateByteSize()>0&&(this.xe=!0,this.Fe=e)}Le(){let e=J(),t=J(),n=J();return this.Ce.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:z(38017,{changeType:i})}})),new Qs(this.Fe,this.Me,e,t,n)}ke(){this.xe=!1,this.Ce=gg()}qe(e,t){this.xe=!0,this.Ce=this.Ce.insert(e,t)}Qe(e){this.xe=!0,this.Ce=this.Ce.remove(e)}$e(){this.ve+=1}Ue(){this.ve-=1,te(this.ve>=0,3241,{ve:this.ve})}Ke(){this.xe=!0,this.Me=!0}},Dc=class{constructor(e){this.We=e,this.Ge=new Map,this.ze=Dt(),this.je=Ao(),this.Je=Ao(),this.He=new he(Q)}Ye(e){for(let t of e.Se)e.be&&e.be.isFoundDocument()?this.Ze(t,e.be):this.Xe(t,e.key,e.be);for(let t of e.removedTargetIds)this.Xe(t,e.key,e.be)}et(e){this.forEachTarget(e,(t=>{let n=this.tt(t);switch(e.state){case 0:this.nt(t)&&n.Be(e.resumeToken);break;case 1:n.Ue(),n.Oe||n.ke(),n.Be(e.resumeToken);break;case 2:n.Ue(),n.Oe||this.removeTarget(t);break;case 3:this.nt(t)&&(n.Ke(),n.Be(e.resumeToken));break;case 4:this.nt(t)&&(this.rt(t),n.Be(e.resumeToken));break;default:z(56790,{state:e.state})}}))}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.Ge.forEach(((n,s)=>{this.nt(s)&&t(s)}))}it(e){let t=e.targetId,n=e.De.count,s=this.st(t);if(s){let i=s.target;if(Ic(i))if(n===0){let o=new K(i.path);this.Xe(t,o,tt.newNoDocument(o,W.min()))}else te(n===1,20013,{expectedCount:n});else{let o=this.ot(t);if(o!==n){let u=this._t(e),c=u?this.ut(u,e,o):1;if(c!==0){this.rt(t);let h=c===2?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.He=this.He.insert(t,h)}fg==null||fg.ct((function(f,p,m,y,T){var R,I,k,O,D,j;let H={localCacheCount:f,existenceFilterCount:p.count,databaseId:m.database,projectId:m.projectId},F=p.unchangedNames;return F&&(H.bloomFilter={applied:T===0,hashCount:(R=F==null?void 0:F.hashCount)!==null&&R!==void 0?R:0,bitmapLength:(O=(k=(I=F==null?void 0:F.bits)===null||I===void 0?void 0:I.bitmap)===null||k===void 0?void 0:k.length)!==null&&O!==void 0?O:0,padding:(j=(D=F==null?void 0:F.bits)===null||D===void 0?void 0:D.padding)!==null&&j!==void 0?j:0,mightContain:E=>{var _;return(_=y==null?void 0:y.mightContain(E))!==null&&_!==void 0&&_}}),H})(o,e.De,this.We.lt(),u,c))}}}}_t(e){let t=e.De.unchangedNames;if(!t||!t.bits)return null;let{bits:{bitmap:n="",padding:s=0},hashCount:i=0}=t,o,u;try{o=kt(n).toUint8Array()}catch(c){if(c instanceof Vo)return ar("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 Oc(o,s,i)}catch(c){return ar(c instanceof Sr?"BloomFilter error: ":"Applying bloom filter failed: ",c),null}return u.fe===0?null:u}ut(e,t,n){return t.De.count===n-this.ht(e,t.targetId)?0:2}ht(e,t){let n=this.We.getRemoteKeysForTarget(t),s=0;return n.forEach((i=>{let o=this.We.lt(),u=`projects/${o.projectId}/databases/${o.database}/documents/${i.path.canonicalString()}`;e.mightContain(u)||(this.Xe(t,i,null),s++)})),s}Pt(e){let t=new Map;this.Ge.forEach(((i,o)=>{let u=this.st(o);if(u){if(i.current&&Ic(u.target)){let c=new K(u.target.path);this.Tt(c).has(o)||this.It(o,c)||this.Xe(o,c,tt.newNoDocument(c,e))}i.Ne&&(t.set(o,i.Le()),i.ke())}}));let n=J();this.Je.forEach(((i,o)=>{let u=!0;o.forEachWhile((c=>{let h=this.st(c);return!h||h.purpose==="TargetPurposeLimboResolution"||(u=!1,!1)})),u&&(n=n.add(i))})),this.ze.forEach(((i,o)=>o.setReadTime(e)));let s=new Uo(e,t,this.He,this.ze,n);return this.ze=Dt(),this.je=Ao(),this.Je=Ao(),this.He=new he(Q),s}Ze(e,t){if(!this.nt(e))return;let n=this.It(e,t.key)?2:0;this.tt(e).qe(t.key,n),this.ze=this.ze.insert(t.key,t),this.je=this.je.insert(t.key,this.Tt(t.key).add(e)),this.Je=this.Je.insert(t.key,this.dt(t.key).add(e))}Xe(e,t,n){if(!this.nt(e))return;let s=this.tt(e);this.It(e,t)?s.qe(t,1):s.Qe(t),this.Je=this.Je.insert(t,this.dt(t).delete(e)),this.Je=this.Je.insert(t,this.dt(t).add(e)),n&&(this.ze=this.ze.insert(t,n))}removeTarget(e){this.Ge.delete(e)}ot(e){let t=this.tt(e).Le();return this.We.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}$e(e){this.tt(e).$e()}tt(e){let t=this.Ge.get(e);return t||(t=new qo,this.Ge.set(e,t)),t}dt(e){let t=this.Je.get(e);return t||(t=new Ie(Q),this.Je=this.Je.insert(e,t)),t}Tt(e){let t=this.je.get(e);return t||(t=new Ie(Q),this.je=this.je.insert(e,t)),t}nt(e){let t=this.st(e)!==null;return t||M("WatchChangeAggregator","Detected inactive target",e),t}st(e){let t=this.Ge.get(e);return t&&t.Oe?null:this.We.Et(e)}rt(e){this.Ge.set(e,new qo),this.We.getRemoteKeysForTarget(e).forEach((t=>{this.Xe(e,t,null)}))}It(e,t){return this.We.getRemoteKeysForTarget(e).has(t)}};function Ao(){return new he(K.comparator)}function gg(){return new he(K.comparator)}var zx={asc:"ASCENDING",desc:"DESCENDING"},Kx={"<":"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"},Gx={and:"AND",or:"OR"},Nc=class{constructor(e,t){this.databaseId=e,this.useProto3Json=t}};function Vc(r,e){return r.useProto3Json||fa(e)?e:{value:e}}function zo(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 Sy(r,e){return r.useProto3Json?e.toBase64():e.toUint8Array()}function Wx(r,e){return zo(r,e.toTimestamp())}function ht(r){return te(!!r,49232),W.fromTimestamp((function(t){let n=Ct(t);return new _e(n.seconds,n.nanos)})(r))}function Hl(r,e){return Lc(r,e).canonicalString()}function Lc(r,e){let t=(function(s){return new pe(["projects",s.projectId,"databases",s.database])})(r).child("documents");return e===void 0?t:t.child(e)}function Ay(r){let e=pe.fromString(r);return te(ky(e),10190,{key:e.toString()}),e}function Fc(r,e){return Hl(r.databaseId,e.path)}function Zu(r,e){let t=Ay(e);if(t.get(1)!==r.databaseId.projectId)throw new B(N.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 B(N.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+t.get(3)+" vs "+r.databaseId.database);return new K(Ry(t))}function xy(r,e){return Hl(r.databaseId,e)}function Hx(r){let e=Ay(r);return e.length===4?pe.emptyPath():Ry(e)}function jc(r){return new pe(["projects",r.databaseId.projectId,"databases",r.databaseId.database]).canonicalString()}function Ry(r){return te(r.length>4&&r.get(4)==="documents",29091,{key:r.toString()}),r.popFirst(5)}function yg(r,e,t){return{name:Fc(r,e),fields:t.value.mapValue.fields}}function Qx(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:z(39313,{state:h})})(e.targetChange.targetChangeType||"NO_CHANGE"),s=e.targetChange.targetIds||[],i=(function(h,f){return h.useProto3Json?(te(f===void 0||typeof f=="string",58123),Ve.fromBase64String(f||"")):(te(f===void 0||f instanceof Buffer||f instanceof Uint8Array,16193),Ve.fromUint8Array(f||new Uint8Array))})(r,e.targetChange.resumeToken),o=e.targetChange.cause,u=o&&(function(h){let f=h.code===void 0?N.UNKNOWN:Iy(h.code);return new B(f,h.message||"")})(o);t=new $o(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=Zu(r,n.document.name),i=ht(n.document.updateTime),o=n.document.createTime?ht(n.document.createTime):W.min(),u=new $e({mapValue:{fields:n.document.fields}}),c=tt.newFoundDocument(s,i,o,u),h=n.targetIds||[],f=n.removedTargetIds||[];t=new Rn(h,f,c.key,c)}else if("documentDelete"in e){e.documentDelete;let n=e.documentDelete;n.document;let s=Zu(r,n.document),i=n.readTime?ht(n.readTime):W.min(),o=tt.newNoDocument(s,i),u=n.removedTargetIds||[];t=new Rn([],u,o.key,o)}else if("documentRemove"in e){e.documentRemove;let n=e.documentRemove;n.document;let s=Zu(r,n.document),i=n.removedTargetIds||[];t=new Rn([],i,s,null)}else{if(!("filter"in e))return z(11601,{At:e});{e.filter;let n=e.filter;n.targetId;let{count:s=0,unchangedNames:i}=n,o=new kc(s,i),u=n.targetId;t=new Bo(u,o)}}return t}function Jx(r,e){let t;if(e instanceof Or)t={update:yg(r,e.key,e.value)};else if(e instanceof Mo)t={delete:Fc(r,e.key)};else if(e instanceof pt)t={update:yg(r,e.key,e.data),updateMask:iR(e.fieldMask)};else{if(!(e instanceof xc))return z(16599,{Rt:e.type});t={verify:Fc(r,e.key)}}return e.fieldTransforms.length>0&&(t.updateTransforms=e.fieldTransforms.map((n=>(function(i,o){let u=o.transform;if(u instanceof Un)return{fieldPath:o.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(u instanceof Cr)return{fieldPath:o.field.canonicalString(),appendMissingElements:{values:u.elements}};if(u instanceof kr)return{fieldPath:o.field.canonicalString(),removeAllFromArray:{values:u.elements}};if(u instanceof Bn)return{fieldPath:o.field.canonicalString(),increment:u.Ee};throw z(20930,{transform:o.transform})})(0,n)))),e.precondition.isNone||(t.currentDocument=(function(s,i){return i.updateTime!==void 0?{updateTime:Wx(s,i.updateTime)}:i.exists!==void 0?{exists:i.exists}:z(27497)})(r,e.precondition)),t}function Xx(r,e){return r&&r.length>0?(te(e!==void 0,14353),r.map((t=>(function(s,i){let o=s.updateTime?ht(s.updateTime):ht(i);return o.isEqual(W.min())&&(o=ht(i)),new Ac(o,s.transformResults||[])})(t,e)))):[]}function Yx(r,e){return{documents:[xy(r,e.path)]}}function Zx(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=xy(r,s);let i=(function(h){if(h.length!==0)return Cy(ft.create(h,"and"))})(e.filters);i&&(t.structuredQuery.where=i);let o=(function(h){if(h.length!==0)return h.map((f=>(function(m){return{field:Sn(m.field),direction:rR(m.dir)}})(f)))})(e.orderBy);o&&(t.structuredQuery.orderBy=o);let u=Vc(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)),{Vt:t,parent:s}}function eR(r){let e=Hx(r.parent),t=r.structuredQuery,n=t.from?t.from.length:0,s=null;if(n>0){te(n===1,65062);let f=t.from[0];f.allDescendants?s=f.collectionId:e=e.child(f.collectionId)}let i=[];t.where&&(i=(function(p){let m=Py(p);return m instanceof ft&&uy(m)?m.getFilters():[m]})(t.where));let o=[];t.orderBy&&(o=(function(p){return p.map((m=>(function(T){return new Fn(An(T.field),(function(I){switch(I){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}})(T.direction))})(m)))})(t.orderBy));let u=null;t.limit&&(u=(function(p){let m;return m=typeof p=="object"?p.value:p,fa(m)?null:m})(t.limit));let c=null;t.startAt&&(c=(function(p){let m=!!p.before,y=p.values||[];return new Ln(y,m)})(t.startAt));let h=null;return t.endAt&&(h=(function(p){let m=!p.before,y=p.values||[];return new Ln(y,m)})(t.endAt)),Ax(e,s,o,i,u,"F",c,h)}function tR(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 z(28987,{purpose:s})}})(e.purpose);return t==null?null:{"goog-listen-tags":t}}function Py(r){return r.unaryFilter!==void 0?(function(t){switch(t.unaryFilter.op){case"IS_NAN":let n=An(t.unaryFilter.field);return we.create(n,"==",{doubleValue:NaN});case"IS_NULL":let s=An(t.unaryFilter.field);return we.create(s,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let i=An(t.unaryFilter.field);return we.create(i,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let o=An(t.unaryFilter.field);return we.create(o,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return z(61313);default:return z(60726)}})(r):r.fieldFilter!==void 0?(function(t){return we.create(An(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";case"OPERATOR_UNSPECIFIED":return z(58110);default:return z(50506)}})(t.fieldFilter.op),t.fieldFilter.value)})(r):r.compositeFilter!==void 0?(function(t){return ft.create(t.compositeFilter.filters.map((n=>Py(n))),(function(s){switch(s){case"AND":return"and";case"OR":return"or";default:return z(1026)}})(t.compositeFilter.op))})(r):z(30097,{filter:r})}function rR(r){return zx[r]}function nR(r){return Kx[r]}function sR(r){return Gx[r]}function Sn(r){return{fieldPath:r.canonicalString()}}function An(r){return qe.fromServerFormat(r.fieldPath)}function Cy(r){return r instanceof we?(function(t){if(t.op==="=="){if(sg(t.value))return{unaryFilter:{field:Sn(t.field),op:"IS_NAN"}};if(ng(t.value))return{unaryFilter:{field:Sn(t.field),op:"IS_NULL"}}}else if(t.op==="!="){if(sg(t.value))return{unaryFilter:{field:Sn(t.field),op:"IS_NOT_NAN"}};if(ng(t.value))return{unaryFilter:{field:Sn(t.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Sn(t.field),op:nR(t.op),value:t.value}}})(r):r instanceof ft?(function(t){let n=t.getFilters().map((s=>Cy(s)));return n.length===1?n[0]:{compositeFilter:{op:sR(t.op),filters:n}}})(r):z(54877,{filter:r})}function iR(r){let e=[];return r.fields.forEach((t=>e.push(t.canonicalString()))),{fieldPaths:e}}function ky(r){return r.length>=4&&r.get(0)==="projects"&&r.get(2)==="databases"}var Js=class r{constructor(e,t,n,s,i=W.min(),o=W.min(),u=Ve.EMPTY_BYTE_STRING,c=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=s,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=o,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 Mc=class{constructor(e){this.gt=e}};function oR(r){let e=eR({parent:r.parent,structuredQuery:r.structuredQuery});return r.limitType==="LAST"?Sc(e,e.limit,"L"):e}var Ko=class{constructor(){}bt(e,t){this.Dt(e,t),t.vt()}Dt(e,t){if("nullValue"in e)this.Ct(t,5);else if("booleanValue"in e)this.Ct(t,10),t.Ft(e.booleanValue?1:0);else if("integerValue"in e)this.Ct(t,15),t.Ft(ae(e.integerValue));else if("doubleValue"in e){let n=ae(e.doubleValue);isNaN(n)?this.Ct(t,13):(this.Ct(t,15),Gs(n)?t.Ft(0):t.Ft(n))}else if("timestampValue"in e){let n=e.timestampValue;this.Ct(t,20),typeof n=="string"&&(n=Ct(n)),t.Mt(`${n.seconds||""}`),t.Ft(n.nanos||0)}else if("stringValue"in e)this.xt(e.stringValue,t),this.Ot(t);else if("bytesValue"in e)this.Ct(t,30),t.Nt(kt(e.bytesValue)),this.Ot(t);else if("referenceValue"in e)this.Bt(e.referenceValue,t);else if("geoPointValue"in e){let n=e.geoPointValue;this.Ct(t,45),t.Ft(n.latitude||0),t.Ft(n.longitude||0)}else"mapValue"in e?iy(e)?this.Ct(t,Number.MAX_SAFE_INTEGER):sy(e)?this.Lt(e.mapValue,t):(this.kt(e.mapValue,t),this.Ot(t)):"arrayValue"in e?(this.qt(e.arrayValue,t),this.Ot(t)):z(19022,{Qt:e})}xt(e,t){this.Ct(t,25),this.$t(e,t)}$t(e,t){t.Mt(e)}kt(e,t){let n=e.fields||{};this.Ct(t,55);for(let s of Object.keys(n))this.xt(s,t),this.Dt(n[s],t)}Lt(e,t){var n,s;let i=e.fields||{};this.Ct(t,53);let o=Dn,u=((s=(n=i[o].arrayValue)===null||n===void 0?void 0:n.values)===null||s===void 0?void 0:s.length)||0;this.Ct(t,15),t.Ft(ae(u)),this.xt(o,t),this.Dt(i[o],t)}qt(e,t){let n=e.values||[];this.Ct(t,50);for(let s of n)this.Dt(s,t)}Bt(e,t){this.Ct(t,37),K.fromName(e).path.forEach((n=>{this.Ct(t,60),this.$t(n,t)}))}Ct(e,t){e.Ft(t)}Ot(e){e.Ft(2)}};Ko.Ut=new Ko;var Uc=class{constructor(){this.Dn=new Bc}addToCollectionParentIndex(e,t){return this.Dn.add(t),V.resolve()}getCollectionParents(e,t){return V.resolve(this.Dn.getEntries(t))}addFieldIndex(e,t){return V.resolve()}deleteFieldIndex(e,t){return V.resolve()}deleteAllFieldIndexes(e){return V.resolve()}createTargetIndexes(e,t){return V.resolve()}getDocumentsMatchingTarget(e,t){return V.resolve(null)}getIndexType(e,t){return V.resolve(0)}getFieldIndexes(e,t){return V.resolve([])}getNextCollectionGroupToUpdate(e){return V.resolve(null)}getMinOffset(e,t){return V.resolve(Pr.min())}getMinOffsetFromCollectionGroup(e,t){return V.resolve(Pr.min())}updateCollectionGroup(e,t,n){return V.resolve()}updateIndexEntries(e,t){return V.resolve()}},Bc=class{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),s=this.index[t]||new Ie(pe.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 Ie(pe.comparator)).toArray()}};var kj=new Uint8Array(0);var _g={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},Oy=41943040,Ge=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}};Ge.DEFAULT_COLLECTION_PERCENTILE=10,Ge.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Ge.DEFAULT=new Ge(Oy,Ge.DEFAULT_COLLECTION_PERCENTILE,Ge.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Ge.DISABLED=new Ge(-1,0,0);var Xs=class r{constructor(e){this._r=e}next(){return this._r+=2,this._r}static ar(){return new r(0)}static ur(){return new r(-1)}};var vg="LruGarbageCollector",aR=1048576;function wg([r,e],[t,n]){let s=Q(r,t);return s===0?Q(e,n):s}var $c=class{constructor(e){this.Tr=e,this.buffer=new Ie(wg),this.Ir=0}dr(){return++this.Ir}Er(e){let t=[e,this.dr()];if(this.buffer.size<this.Tr)this.buffer=this.buffer.add(t);else{let n=this.buffer.last();wg(t,n)<0&&(this.buffer=this.buffer.delete(n).add(t))}}get maxValue(){return this.buffer.last()[0]}},qc=class{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Ar=null}start(){this.garbageCollector.params.cacheSizeCollectionThreshold!==-1&&this.Rr(6e4)}stop(){this.Ar&&(this.Ar.cancel(),this.Ar=null)}get started(){return this.Ar!==null}Rr(e){M(vg,`Garbage collection scheduled in ${e}ms`),this.Ar=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,(async()=>{this.Ar=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(t){Hn(t)?M(vg,"Ignoring IndexedDB error during garbage collection: ",t):await Wn(t)}await this.Rr(3e5)}))}},zc=class{constructor(e,t){this.Vr=e,this.params=t}calculateTargetCount(e,t){return this.Vr.mr(e).next((n=>Math.floor(t/100*n)))}nthSequenceNumber(e,t){if(t===0)return V.resolve(On.ue);let n=new $c(t);return this.Vr.forEachTarget(e,(s=>n.Er(s.sequenceNumber))).next((()=>this.Vr.gr(e,(s=>n.Er(s))))).next((()=>n.maxValue))}removeTargets(e,t,n){return this.Vr.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Vr.removeOrphanedDocuments(e,t)}collect(e,t){return this.params.cacheSizeCollectionThreshold===-1?(M("LruGarbageCollector","Garbage collection skipped; disabled"),V.resolve(_g)):this.getCacheSize(e).next((n=>n<this.params.cacheSizeCollectionThreshold?(M("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),_g):this.pr(e,t)))}getCacheSize(e){return this.Vr.getCacheSize(e)}pr(e,t){let n,s,i,o,u,c,h,f=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next((p=>(p>this.params.maximumSequenceNumbersToCollect?(M("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${p}`),s=this.params.maximumSequenceNumbersToCollect):s=p,o=Date.now(),this.nthSequenceNumber(e,s)))).next((p=>(n=p,u=Date.now(),this.removeTargets(e,n,t)))).next((p=>(i=p,c=Date.now(),this.removeOrphanedDocuments(e,n)))).next((p=>(h=Date.now(),Tn()<=X.DEBUG&&M("LruGarbageCollector",`LRU Garbage Collection
|
|
12
|
+
}`}};var Dc=class{constructor(e,t){this.count=e,this.unchangedNames=t}};var ye,Z;function Sx(r){switch(r){case O.OK:return K(64938);case O.CANCELLED:case O.UNKNOWN:case O.DEADLINE_EXCEEDED:case O.RESOURCE_EXHAUSTED:case O.INTERNAL:case O.UNAVAILABLE:case O.UNAUTHENTICATED:return!1;case O.INVALID_ARGUMENT:case O.NOT_FOUND:case O.ALREADY_EXISTS:case O.PERMISSION_DENIED:case O.FAILED_PRECONDITION:case O.ABORTED:case O.OUT_OF_RANGE:case O.UNIMPLEMENTED:case O.DATA_LOSS:return!0;default:return K(15467,{code:r})}}function yy(r){if(r===void 0)return kt("GRPC error has no .code"),O.UNKNOWN;switch(r){case ye.OK:return O.OK;case ye.CANCELLED:return O.CANCELLED;case ye.UNKNOWN:return O.UNKNOWN;case ye.DEADLINE_EXCEEDED:return O.DEADLINE_EXCEEDED;case ye.RESOURCE_EXHAUSTED:return O.RESOURCE_EXHAUSTED;case ye.INTERNAL:return O.INTERNAL;case ye.UNAVAILABLE:return O.UNAVAILABLE;case ye.UNAUTHENTICATED:return O.UNAUTHENTICATED;case ye.INVALID_ARGUMENT:return O.INVALID_ARGUMENT;case ye.NOT_FOUND:return O.NOT_FOUND;case ye.ALREADY_EXISTS:return O.ALREADY_EXISTS;case ye.PERMISSION_DENIED:return O.PERMISSION_DENIED;case ye.FAILED_PRECONDITION:return O.FAILED_PRECONDITION;case ye.ABORTED:return O.ABORTED;case ye.OUT_OF_RANGE:return O.OUT_OF_RANGE;case ye.UNIMPLEMENTED:return O.UNIMPLEMENTED;case ye.DATA_LOSS:return O.DATA_LOSS;default:return K(39323,{code:r})}}(Z=ye||(ye={}))[Z.OK=0]="OK",Z[Z.CANCELLED=1]="CANCELLED",Z[Z.UNKNOWN=2]="UNKNOWN",Z[Z.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",Z[Z.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",Z[Z.NOT_FOUND=5]="NOT_FOUND",Z[Z.ALREADY_EXISTS=6]="ALREADY_EXISTS",Z[Z.PERMISSION_DENIED=7]="PERMISSION_DENIED",Z[Z.UNAUTHENTICATED=16]="UNAUTHENTICATED",Z[Z.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",Z[Z.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",Z[Z.ABORTED=10]="ABORTED",Z[Z.OUT_OF_RANGE=11]="OUT_OF_RANGE",Z[Z.UNIMPLEMENTED=12]="UNIMPLEMENTED",Z[Z.INTERNAL=13]="INTERNAL",Z[Z.UNAVAILABLE=14]="UNAVAILABLE",Z[Z.DATA_LOSS=15]="DATA_LOSS";var ic=null;function xx(){return new TextEncoder}var Rx=new xt([4294967295,4294967295],0);function ig(r){let e=xx().encode(r),t=new Xu;return t.update(e),new Uint8Array(t.digest())}function og(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 xt([t,n],0),new xt([s,i],0)]}var Nc=class r{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new xr(`Invalid padding: ${t}`);if(n<0)throw new xr(`Invalid hash count: ${n}`);if(e.length>0&&this.hashCount===0)throw new xr(`Invalid hash count: ${n}`);if(e.length===0&&t!==0)throw new xr(`Invalid padding when bitmap length is 0: ${t}`);this.ge=8*e.length-t,this.pe=xt.fromNumber(this.ge)}ye(e,t,n){let s=e.add(t.multiply(xt.fromNumber(n)));return s.compare(Rx)===1&&(s=new xt([s.getBits(0),s.getBits(1)],0)),s.modulo(this.pe).toNumber()}we(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(this.ge===0)return!1;let t=ig(e),[n,s]=og(t);for(let i=0;i<this.hashCount;i++){let o=this.ye(n,s,i);if(!this.we(o))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)),o=new r(i,s,t);return n.forEach((u=>o.insert(u))),o}insert(e){if(this.ge===0)return;let t=ig(e),[n,s]=og(t);for(let i=0;i<this.hashCount;i++){let o=this.ye(n,s,i);this.Se(o)}}Se(e){let t=Math.floor(e/8),n=e%8;this.bitmap[t]|=1<<n}},xr=class extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}};var Wo=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,Zs.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new r(H.min(),s,new de(Y),Lt(),Q())}},Zs=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,Q(),Q(),Q())}};var Dn=class{constructor(e,t,n,s){this.be=e,this.removedTargetIds=t,this.key=n,this.De=s}},Ho=class{constructor(e,t){this.targetId=e,this.Ce=t}},Jo=class{constructor(e,t,n=Pe.EMPTY_BYTE_STRING,s=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=s}},Qo=class{constructor(){this.ve=0,this.Fe=ag(),this.Me=Pe.EMPTY_BYTE_STRING,this.xe=!1,this.Oe=!0}get current(){return this.xe}get resumeToken(){return this.Me}get Ne(){return this.ve!==0}get Be(){return this.Oe}Le(e){e.approximateByteSize()>0&&(this.Oe=!0,this.Me=e)}ke(){let e=Q(),t=Q(),n=Q();return this.Fe.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:K(38017,{changeType:i})}})),new Zs(this.Me,this.xe,e,t,n)}qe(){this.Oe=!1,this.Fe=ag()}Ke(e,t){this.Oe=!0,this.Fe=this.Fe.insert(e,t)}Ue(e){this.Oe=!0,this.Fe=this.Fe.remove(e)}$e(){this.ve+=1}We(){this.ve-=1,te(this.ve>=0,3241,{ve:this.ve})}Qe(){this.Oe=!0,this.xe=!0}},Vc=class{constructor(e){this.Ge=e,this.ze=new Map,this.je=Lt(),this.Je=Co(),this.He=Co(),this.Ze=new de(Y)}Xe(e){for(let t of e.be)e.De&&e.De.isFoundDocument()?this.Ye(t,e.De):this.et(t,e.key,e.De);for(let t of e.removedTargetIds)this.et(t,e.key,e.De)}tt(e){this.forEachTarget(e,(t=>{let n=this.nt(t);switch(e.state){case 0:this.rt(t)&&n.Le(e.resumeToken);break;case 1:n.We(),n.Ne||n.qe(),n.Le(e.resumeToken);break;case 2:n.We(),n.Ne||this.removeTarget(t);break;case 3:this.rt(t)&&(n.Qe(),n.Le(e.resumeToken));break;case 4:this.rt(t)&&(this.it(t),n.Le(e.resumeToken));break;default:K(56790,{state:e.state})}}))}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.ze.forEach(((n,s)=>{this.rt(s)&&t(s)}))}st(e){let t=e.targetId,n=e.Ce.count,s=this.ot(t);if(s){let i=s.target;if(xc(i))if(n===0){let o=new q(i.path);this.et(t,o,Ze.newNoDocument(o,H.min()))}else te(n===1,20013,{expectedCount:n});else{let o=this._t(t);if(o!==n){let u=this.ut(e),c=u?this.ct(u,e,o):1;if(c!==0){this.it(t);let l=c===2?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ze=this.Ze.insert(t,l)}ic==null||ic.o((function(f,p,g,y,I){var k,D,N,U,z,F;let R={localCacheCount:f,existenceFilterCount:p.count,databaseId:g.database,projectId:g.projectId},A=p.unchangedNames;return A&&(R.bloomFilter={applied:I===0,hashCount:(k=A==null?void 0:A.hashCount)!=null?k:0,bitmapLength:(U=(N=(D=A==null?void 0:A.bits)==null?void 0:D.bitmap)==null?void 0:N.length)!=null?U:0,padding:(F=(z=A==null?void 0:A.bits)==null?void 0:z.padding)!=null?F:0,mightContain:E=>{var _;return(_=y==null?void 0:y.mightContain(E))!=null?_:!1}}),R})(o,e.Ce,this.Ge.ht(),u,c))}}}}ut(e){let t=e.Ce.unchangedNames;if(!t||!t.bits)return null;let{bits:{bitmap:n="",padding:s=0},hashCount:i=0}=t,o,u;try{o=Nt(n).toUint8Array()}catch(c){if(c instanceof qo)return Ot("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 Nc(o,s,i)}catch(c){return Ot(c instanceof xr?"BloomFilter error: ":"Applying bloom filter failed: ",c),null}return u.ge===0?null:u}ct(e,t,n){return t.Ce.count===n-this.Pt(e,t.targetId)?0:2}Pt(e,t){let n=this.Ge.getRemoteKeysForTarget(t),s=0;return n.forEach((i=>{let o=this.Ge.ht(),u=`projects/${o.projectId}/databases/${o.database}/documents/${i.path.canonicalString()}`;e.mightContain(u)||(this.et(t,i,null),s++)})),s}Tt(e){let t=new Map;this.ze.forEach(((i,o)=>{let u=this.ot(o);if(u){if(i.current&&xc(u.target)){let c=new q(u.target.path);this.Et(c).has(o)||this.It(o,c)||this.et(o,c,Ze.newNoDocument(c,e))}i.Be&&(t.set(o,i.ke()),i.qe())}}));let n=Q();this.He.forEach(((i,o)=>{let u=!0;o.forEachWhile((c=>{let l=this.ot(c);return!l||l.purpose==="TargetPurposeLimboResolution"||(u=!1,!1)})),u&&(n=n.add(i))})),this.je.forEach(((i,o)=>o.setReadTime(e)));let s=new Wo(e,t,this.Ze,this.je,n);return this.je=Lt(),this.Je=Co(),this.He=Co(),this.Ze=new de(Y),s}Ye(e,t){if(!this.rt(e))return;let n=this.It(e,t.key)?2:0;this.nt(e).Ke(t.key,n),this.je=this.je.insert(t.key,t),this.Je=this.Je.insert(t.key,this.Et(t.key).add(e)),this.He=this.He.insert(t.key,this.Rt(t.key).add(e))}et(e,t,n){if(!this.rt(e))return;let s=this.nt(e);this.It(e,t)?s.Ke(t,1):s.Ue(t),this.He=this.He.insert(t,this.Rt(t).delete(e)),this.He=this.He.insert(t,this.Rt(t).add(e)),n&&(this.je=this.je.insert(t,n))}removeTarget(e){this.ze.delete(e)}_t(e){let t=this.nt(e).ke();return this.Ge.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}$e(e){this.nt(e).$e()}nt(e){let t=this.ze.get(e);return t||(t=new Qo,this.ze.set(e,t)),t}Rt(e){let t=this.He.get(e);return t||(t=new xe(Y),this.He=this.He.insert(e,t)),t}Et(e){let t=this.Je.get(e);return t||(t=new xe(Y),this.Je=this.Je.insert(e,t)),t}rt(e){let t=this.ot(e)!==null;return t||M("WatchChangeAggregator","Detected inactive target",e),t}ot(e){let t=this.ze.get(e);return t&&t.Ne?null:this.Ge.At(e)}it(e){this.ze.set(e,new Qo),this.Ge.getRemoteKeysForTarget(e).forEach((t=>{this.et(e,t,null)}))}It(e,t){return this.Ge.getRemoteKeysForTarget(e).has(t)}};function Co(){return new de(q.comparator)}function ag(){return new de(q.comparator)}var Px={asc:"ASCENDING",desc:"DESCENDING"},Cx={"<":"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"},kx={and:"AND",or:"OR"},Lc=class{constructor(e,t){this.databaseId=e,this.useProto3Json=t}};function Fc(r,e){return r.useProto3Json||wa(e)?e:{value:e}}function Yo(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 _y(r,e){return r.useProto3Json?e.toBase64():e.toUint8Array()}function Ox(r,e){return Yo(r,e.toTimestamp())}function dt(r){return te(!!r,49232),H.fromTimestamp((function(t){let n=Dt(t);return new ge(n.seconds,n.nanos)})(r))}function ql(r,e){return Mc(r,e).canonicalString()}function Mc(r,e){let t=(function(s){return new he(["projects",s.projectId,"databases",s.database])})(r).child("documents");return e===void 0?t:t.child(e)}function wy(r){let e=he.fromString(r);return te(Iy(e),10190,{key:e.toString()}),e}function jc(r,e){return ql(r.databaseId,e.path)}function oc(r,e){let t=wy(e);if(t.get(1)!==r.databaseId.projectId)throw new B(O.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 B(O.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+t.get(3)+" vs "+r.databaseId.database);return new q(by(t))}function vy(r,e){return ql(r.databaseId,e)}function Dx(r){let e=wy(r);return e.length===4?he.emptyPath():by(e)}function Uc(r){return new he(["projects",r.databaseId.projectId,"databases",r.databaseId.database]).canonicalString()}function by(r){return te(r.length>4&&r.get(4)==="documents",29091,{key:r.toString()}),r.popFirst(5)}function ug(r,e,t){return{name:jc(r,e),fields:t.value.mapValue.fields}}function Nx(r,e){let t;if("targetChange"in e){e.targetChange;let n=(function(l){return l==="NO_CHANGE"?0:l==="ADD"?1:l==="REMOVE"?2:l==="CURRENT"?3:l==="RESET"?4:K(39313,{state:l})})(e.targetChange.targetChangeType||"NO_CHANGE"),s=e.targetChange.targetIds||[],i=(function(l,f){return l.useProto3Json?(te(f===void 0||typeof f=="string",58123),Pe.fromBase64String(f||"")):(te(f===void 0||f instanceof Buffer||f instanceof Uint8Array,16193),Pe.fromUint8Array(f||new Uint8Array))})(r,e.targetChange.resumeToken),o=e.targetChange.cause,u=o&&(function(l){let f=l.code===void 0?O.UNKNOWN:yy(l.code);return new B(f,l.message||"")})(o);t=new Jo(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=oc(r,n.document.name),i=dt(n.document.updateTime),o=n.document.createTime?dt(n.document.createTime):H.min(),u=new Ue({mapValue:{fields:n.document.fields}}),c=Ze.newFoundDocument(s,i,o,u),l=n.targetIds||[],f=n.removedTargetIds||[];t=new Dn(l,f,c.key,c)}else if("documentDelete"in e){e.documentDelete;let n=e.documentDelete;n.document;let s=oc(r,n.document),i=n.readTime?dt(n.readTime):H.min(),o=Ze.newNoDocument(s,i),u=n.removedTargetIds||[];t=new Dn([],u,o.key,o)}else if("documentRemove"in e){e.documentRemove;let n=e.documentRemove;n.document;let s=oc(r,n.document),i=n.removedTargetIds||[];t=new Dn([],i,s,null)}else{if(!("filter"in e))return K(11601,{Vt:e});{e.filter;let n=e.filter;n.targetId;let{count:s=0,unchangedNames:i}=n,o=new Dc(s,i),u=n.targetId;t=new Ho(u,o)}}return t}function Vx(r,e){let t;if(e instanceof Vr)t={update:ug(r,e.key,e.value)};else if(e instanceof Xs)t={delete:jc(r,e.key)};else if(e instanceof gt)t={update:ug(r,e.key,e.data),updateMask:zx(e.fieldMask)};else{if(!(e instanceof Pc))return K(16599,{dt:e.type});t={verify:jc(r,e.key)}}return e.fieldTransforms.length>0&&(t.updateTransforms=e.fieldTransforms.map((n=>(function(i,o){let u=o.transform;if(u instanceof Bn)return{fieldPath:o.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(u instanceof Dr)return{fieldPath:o.field.canonicalString(),appendMissingElements:{values:u.elements}};if(u instanceof Nr)return{fieldPath:o.field.canonicalString(),removeAllFromArray:{values:u.elements}};if(u instanceof $n)return{fieldPath:o.field.canonicalString(),increment:u.Ae};throw K(20930,{transform:o.transform})})(0,n)))),e.precondition.isNone||(t.currentDocument=(function(s,i){return i.updateTime!==void 0?{updateTime:Ox(s,i.updateTime)}:i.exists!==void 0?{exists:i.exists}:K(27497)})(r,e.precondition)),t}function Lx(r,e){return r&&r.length>0?(te(e!==void 0,14353),r.map((t=>(function(s,i){let o=s.updateTime?dt(s.updateTime):dt(i);return o.isEqual(H.min())&&(o=dt(i)),new Rc(o,s.transformResults||[])})(t,e)))):[]}function Fx(r,e){return{documents:[vy(r,e.path)]}}function Mx(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=vy(r,s);let i=(function(l){if(l.length!==0)return Ty(et.create(l,"and"))})(e.filters);i&&(t.structuredQuery.where=i);let o=(function(l){if(l.length!==0)return l.map((f=>(function(g){return{field:Pn(g.field),direction:Bx(g.dir)}})(f)))})(e.orderBy);o&&(t.structuredQuery.orderBy=o);let u=Fc(r,e.limit);return u!==null&&(t.structuredQuery.limit=u),e.startAt&&(t.structuredQuery.startAt=(function(l){return{before:l.inclusive,values:l.position}})(e.startAt)),e.endAt&&(t.structuredQuery.endAt=(function(l){return{before:!l.inclusive,values:l.position}})(e.endAt)),{ft:t,parent:s}}function jx(r){let e=Dx(r.parent),t=r.structuredQuery,n=t.from?t.from.length:0,s=null;if(n>0){te(n===1,65062);let f=t.from[0];f.allDescendants?s=f.collectionId:e=e.child(f.collectionId)}let i=[];t.where&&(i=(function(p){let g=Ey(p);return g instanceof et&&ey(g)?g.getFilters():[g]})(t.where));let o=[];t.orderBy&&(o=(function(p){return p.map((g=>(function(I){return new Or(Cn(I.field),(function(A){switch(A){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}})(I.direction))})(g)))})(t.orderBy));let u=null;t.limit&&(u=(function(p){let g;return g=typeof p=="object"?p.value:p,wa(g)?null:g})(t.limit));let c=null;t.startAt&&(c=(function(p){let g=!!p.before,y=p.values||[];return new kr(y,g)})(t.startAt));let l=null;return t.endAt&&(l=(function(p){let g=!p.before,y=p.values||[];return new kr(y,g)})(t.endAt)),lx(e,s,o,i,u,"F",c,l)}function Ux(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 K(28987,{purpose:s})}})(e.purpose);return t==null?null:{"goog-listen-tags":t}}function Ey(r){return r.unaryFilter!==void 0?(function(t){switch(t.unaryFilter.op){case"IS_NAN":let n=Cn(t.unaryFilter.field);return we.create(n,"==",{doubleValue:NaN});case"IS_NULL":let s=Cn(t.unaryFilter.field);return we.create(s,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let i=Cn(t.unaryFilter.field);return we.create(i,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let o=Cn(t.unaryFilter.field);return we.create(o,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return K(61313);default:return K(60726)}})(r):r.fieldFilter!==void 0?(function(t){return we.create(Cn(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";case"OPERATOR_UNSPECIFIED":return K(58110);default:return K(50506)}})(t.fieldFilter.op),t.fieldFilter.value)})(r):r.compositeFilter!==void 0?(function(t){return et.create(t.compositeFilter.filters.map((n=>Ey(n))),(function(s){switch(s){case"AND":return"and";case"OR":return"or";default:return K(1026)}})(t.compositeFilter.op))})(r):K(30097,{filter:r})}function Bx(r){return Px[r]}function $x(r){return Cx[r]}function qx(r){return kx[r]}function Pn(r){return{fieldPath:r.canonicalString()}}function Cn(r){return Be.fromServerFormat(r.fieldPath)}function Ty(r){return r instanceof we?(function(t){if(t.op==="=="){if(Qm(t.value))return{unaryFilter:{field:Pn(t.field),op:"IS_NAN"}};if(Jm(t.value))return{unaryFilter:{field:Pn(t.field),op:"IS_NULL"}}}else if(t.op==="!="){if(Qm(t.value))return{unaryFilter:{field:Pn(t.field),op:"IS_NOT_NAN"}};if(Jm(t.value))return{unaryFilter:{field:Pn(t.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Pn(t.field),op:$x(t.op),value:t.value}}})(r):r instanceof et?(function(t){let n=t.getFilters().map((s=>Ty(s)));return n.length===1?n[0]:{compositeFilter:{op:qx(t.op),filters:n}}})(r):K(54877,{filter:r})}function zx(r){let e=[];return r.fields.forEach((t=>e.push(t.canonicalString()))),{fieldPaths:e}}function Iy(r){return r.length>=4&&r.get(0)==="projects"&&r.get(2)==="databases"}function Ay(r){return!!r&&typeof r._toProto=="function"&&r._protoValueType==="ProtoValue"}var ei=class r{constructor(e,t,n,s,i=H.min(),o=H.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=o,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 Bc=class{constructor(e){this.yt=e}};function Sy(r){let e=jx({parent:r.parent,structuredQuery:r.structuredQuery});return r.limitType==="LAST"?Go(e,e.limit,"L"):e}var Xo=class{constructor(){}Dt(e,t){this.Ct(e,t),t.vt()}Ct(e,t){if("nullValue"in e)this.Ft(t,5);else if("booleanValue"in e)this.Ft(t,10),t.Mt(e.booleanValue?1:0);else if("integerValue"in e)this.Ft(t,15),t.Mt(ae(e.integerValue));else if("doubleValue"in e){let n=ae(e.doubleValue);isNaN(n)?this.Ft(t,13):(this.Ft(t,15),Hs(n)?t.Mt(0):t.Mt(n))}else if("timestampValue"in e){let n=e.timestampValue;this.Ft(t,20),typeof n=="string"&&(n=Dt(n)),t.xt(`${n.seconds||""}`),t.Mt(n.nanos||0)}else if("stringValue"in e)this.Ot(e.stringValue,t),this.Nt(t);else if("bytesValue"in e)this.Ft(t,30),t.Bt(Nt(e.bytesValue)),this.Nt(t);else if("referenceValue"in e)this.Lt(e.referenceValue,t);else if("geoPointValue"in e){let n=e.geoPointValue;this.Ft(t,45),t.Mt(n.latitude||0),t.Mt(n.longitude||0)}else"mapValue"in e?Yg(e)?this.Ft(t,Number.MAX_SAFE_INTEGER):Qg(e)?this.kt(e.mapValue,t):(this.qt(e.mapValue,t),this.Nt(t)):"arrayValue"in e?(this.Kt(e.arrayValue,t),this.Nt(t)):K(19022,{Ut:e})}Ot(e,t){this.Ft(t,25),this.$t(e,t)}$t(e,t){t.xt(e)}qt(e,t){let n=e.fields||{};this.Ft(t,55);for(let s of Object.keys(n))this.Ot(s,t),this.Ct(n[s],t)}kt(e,t){var o,u;let n=e.fields||{};this.Ft(t,53);let s=Ln,i=((u=(o=n[s].arrayValue)==null?void 0:o.values)==null?void 0:u.length)||0;this.Ft(t,15),t.Mt(ae(i)),this.Ot(s,t),this.Ct(n[s],t)}Kt(e,t){let n=e.values||[];this.Ft(t,50);for(let s of n)this.Ct(s,t)}Lt(e,t){this.Ft(t,37),q.fromName(e).path.forEach((n=>{this.Ft(t,60),this.$t(n,t)}))}Ft(e,t){e.Mt(t)}Nt(e){e.Mt(2)}};Xo.Wt=new Xo;var $c=class{constructor(){this.bn=new qc}addToCollectionParentIndex(e,t){return this.bn.add(t),V.resolve()}getCollectionParents(e,t){return V.resolve(this.bn.getEntries(t))}addFieldIndex(e,t){return V.resolve()}deleteFieldIndex(e,t){return V.resolve()}deleteAllFieldIndexes(e){return V.resolve()}createTargetIndexes(e,t){return V.resolve()}getDocumentsMatchingTarget(e,t){return V.resolve(null)}getIndexType(e,t){return V.resolve(0)}getFieldIndexes(e,t){return V.resolve([])}getNextCollectionGroupToUpdate(e){return V.resolve(null)}getMinOffset(e,t){return V.resolve(Cr.min())}getMinOffsetFromCollectionGroup(e,t){return V.resolve(Cr.min())}updateCollectionGroup(e,t,n){return V.resolve()}updateIndexEntries(e,t){return V.resolve()}},qc=class{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),s=this.index[t]||new xe(he.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 xe(he.comparator)).toArray()}};var yj=new Uint8Array(0);var cg={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},xy=41943040,Ke=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}};Ke.DEFAULT_COLLECTION_PERCENTILE=10,Ke.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Ke.DEFAULT=new Ke(xy,Ke.DEFAULT_COLLECTION_PERCENTILE,Ke.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Ke.DISABLED=new Ke(-1,0,0);var ti=class r{constructor(e){this.sr=e}next(){return this.sr+=2,this.sr}static _r(){return new r(0)}static ar(){return new r(-1)}};var lg="LruGarbageCollector",Kx=1048576;function hg([r,e],[t,n]){let s=Y(r,t);return s===0?Y(e,n):s}var zc=class{constructor(e){this.Pr=e,this.buffer=new xe(hg),this.Tr=0}Er(){return++this.Tr}Ir(e){let t=[e,this.Er()];if(this.buffer.size<this.Pr)this.buffer=this.buffer.add(t);else{let n=this.buffer.last();hg(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.Rr=null}start(){this.garbageCollector.params.cacheSizeCollectionThreshold!==-1&&this.Ar(6e4)}stop(){this.Rr&&(this.Rr.cancel(),this.Rr=null)}get started(){return this.Rr!==null}Ar(e){M(lg,`Garbage collection scheduled in ${e}ms`),this.Rr=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,(async()=>{this.Rr=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(t){Xn(t)?M(lg,"Ignoring IndexedDB error during garbage collection: ",t):await Yn(t)}await this.Ar(3e5)}))}},Gc=class{constructor(e,t){this.Vr=e,this.params=t}calculateTargetCount(e,t){return this.Vr.dr(e).next((n=>Math.floor(t/100*n)))}nthSequenceNumber(e,t){if(t===0)return V.resolve(Vn.ce);let n=new zc(t);return this.Vr.forEachTarget(e,(s=>n.Ir(s.sequenceNumber))).next((()=>this.Vr.mr(e,(s=>n.Ir(s))))).next((()=>n.maxValue))}removeTargets(e,t,n){return this.Vr.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Vr.removeOrphanedDocuments(e,t)}collect(e,t){return this.params.cacheSizeCollectionThreshold===-1?(M("LruGarbageCollector","Garbage collection skipped; disabled"),V.resolve(cg)):this.getCacheSize(e).next((n=>n<this.params.cacheSizeCollectionThreshold?(M("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),cg):this.gr(e,t)))}getCacheSize(e){return this.Vr.getCacheSize(e)}gr(e,t){let n,s,i,o,u,c,l,f=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next((p=>(p>this.params.maximumSequenceNumbersToCollect?(M("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${p}`),s=this.params.maximumSequenceNumbersToCollect):s=p,o=Date.now(),this.nthSequenceNumber(e,s)))).next((p=>(n=p,u=Date.now(),this.removeTargets(e,n,t)))).next((p=>(i=p,c=Date.now(),this.removeOrphanedDocuments(e,n)))).next((p=>(l=Date.now(),xn()<=X.DEBUG&&M("LruGarbageCollector",`LRU Garbage Collection
|
|
27
13
|
Counted targets in ${o-f}ms
|
|
28
14
|
Determined least recently used ${s} in `+(u-o)+`ms
|
|
29
15
|
Removed ${i} targets in `+(c-u)+`ms
|
|
30
|
-
Removed ${p} documents in `+(
|
|
31
|
-
Total Duration: ${h-f}ms`),V.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:p}))))}};function uR(r,e){return new zc(r,e)}var Kc=class{constructor(){this.changes=new Ot((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,tt.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let n=this.changes.get(t);return n!==void 0?V.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 Gc=class{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}};var Wc=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&&qs(n.mutation,s,We.empty(),_e.now()),s)))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next((n=>this.getLocalViewOfDocuments(e,n,J()).next((()=>n))))}getLocalViewOfDocuments(e,t,n=J()){let s=Ir();return this.populateOverlays(e,s,t).next((()=>this.computeViews(e,t,s,n).next((i=>{let o=Ms();return i.forEach(((u,c)=>{o=o.insert(u,c.overlayedDocument)})),o}))))}getOverlayedDocuments(e,t){let n=Ir();return this.populateOverlays(e,n,t).next((()=>this.computeViews(e,t,n,J())))}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(((o,u)=>{t.set(o,u)}))}))}computeViews(e,t,n,s){let i=Dt(),o=$s(),u=(function(){return $s()})();return t.forEach(((c,h)=>{let f=n.get(h.key);s.has(h.key)&&(f===void 0||f.mutation instanceof pt)?i=i.insert(h.key,h):f!==void 0?(o.set(h.key,f.mutation.getFieldMask()),qs(f.mutation,h,f.mutation.getFieldMask(),_e.now())):o.set(h.key,We.empty())})),this.recalculateAndSaveOverlays(e,i).next((c=>(c.forEach(((h,f)=>o.set(h,f))),t.forEach(((h,f)=>{var p;return u.set(h,new Gc(f,(p=o.get(h))!==null&&p!==void 0?p:null))})),u)))}recalculateAndSaveOverlays(e,t){let n=$s(),s=new he(((o,u)=>o-u)),i=J();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next((o=>{for(let u of o)u.keys().forEach((c=>{let h=t.get(c);if(h===null)return;let f=n.get(c)||We.empty();f=u.applyToLocalView(h,f),n.set(c,f);let p=(s.get(u.batchId)||J()).add(c);s=s.insert(u.batchId,p)}))})).next((()=>{let o=[],u=s.getReverseIterator();for(;u.hasNext();){let c=u.getNext(),h=c.key,f=c.value,p=gy();f.forEach((m=>{if(!i.has(m)){let y=Ey(t.get(m),n.get(m));y!==null&&p.set(m,y),i=i.add(m)}})),o.push(this.documentOverlayCache.saveOverlays(e,h,p))}return V.waitFor(o)})).next((()=>n))}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next((n=>this.recalculateAndSaveOverlays(e,n)))}getDocumentsMatchingQuery(e,t,n,s){return(function(o){return K.isDocumentKey(o.path)&&o.collectionGroup===null&&o.filters.length===0})(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):xx(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 o=s-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,s-i.size):V.resolve(Ir()),u=Ks,c=i;return o.next((h=>V.forEach(h,((f,p)=>(u<p.largestBatchId&&(u=p.largestBatchId),i.get(f)?V.resolve():this.remoteDocumentCache.getEntry(e,f).next((m=>{c=c.insert(f,m)}))))).next((()=>this.populateOverlays(e,h,i))).next((()=>this.computeViews(e,c,h,J()))).next((f=>({batchId:u,changes:my(f)})))))}))}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new K(t)).next((n=>{let s=Ms();return n.isFoundDocument()&&(s=s.insert(n.key,n)),s}))}getDocumentsMatchingCollectionGroupQuery(e,t,n,s){let i=t.collectionGroup,o=Ms();return this.indexManager.getCollectionParents(e,i).next((u=>V.forEach(u,(c=>{let h=(function(p,m){return new jn(m,null,p.explicitOrderBy.slice(),p.filters.slice(),p.limit,p.limitType,p.startAt,p.endAt)})(t,c.child(i));return this.getDocumentsMatchingCollectionQuery(e,h,n,s).next((f=>{f.forEach(((p,m)=>{o=o.insert(p,m)}))}))})).next((()=>o))))}getDocumentsMatchingCollectionQuery(e,t,n,s){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next((o=>(i=o,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,s)))).next((o=>{i.forEach(((c,h)=>{let f=h.getKey();o.get(f)===null&&(o=o.insert(f,tt.newInvalidDocument(f)))}));let u=Ms();return o.forEach(((c,h)=>{let f=i.get(c);f!==void 0&&qs(f.mutation,h,We.empty(),_e.now()),ya(t,h)&&(u=u.insert(c,h))})),u}))}};var Hc=class{constructor(e){this.serializer=e,this.Br=new Map,this.Lr=new Map}getBundleMetadata(e,t){return V.resolve(this.Br.get(t))}saveBundleMetadata(e,t){return this.Br.set(t.id,(function(s){return{id:s.id,version:s.version,createTime:ht(s.createTime)}})(t)),V.resolve()}getNamedQuery(e,t){return V.resolve(this.Lr.get(t))}saveNamedQuery(e,t){return this.Lr.set(t.name,(function(s){return{name:s.name,query:oR(s.bundledQuery),readTime:ht(s.readTime)}})(t)),V.resolve()}};var Qc=class{constructor(){this.overlays=new he(K.comparator),this.kr=new Map}getOverlay(e,t){return V.resolve(this.overlays.get(t))}getOverlays(e,t){let n=Ir();return V.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.wt(e,t,i)})),V.resolve()}removeOverlaysForBatchId(e,t,n){let s=this.kr.get(n);return s!==void 0&&(s.forEach((i=>this.overlays=this.overlays.remove(i))),this.kr.delete(n)),V.resolve()}getOverlaysForCollection(e,t,n){let s=Ir(),i=t.length+1,o=new K(t.child("")),u=this.overlays.getIteratorFrom(o);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 V.resolve(s)}getOverlaysForCollectionGroup(e,t,n,s){let i=new he(((h,f)=>h-f)),o=this.overlays.getIterator();for(;o.hasNext();){let h=o.getNext().value;if(h.getKey().getCollectionGroup()===t&&h.largestBatchId>n){let f=i.get(h.largestBatchId);f===null&&(f=Ir(),i=i.insert(h.largestBatchId,f)),f.set(h.getKey(),h)}}let u=Ir(),c=i.getIterator();for(;c.hasNext()&&(c.getNext().value.forEach(((h,f)=>u.set(h,f))),!(u.size()>=s)););return V.resolve(u)}wt(e,t,n){let s=this.overlays.get(n.key);if(s!==null){let o=this.kr.get(s.largestBatchId).delete(n.key);this.kr.set(s.largestBatchId,o)}this.overlays=this.overlays.insert(n.key,new Cc(t,n));let i=this.kr.get(t);i===void 0&&(i=J(),this.kr.set(t,i)),this.kr.set(t,i.add(n.key))}};var Jc=class{constructor(){this.sessionToken=Ve.EMPTY_BYTE_STRING}getSessionToken(e){return V.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,V.resolve()}};var Ys=class{constructor(){this.qr=new Ie(ge.Qr),this.$r=new Ie(ge.Ur)}isEmpty(){return this.qr.isEmpty()}addReference(e,t){let n=new ge(e,t);this.qr=this.qr.add(n),this.$r=this.$r.add(n)}Kr(e,t){e.forEach((n=>this.addReference(n,t)))}removeReference(e,t){this.Wr(new ge(e,t))}Gr(e,t){e.forEach((n=>this.removeReference(n,t)))}zr(e){let t=new K(new pe([])),n=new ge(t,e),s=new ge(t,e+1),i=[];return this.$r.forEachInRange([n,s],(o=>{this.Wr(o),i.push(o.key)})),i}jr(){this.qr.forEach((e=>this.Wr(e)))}Wr(e){this.qr=this.qr.delete(e),this.$r=this.$r.delete(e)}Jr(e){let t=new K(new pe([])),n=new ge(t,e),s=new ge(t,e+1),i=J();return this.$r.forEachInRange([n,s],(o=>{i=i.add(o.key)})),i}containsKey(e){let t=new ge(e,0),n=this.qr.firstAfterOrEqual(t);return n!==null&&e.isEqual(n.key)}},ge=class{constructor(e,t){this.key=e,this.Hr=t}static Qr(e,t){return K.comparator(e.key,t.key)||Q(e.Hr,t.Hr)}static Ur(e,t){return Q(e.Hr,t.Hr)||K.comparator(e.key,t.key)}};var Xc=class{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.er=1,this.Yr=new Ie(ge.Qr)}checkEmpty(e){return V.resolve(this.mutationQueue.length===0)}addMutationBatch(e,t,n,s){let i=this.er;this.er++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let o=new Rc(i,t,n,s);this.mutationQueue.push(o);for(let u of s)this.Yr=this.Yr.add(new ge(u.key,i)),this.indexManager.addToCollectionParentIndex(e,u.key.path.popLast());return V.resolve(o)}lookupMutationBatch(e,t){return V.resolve(this.Zr(t))}getNextMutationBatchAfterBatchId(e,t){let n=t+1,s=this.Xr(n),i=s<0?0:s;return V.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return V.resolve(this.mutationQueue.length===0?Ul:this.er-1)}getAllMutationBatches(e){return V.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new ge(t,0),s=new ge(t,Number.POSITIVE_INFINITY),i=[];return this.Yr.forEachInRange([n,s],(o=>{let u=this.Zr(o.Hr);i.push(u)})),V.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new Ie(Q);return t.forEach((s=>{let i=new ge(s,0),o=new ge(s,Number.POSITIVE_INFINITY);this.Yr.forEachInRange([i,o],(u=>{n=n.add(u.Hr)}))})),V.resolve(this.ei(n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,s=n.length+1,i=n;K.isDocumentKey(i)||(i=i.child(""));let o=new ge(new K(i),0),u=new Ie(Q);return this.Yr.forEachWhile((c=>{let h=c.key.path;return!!n.isPrefixOf(h)&&(h.length===s&&(u=u.add(c.Hr)),!0)}),o),V.resolve(this.ei(u))}ei(e){let t=[];return e.forEach((n=>{let s=this.Zr(n);s!==null&&t.push(s)})),t}removeMutationBatch(e,t){te(this.ti(t.batchId,"removed")===0,55003),this.mutationQueue.shift();let n=this.Yr;return V.forEach(t.mutations,(s=>{let i=new ge(s.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,s.key)})).next((()=>{this.Yr=n}))}rr(e){}containsKey(e,t){let n=new ge(t,0),s=this.Yr.firstAfterOrEqual(n);return V.resolve(t.isEqual(s&&s.key))}performConsistencyCheck(e){return this.mutationQueue.length,V.resolve()}ti(e,t){return this.Xr(e)}Xr(e){return this.mutationQueue.length===0?0:e-this.mutationQueue[0].batchId}Zr(e){let t=this.Xr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}};var Yc=class{constructor(e){this.ni=e,this.docs=(function(){return new he(K.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,o=this.ni(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:o}),this.size+=o-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 V.resolve(n?n.document.mutableCopy():tt.newInvalidDocument(t))}getEntries(e,t){let n=Dt();return t.forEach((s=>{let i=this.docs.get(s);n=n.insert(s,i?i.document.mutableCopy():tt.newInvalidDocument(s))})),V.resolve(n)}getDocumentsMatchingQuery(e,t,n,s){let i=Dt(),o=t.path,u=new K(o.child("__id-9223372036854775808__")),c=this.docs.getIteratorFrom(u);for(;c.hasNext();){let{key:h,value:{document:f}}=c.getNext();if(!o.isPrefixOf(h.path))break;h.path.length>o.length+1||ax(ox(f),n)<=0||(s.has(f.key)||ya(t,f))&&(i=i.insert(f.key,f.mutableCopy()))}return V.resolve(i)}getAllFromCollectionGroup(e,t,n,s){z(9500)}ri(e,t){return V.forEach(this.docs,(n=>t(n)))}newChangeBuffer(e){return new Zc(this)}getSize(e){return V.resolve(this.size)}},Zc=class extends Kc{constructor(e){super(),this.Or=e}applyChanges(e){let t=[];return this.changes.forEach(((n,s)=>{s.isValidDocument()?t.push(this.Or.addEntry(e,s)):this.Or.removeEntry(n)})),V.waitFor(t)}getFromCache(e,t){return this.Or.getEntry(e,t)}getAllFromCache(e,t){return this.Or.getEntries(e,t)}};var el=class{constructor(e){this.persistence=e,this.ii=new Ot((t=>Kl(t)),Gl),this.lastRemoteSnapshotVersion=W.min(),this.highestTargetId=0,this.si=0,this.oi=new Ys,this.targetCount=0,this._i=Xs.ar()}forEachTarget(e,t){return this.ii.forEach(((n,s)=>t(s))),V.resolve()}getLastRemoteSnapshotVersion(e){return V.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return V.resolve(this.si)}allocateTargetId(e){return this.highestTargetId=this._i.next(),V.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.si&&(this.si=t),V.resolve()}hr(e){this.ii.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this._i=new Xs(t),this.highestTargetId=t),e.sequenceNumber>this.si&&(this.si=e.sequenceNumber)}addTargetData(e,t){return this.hr(t),this.targetCount+=1,V.resolve()}updateTargetData(e,t){return this.hr(t),V.resolve()}removeTargetData(e,t){return this.ii.delete(t.target),this.oi.zr(t.targetId),this.targetCount-=1,V.resolve()}removeTargets(e,t,n){let s=0,i=[];return this.ii.forEach(((o,u)=>{u.sequenceNumber<=t&&n.get(u.targetId)===null&&(this.ii.delete(o),i.push(this.removeMatchingKeysForTargetId(e,u.targetId)),s++)})),V.waitFor(i).next((()=>s))}getTargetCount(e){return V.resolve(this.targetCount)}getTargetData(e,t){let n=this.ii.get(t)||null;return V.resolve(n)}addMatchingKeys(e,t,n){return this.oi.Kr(t,n),V.resolve()}removeMatchingKeys(e,t,n){this.oi.Gr(t,n);let s=this.persistence.referenceDelegate,i=[];return s&&t.forEach((o=>{i.push(s.markPotentiallyOrphaned(e,o))})),V.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.oi.zr(t),V.resolve()}getMatchingKeysForTargetId(e,t){let n=this.oi.Jr(t);return V.resolve(n)}containsKey(e,t){return V.resolve(this.oi.containsKey(t))}};var Go=class{constructor(e,t){this.ai={},this.overlays={},this.ui=new On(0),this.ci=!1,this.ci=!0,this.li=new Jc,this.referenceDelegate=e(this),this.hi=new el(this),this.indexManager=new Uc,this.remoteDocumentCache=(function(s){return new Yc(s)})((n=>this.referenceDelegate.Pi(n))),this.serializer=new Mc(t),this.Ti=new Hc(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.ci=!1,Promise.resolve()}get started(){return this.ci}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new Qc,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.ai[e.toKey()];return n||(n=new Xc(t,this.referenceDelegate),this.ai[e.toKey()]=n),n}getGlobalsCache(){return this.li}getTargetCache(){return this.hi}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ti}runTransaction(e,t,n){M("MemoryPersistence","Starting transaction:",e);let s=new tl(this.ui.next());return this.referenceDelegate.Ii(),n(s).next((i=>this.referenceDelegate.di(s).next((()=>i)))).toPromise().then((i=>(s.raiseOnCommittedEvent(),i)))}Ei(e,t){return V.or(Object.values(this.ai).map((n=>()=>n.containsKey(e,t))))}},tl=class extends hc{constructor(e){super(),this.currentSequenceNumber=e}},rl=class r{constructor(e){this.persistence=e,this.Ai=new Ys,this.Ri=null}static Vi(e){return new r(e)}get mi(){if(this.Ri)return this.Ri;throw z(60996)}addReference(e,t,n){return this.Ai.addReference(n,t),this.mi.delete(n.toString()),V.resolve()}removeReference(e,t,n){return this.Ai.removeReference(n,t),this.mi.add(n.toString()),V.resolve()}markPotentiallyOrphaned(e,t){return this.mi.add(t.toString()),V.resolve()}removeTarget(e,t){this.Ai.zr(t.targetId).forEach((s=>this.mi.add(s.toString())));let n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next((s=>{s.forEach((i=>this.mi.add(i.toString())))})).next((()=>n.removeTargetData(e,t)))}Ii(){this.Ri=new Set}di(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return V.forEach(this.mi,(n=>{let s=K.fromPath(n);return this.fi(e,s).next((i=>{i||t.removeEntry(s,W.min())}))})).next((()=>(this.Ri=null,t.apply(e))))}updateLimboDocument(e,t){return this.fi(e,t).next((n=>{n?this.mi.delete(t.toString()):this.mi.add(t.toString())}))}Pi(e){return 0}fi(e,t){return V.or([()=>V.resolve(this.Ai.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ei(e,t)])}},Wo=class r{constructor(e,t){this.persistence=e,this.gi=new Ot((n=>hx(n.path)),((n,s)=>n.isEqual(s))),this.garbageCollector=uR(this,t)}static Vi(e,t){return new r(e,t)}Ii(){}di(e){return V.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}mr(e){let t=this.yr(e);return this.persistence.getTargetCache().getTargetCount(e).next((n=>t.next((s=>n+s))))}yr(e){let t=0;return this.gr(e,(n=>{t++})).next((()=>t))}gr(e,t){return V.forEach(this.gi,((n,s)=>this.Sr(e,n,s).next((i=>i?V.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.ri(e,(o=>this.Sr(e,o,t).next((u=>{u||(n++,i.removeEntry(o,W.min()))})))).next((()=>i.apply(e))).next((()=>n))}markPotentiallyOrphaned(e,t){return this.gi.set(t,e.currentSequenceNumber),V.resolve()}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,n)}addReference(e,t,n){return this.gi.set(n,e.currentSequenceNumber),V.resolve()}removeReference(e,t,n){return this.gi.set(n,e.currentSequenceNumber),V.resolve()}updateLimboDocument(e,t){return this.gi.set(t,e.currentSequenceNumber),V.resolve()}Pi(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=Ro(e.data.value)),t}Sr(e,t,n){return V.or([()=>this.persistence.Ei(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let s=this.gi.get(t);return V.resolve(s!==void 0&&s>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}};var nl=class r{constructor(e,t,n,s){this.targetId=e,this.fromCache=t,this.Is=n,this.ds=s}static Es(e,t){let n=J(),s=J();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 sl=class{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}};var il=class{constructor(){this.As=!1,this.Rs=!1,this.Vs=100,this.fs=(function(){return Im()?8:cx(Tm())>0?6:4})()}initialize(e,t){this.gs=e,this.indexManager=t,this.As=!0}getDocumentsMatchingQuery(e,t,n,s){let i={result:null};return this.ps(e,t).next((o=>{i.result=o})).next((()=>{if(!i.result)return this.ys(e,t,s,n).next((o=>{i.result=o}))})).next((()=>{if(i.result)return;let o=new sl;return this.ws(e,t,o).next((u=>{if(i.result=u,this.Rs)return this.Ss(e,t,o,u.size)}))})).next((()=>i.result))}Ss(e,t,n,s){return n.documentReadCount<this.Vs?(Tn()<=X.DEBUG&&M("QueryEngine","SDK will not create cache indexes for query:",In(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Vs,"documents"),V.resolve()):(Tn()<=X.DEBUG&&M("QueryEngine","Query:",In(t),"scans",n.documentReadCount,"local documents and returns",s,"documents as results."),n.documentReadCount>this.fs*s?(Tn()<=X.DEBUG&&M("QueryEngine","The SDK decides to create cache indexes for query:",In(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,lt(t))):V.resolve())}ps(e,t){if(ug(t))return V.resolve(null);let n=lt(t);return this.indexManager.getIndexType(e,n).next((s=>s===0?null:(t.limit!==null&&s===1&&(t=Sc(t,null,"F"),n=lt(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next((i=>{let o=J(...i);return this.gs.getDocuments(e,o).next((u=>this.indexManager.getMinOffset(e,n).next((c=>{let h=this.bs(t,u);return this.Ds(t,h,o,c.readTime)?this.ps(e,Sc(t,null,"F")):this.vs(e,h,t,c)}))))})))))}ys(e,t,n,s){return ug(t)||s.isEqual(W.min())?V.resolve(null):this.gs.getDocuments(e,n).next((i=>{let o=this.bs(t,i);return this.Ds(t,o,n,s)?V.resolve(null):(Tn()<=X.DEBUG&&M("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),In(t)),this.vs(e,o,t,ix(s,Ks)).next((u=>u)))}))}bs(e,t){let n=new Ie(fy(e));return t.forEach(((s,i)=>{ya(e,i)&&(n=n.add(i))})),n}Ds(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)}ws(e,t,n){return Tn()<=X.DEBUG&&M("QueryEngine","Using full collection scan to execute query:",In(t)),this.gs.getDocumentsMatchingQuery(e,t,Pr.min(),n)}vs(e,t,n,s){return this.gs.getDocumentsMatchingQuery(e,n,s).next((i=>(t.forEach((o=>{i=i.insert(o.key,o)})),i)))}};var Ql="LocalStore",cR=3e8,ol=class{constructor(e,t,n,s){this.persistence=e,this.Cs=t,this.serializer=s,this.Fs=new he(Q),this.Ms=new Ot((i=>Kl(i)),Gl),this.xs=new Map,this.Os=e.getRemoteDocumentCache(),this.hi=e.getTargetCache(),this.Ti=e.getBundleCache(),this.Ns(n)}Ns(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Wc(this.Os,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Os.setIndexManager(this.indexManager),this.Cs.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(t=>e.collect(t,this.Fs)))}};function lR(r,e,t,n){return new ol(r,e,t,n)}async function Dy(r,e){let t=G(r);return await t.persistence.runTransaction("Handle user change","readonly",(n=>{let s;return t.mutationQueue.getAllMutationBatches(n).next((i=>(s=i,t.Ns(e),t.mutationQueue.getAllMutationBatches(n)))).next((i=>{let o=[],u=[],c=J();for(let h of s){o.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=>({Bs:h,removedBatchIds:o,addedBatchIds:u})))}))}))}function hR(r,e){let t=G(r);return t.persistence.runTransaction("Acknowledge batch","readwrite-primary",(n=>{let s=e.batch.keys(),i=t.Os.newChangeBuffer({trackRemovals:!0});return(function(u,c,h,f){let p=h.batch,m=p.keys(),y=V.resolve();return m.forEach((T=>{y=y.next((()=>f.getEntry(c,T))).next((R=>{let I=h.docVersions.get(T);te(I!==null,48541),R.version.compareTo(I)<0&&(p.applyToRemoteDocument(R,h),R.isValidDocument()&&(R.setReadTime(h.commitVersion),f.addEntry(R)))}))})),y.next((()=>u.mutationQueue.removeMutationBatch(c,p)))})(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=J();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 Ny(r){let e=G(r);return e.persistence.runTransaction("Get last remote snapshot version","readonly",(t=>e.hi.getLastRemoteSnapshotVersion(t)))}function dR(r,e){let t=G(r),n=e.snapshotVersion,s=t.Fs;return t.persistence.runTransaction("Apply remote event","readwrite-primary",(i=>{let o=t.Os.newChangeBuffer({trackRemovals:!0});s=t.Fs;let u=[];e.targetChanges.forEach(((f,p)=>{let m=s.get(p);if(!m)return;u.push(t.hi.removeMatchingKeys(i,f.removedDocuments,p).next((()=>t.hi.addMatchingKeys(i,f.addedDocuments,p))));let y=m.withSequenceNumber(i.currentSequenceNumber);e.targetMismatches.get(p)!==null?y=y.withResumeToken(Ve.EMPTY_BYTE_STRING,W.min()).withLastLimboFreeSnapshotVersion(W.min()):f.resumeToken.approximateByteSize()>0&&(y=y.withResumeToken(f.resumeToken,n)),s=s.insert(p,y),(function(R,I,k){return R.resumeToken.approximateByteSize()===0||I.snapshotVersion.toMicroseconds()-R.snapshotVersion.toMicroseconds()>=cR?!0:k.addedDocuments.size+k.modifiedDocuments.size+k.removedDocuments.size>0})(m,y,f)&&u.push(t.hi.updateTargetData(i,y))}));let c=Dt(),h=J();if(e.documentUpdates.forEach((f=>{e.resolvedLimboDocuments.has(f)&&u.push(t.persistence.referenceDelegate.updateLimboDocument(i,f))})),u.push(fR(i,o,e.documentUpdates).next((f=>{c=f.Ls,h=f.ks}))),!n.isEqual(W.min())){let f=t.hi.getLastRemoteSnapshotVersion(i).next((p=>t.hi.setTargetsMetadata(i,i.currentSequenceNumber,n)));u.push(f)}return V.waitFor(u).next((()=>o.apply(i))).next((()=>t.localDocuments.getLocalViewOfDocuments(i,c,h))).next((()=>c))})).then((i=>(t.Fs=s,i)))}function fR(r,e,t){let n=J(),s=J();return t.forEach((i=>n=n.add(i))),e.getEntries(r,n).next((i=>{let o=Dt();return t.forEach(((u,c)=>{let h=i.get(u);c.isFoundDocument()!==h.isFoundDocument()&&(s=s.add(u)),c.isNoDocument()&&c.version.isEqual(W.min())?(e.removeEntry(u,c.readTime),o=o.insert(u,c)):!h.isValidDocument()||c.version.compareTo(h.version)>0||c.version.compareTo(h.version)===0&&h.hasPendingWrites?(e.addEntry(c),o=o.insert(u,c)):M(Ql,"Ignoring outdated watch update for ",u,". Current version:",h.version," Watch version:",c.version)})),{Ls:o,ks:s}}))}function pR(r,e){let t=G(r);return t.persistence.runTransaction("Get next mutation batch","readonly",(n=>(e===void 0&&(e=Ul),t.mutationQueue.getNextMutationBatchAfterBatchId(n,e))))}function mR(r,e){let t=G(r);return t.persistence.runTransaction("Allocate target","readwrite",(n=>{let s;return t.hi.getTargetData(n,e).next((i=>i?(s=i,V.resolve(s)):t.hi.allocateTargetId(n).next((o=>(s=new Js(e,o,"TargetPurposeListen",n.currentSequenceNumber),t.hi.addTargetData(n,s).next((()=>s)))))))})).then((n=>{let s=t.Fs.get(n.targetId);return(s===null||n.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(t.Fs=t.Fs.insert(n.targetId,n),t.Ms.set(e,n.targetId)),n}))}async function al(r,e,t){let n=G(r),s=n.Fs.get(e),i=t?"readwrite":"readwrite-primary";try{t||await n.persistence.runTransaction("Release target",i,(o=>n.persistence.referenceDelegate.removeTarget(o,s)))}catch(o){if(!Hn(o))throw o;M(Ql,`Failed to update sequence numbers for target ${e}: ${o}`)}n.Fs=n.Fs.remove(e),n.Ms.delete(s.target)}function bg(r,e,t){let n=G(r),s=W.min(),i=J();return n.persistence.runTransaction("Execute query","readwrite",(o=>(function(c,h,f){let p=G(c),m=p.Ms.get(f);return m!==void 0?V.resolve(p.Fs.get(m)):p.hi.getTargetData(h,f)})(n,o,lt(e)).next((u=>{if(u)return s=u.lastLimboFreeSnapshotVersion,n.hi.getMatchingKeysForTargetId(o,u.targetId).next((c=>{i=c}))})).next((()=>n.Cs.getDocumentsMatchingQuery(o,e,t?s:W.min(),t?i:J()))).next((u=>(gR(n,Px(e),u),{documents:u,qs:i})))))}function gR(r,e,t){let n=r.xs.get(e)||W.min();t.forEach(((s,i)=>{i.readTime.compareTo(n)>0&&(n=i.readTime)})),r.xs.set(e,n)}var Ho=class{constructor(){this.activeTargetIds=Vx()}Gs(e){this.activeTargetIds=this.activeTargetIds.add(e)}zs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Ws(){let e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}};var ul=class{constructor(){this.Fo=new Ho,this.Mo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this.Fo.Gs(e),this.Mo[e]||"not-current"}updateQueryState(e,t,n){this.Mo[e]=t}removeLocalQueryTarget(e){this.Fo.zs(e)}isLocalQueryTarget(e){return this.Fo.activeTargetIds.has(e)}clearQueryState(e){delete this.Mo[e]}getAllActiveQueryTargets(){return this.Fo.activeTargetIds}isActiveQueryTarget(e){return this.Fo.activeTargetIds.has(e)}start(){return this.Fo=new Ho,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}};var cl=class{xo(e){}shutdown(){}};var Eg="ConnectivityMonitor",Qo=class{constructor(){this.Oo=()=>this.No(),this.Bo=()=>this.Lo(),this.ko=[],this.qo()}xo(e){this.ko.push(e)}shutdown(){window.removeEventListener("online",this.Oo),window.removeEventListener("offline",this.Bo)}qo(){window.addEventListener("online",this.Oo),window.addEventListener("offline",this.Bo)}No(){M(Eg,"Network connectivity changed: AVAILABLE");for(let e of this.ko)e(0)}Lo(){M(Eg,"Network connectivity changed: UNAVAILABLE");for(let e of this.ko)e(1)}static C(){return typeof window!="undefined"&&window.addEventListener!==void 0&&window.removeEventListener!==void 0}};var xo=null;function ll(){return xo===null?xo=(function(){return 268435456+Math.round(2147483648*Math.random())})():xo++,"0x"+xo.toString(16)}var ec="RestConnection",yR={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"},hl=class{get Qo(){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.$o=t+"://"+e.host,this.Uo=`projects/${n}/databases/${s}`,this.Ko=this.databaseId.database===Lo?`project_id=${n}`:`project_id=${n}&database_id=${s}`}Wo(e,t,n,s,i){let o=ll(),u=this.Go(e,t.toUriEncodedString());M(ec,`Sending RPC '${e}' ${o}:`,u,n);let c={"google-cloud-resource-prefix":this.Uo,"x-goog-request-params":this.Ko};this.zo(c,s,i);let{host:h}=new URL(u),f=vo(h);return this.jo(e,u,c,n,f).then((p=>(M(ec,`Received RPC '${e}' ${o}: `,p),p)),(p=>{throw ar(ec,`RPC '${e}' ${o} failed with error: `,p,"url: ",u,"request:",n),p}))}Jo(e,t,n,s,i,o){return this.Wo(e,t,n,s,i)}zo(e,t,n){e["X-Goog-Api-Client"]=(function(){return"gl-js/ fire/"+Gn})(),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))}Go(e,t){let n=yR[e];return`${this.$o}/v1/${t}:${n}`}terminate(){}};var dl=class{constructor(e){this.Ho=e.Ho,this.Yo=e.Yo}Zo(e){this.Xo=e}e_(e){this.t_=e}n_(e){this.r_=e}onMessage(e){this.i_=e}close(){this.Yo()}send(e){this.Ho(e)}s_(){this.Xo()}o_(){this.t_()}__(e){this.r_(e)}a_(e){this.i_(e)}};var Ne="WebChannelConnection",fl=class extends hl{constructor(e){super(e),this.u_=[],this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}jo(e,t,n,s,i){let o=ll();return new Promise(((u,c)=>{let h=new Hu;h.setWithCredentials(!0),h.listenOnce(Qu.COMPLETE,(()=>{try{switch(h.getLastErrorCode()){case js.NO_ERROR:let p=h.getResponseJson();M(Ne,`XHR for RPC '${e}' ${o} received:`,JSON.stringify(p)),u(p);break;case js.TIMEOUT:M(Ne,`RPC '${e}' ${o} timed out`),c(new B(N.DEADLINE_EXCEEDED,"Request time out"));break;case js.HTTP_ERROR:let m=h.getStatus();if(M(Ne,`RPC '${e}' ${o} failed with status:`,m,"response text:",h.getResponseText()),m>0){let y=h.getResponseJson();Array.isArray(y)&&(y=y[0]);let T=y==null?void 0:y.error;if(T&&T.status&&T.message){let R=(function(k){let O=k.toLowerCase().replace(/_/g,"-");return Object.values(N).indexOf(O)>=0?O:N.UNKNOWN})(T.status);c(new B(R,T.message))}else c(new B(N.UNKNOWN,"Server responded with status "+h.getStatus()))}else c(new B(N.UNAVAILABLE,"Connection failed."));break;default:z(9055,{c_:e,streamId:o,l_:h.getLastErrorCode(),h_:h.getLastError()})}}finally{M(Ne,`RPC '${e}' ${o} completed.`)}}));let f=JSON.stringify(s);M(Ne,`RPC '${e}' ${o} sending request:`,s),h.send(t,"POST",f,n,15)}))}P_(e,t,n){let s=ll(),i=[this.$o,"/","google.firestore.v1.Firestore","/",e,"/channel"],o=Yu(),u=Xu(),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.zo(c.initMessageHeaders,t,n),c.encodeInitMessageHeaders=!0;let f=i.join("");M(Ne,`Creating RPC '${e}' stream ${s}: ${f}`,c);let p=o.createWebChannel(f,c);this.T_(p);let m=!1,y=!1,T=new dl({Ho:I=>{y?M(Ne,`Not sending because RPC '${e}' stream ${s} is closed:`,I):(m||(M(Ne,`Opening RPC '${e}' stream ${s} transport.`),p.open(),m=!0),M(Ne,`RPC '${e}' stream ${s} sending:`,I),p.send(I))},Yo:()=>p.close()}),R=(I,k,O)=>{I.listen(k,(D=>{try{O(D)}catch(j){setTimeout((()=>{throw j}),0)}}))};return R(p,En.EventType.OPEN,(()=>{y||(M(Ne,`RPC '${e}' stream ${s} transport opened.`),T.s_())})),R(p,En.EventType.CLOSE,(()=>{y||(y=!0,M(Ne,`RPC '${e}' stream ${s} transport closed`),T.__(),this.I_(p))})),R(p,En.EventType.ERROR,(I=>{y||(y=!0,ar(Ne,`RPC '${e}' stream ${s} transport errored. Name:`,I.name,"Message:",I.message),T.__(new B(N.UNAVAILABLE,"The operation could not be completed")))})),R(p,En.EventType.MESSAGE,(I=>{var k;if(!y){let O=I.data[0];te(!!O,16349);let D=O,j=(D==null?void 0:D.error)||((k=D[0])===null||k===void 0?void 0:k.error);if(j){M(Ne,`RPC '${e}' stream ${s} received error:`,j);let H=j.status,F=(function(w){let S=me[w];if(S!==void 0)return Iy(S)})(H),E=j.message;F===void 0&&(F=N.INTERNAL,E="Unknown error status: "+H+" with message "+j.message),y=!0,T.__(new B(F,E)),p.close()}else M(Ne,`RPC '${e}' stream ${s} received:`,O),T.a_(O)}})),R(u,Ju.STAT_EVENT,(I=>{I.stat===Io.PROXY?M(Ne,`RPC '${e}' stream ${s} detected buffering proxy`):I.stat===Io.NOPROXY&&M(Ne,`RPC '${e}' stream ${s} detected no buffering proxy`)})),setTimeout((()=>{T.o_()}),0),T}terminate(){this.u_.forEach((e=>e.close())),this.u_=[]}T_(e){this.u_.push(e)}I_(e){this.u_=this.u_.filter((t=>t===e))}};function tc(){return typeof document!="undefined"?document:null}function _a(r){return new Nc(r,!0)}var Jo=class{constructor(e,t,n=1e3,s=1.5,i=6e4){this.Fi=e,this.timerId=t,this.d_=n,this.E_=s,this.A_=i,this.R_=0,this.V_=null,this.m_=Date.now(),this.reset()}reset(){this.R_=0}f_(){this.R_=this.A_}g_(e){this.cancel();let t=Math.floor(this.R_+this.p_()),n=Math.max(0,Date.now()-this.m_),s=Math.max(0,t-n);s>0&&M("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.R_} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.V_=this.Fi.enqueueAfterDelay(this.timerId,s,(()=>(this.m_=Date.now(),e()))),this.R_*=this.E_,this.R_<this.d_&&(this.R_=this.d_),this.R_>this.A_&&(this.R_=this.A_)}y_(){this.V_!==null&&(this.V_.skipDelay(),this.V_=null)}cancel(){this.V_!==null&&(this.V_.cancel(),this.V_=null)}p_(){return(Math.random()-.5)*this.R_}};var Tg="PersistentStream",Xo=class{constructor(e,t,n,s,i,o,u,c){this.Fi=e,this.w_=n,this.S_=s,this.connection=i,this.authCredentialsProvider=o,this.appCheckCredentialsProvider=u,this.listener=c,this.state=0,this.b_=0,this.D_=null,this.v_=null,this.stream=null,this.C_=0,this.F_=new Jo(e,t)}M_(){return this.state===1||this.state===5||this.x_()}x_(){return this.state===2||this.state===3}start(){this.C_=0,this.state!==4?this.auth():this.O_()}async stop(){this.M_()&&await this.close(0)}N_(){this.state=0,this.F_.reset()}B_(){this.x_()&&this.D_===null&&(this.D_=this.Fi.enqueueAfterDelay(this.w_,6e4,(()=>this.L_())))}k_(e){this.q_(),this.stream.send(e)}async L_(){if(this.x_())return this.close(0)}q_(){this.D_&&(this.D_.cancel(),this.D_=null)}Q_(){this.v_&&(this.v_.cancel(),this.v_=null)}async close(e,t){this.q_(),this.Q_(),this.F_.cancel(),this.b_++,e!==4?this.F_.reset():t&&t.code===N.RESOURCE_EXHAUSTED?(Pt(t.toString()),Pt("Using maximum backoff delay to prevent overloading the backend."),this.F_.f_()):t&&t.code===N.UNAUTHENTICATED&&this.state!==3&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),this.stream!==null&&(this.U_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.n_(t)}U_(){}auth(){this.state=1;let e=this.K_(this.b_),t=this.b_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([n,s])=>{this.b_===t&&this.W_(n,s)}),(n=>{e((()=>{let s=new B(N.UNKNOWN,"Fetching auth token failed: "+n.message);return this.G_(s)}))}))}W_(e,t){let n=this.K_(this.b_);this.stream=this.z_(e,t),this.stream.Zo((()=>{n((()=>this.listener.Zo()))})),this.stream.e_((()=>{n((()=>(this.state=2,this.v_=this.Fi.enqueueAfterDelay(this.S_,1e4,(()=>(this.x_()&&(this.state=3),Promise.resolve()))),this.listener.e_())))})),this.stream.n_((s=>{n((()=>this.G_(s)))})),this.stream.onMessage((s=>{n((()=>++this.C_==1?this.j_(s):this.onNext(s)))}))}O_(){this.state=5,this.F_.g_((async()=>{this.state=0,this.start()}))}G_(e){return M(Tg,`close with error: ${e}`),this.stream=null,this.close(4,e)}K_(e){return t=>{this.Fi.enqueueAndForget((()=>this.b_===e?t():(M(Tg,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}},pl=class extends Xo{constructor(e,t,n,s,i,o){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,s,o),this.serializer=i}z_(e,t){return this.connection.P_("Listen",e,t)}j_(e){return this.onNext(e)}onNext(e){this.F_.reset();let t=Qx(this.serializer,e),n=(function(i){if(!("targetChange"in i))return W.min();let o=i.targetChange;return o.targetIds&&o.targetIds.length?W.min():o.readTime?ht(o.readTime):W.min()})(e);return this.listener.J_(t,n)}H_(e){let t={};t.database=jc(this.serializer),t.addTarget=(function(i,o){let u,c=o.target;if(u=Ic(c)?{documents:Yx(i,c)}:{query:Zx(i,c).Vt},u.targetId=o.targetId,o.resumeToken.approximateByteSize()>0){u.resumeToken=Sy(i,o.resumeToken);let h=Vc(i,o.expectedCount);h!==null&&(u.expectedCount=h)}else if(o.snapshotVersion.compareTo(W.min())>0){u.readTime=zo(i,o.snapshotVersion.toTimestamp());let h=Vc(i,o.expectedCount);h!==null&&(u.expectedCount=h)}return u})(this.serializer,e);let n=tR(this.serializer,e);n&&(t.labels=n),this.k_(t)}Y_(e){let t={};t.database=jc(this.serializer),t.removeTarget=e,this.k_(t)}},ml=class extends Xo{constructor(e,t,n,s,i,o){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,s,o),this.serializer=i}get Z_(){return this.C_>0}start(){this.lastStreamToken=void 0,super.start()}U_(){this.Z_&&this.X_([])}z_(e,t){return this.connection.P_("Write",e,t)}j_(e){return te(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,te(!e.writeResults||e.writeResults.length===0,55816),this.listener.ea()}onNext(e){te(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.F_.reset();let t=Xx(e.writeResults,e.commitTime),n=ht(e.commitTime);return this.listener.ta(n,t)}na(){let e={};e.database=jc(this.serializer),this.k_(e)}X_(e){let t={streamToken:this.lastStreamToken,writes:e.map((n=>Jx(this.serializer,n)))};this.k_(t)}};var gl=class{},yl=class extends gl{constructor(e,t,n,s){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=s,this.ra=!1}ia(){if(this.ra)throw new B(N.FAILED_PRECONDITION,"The client has already been terminated.")}Wo(e,t,n,s){return this.ia(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([i,o])=>this.connection.Wo(e,Lc(t,n),s,i,o))).catch((i=>{throw i.name==="FirebaseError"?(i.code===N.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),i):new B(N.UNKNOWN,i.toString())}))}Jo(e,t,n,s,i){return this.ia(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([o,u])=>this.connection.Jo(e,Lc(t,n),s,o,u,i))).catch((o=>{throw o.name==="FirebaseError"?(o.code===N.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),o):new B(N.UNKNOWN,o.toString())}))}terminate(){this.ra=!0,this.connection.terminate()}},_l=class{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.sa=0,this.oa=null,this._a=!0}aa(){this.sa===0&&(this.ua("Unknown"),this.oa=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.oa=null,this.ca("Backend didn't respond within 10 seconds."),this.ua("Offline"),Promise.resolve()))))}la(e){this.state==="Online"?this.ua("Unknown"):(this.sa++,this.sa>=1&&(this.ha(),this.ca(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.ua("Offline")))}set(e){this.ha(),this.sa=0,e==="Online"&&(this._a=!1),this.ua(e)}ua(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}ca(e){let t=`Could not reach Cloud Firestore backend. ${e}
|
|
32
|
-
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.
|
|
16
|
+
Removed ${p} documents in `+(l-c)+`ms
|
|
17
|
+
Total Duration: ${l-f}ms`),V.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:p}))))}};function Gx(r,e){return new Gc(r,e)}var Wc=class{constructor(){this.changes=new Vt((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,Ze.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let n=this.changes.get(t);return n!==void 0?V.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 Hc=class{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}};var Jc=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&&Gs(n.mutation,s,Ge.empty(),ge.now()),s)))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next((n=>this.getLocalViewOfDocuments(e,n,Q()).next((()=>n))))}getLocalViewOfDocuments(e,t,n=Q()){let s=Sr();return this.populateOverlays(e,s,t).next((()=>this.computeViews(e,t,s,n).next((i=>{let o=qs();return i.forEach(((u,c)=>{o=o.insert(u,c.overlayedDocument)})),o}))))}getOverlayedDocuments(e,t){let n=Sr();return this.populateOverlays(e,n,t).next((()=>this.computeViews(e,t,n,Q())))}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(((o,u)=>{t.set(o,u)}))}))}computeViews(e,t,n,s){let i=Lt(),o=Ks(),u=(function(){return Ks()})();return t.forEach(((c,l)=>{let f=n.get(l.key);s.has(l.key)&&(f===void 0||f.mutation instanceof gt)?i=i.insert(l.key,l):f!==void 0?(o.set(l.key,f.mutation.getFieldMask()),Gs(f.mutation,l,f.mutation.getFieldMask(),ge.now())):o.set(l.key,Ge.empty())})),this.recalculateAndSaveOverlays(e,i).next((c=>(c.forEach(((l,f)=>o.set(l,f))),t.forEach(((l,f)=>{var p;return u.set(l,new Hc(f,(p=o.get(l))!=null?p:null))})),u)))}recalculateAndSaveOverlays(e,t){let n=Ks(),s=new de(((o,u)=>o-u)),i=Q();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next((o=>{for(let u of o)u.keys().forEach((c=>{let l=t.get(c);if(l===null)return;let f=n.get(c)||Ge.empty();f=u.applyToLocalView(l,f),n.set(c,f);let p=(s.get(u.batchId)||Q()).add(c);s=s.insert(u.batchId,p)}))})).next((()=>{let o=[],u=s.getReverseIterator();for(;u.hasNext();){let c=u.getNext(),l=c.key,f=c.value,p=cy();f.forEach((g=>{if(!i.has(g)){let y=my(t.get(g),n.get(g));y!==null&&p.set(g,y),i=i.add(g)}})),o.push(this.documentOverlayCache.saveOverlays(e,l,p))}return V.waitFor(o)})).next((()=>n))}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next((n=>this.recalculateAndSaveOverlays(e,n)))}getDocumentsMatchingQuery(e,t,n,s){return hx(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):sy(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 o=s-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,s-i.size):V.resolve(Sr()),u=Ws,c=i;return o.next((l=>V.forEach(l,((f,p)=>(u<p.largestBatchId&&(u=p.largestBatchId),i.get(f)?V.resolve():this.remoteDocumentCache.getEntry(e,f).next((g=>{c=c.insert(f,g)}))))).next((()=>this.populateOverlays(e,l,i))).next((()=>this.computeViews(e,c,l,Q()))).next((f=>({batchId:u,changes:uy(f)})))))}))}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new q(t)).next((n=>{let s=qs();return n.isFoundDocument()&&(s=s.insert(n.key,n)),s}))}getDocumentsMatchingCollectionGroupQuery(e,t,n,s){let i=t.collectionGroup,o=qs();return this.indexManager.getCollectionParents(e,i).next((u=>V.forEach(u,(c=>{let l=(function(p,g){return new jn(g,null,p.explicitOrderBy.slice(),p.filters.slice(),p.limit,p.limitType,p.startAt,p.endAt)})(t,c.child(i));return this.getDocumentsMatchingCollectionQuery(e,l,n,s).next((f=>{f.forEach(((p,g)=>{o=o.insert(p,g)}))}))})).next((()=>o))))}getDocumentsMatchingCollectionQuery(e,t,n,s){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next((o=>(i=o,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,s)))).next((o=>{i.forEach(((c,l)=>{let f=l.getKey();o.get(f)===null&&(o=o.insert(f,Ze.newInvalidDocument(f)))}));let u=qs();return o.forEach(((c,l)=>{let f=i.get(c);f!==void 0&&Gs(f.mutation,l,Ge.empty(),ge.now()),Ta(t,l)&&(u=u.insert(c,l))})),u}))}};var Qc=class{constructor(e){this.serializer=e,this.Nr=new Map,this.Br=new Map}getBundleMetadata(e,t){return V.resolve(this.Nr.get(t))}saveBundleMetadata(e,t){return this.Nr.set(t.id,(function(s){return{id:s.id,version:s.version,createTime:dt(s.createTime)}})(t)),V.resolve()}getNamedQuery(e,t){return V.resolve(this.Br.get(t))}saveNamedQuery(e,t){return this.Br.set(t.name,(function(s){return{name:s.name,query:Sy(s.bundledQuery),readTime:dt(s.readTime)}})(t)),V.resolve()}};var Yc=class{constructor(){this.overlays=new de(q.comparator),this.Lr=new Map}getOverlay(e,t){return V.resolve(this.overlays.get(t))}getOverlays(e,t){let n=Sr();return V.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.St(e,t,i)})),V.resolve()}removeOverlaysForBatchId(e,t,n){let s=this.Lr.get(n);return s!==void 0&&(s.forEach((i=>this.overlays=this.overlays.remove(i))),this.Lr.delete(n)),V.resolve()}getOverlaysForCollection(e,t,n){let s=Sr(),i=t.length+1,o=new q(t.child("")),u=this.overlays.getIteratorFrom(o);for(;u.hasNext();){let c=u.getNext().value,l=c.getKey();if(!t.isPrefixOf(l.path))break;l.path.length===i&&c.largestBatchId>n&&s.set(c.getKey(),c)}return V.resolve(s)}getOverlaysForCollectionGroup(e,t,n,s){let i=new de(((l,f)=>l-f)),o=this.overlays.getIterator();for(;o.hasNext();){let l=o.getNext().value;if(l.getKey().getCollectionGroup()===t&&l.largestBatchId>n){let f=i.get(l.largestBatchId);f===null&&(f=Sr(),i=i.insert(l.largestBatchId,f)),f.set(l.getKey(),l)}}let u=Sr(),c=i.getIterator();for(;c.hasNext()&&(c.getNext().value.forEach(((l,f)=>u.set(l,f))),!(u.size()>=s)););return V.resolve(u)}St(e,t,n){let s=this.overlays.get(n.key);if(s!==null){let o=this.Lr.get(s.largestBatchId).delete(n.key);this.Lr.set(s.largestBatchId,o)}this.overlays=this.overlays.insert(n.key,new Oc(t,n));let i=this.Lr.get(t);i===void 0&&(i=Q(),this.Lr.set(t,i)),this.Lr.set(t,i.add(n.key))}};var Xc=class{constructor(){this.sessionToken=Pe.EMPTY_BYTE_STRING}getSessionToken(e){return V.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,V.resolve()}};var ri=class{constructor(){this.kr=new xe(_e.qr),this.Kr=new xe(_e.Ur)}isEmpty(){return this.kr.isEmpty()}addReference(e,t){let n=new _e(e,t);this.kr=this.kr.add(n),this.Kr=this.Kr.add(n)}$r(e,t){e.forEach((n=>this.addReference(n,t)))}removeReference(e,t){this.Wr(new _e(e,t))}Qr(e,t){e.forEach((n=>this.removeReference(n,t)))}Gr(e){let t=new q(new he([])),n=new _e(t,e),s=new _e(t,e+1),i=[];return this.Kr.forEachInRange([n,s],(o=>{this.Wr(o),i.push(o.key)})),i}zr(){this.kr.forEach((e=>this.Wr(e)))}Wr(e){this.kr=this.kr.delete(e),this.Kr=this.Kr.delete(e)}jr(e){let t=new q(new he([])),n=new _e(t,e),s=new _e(t,e+1),i=Q();return this.Kr.forEachInRange([n,s],(o=>{i=i.add(o.key)})),i}containsKey(e){let t=new _e(e,0),n=this.kr.firstAfterOrEqual(t);return n!==null&&e.isEqual(n.key)}},_e=class{constructor(e,t){this.key=e,this.Jr=t}static qr(e,t){return q.comparator(e.key,t.key)||Y(e.Jr,t.Jr)}static Ur(e,t){return Y(e.Jr,t.Jr)||q.comparator(e.key,t.key)}};var Zc=class{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Yn=1,this.Hr=new xe(_e.qr)}checkEmpty(e){return V.resolve(this.mutationQueue.length===0)}addMutationBatch(e,t,n,s){let i=this.Yn;this.Yn++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let o=new Cc(i,t,n,s);this.mutationQueue.push(o);for(let u of s)this.Hr=this.Hr.add(new _e(u.key,i)),this.indexManager.addToCollectionParentIndex(e,u.key.path.popLast());return V.resolve(o)}lookupMutationBatch(e,t){return V.resolve(this.Zr(t))}getNextMutationBatchAfterBatchId(e,t){let n=t+1,s=this.Xr(n),i=s<0?0:s;return V.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return V.resolve(this.mutationQueue.length===0?Ll:this.Yn-1)}getAllMutationBatches(e){return V.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new _e(t,0),s=new _e(t,Number.POSITIVE_INFINITY),i=[];return this.Hr.forEachInRange([n,s],(o=>{let u=this.Zr(o.Jr);i.push(u)})),V.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new xe(Y);return t.forEach((s=>{let i=new _e(s,0),o=new _e(s,Number.POSITIVE_INFINITY);this.Hr.forEachInRange([i,o],(u=>{n=n.add(u.Jr)}))})),V.resolve(this.Yr(n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,s=n.length+1,i=n;q.isDocumentKey(i)||(i=i.child(""));let o=new _e(new q(i),0),u=new xe(Y);return this.Hr.forEachWhile((c=>{let l=c.key.path;return!!n.isPrefixOf(l)&&(l.length===s&&(u=u.add(c.Jr)),!0)}),o),V.resolve(this.Yr(u))}Yr(e){let t=[];return e.forEach((n=>{let s=this.Zr(n);s!==null&&t.push(s)})),t}removeMutationBatch(e,t){te(this.ei(t.batchId,"removed")===0,55003),this.mutationQueue.shift();let n=this.Hr;return V.forEach(t.mutations,(s=>{let i=new _e(s.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,s.key)})).next((()=>{this.Hr=n}))}nr(e){}containsKey(e,t){let n=new _e(t,0),s=this.Hr.firstAfterOrEqual(n);return V.resolve(t.isEqual(s&&s.key))}performConsistencyCheck(e){return this.mutationQueue.length,V.resolve()}ei(e,t){return this.Xr(e)}Xr(e){return this.mutationQueue.length===0?0:e-this.mutationQueue[0].batchId}Zr(e){let t=this.Xr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}};var el=class{constructor(e){this.ti=e,this.docs=(function(){return new de(q.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,o=this.ti(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:o}),this.size+=o-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 V.resolve(n?n.document.mutableCopy():Ze.newInvalidDocument(t))}getEntries(e,t){let n=Lt();return t.forEach((s=>{let i=this.docs.get(s);n=n.insert(s,i?i.document.mutableCopy():Ze.newInvalidDocument(s))})),V.resolve(n)}getDocumentsMatchingQuery(e,t,n,s){let i=Lt(),o=t.path,u=new q(o.child("__id-9223372036854775808__")),c=this.docs.getIteratorFrom(u);for(;c.hasNext();){let{key:l,value:{document:f}}=c.getNext();if(!o.isPrefixOf(l.path))break;l.path.length>o.length+1||KS(zS(f),n)<=0||(s.has(f.key)||Ta(t,f))&&(i=i.insert(f.key,f.mutableCopy()))}return V.resolve(i)}getAllFromCollectionGroup(e,t,n,s){K(9500)}ni(e,t){return V.forEach(this.docs,(n=>t(n)))}newChangeBuffer(e){return new tl(this)}getSize(e){return V.resolve(this.size)}},tl=class extends Wc{constructor(e){super(),this.Mr=e}applyChanges(e){let t=[];return this.changes.forEach(((n,s)=>{s.isValidDocument()?t.push(this.Mr.addEntry(e,s)):this.Mr.removeEntry(n)})),V.waitFor(t)}getFromCache(e,t){return this.Mr.getEntry(e,t)}getAllFromCache(e,t){return this.Mr.getEntries(e,t)}};var rl=class{constructor(e){this.persistence=e,this.ri=new Vt((t=>Ul(t)),Bl),this.lastRemoteSnapshotVersion=H.min(),this.highestTargetId=0,this.ii=0,this.si=new ri,this.targetCount=0,this.oi=ti._r()}forEachTarget(e,t){return this.ri.forEach(((n,s)=>t(s))),V.resolve()}getLastRemoteSnapshotVersion(e){return V.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return V.resolve(this.ii)}allocateTargetId(e){return this.highestTargetId=this.oi.next(),V.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.ii&&(this.ii=t),V.resolve()}lr(e){this.ri.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this.oi=new ti(t),this.highestTargetId=t),e.sequenceNumber>this.ii&&(this.ii=e.sequenceNumber)}addTargetData(e,t){return this.lr(t),this.targetCount+=1,V.resolve()}updateTargetData(e,t){return this.lr(t),V.resolve()}removeTargetData(e,t){return this.ri.delete(t.target),this.si.Gr(t.targetId),this.targetCount-=1,V.resolve()}removeTargets(e,t,n){let s=0,i=[];return this.ri.forEach(((o,u)=>{u.sequenceNumber<=t&&n.get(u.targetId)===null&&(this.ri.delete(o),i.push(this.removeMatchingKeysForTargetId(e,u.targetId)),s++)})),V.waitFor(i).next((()=>s))}getTargetCount(e){return V.resolve(this.targetCount)}getTargetData(e,t){let n=this.ri.get(t)||null;return V.resolve(n)}addMatchingKeys(e,t,n){return this.si.$r(t,n),V.resolve()}removeMatchingKeys(e,t,n){this.si.Qr(t,n);let s=this.persistence.referenceDelegate,i=[];return s&&t.forEach((o=>{i.push(s.markPotentiallyOrphaned(e,o))})),V.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.si.Gr(t),V.resolve()}getMatchingKeysForTargetId(e,t){let n=this.si.jr(t);return V.resolve(n)}containsKey(e,t){return V.resolve(this.si.containsKey(t))}};var Zo=class{constructor(e,t){this._i={},this.overlays={},this.ai=new Vn(0),this.ui=!1,this.ui=!0,this.ci=new Xc,this.referenceDelegate=e(this),this.li=new rl(this),this.indexManager=new $c,this.remoteDocumentCache=(function(s){return new el(s)})((n=>this.referenceDelegate.hi(n))),this.serializer=new Bc(t),this.Pi=new Qc(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.ui=!1,Promise.resolve()}get started(){return this.ui}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new Yc,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this._i[e.toKey()];return n||(n=new Zc(t,this.referenceDelegate),this._i[e.toKey()]=n),n}getGlobalsCache(){return this.ci}getTargetCache(){return this.li}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Pi}runTransaction(e,t,n){M("MemoryPersistence","Starting transaction:",e);let s=new nl(this.ai.next());return this.referenceDelegate.Ti(),n(s).next((i=>this.referenceDelegate.Ei(s).next((()=>i)))).toPromise().then((i=>(s.raiseOnCommittedEvent(),i)))}Ii(e,t){return V.or(Object.values(this._i).map((n=>()=>n.containsKey(e,t))))}},nl=class extends pc{constructor(e){super(),this.currentSequenceNumber=e}},sl=class r{constructor(e){this.persistence=e,this.Ri=new ri,this.Ai=null}static Vi(e){return new r(e)}get di(){if(this.Ai)return this.Ai;throw K(60996)}addReference(e,t,n){return this.Ri.addReference(n,t),this.di.delete(n.toString()),V.resolve()}removeReference(e,t,n){return this.Ri.removeReference(n,t),this.di.add(n.toString()),V.resolve()}markPotentiallyOrphaned(e,t){return this.di.add(t.toString()),V.resolve()}removeTarget(e,t){this.Ri.Gr(t.targetId).forEach((s=>this.di.add(s.toString())));let n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next((s=>{s.forEach((i=>this.di.add(i.toString())))})).next((()=>n.removeTargetData(e,t)))}Ti(){this.Ai=new Set}Ei(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return V.forEach(this.di,(n=>{let s=q.fromPath(n);return this.mi(e,s).next((i=>{i||t.removeEntry(s,H.min())}))})).next((()=>(this.Ai=null,t.apply(e))))}updateLimboDocument(e,t){return this.mi(e,t).next((n=>{n?this.di.delete(t.toString()):this.di.add(t.toString())}))}hi(e){return 0}mi(e,t){return V.or([()=>V.resolve(this.Ri.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ii(e,t)])}},ea=class r{constructor(e,t){this.persistence=e,this.fi=new Vt((n=>JS(n.path)),((n,s)=>n.isEqual(s))),this.garbageCollector=Gx(this,t)}static Vi(e,t){return new r(e,t)}Ti(){}Ei(e){return V.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}dr(e){let t=this.pr(e);return this.persistence.getTargetCache().getTargetCount(e).next((n=>t.next((s=>n+s))))}pr(e){let t=0;return this.mr(e,(n=>{t++})).next((()=>t))}mr(e,t){return V.forEach(this.fi,((n,s)=>this.wr(e,n,s).next((i=>i?V.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.ni(e,(o=>this.wr(e,o,t).next((u=>{u||(n++,i.removeEntry(o,H.min()))})))).next((()=>i.apply(e))).next((()=>n))}markPotentiallyOrphaned(e,t){return this.fi.set(t,e.currentSequenceNumber),V.resolve()}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,n)}addReference(e,t,n){return this.fi.set(n,e.currentSequenceNumber),V.resolve()}removeReference(e,t,n){return this.fi.set(n,e.currentSequenceNumber),V.resolve()}updateLimboDocument(e,t){return this.fi.set(t,e.currentSequenceNumber),V.resolve()}hi(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=Oo(e.data.value)),t}wr(e,t,n){return V.or([()=>this.persistence.Ii(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let s=this.fi.get(t);return V.resolve(s!==void 0&&s>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}};var il=class r{constructor(e,t,n,s){this.targetId=e,this.fromCache=t,this.Ts=n,this.Es=s}static Is(e,t){let n=Q(),s=Q();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 ol=class{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}};var al=class{constructor(){this.Rs=!1,this.As=!1,this.Vs=100,this.ds=(function(){return _m()?8:WS(ym())>0?6:4})()}initialize(e,t){this.fs=e,this.indexManager=t,this.Rs=!0}getDocumentsMatchingQuery(e,t,n,s){let i={result:null};return this.gs(e,t).next((o=>{i.result=o})).next((()=>{if(!i.result)return this.ps(e,t,s,n).next((o=>{i.result=o}))})).next((()=>{if(i.result)return;let o=new ol;return this.ys(e,t,o).next((u=>{if(i.result=u,this.As)return this.ws(e,t,o,u.size)}))})).next((()=>i.result))}ws(e,t,n,s){return n.documentReadCount<this.Vs?(xn()<=X.DEBUG&&M("QueryEngine","SDK will not create cache indexes for query:",Rn(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Vs,"documents"),V.resolve()):(xn()<=X.DEBUG&&M("QueryEngine","Query:",Rn(t),"scans",n.documentReadCount,"local documents and returns",s,"documents as results."),n.documentReadCount>this.ds*s?(xn()<=X.DEBUG&&M("QueryEngine","The SDK decides to create cache indexes for query:",Rn(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,ht(t))):V.resolve())}gs(e,t){if(eg(t))return V.resolve(null);let n=ht(t);return this.indexManager.getIndexType(e,n).next((s=>s===0?null:(t.limit!==null&&s===1&&(t=Go(t,null,"F"),n=ht(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next((i=>{let o=Q(...i);return this.fs.getDocuments(e,o).next((u=>this.indexManager.getMinOffset(e,n).next((c=>{let l=this.Ss(t,u);return this.bs(t,l,o,c.readTime)?this.gs(e,Go(t,null,"F")):this.Ds(e,l,t,c)}))))})))))}ps(e,t,n,s){return eg(t)||s.isEqual(H.min())?V.resolve(null):this.fs.getDocuments(e,n).next((i=>{let o=this.Ss(t,i);return this.bs(t,o,n,s)?V.resolve(null):(xn()<=X.DEBUG&&M("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),Rn(t)),this.Ds(e,o,t,qS(s,Ws)).next((u=>u)))}))}Ss(e,t){let n=new xe(oy(e));return t.forEach(((s,i)=>{Ta(e,i)&&(n=n.add(i))})),n}bs(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)}ys(e,t,n){return xn()<=X.DEBUG&&M("QueryEngine","Using full collection scan to execute query:",Rn(t)),this.fs.getDocumentsMatchingQuery(e,t,Cr.min(),n)}Ds(e,t,n,s){return this.fs.getDocumentsMatchingQuery(e,n,s).next((i=>(t.forEach((o=>{i=i.insert(o.key,o)})),i)))}};var zl="LocalStore",Wx=3e8,ul=class{constructor(e,t,n,s){this.persistence=e,this.Cs=t,this.serializer=s,this.vs=new de(Y),this.Fs=new Vt((i=>Ul(i)),Bl),this.Ms=new Map,this.xs=e.getRemoteDocumentCache(),this.li=e.getTargetCache(),this.Pi=e.getBundleCache(),this.Os(n)}Os(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Jc(this.xs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.xs.setIndexManager(this.indexManager),this.Cs.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(t=>e.collect(t,this.vs)))}};function Hx(r,e,t,n){return new ul(r,e,t,n)}async function Ry(r,e){let t=W(r);return await t.persistence.runTransaction("Handle user change","readonly",(n=>{let s;return t.mutationQueue.getAllMutationBatches(n).next((i=>(s=i,t.Os(e),t.mutationQueue.getAllMutationBatches(n)))).next((i=>{let o=[],u=[],c=Q();for(let l of s){o.push(l.batchId);for(let f of l.mutations)c=c.add(f.key)}for(let l of i){u.push(l.batchId);for(let f of l.mutations)c=c.add(f.key)}return t.localDocuments.getDocuments(n,c).next((l=>({Ns:l,removedBatchIds:o,addedBatchIds:u})))}))}))}function Jx(r,e){let t=W(r);return t.persistence.runTransaction("Acknowledge batch","readwrite-primary",(n=>{let s=e.batch.keys(),i=t.xs.newChangeBuffer({trackRemovals:!0});return(function(u,c,l,f){let p=l.batch,g=p.keys(),y=V.resolve();return g.forEach((I=>{y=y.next((()=>f.getEntry(c,I))).next((R=>{let A=l.docVersions.get(I);te(A!==null,48541),R.version.compareTo(A)<0&&(p.applyToRemoteDocument(R,l),R.isValidDocument()&&(R.setReadTime(l.commitVersion),f.addEntry(R)))}))})),y.next((()=>u.mutationQueue.removeMutationBatch(c,p)))})(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=Q();for(let l=0;l<u.mutationResults.length;++l)u.mutationResults[l].transformResults.length>0&&(c=c.add(u.batch.mutations[l].key));return c})(e)))).next((()=>t.localDocuments.getDocuments(n,s)))}))}function Py(r){let e=W(r);return e.persistence.runTransaction("Get last remote snapshot version","readonly",(t=>e.li.getLastRemoteSnapshotVersion(t)))}function Qx(r,e){let t=W(r),n=e.snapshotVersion,s=t.vs;return t.persistence.runTransaction("Apply remote event","readwrite-primary",(i=>{let o=t.xs.newChangeBuffer({trackRemovals:!0});s=t.vs;let u=[];e.targetChanges.forEach(((f,p)=>{let g=s.get(p);if(!g)return;u.push(t.li.removeMatchingKeys(i,f.removedDocuments,p).next((()=>t.li.addMatchingKeys(i,f.addedDocuments,p))));let y=g.withSequenceNumber(i.currentSequenceNumber);e.targetMismatches.get(p)!==null?y=y.withResumeToken(Pe.EMPTY_BYTE_STRING,H.min()).withLastLimboFreeSnapshotVersion(H.min()):f.resumeToken.approximateByteSize()>0&&(y=y.withResumeToken(f.resumeToken,n)),s=s.insert(p,y),(function(R,A,k){return R.resumeToken.approximateByteSize()===0||A.snapshotVersion.toMicroseconds()-R.snapshotVersion.toMicroseconds()>=Wx?!0:k.addedDocuments.size+k.modifiedDocuments.size+k.removedDocuments.size>0})(g,y,f)&&u.push(t.li.updateTargetData(i,y))}));let c=Lt(),l=Q();if(e.documentUpdates.forEach((f=>{e.resolvedLimboDocuments.has(f)&&u.push(t.persistence.referenceDelegate.updateLimboDocument(i,f))})),u.push(Yx(i,o,e.documentUpdates).next((f=>{c=f.Bs,l=f.Ls}))),!n.isEqual(H.min())){let f=t.li.getLastRemoteSnapshotVersion(i).next((p=>t.li.setTargetsMetadata(i,i.currentSequenceNumber,n)));u.push(f)}return V.waitFor(u).next((()=>o.apply(i))).next((()=>t.localDocuments.getLocalViewOfDocuments(i,c,l))).next((()=>c))})).then((i=>(t.vs=s,i)))}function Yx(r,e,t){let n=Q(),s=Q();return t.forEach((i=>n=n.add(i))),e.getEntries(r,n).next((i=>{let o=Lt();return t.forEach(((u,c)=>{let l=i.get(u);c.isFoundDocument()!==l.isFoundDocument()&&(s=s.add(u)),c.isNoDocument()&&c.version.isEqual(H.min())?(e.removeEntry(u,c.readTime),o=o.insert(u,c)):!l.isValidDocument()||c.version.compareTo(l.version)>0||c.version.compareTo(l.version)===0&&l.hasPendingWrites?(e.addEntry(c),o=o.insert(u,c)):M(zl,"Ignoring outdated watch update for ",u,". Current version:",l.version," Watch version:",c.version)})),{Bs:o,Ls:s}}))}function Xx(r,e){let t=W(r);return t.persistence.runTransaction("Get next mutation batch","readonly",(n=>(e===void 0&&(e=Ll),t.mutationQueue.getNextMutationBatchAfterBatchId(n,e))))}function Zx(r,e){let t=W(r);return t.persistence.runTransaction("Allocate target","readwrite",(n=>{let s;return t.li.getTargetData(n,e).next((i=>i?(s=i,V.resolve(s)):t.li.allocateTargetId(n).next((o=>(s=new ei(e,o,"TargetPurposeListen",n.currentSequenceNumber),t.li.addTargetData(n,s).next((()=>s)))))))})).then((n=>{let s=t.vs.get(n.targetId);return(s===null||n.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(t.vs=t.vs.insert(n.targetId,n),t.Fs.set(e,n.targetId)),n}))}async function cl(r,e,t){let n=W(r),s=n.vs.get(e),i=t?"readwrite":"readwrite-primary";try{t||await n.persistence.runTransaction("Release target",i,(o=>n.persistence.referenceDelegate.removeTarget(o,s)))}catch(o){if(!Xn(o))throw o;M(zl,`Failed to update sequence numbers for target ${e}: ${o}`)}n.vs=n.vs.remove(e),n.Fs.delete(s.target)}function dg(r,e,t){let n=W(r),s=H.min(),i=Q();return n.persistence.runTransaction("Execute query","readwrite",(o=>(function(c,l,f){let p=W(c),g=p.Fs.get(f);return g!==void 0?V.resolve(p.vs.get(g)):p.li.getTargetData(l,f)})(n,o,ht(e)).next((u=>{if(u)return s=u.lastLimboFreeSnapshotVersion,n.li.getMatchingKeysForTargetId(o,u.targetId).next((c=>{i=c}))})).next((()=>n.Cs.getDocumentsMatchingQuery(o,e,t?s:H.min(),t?i:Q()))).next((u=>(eR(n,fx(e),u),{documents:u,ks:i})))))}function eR(r,e,t){let n=r.Ms.get(e)||H.min();t.forEach(((s,i)=>{i.readTime.compareTo(n)>0&&(n=i.readTime)})),r.Ms.set(e,n)}var ta=class{constructor(){this.activeTargetIds=wx()}Qs(e){this.activeTargetIds=this.activeTargetIds.add(e)}Gs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Ws(){let e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}};var ll=class{constructor(){this.vo=new ta,this.Fo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this.vo.Qs(e),this.Fo[e]||"not-current"}updateQueryState(e,t,n){this.Fo[e]=t}removeLocalQueryTarget(e){this.vo.Gs(e)}isLocalQueryTarget(e){return this.vo.activeTargetIds.has(e)}clearQueryState(e){delete this.Fo[e]}getAllActiveQueryTargets(){return this.vo.activeTargetIds}isActiveQueryTarget(e){return this.vo.activeTargetIds.has(e)}start(){return this.vo=new ta,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}};var hl=class{Mo(e){}shutdown(){}};var fg="ConnectivityMonitor",ra=class{constructor(){this.xo=()=>this.Oo(),this.No=()=>this.Bo(),this.Lo=[],this.ko()}Mo(e){this.Lo.push(e)}shutdown(){window.removeEventListener("online",this.xo),window.removeEventListener("offline",this.No)}ko(){window.addEventListener("online",this.xo),window.addEventListener("offline",this.No)}Oo(){M(fg,"Network connectivity changed: AVAILABLE");for(let e of this.Lo)e(0)}Bo(){M(fg,"Network connectivity changed: UNAVAILABLE");for(let e of this.Lo)e(1)}static v(){return typeof window!="undefined"&&window.addEventListener!==void 0&&window.removeEventListener!==void 0}};var ko=null;function dl(){return ko===null?ko=(function(){return 268435456+Math.round(2147483648*Math.random())})():ko++,"0x"+ko.toString(16)}var ac="RestConnection",tR={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery",ExecutePipeline:"executePipeline"},fl=class{get qo(){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.Ko=t+"://"+e.host,this.Uo=`projects/${n}/databases/${s}`,this.$o=this.databaseId.database===zo?`project_id=${n}`:`project_id=${n}&database_id=${s}`}Wo(e,t,n,s,i){let o=dl(),u=this.Qo(e,t.toUriEncodedString());M(ac,`Sending RPC '${e}' ${o}:`,u,n);let c={"google-cloud-resource-prefix":this.Uo,"x-goog-request-params":this.$o};this.Go(c,s,i);let{host:l}=new URL(u),f=Lu(l);return this.zo(e,u,c,n,f).then((p=>(M(ac,`Received RPC '${e}' ${o}: `,p),p)),(p=>{throw Ot(ac,`RPC '${e}' ${o} failed with error: `,p,"url: ",u,"request:",n),p}))}jo(e,t,n,s,i,o){return this.Wo(e,t,n,s,i)}Go(e,t,n){e["X-Goog-Api-Client"]=(function(){return"gl-js/ fire/"+Jn})(),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))}Qo(e,t){let n=tR[e],s=`${this.Ko}/v1/${t}:${n}`;return this.databaseInfo.apiKey&&(s=`${s}?key=${encodeURIComponent(this.databaseInfo.apiKey)}`),s}terminate(){}};var pl=class{constructor(e){this.Jo=e.Jo,this.Ho=e.Ho}Zo(e){this.Xo=e}Yo(e){this.e_=e}t_(e){this.n_=e}onMessage(e){this.r_=e}close(){this.Ho()}send(e){this.Jo(e)}i_(){this.Xo()}s_(){this.e_()}o_(e){this.n_(e)}__(e){this.r_(e)}};var De="WebChannelConnection",$s=(r,e,t)=>{r.listen(e,(n=>{try{t(n)}catch(s){setTimeout((()=>{throw s}),0)}}))},na=class r extends fl{constructor(e){super(e),this.a_=[],this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}static u_(){if(!r.c_){let e=rc();$s(e,tc.STAT_EVENT,(t=>{t.stat===Ro.PROXY?M(De,"STAT_EVENT: detected buffering proxy"):t.stat===Ro.NOPROXY&&M(De,"STAT_EVENT: detected no buffering proxy")})),r.c_=!0}}zo(e,t,n,s,i){let o=dl();return new Promise(((u,c)=>{let l=new Zu;l.setWithCredentials(!0),l.listenOnce(ec.COMPLETE,(()=>{try{switch(l.getLastErrorCode()){case Bs.NO_ERROR:let p=l.getResponseJson();M(De,`XHR for RPC '${e}' ${o} received:`,JSON.stringify(p)),u(p);break;case Bs.TIMEOUT:M(De,`RPC '${e}' ${o} timed out`),c(new B(O.DEADLINE_EXCEEDED,"Request time out"));break;case Bs.HTTP_ERROR:let g=l.getStatus();if(M(De,`RPC '${e}' ${o} failed with status:`,g,"response text:",l.getResponseText()),g>0){let y=l.getResponseJson();Array.isArray(y)&&(y=y[0]);let I=y==null?void 0:y.error;if(I&&I.status&&I.message){let R=(function(k){let D=k.toLowerCase().replace(/_/g,"-");return Object.values(O).indexOf(D)>=0?D:O.UNKNOWN})(I.status);c(new B(R,I.message))}else c(new B(O.UNKNOWN,"Server responded with status "+l.getStatus()))}else c(new B(O.UNAVAILABLE,"Connection failed."));break;default:K(9055,{l_:e,streamId:o,h_:l.getLastErrorCode(),P_:l.getLastError()})}}finally{M(De,`RPC '${e}' ${o} completed.`)}}));let f=JSON.stringify(s);M(De,`RPC '${e}' ${o} sending request:`,s),l.send(t,"POST",f,n,15)}))}T_(e,t,n){let s=dl(),i=[this.Ko,"/","google.firestore.v1.Firestore","/",e,"/channel"],o=this.createWebChannelTransport(),u={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},c=this.longPollingOptions.timeoutSeconds;c!==void 0&&(u.longPollingTimeout=Math.round(1e3*c)),this.useFetchStreams&&(u.useFetchStreams=!0),this.Go(u.initMessageHeaders,t,n),u.encodeInitMessageHeaders=!0;let l=i.join("");M(De,`Creating RPC '${e}' stream ${s}: ${l}`,u);let f=o.createWebChannel(l,u);this.E_(f);let p=!1,g=!1,y=new pl({Jo:I=>{g?M(De,`Not sending because RPC '${e}' stream ${s} is closed:`,I):(p||(M(De,`Opening RPC '${e}' stream ${s} transport.`),f.open(),p=!0),M(De,`RPC '${e}' stream ${s} sending:`,I),f.send(I))},Ho:()=>f.close()});return $s(f,Sn.EventType.OPEN,(()=>{g||(M(De,`RPC '${e}' stream ${s} transport opened.`),y.i_())})),$s(f,Sn.EventType.CLOSE,(()=>{g||(g=!0,M(De,`RPC '${e}' stream ${s} transport closed`),y.o_(),this.I_(f))})),$s(f,Sn.EventType.ERROR,(I=>{g||(g=!0,Ot(De,`RPC '${e}' stream ${s} transport errored. Name:`,I.name,"Message:",I.message),y.o_(new B(O.UNAVAILABLE,"The operation could not be completed")))})),$s(f,Sn.EventType.MESSAGE,(I=>{var R;if(!g){let A=I.data[0];te(!!A,16349);let k=A,D=(k==null?void 0:k.error)||((R=k[0])==null?void 0:R.error);if(D){M(De,`RPC '${e}' stream ${s} received error:`,D);let N=D.status,U=(function(E){let _=ye[E];if(_!==void 0)return yy(_)})(N),z=D.message;N==="NOT_FOUND"&&z.includes("database")&&z.includes("does not exist")&&z.includes(this.databaseId.database)&&Ot(`Database '${this.databaseId.database}' not found. Please check your project configuration.`),U===void 0&&(U=O.INTERNAL,z="Unknown error status: "+N+" with message "+D.message),g=!0,y.o_(new B(U,z)),f.close()}else M(De,`RPC '${e}' stream ${s} received:`,A),y.__(A)}})),r.u_(),setTimeout((()=>{y.s_()}),0),y}terminate(){this.a_.forEach((e=>e.close())),this.a_=[]}E_(e){this.a_.push(e)}I_(e){this.a_=this.a_.filter((t=>t===e))}Go(e,t,n){super.Go(e,t,n),this.databaseInfo.apiKey&&(e["x-goog-api-key"]=this.databaseInfo.apiKey)}createWebChannelTransport(){return nc()}};function rR(r){return new na(r)}function uc(){return typeof document!="undefined"?document:null}function ui(r){return new Lc(r,!0)}na.c_=!1;var sa=class{constructor(e,t,n=1e3,s=1.5,i=6e4){this.Ci=e,this.timerId=t,this.R_=n,this.A_=s,this.V_=i,this.d_=0,this.m_=null,this.f_=Date.now(),this.reset()}reset(){this.d_=0}g_(){this.d_=this.V_}p_(e){this.cancel();let t=Math.floor(this.d_+this.y_()),n=Math.max(0,Date.now()-this.f_),s=Math.max(0,t-n);s>0&&M("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.d_} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.m_=this.Ci.enqueueAfterDelay(this.timerId,s,(()=>(this.f_=Date.now(),e()))),this.d_*=this.A_,this.d_<this.R_&&(this.d_=this.R_),this.d_>this.V_&&(this.d_=this.V_)}w_(){this.m_!==null&&(this.m_.skipDelay(),this.m_=null)}cancel(){this.m_!==null&&(this.m_.cancel(),this.m_=null)}y_(){return(Math.random()-.5)*this.d_}};var pg="PersistentStream",ia=class{constructor(e,t,n,s,i,o,u,c){this.Ci=e,this.S_=n,this.b_=s,this.connection=i,this.authCredentialsProvider=o,this.appCheckCredentialsProvider=u,this.listener=c,this.state=0,this.D_=0,this.C_=null,this.v_=null,this.stream=null,this.F_=0,this.M_=new sa(e,t)}x_(){return this.state===1||this.state===5||this.O_()}O_(){return this.state===2||this.state===3}start(){this.F_=0,this.state!==4?this.auth():this.N_()}async stop(){this.x_()&&await this.close(0)}B_(){this.state=0,this.M_.reset()}L_(){this.O_()&&this.C_===null&&(this.C_=this.Ci.enqueueAfterDelay(this.S_,6e4,(()=>this.k_())))}q_(e){this.K_(),this.stream.send(e)}async k_(){if(this.O_())return this.close(0)}K_(){this.C_&&(this.C_.cancel(),this.C_=null)}U_(){this.v_&&(this.v_.cancel(),this.v_=null)}async close(e,t){this.K_(),this.U_(),this.M_.cancel(),this.D_++,e!==4?this.M_.reset():t&&t.code===O.RESOURCE_EXHAUSTED?(kt(t.toString()),kt("Using maximum backoff delay to prevent overloading the backend."),this.M_.g_()):t&&t.code===O.UNAUTHENTICATED&&this.state!==3&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),this.stream!==null&&(this.W_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.t_(t)}W_(){}auth(){this.state=1;let e=this.Q_(this.D_),t=this.D_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([n,s])=>{this.D_===t&&this.G_(n,s)}),(n=>{e((()=>{let s=new B(O.UNKNOWN,"Fetching auth token failed: "+n.message);return this.z_(s)}))}))}G_(e,t){let n=this.Q_(this.D_);this.stream=this.j_(e,t),this.stream.Zo((()=>{n((()=>this.listener.Zo()))})),this.stream.Yo((()=>{n((()=>(this.state=2,this.v_=this.Ci.enqueueAfterDelay(this.b_,1e4,(()=>(this.O_()&&(this.state=3),Promise.resolve()))),this.listener.Yo())))})),this.stream.t_((s=>{n((()=>this.z_(s)))})),this.stream.onMessage((s=>{n((()=>++this.F_==1?this.J_(s):this.onNext(s)))}))}N_(){this.state=5,this.M_.p_((async()=>{this.state=0,this.start()}))}z_(e){return M(pg,`close with error: ${e}`),this.stream=null,this.close(4,e)}Q_(e){return t=>{this.Ci.enqueueAndForget((()=>this.D_===e?t():(M(pg,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}},ml=class extends ia{constructor(e,t,n,s,i,o){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,s,o),this.serializer=i}j_(e,t){return this.connection.T_("Listen",e,t)}J_(e){return this.onNext(e)}onNext(e){this.M_.reset();let t=Nx(this.serializer,e),n=(function(i){if(!("targetChange"in i))return H.min();let o=i.targetChange;return o.targetIds&&o.targetIds.length?H.min():o.readTime?dt(o.readTime):H.min()})(e);return this.listener.H_(t,n)}Z_(e){let t={};t.database=Uc(this.serializer),t.addTarget=(function(i,o){let u,c=o.target;if(u=xc(c)?{documents:Fx(i,c)}:{query:Mx(i,c).ft},u.targetId=o.targetId,o.resumeToken.approximateByteSize()>0){u.resumeToken=_y(i,o.resumeToken);let l=Fc(i,o.expectedCount);l!==null&&(u.expectedCount=l)}else if(o.snapshotVersion.compareTo(H.min())>0){u.readTime=Yo(i,o.snapshotVersion.toTimestamp());let l=Fc(i,o.expectedCount);l!==null&&(u.expectedCount=l)}return u})(this.serializer,e);let n=Ux(this.serializer,e);n&&(t.labels=n),this.q_(t)}X_(e){let t={};t.database=Uc(this.serializer),t.removeTarget=e,this.q_(t)}},gl=class extends ia{constructor(e,t,n,s,i,o){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,s,o),this.serializer=i}get Y_(){return this.F_>0}start(){this.lastStreamToken=void 0,super.start()}W_(){this.Y_&&this.ea([])}j_(e,t){return this.connection.T_("Write",e,t)}J_(e){return te(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,te(!e.writeResults||e.writeResults.length===0,55816),this.listener.ta()}onNext(e){te(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.M_.reset();let t=Lx(e.writeResults,e.commitTime),n=dt(e.commitTime);return this.listener.na(n,t)}ra(){let e={};e.database=Uc(this.serializer),this.q_(e)}ea(e){let t={streamToken:this.lastStreamToken,writes:e.map((n=>Vx(this.serializer,n)))};this.q_(t)}};var yl=class{},_l=class extends yl{constructor(e,t,n,s){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=s,this.ia=!1}sa(){if(this.ia)throw new B(O.FAILED_PRECONDITION,"The client has already been terminated.")}Wo(e,t,n,s){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([i,o])=>this.connection.Wo(e,Mc(t,n),s,i,o))).catch((i=>{throw i.name==="FirebaseError"?(i.code===O.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),i):new B(O.UNKNOWN,i.toString())}))}jo(e,t,n,s,i){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([o,u])=>this.connection.jo(e,Mc(t,n),s,o,u,i))).catch((o=>{throw o.name==="FirebaseError"?(o.code===O.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),o):new B(O.UNKNOWN,o.toString())}))}terminate(){this.ia=!0,this.connection.terminate()}};function nR(r,e,t,n){return new _l(r,e,t,n)}var wl=class{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.oa=0,this._a=null,this.aa=!0}ua(){this.oa===0&&(this.ca("Unknown"),this._a=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this._a=null,this.la("Backend didn't respond within 10 seconds."),this.ca("Offline"),Promise.resolve()))))}ha(e){this.state==="Online"?this.ca("Unknown"):(this.oa++,this.oa>=1&&(this.Pa(),this.la(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.ca("Offline")))}set(e){this.Pa(),this.oa=0,e==="Online"&&(this.aa=!1),this.ca(e)}ca(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}la(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.aa?(kt(t),this.aa=!1):M("OnlineStateTracker",t)}Pa(){this._a!==null&&(this._a.cancel(),this._a=null)}};var Lr="RemoteStore",vl=class{constructor(e,t,n,s,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Ta=[],this.Ea=new Map,this.Ia=new Set,this.Ra=[],this.Aa=i,this.Aa.Mo((o=>{n.enqueueAndForget((async()=>{Ur(this)&&(M(Lr,"Restarting streams for network reachability change."),await(async function(c){let l=W(c);l.Ia.add(4),await ci(l),l.Va.set("Unknown"),l.Ia.delete(4),await Ia(l)})(this))}))})),this.Va=new wl(n,s)}};async function Ia(r){if(Ur(r))for(let e of r.Ra)await e(!0)}async function ci(r){for(let e of r.Ra)await e(!1)}function Cy(r,e){let t=W(r);t.Ea.has(e.targetId)||(t.Ea.set(e.targetId,e),Hl(t)?Wl(t):Zn(t).O_()&&Gl(t,e))}function Kl(r,e){let t=W(r),n=Zn(t);t.Ea.delete(e),n.O_()&&ky(t,e),t.Ea.size===0&&(n.O_()?n.L_():Ur(t)&&t.Va.set("Unknown"))}function Gl(r,e){if(r.da.$e(e.targetId),e.resumeToken.approximateByteSize()>0||e.snapshotVersion.compareTo(H.min())>0){let t=r.remoteSyncer.getRemoteKeysForTarget(e.targetId).size;e=e.withExpectedCount(t)}Zn(r).Z_(e)}function ky(r,e){r.da.$e(e),Zn(r).X_(e)}function Wl(r){r.da=new Vc({getRemoteKeysForTarget:e=>r.remoteSyncer.getRemoteKeysForTarget(e),At:e=>r.Ea.get(e)||null,ht:()=>r.datastore.serializer.databaseId}),Zn(r).start(),r.Va.ua()}function Hl(r){return Ur(r)&&!Zn(r).x_()&&r.Ea.size>0}function Ur(r){return W(r).Ia.size===0}function Oy(r){r.da=void 0}async function sR(r){r.Va.set("Online")}async function iR(r){r.Ea.forEach(((e,t)=>{Gl(r,e)}))}async function oR(r,e){Oy(r),Hl(r)?(r.Va.ha(e),Wl(r)):r.Va.set("Unknown")}async function aR(r,e,t){if(r.Va.set("Online"),e instanceof Jo&&e.state===2&&e.cause)try{await(async function(s,i){let o=i.cause;for(let u of i.targetIds)s.Ea.has(u)&&(await s.remoteSyncer.rejectListen(u,o),s.Ea.delete(u),s.da.removeTarget(u))})(r,e)}catch(n){M(Lr,"Failed to remove targets %s: %s ",e.targetIds.join(","),n),await oa(r,n)}else if(e instanceof Dn?r.da.Xe(e):e instanceof Ho?r.da.st(e):r.da.tt(e),!t.isEqual(H.min()))try{let n=await Py(r.localStore);t.compareTo(n)>=0&&await(function(i,o){let u=i.da.Tt(o);return u.targetChanges.forEach(((c,l)=>{if(c.resumeToken.approximateByteSize()>0){let f=i.Ea.get(l);f&&i.Ea.set(l,f.withResumeToken(c.resumeToken,o))}})),u.targetMismatches.forEach(((c,l)=>{let f=i.Ea.get(c);if(!f)return;i.Ea.set(c,f.withResumeToken(Pe.EMPTY_BYTE_STRING,f.snapshotVersion)),ky(i,c);let p=new ei(f.target,c,l,f.sequenceNumber);Gl(i,p)})),i.remoteSyncer.applyRemoteEvent(u)})(r,t)}catch(n){M(Lr,"Failed to raise snapshot:",n),await oa(r,n)}}async function oa(r,e,t){if(!Xn(e))throw e;r.Ia.add(1),await ci(r),r.Va.set("Offline"),t||(t=()=>Py(r.localStore)),r.asyncQueue.enqueueRetryable((async()=>{M(Lr,"Retrying IndexedDB access"),await t(),r.Ia.delete(1),await Ia(r)}))}function Dy(r,e){return e().catch((t=>oa(r,t,e)))}async function Aa(r){let e=W(r),t=lr(e),n=e.Ta.length>0?e.Ta[e.Ta.length-1].batchId:Ll;for(;uR(e);)try{let s=await Xx(e.localStore,n);if(s===null){e.Ta.length===0&&t.L_();break}n=s.batchId,cR(e,s)}catch(s){await oa(e,s)}Ny(e)&&Vy(e)}function uR(r){return Ur(r)&&r.Ta.length<10}function cR(r,e){r.Ta.push(e);let t=lr(r);t.O_()&&t.Y_&&t.ea(e.mutations)}function Ny(r){return Ur(r)&&!lr(r).x_()&&r.Ta.length>0}function Vy(r){lr(r).start()}async function lR(r){lr(r).ra()}async function hR(r){let e=lr(r);for(let t of r.Ta)e.ea(t.mutations)}async function dR(r,e,t){let n=r.Ta.shift(),s=kc.from(n,e,t);await Dy(r,(()=>r.remoteSyncer.applySuccessfulWrite(s))),await Aa(r)}async function fR(r,e){e&&lr(r).Y_&&await(async function(n,s){if((function(o){return Sx(o)&&o!==O.ABORTED})(s.code)){let i=n.Ta.shift();lr(n).B_(),await Dy(n,(()=>n.remoteSyncer.rejectFailedWrite(i.batchId,s))),await Aa(n)}})(r,e),Ny(r)&&Vy(r)}async function mg(r,e){let t=W(r);t.asyncQueue.verifyOperationInProgress(),M(Lr,"RemoteStore received new credentials");let n=Ur(t);t.Ia.add(3),await ci(t),n&&t.Va.set("Unknown"),await t.remoteSyncer.handleCredentialChange(e),t.Ia.delete(3),await Ia(t)}async function pR(r,e){let t=W(r);e?(t.Ia.delete(2),await Ia(t)):e||(t.Ia.add(2),await ci(t),t.Va.set("Unknown"))}function Zn(r){return r.ma||(r.ma=(function(t,n,s){let i=W(t);return i.sa(),new ml(n,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)})(r.datastore,r.asyncQueue,{Zo:sR.bind(null,r),Yo:iR.bind(null,r),t_:oR.bind(null,r),H_:aR.bind(null,r)}),r.Ra.push((async e=>{e?(r.ma.B_(),Hl(r)?Wl(r):r.Va.set("Unknown")):(await r.ma.stop(),Oy(r))}))),r.ma}function lr(r){return r.fa||(r.fa=(function(t,n,s){let i=W(t);return i.sa(),new gl(n,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,s)})(r.datastore,r.asyncQueue,{Zo:()=>Promise.resolve(),Yo:lR.bind(null,r),t_:fR.bind(null,r),ta:hR.bind(null,r),na:dR.bind(null,r)}),r.Ra.push((async e=>{e?(r.fa.B_(),await Aa(r)):(await r.fa.stop(),r.Ta.length>0&&(M(Lr,`Stopping write stream with ${r.Ta.length} pending writes`),r.Ta=[]))}))),r.fa}var bl=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 ct,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((o=>{}))}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,s,i){let o=Date.now()+n,u=new r(e,t,o,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 B(O.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 Jl(r,e){if(kt("AsyncQueue",`${e}: ${r}`),Xn(r))return new B(O.UNAVAILABLE,`${e}: ${r}`);throw r}var ni=class r{static emptySet(e){return new r(e.comparator)}constructor(e){this.comparator=e?(t,n)=>e(t,n)||q.comparator(t.key,n.key):(t,n)=>q.comparator(t.key,n.key),this.keyedMap=qs(),this.sortedSet=new de(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 (
|
|
33
19
|
`+e.join(`
|
|
34
20
|
`)+`
|
|
35
|
-
)`}copy(e,t){let n=new r;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}};var ea=class{constructor(){this.fa=new he(K.comparator)}track(e){let t=e.doc.key,n=this.fa.get(t);n?e.type!==0&&n.type===3?this.fa=this.fa.insert(t,e):e.type===3&&n.type!==1?this.fa=this.fa.insert(t,{type:n.type,doc:e.doc}):e.type===2&&n.type===2?this.fa=this.fa.insert(t,{type:2,doc:e.doc}):e.type===2&&n.type===0?this.fa=this.fa.insert(t,{type:0,doc:e.doc}):e.type===1&&n.type===0?this.fa=this.fa.remove(t):e.type===1&&n.type===2?this.fa=this.fa.insert(t,{type:1,doc:n.doc}):e.type===0&&n.type===1?this.fa=this.fa.insert(t,{type:2,doc:e.doc}):z(63341,{At:e,ga:n}):this.fa=this.fa.insert(t,e)}pa(){let e=[];return this.fa.inorderTraversal(((t,n)=>{e.push(n)})),e}},qn=class r{constructor(e,t,n,s,i,o,u,c,h){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=s,this.mutatedKeys=i,this.fromCache=o,this.syncStateChanged=u,this.excludesMetadataChanges=c,this.hasCachedResults=h}static fromInitialDocuments(e,t,n,s,i){let o=[];return t.forEach((u=>{o.push({type:0,doc:u})})),new r(e,t,Zo.emptySet(t),o,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)&&ga(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 bl=class{constructor(){this.ya=void 0,this.wa=[]}Sa(){return this.wa.some((e=>e.ba()))}},El=class{constructor(){this.queries=Sg(),this.onlineState="Unknown",this.Da=new Set}terminate(){(function(t,n){let s=G(t),i=s.queries;s.queries=Sg(),i.forEach(((o,u)=>{for(let c of u.wa)c.onError(n)}))})(this,new B(N.ABORTED,"Firestore shutting down"))}};function Sg(){return new Ot((r=>dy(r)),ga)}async function By(r,e){let t=G(r),n=3,s=e.query,i=t.queries.get(s);i?!i.Sa()&&e.ba()&&(n=2):(i=new bl,n=e.ba()?0:1);try{switch(n){case 0:i.ya=await t.onListen(s,!0);break;case 1:i.ya=await t.onListen(s,!1);break;case 2:await t.onFirstRemoteStoreListen(s)}}catch(o){let u=eh(o,`Initialization of query '${In(e.query)}' failed`);return void e.onError(u)}t.queries.set(s,i),i.wa.push(e),e.va(t.onlineState),i.ya&&e.Ca(i.ya)&&th(t)}async function $y(r,e){let t=G(r),n=e.query,s=3,i=t.queries.get(n);if(i){let o=i.wa.indexOf(e);o>=0&&(i.wa.splice(o,1),i.wa.length===0?s=e.ba()?0:1:!i.Sa()&&e.ba()&&(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 PR(r,e){let t=G(r),n=!1;for(let s of e){let i=s.query,o=t.queries.get(i);if(o){for(let u of o.wa)u.Ca(s)&&(n=!0);o.ya=s}}n&&th(t)}function CR(r,e,t){let n=G(r),s=n.queries.get(e);if(s)for(let i of s.wa)i.onError(t);n.queries.delete(e)}function th(r){r.Da.forEach((e=>{e.next()}))}var Tl,Ag;(Ag=Tl||(Tl={})).Fa="default",Ag.Cache="cache";var ta=class{constructor(e,t,n){this.query=e,this.Ma=t,this.xa=!1,this.Oa=null,this.onlineState="Unknown",this.options=n||{}}Ca(e){if(!this.options.includeMetadataChanges){let n=[];for(let s of e.docChanges)s.type!==3&&n.push(s);e=new qn(e.query,e.docs,e.oldDocs,n,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.xa?this.Na(e)&&(this.Ma.next(e),t=!0):this.Ba(e,this.onlineState)&&(this.La(e),t=!0),this.Oa=e,t}onError(e){this.Ma.error(e)}va(e){this.onlineState=e;let t=!1;return this.Oa&&!this.xa&&this.Ba(this.Oa,e)&&(this.La(this.Oa),t=!0),t}Ba(e,t){if(!e.fromCache||!this.ba())return!0;let n=t!=="Offline";return(!this.options.ka||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||t==="Offline")}Na(e){if(e.docChanges.length>0)return!0;let t=this.Oa&&this.Oa.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&this.options.includeMetadataChanges===!0}La(e){e=qn.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.xa=!0,this.Ma.next(e)}ba(){return this.options.source!==Tl.Cache}};var ra=class{constructor(e){this.key=e}},na=class{constructor(e){this.key=e}},Il=class{constructor(e,t){this.query=e,this.Ha=t,this.Ya=null,this.hasCachedResults=!1,this.current=!1,this.Za=J(),this.mutatedKeys=J(),this.Xa=fy(e),this.eu=new Zo(this.Xa)}get tu(){return this.Ha}nu(e,t){let n=t?t.ru:new ea,s=t?t.eu:this.eu,i=t?t.mutatedKeys:this.mutatedKeys,o=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,p)=>{let m=s.get(f),y=ya(this.query,p)?p:null,T=!!m&&this.mutatedKeys.has(m.key),R=!!y&&(y.hasLocalMutations||this.mutatedKeys.has(y.key)&&y.hasCommittedMutations),I=!1;m&&y?m.data.isEqual(y.data)?T!==R&&(n.track({type:3,doc:y}),I=!0):this.iu(m,y)||(n.track({type:2,doc:y}),I=!0,(c&&this.Xa(y,c)>0||h&&this.Xa(y,h)<0)&&(u=!0)):!m&&y?(n.track({type:0,doc:y}),I=!0):m&&!y&&(n.track({type:1,doc:m}),I=!0,(c||h)&&(u=!0)),I&&(y?(o=o.add(y),i=R?i.add(f):i.delete(f)):(o=o.delete(f),i=i.delete(f)))})),this.query.limit!==null)for(;o.size>this.query.limit;){let f=this.query.limitType==="F"?o.last():o.first();o=o.delete(f.key),i=i.delete(f.key),n.track({type:1,doc:f})}return{eu:o,ru:n,Ds:u,mutatedKeys:i}}iu(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,s){let i=this.eu;this.eu=e.eu,this.mutatedKeys=e.mutatedKeys;let o=e.ru.pa();o.sort(((f,p)=>(function(y,T){let R=I=>{switch(I){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return z(20277,{At:I})}};return R(y)-R(T)})(f.type,p.type)||this.Xa(f.doc,p.doc))),this.su(n),s=s!=null&&s;let u=t&&!s?this.ou():[],c=this.Za.size===0&&this.current&&!s?1:0,h=c!==this.Ya;return this.Ya=c,o.length!==0||h?{snapshot:new qn(this.query,e.eu,i,o,e.mutatedKeys,c===0,h,!1,!!n&&n.resumeToken.approximateByteSize()>0),_u:u}:{_u:u}}va(e){return this.current&&e==="Offline"?(this.current=!1,this.applyChanges({eu:this.eu,ru:new ea,mutatedKeys:this.mutatedKeys,Ds:!1},!1)):{_u:[]}}au(e){return!this.Ha.has(e)&&!!this.eu.has(e)&&!this.eu.get(e).hasLocalMutations}su(e){e&&(e.addedDocuments.forEach((t=>this.Ha=this.Ha.add(t))),e.modifiedDocuments.forEach((t=>{})),e.removedDocuments.forEach((t=>this.Ha=this.Ha.delete(t))),this.current=e.current)}ou(){if(!this.current)return[];let e=this.Za;this.Za=J(),this.eu.forEach((n=>{this.au(n.key)&&(this.Za=this.Za.add(n.key))}));let t=[];return e.forEach((n=>{this.Za.has(n)||t.push(new na(n))})),this.Za.forEach((n=>{e.has(n)||t.push(new ra(n))})),t}uu(e){this.Ha=e.qs,this.Za=J();let t=this.nu(e.documents);return this.applyChanges(t,!0)}cu(){return qn.fromInitialDocuments(this.query,this.eu,this.mutatedKeys,this.Ya===0,this.hasCachedResults)}},rh="SyncEngine",Sl=class{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}},Al=class{constructor(e){this.key=e,this.lu=!1}},xl=class{constructor(e,t,n,s,i,o){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=s,this.currentUser=i,this.maxConcurrentLimboResolutions=o,this.hu={},this.Pu=new Ot((u=>dy(u)),ga),this.Tu=new Map,this.Iu=new Set,this.du=new he(K.comparator),this.Eu=new Map,this.Au=new Ys,this.Ru={},this.Vu=new Map,this.mu=Xs.ur(),this.onlineState="Unknown",this.fu=void 0}get isPrimaryClient(){return this.fu===!0}};async function kR(r,e,t=!0){let n=Hy(r),s,i=n.Pu.get(e);return i?(n.sharedClientState.addLocalQueryTarget(i.targetId),s=i.view.cu()):s=await qy(n,e,t,!0),s}async function OR(r,e){let t=Hy(r);await qy(t,e,!0,!1)}async function qy(r,e,t,n){let s=await mR(r.localStore,lt(e)),i=s.targetId,o=r.sharedClientState.addLocalQueryTarget(i,t),u;return n&&(u=await DR(r,e,i,o==="current",s.resumeToken)),r.isPrimaryClient&&t&&Vy(r.remoteStore,s),u}async function DR(r,e,t,n,s){r.gu=(p,m,y)=>(async function(R,I,k,O){let D=I.view.nu(k);D.Ds&&(D=await bg(R.localStore,I.query,!1).then((({documents:E})=>I.view.nu(E,D))));let j=O&&O.targetChanges.get(I.targetId),H=O&&O.targetMismatches.get(I.targetId)!=null,F=I.view.applyChanges(D,R.isPrimaryClient,j,H);return Rg(R,I.targetId,F._u),F.snapshot})(r,p,m,y);let i=await bg(r.localStore,e,!0),o=new Il(e,i.qs),u=o.nu(i.documents),c=Qs.createSynthesizedTargetChangeForCurrentChange(t,n&&r.onlineState!=="Offline",s),h=o.applyChanges(u,r.isPrimaryClient,c);Rg(r,t,h._u);let f=new Sl(e,t,o);return r.Pu.set(e,f),r.Tu.has(t)?r.Tu.get(t).push(e):r.Tu.set(t,[e]),h.snapshot}async function NR(r,e,t){let n=G(r),s=n.Pu.get(e),i=n.Tu.get(s.targetId);if(i.length>1)return n.Tu.set(s.targetId,i.filter((o=>!ga(o,e)))),void n.Pu.delete(e);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(s.targetId),n.sharedClientState.isActiveQueryTarget(s.targetId)||await al(n.localStore,s.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(s.targetId),t&&Jl(n.remoteStore,s.targetId),Rl(n,s.targetId)})).catch(Wn)):(Rl(n,s.targetId),await al(n.localStore,s.targetId,!0))}async function VR(r,e){let t=G(r),n=t.Pu.get(e),s=t.Tu.get(n.targetId);t.isPrimaryClient&&s.length===1&&(t.sharedClientState.removeLocalQueryTarget(n.targetId),Jl(t.remoteStore,n.targetId))}async function LR(r,e,t){let n=qR(r);try{let s=await(function(o,u){let c=G(o),h=_e.now(),f=u.reduce(((y,T)=>y.add(T.key)),J()),p,m;return c.persistence.runTransaction("Locally write mutations","readwrite",(y=>{let T=Dt(),R=J();return c.Os.getEntries(y,f).next((I=>{T=I,T.forEach(((k,O)=>{O.isValidDocument()||(R=R.add(k))}))})).next((()=>c.localDocuments.getOverlayedDocuments(y,T))).next((I=>{p=I;let k=[];for(let O of u){let D=Bx(O,p.get(O.key).overlayedDocument);D!=null&&k.push(new pt(O.key,D,oy(D.value.mapValue),nr.exists(!0)))}return c.mutationQueue.addMutationBatch(y,h,k,u)})).next((I=>{m=I;let k=I.applyToLocalDocumentSet(p,R);return c.documentOverlayCache.saveOverlays(y,I.batchId,k)}))})).then((()=>({batchId:m.batchId,changes:my(p)})))})(n.localStore,e);n.sharedClientState.addPendingMutation(s.batchId),(function(o,u,c){let h=o.Ru[o.currentUser.toKey()];h||(h=new he(Q)),h=h.insert(u,c),o.Ru[o.currentUser.toKey()]=h})(n,s.batchId,t),await ii(n,s.changes),await wa(n.remoteStore)}catch(s){let i=eh(s,"Failed to persist write");t.reject(i)}}async function zy(r,e){let t=G(r);try{let n=await dR(t.localStore,e);e.targetChanges.forEach(((s,i)=>{let o=t.Eu.get(i);o&&(te(s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size<=1,22616),s.addedDocuments.size>0?o.lu=!0:s.modifiedDocuments.size>0?te(o.lu,14607):s.removedDocuments.size>0&&(te(o.lu,42227),o.lu=!1))})),await ii(t,n,e)}catch(n){await Wn(n)}}function xg(r,e,t){let n=G(r);if(n.isPrimaryClient&&t===0||!n.isPrimaryClient&&t===1){let s=[];n.Pu.forEach(((i,o)=>{let u=o.view.va(e);u.snapshot&&s.push(u.snapshot)})),(function(o,u){let c=G(o);c.onlineState=u;let h=!1;c.queries.forEach(((f,p)=>{for(let m of p.wa)m.va(u)&&(h=!0)})),h&&th(c)})(n.eventManager,e),s.length&&n.hu.J_(s),n.onlineState=e,n.isPrimaryClient&&n.sharedClientState.setOnlineState(e)}}async function FR(r,e,t){let n=G(r);n.sharedClientState.updateQueryState(e,"rejected",t);let s=n.Eu.get(e),i=s&&s.key;if(i){let o=new he(K.comparator);o=o.insert(i,tt.newNoDocument(i,W.min()));let u=J().add(i),c=new Uo(W.min(),new Map,new he(Q),o,u);await zy(n,c),n.du=n.du.remove(i),n.Eu.delete(e),nh(n)}else await al(n.localStore,e,!1).then((()=>Rl(n,e,t))).catch(Wn)}async function jR(r,e){let t=G(r),n=e.batch.batchId;try{let s=await hR(t.localStore,e);Gy(t,n,null),Ky(t,n),t.sharedClientState.updateMutationState(n,"acknowledged"),await ii(t,s)}catch(s){await Wn(s)}}async function MR(r,e,t){let n=G(r);try{let s=await(function(o,u){let c=G(o);return c.persistence.runTransaction("Reject batch","readwrite-primary",(h=>{let f;return c.mutationQueue.lookupMutationBatch(h,u).next((p=>(te(p!==null,37113),f=p.keys(),c.mutationQueue.removeMutationBatch(h,p)))).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);Gy(n,e,t),Ky(n,e),n.sharedClientState.updateMutationState(e,"rejected",t),await ii(n,s)}catch(s){await Wn(s)}}function Ky(r,e){(r.Vu.get(e)||[]).forEach((t=>{t.resolve()})),r.Vu.delete(e)}function Gy(r,e,t){let n=G(r),s=n.Ru[n.currentUser.toKey()];if(s){let i=s.get(e);i&&(t?i.reject(t):i.resolve(),s=s.remove(e)),n.Ru[n.currentUser.toKey()]=s}}function Rl(r,e,t=null){r.sharedClientState.removeLocalQueryTarget(e);for(let n of r.Tu.get(e))r.Pu.delete(n),t&&r.hu.pu(n,t);r.Tu.delete(e),r.isPrimaryClient&&r.Au.zr(e).forEach((n=>{r.Au.containsKey(n)||Wy(r,n)}))}function Wy(r,e){r.Iu.delete(e.path.canonicalString());let t=r.du.get(e);t!==null&&(Jl(r.remoteStore,t),r.du=r.du.remove(e),r.Eu.delete(t),nh(r))}function Rg(r,e,t){for(let n of t)n instanceof ra?(r.Au.addReference(n.key,e),UR(r,n)):n instanceof na?(M(rh,"Document no longer in limbo: "+n.key),r.Au.removeReference(n.key,e),r.Au.containsKey(n.key)||Wy(r,n.key)):z(19791,{yu:n})}function UR(r,e){let t=e.key,n=t.path.canonicalString();r.du.get(t)||r.Iu.has(n)||(M(rh,"New document in limbo: "+t),r.Iu.add(n),nh(r))}function nh(r){for(;r.Iu.size>0&&r.du.size<r.maxConcurrentLimboResolutions;){let e=r.Iu.values().next().value;r.Iu.delete(e);let t=new K(pe.fromString(e)),n=r.mu.next();r.Eu.set(n,new Al(t)),r.du=r.du.insert(t,n),Vy(r.remoteStore,new Js(lt(ma(t.path)),n,"TargetPurposeLimboResolution",On.ue))}}async function ii(r,e,t){let n=G(r),s=[],i=[],o=[];n.Pu.isEmpty()||(n.Pu.forEach(((u,c)=>{o.push(n.gu(c,e,t).then((h=>{var f;if((h||t)&&n.isPrimaryClient){let p=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,p?"current":"not-current")}if(h){s.push(h);let p=nl.Es(c.targetId,h);i.push(p)}})))})),await Promise.all(o),n.hu.J_(s),await(async function(c,h){let f=G(c);try{await f.persistence.runTransaction("notifyLocalViewChanges","readwrite",(p=>V.forEach(h,(m=>V.forEach(m.Is,(y=>f.persistence.referenceDelegate.addReference(p,m.targetId,y))).next((()=>V.forEach(m.ds,(y=>f.persistence.referenceDelegate.removeReference(p,m.targetId,y)))))))))}catch(p){if(!Hn(p))throw p;M(Ql,"Failed to update sequence numbers: "+p)}for(let p of h){let m=p.targetId;if(!p.fromCache){let y=f.Fs.get(m),T=y.snapshotVersion,R=y.withLastLimboFreeSnapshotVersion(T);f.Fs=f.Fs.insert(m,R)}}})(n.localStore,i))}async function BR(r,e){let t=G(r);if(!t.currentUser.isEqual(e)){M(rh,"User change. New user:",e.toKey());let n=await Dy(t.localStore,e);t.currentUser=e,(function(i,o){i.Vu.forEach((u=>{u.forEach((c=>{c.reject(new B(N.CANCELLED,o))}))})),i.Vu.clear()})(t,"'waitForPendingWrites' promise is rejected due to a user change."),t.sharedClientState.handleUserChange(e,n.removedBatchIds,n.addedBatchIds),await ii(t,n.Bs)}}function $R(r,e){let t=G(r),n=t.Eu.get(e);if(n&&n.lu)return J().add(n.key);{let s=J(),i=t.Tu.get(e);if(!i)return s;for(let o of i){let u=t.Pu.get(o);s=s.unionWith(u.view.tu)}return s}}function Hy(r){let e=G(r);return e.remoteStore.remoteSyncer.applyRemoteEvent=zy.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=$R.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=FR.bind(null,e),e.hu.J_=PR.bind(null,e.eventManager),e.hu.pu=CR.bind(null,e.eventManager),e}function qR(r){let e=G(r);return e.remoteStore.remoteSyncer.applySuccessfulWrite=jR.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=MR.bind(null,e),e}var zn=class{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=_a(e.databaseInfo.databaseId),this.sharedClientState=this.bu(e),this.persistence=this.Du(e),await this.persistence.start(),this.localStore=this.vu(e),this.gcScheduler=this.Cu(e,this.localStore),this.indexBackfillerScheduler=this.Fu(e,this.localStore)}Cu(e,t){return null}Fu(e,t){return null}vu(e){return lR(this.persistence,new il,e.initialUser,this.serializer)}Du(e){return new Go(rl.Vi,this.serializer)}bu(e){return new ul}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()}};zn.provider={build:()=>new zn};var Pl=class extends zn{constructor(e){super(),this.cacheSizeBytes=e}Cu(e,t){te(this.persistence.referenceDelegate instanceof Wo,46915);let n=this.persistence.referenceDelegate.garbageCollector;return new qc(n,e.asyncQueue,t)}Du(e){let t=this.cacheSizeBytes!==void 0?Ge.withCacheSize(this.cacheSizeBytes):Ge.DEFAULT;return new Go((n=>Wo.Vi(n,t)),this.serializer)}};var Zs=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=>xg(this.syncEngine,n,1),this.remoteStore.remoteSyncer.handleCredentialChange=BR.bind(null,this.syncEngine),await RR(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return(function(){return new El})()}createDatastore(e){let t=_a(e.databaseInfo.databaseId),n=(function(i){return new fl(i)})(e.databaseInfo);return(function(i,o,u,c){return new yl(i,o,u,c)})(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return(function(n,s,i,o,u){return new vl(n,s,i,o,u)})(this.localStore,this.datastore,e.asyncQueue,(t=>xg(this.syncEngine,t,0)),(function(){return Qo.C()?new Qo:new cl})())}createSyncEngine(e,t){return(function(s,i,o,u,c,h,f){let p=new xl(s,i,o,u,c,h);return f&&(p.fu=!0),p})(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e,t;await(async function(s){let i=G(s);M(Dr,"RemoteStore shutting down."),i.Ia.add(5),await si(i),i.Ea.shutdown(),i.Aa.set("Unknown")})(this.remoteStore),(e=this.datastore)===null||e===void 0||e.terminate(),(t=this.eventManager)===null||t===void 0||t.terminate()}};Zs.provider={build:()=>new Zs};var sa=class{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.xu(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.xu(this.observer.error,e):Pt("Uncaught Error in snapshot listener:",e.toString()))}Ou(){this.muted=!0}xu(e,t){setTimeout((()=>{this.muted||e(t)}),0)}};var lr="FirestoreClient",Cl=class{constructor(e,t,n,s,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=s,this.user=Te.UNAUTHENTICATED,this.clientId=zs.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,(async o=>{M(lr,"Received user=",o.uid),await this.authCredentialListener(o),this.user=o})),this.appCheckCredentials.start(n,(o=>(M(lr,"Received new app check token=",o),this.appCheckCredentialListener(o,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 at;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=eh(t,"Failed to shutdown persistence");e.reject(n)}})),e.promise}};async function rc(r,e){r.asyncQueue.verifyOperationInProgress(),M(lr,"Initializing OfflineComponentProvider");let t=r.configuration;await e.initialize(t);let n=t.initialUser;r.setCredentialChangeListener((async s=>{n.isEqual(s)||(await Dy(e.localStore,s),n=s)})),e.persistence.setDatabaseDeletedListener((()=>{ar("Terminating Firestore due to IndexedDb database deletion"),r.terminate().then((()=>{M("Terminating Firestore due to IndexedDb database deletion completed successfully")})).catch((s=>{ar("Terminating Firestore due to IndexedDb database deletion failed",s)}))})),r._offlineComponents=e}async function Pg(r,e){r.asyncQueue.verifyOperationInProgress();let t=await zR(r);M(lr,"Initializing OnlineComponentProvider"),await e.initialize(t,r.configuration),r.setCredentialChangeListener((n=>Ig(e.remoteStore,n))),r.setAppCheckTokenChangeListener(((n,s)=>Ig(e.remoteStore,s))),r._onlineComponents=e}async function zR(r){if(!r._offlineComponents)if(r._uninitializedComponentsProvider){M(lr,"Using user provided OfflineComponentProvider");try{await rc(r,r._uninitializedComponentsProvider._offline)}catch(e){let t=e;if(!(function(s){return s.name==="FirebaseError"?s.code===N.FAILED_PRECONDITION||s.code===N.UNIMPLEMENTED:!(typeof DOMException!="undefined"&&s instanceof DOMException)||s.code===22||s.code===20||s.code===11})(t))throw t;ar("Error using user provided cache. Falling back to memory cache: "+t),await rc(r,new zn)}}else M(lr,"Using default OfflineComponentProvider"),await rc(r,new Pl(void 0));return r._offlineComponents}async function Qy(r){return r._onlineComponents||(r._uninitializedComponentsProvider?(M(lr,"Using user provided OnlineComponentProvider"),await Pg(r,r._uninitializedComponentsProvider._online)):(M(lr,"Using default OnlineComponentProvider"),await Pg(r,new Zs))),r._onlineComponents}function KR(r){return Qy(r).then((e=>e.syncEngine))}async function kl(r){let e=await Qy(r),t=e.eventManager;return t.onListen=kR.bind(null,e.syncEngine),t.onUnlisten=NR.bind(null,e.syncEngine),t.onFirstRemoteStoreListen=OR.bind(null,e.syncEngine),t.onLastRemoteStoreUnlisten=VR.bind(null,e.syncEngine),t}function GR(r,e,t={}){let n=new at;return r.asyncQueue.enqueueAndForget((async()=>(function(i,o,u,c,h){let f=new sa({next:m=>{f.Ou(),o.enqueueAndForget((()=>$y(i,p)));let y=m.docs.has(u);!y&&m.fromCache?h.reject(new B(N.UNAVAILABLE,"Failed to get document because the client is offline.")):y&&m.fromCache&&c&&c.source==="server"?h.reject(new B(N.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(m)},error:m=>h.reject(m)}),p=new ta(ma(u.path),f,{includeMetadataChanges:!0,ka:!0});return By(i,p)})(await kl(r),r.asyncQueue,e,t,n))),n.promise}function Jy(r){let e={};return r.timeoutSeconds!==void 0&&(e.timeoutSeconds=r.timeoutSeconds),e}var Cg=new Map;var Xy="firestore.googleapis.com",kg=!0,ia=class{constructor(e){var t,n;if(e.host===void 0){if(e.ssl!==void 0)throw new B(N.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=Xy,this.ssl=kg}else this.host=e.host,this.ssl=(t=e.ssl)!==null&&t!==void 0?t:kg;if(this.isUsingEmulator=e.emulatorOptions!==void 0,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e.cacheSizeBytes===void 0)this.cacheSizeBytes=Oy;else{if(e.cacheSizeBytes!==-1&&e.cacheSizeBytes<aR)throw new B(N.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}sx("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=Jy((n=e.experimentalLongPollingOptions)!==null&&n!==void 0?n:{}),(function(i){if(i.timeoutSeconds!==void 0){if(isNaN(i.timeoutSeconds))throw new B(N.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (must not be NaN)`);if(i.timeoutSeconds<5)throw new B(N.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (minimum allowed value is 5)`);if(i.timeoutSeconds>30)throw new B(N.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}},ei=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 ia({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new B(N.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 B(N.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 ia(e),this._emulatorOptions=e.emulatorOptions||{},e.credentials!==void 0&&(this._authCredentials=(function(n){if(!n)return new nc;switch(n.type){case"firstParty":return new ac(n.sessionIndex||"0",n.iamToken||null,n.authTokenFactory||null);case"provider":return n.client;default:throw new B(N.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}})(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask==="notTerminated"&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){this._terminateTask==="notTerminated"?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return(function(t){let n=Cg.get(t);n&&(M("ComponentProvider","Removing Datastore"),Cg.delete(t),n.terminate())})(this),Promise.resolve()}};function WR(r,e,t,n={}){var s;r=ut(r,ei);let i=vo(e),o=r._getSettings(),u=Object.assign(Object.assign({},o),{emulatorOptions:r._getEmulatorOptions()}),c=`${e}:${t}`;i&&(wm(`https://${c}`),Em("Firestore",!0)),o.host!==Xy&&o.host!==c&&ar("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let h=Object.assign(Object.assign({},o),{host:c,ssl:i,emulatorOptions:n});if(!wn(h,u)&&(r._setSettings(h),n.mockUserToken)){let f,p;if(typeof n.mockUserToken=="string")f=n.mockUserToken,p=Te.MOCK_USER;else{f=bm(n.mockUserToken,(s=r._app)===null||s===void 0?void 0:s.options.projectId);let m=n.mockUserToken.sub||n.mockUserToken.user_id;if(!m)throw new B(N.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");p=new Te(m)}r._authCredentials=new sc(new ko(f,p))}}var oa=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)}},xe=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 ti(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new r(this.firestore,e,this._key)}toJSON(){return{type:r._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,t,n){if(ni(t,r._jsonSchema))return new r(e,n||null,new K(pe.fromString(t.referencePath)))}};xe._jsonSchemaVersion="firestore/documentReference/1.0",xe._jsonSchema={type:ye("string",xe._jsonSchemaVersion),referencePath:ye("string")};var ti=class r extends oa{constructor(e,t,n){super(e,t,ma(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 xe(this.firestore,null,new K(e))}withConverter(e){return new r(this.firestore,e,this._path)}};function ba(r,e,...t){if(r=It(r),arguments.length===1&&(e=zs.newId()),nx("doc","path",e),r instanceof ei){let n=pe.fromString(e,...t);return Jm(n),new xe(r,null,new K(n))}{if(!(r instanceof xe||r instanceof ti))throw new B(N.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let n=r._path.child(pe.fromString(e,...t));return Jm(n),new xe(r.firestore,r instanceof ti?r.converter:null,new K(n))}}var Og="AsyncQueue",aa=class{constructor(e=Promise.resolve()){this.Zu=[],this.Xu=!1,this.ec=[],this.tc=null,this.nc=!1,this.rc=!1,this.sc=[],this.F_=new Jo(this,"async_queue_retry"),this.oc=()=>{let n=tc();n&&M(Og,"Visibility state changed to "+n.visibilityState),this.F_.y_()},this._c=e;let t=tc();t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",this.oc)}get isShuttingDown(){return this.Xu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.ac(),this.uc(e)}enterRestrictedMode(e){if(!this.Xu){this.Xu=!0,this.rc=e||!1;let t=tc();t&&typeof t.removeEventListener=="function"&&t.removeEventListener("visibilitychange",this.oc)}}enqueue(e){if(this.ac(),this.Xu)return new Promise((()=>{}));let t=new at;return this.uc((()=>this.Xu&&this.rc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.Zu.push(e),this.cc())))}async cc(){if(this.Zu.length!==0){try{await this.Zu[0](),this.Zu.shift(),this.F_.reset()}catch(e){if(!Hn(e))throw e;M(Og,"Operation failed with retryable error: "+e)}this.Zu.length>0&&this.F_.g_((()=>this.cc()))}}uc(e){let t=this._c.then((()=>(this.nc=!0,e().catch((n=>{throw this.tc=n,this.nc=!1,Pt("INTERNAL UNHANDLED ERROR: ",Dg(n)),n})).then((n=>(this.nc=!1,n))))));return this._c=t,t}enqueueAfterDelay(e,t,n){this.ac(),this.sc.indexOf(e)>-1&&(t=0);let s=wl.createAndSchedule(this,e,t,n,(i=>this.lc(i)));return this.ec.push(s),s}ac(){this.tc&&z(47125,{hc:Dg(this.tc)})}verifyOperationInProgress(){}async Pc(){let e;do e=this._c,await e;while(e!==this._c)}Tc(e){for(let t of this.ec)if(t.timerId===e)return!0;return!1}Ic(e){return this.Pc().then((()=>{this.ec.sort(((t,n)=>t.targetTimeMs-n.targetTimeMs));for(let t of this.ec)if(t.skipDelay(),e!=="all"&&t.timerId===e)break;return this.Pc()}))}dc(e){this.sc.push(e)}lc(e){let t=this.ec.indexOf(e);this.ec.splice(t,1)}};function Dg(r){let e=r.message||"";return r.stack&&(e=r.stack.includes(r.message)?r.stack:r.message+`
|
|
36
|
-
`+r.stack),e}function Ng(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 hr=class extends ei{constructor(e,t,n,s){super(e,t,n,s),this.type="firestore",this._queue=new aa,this._persistenceKey=(s==null?void 0:s.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new aa(e),this._firestoreClient=void 0,await e}}};function Yy(r,e){let t=typeof r=="object"?r:Bm(),n=typeof r=="string"?r:e||Lo,s=jm(t,"firestore").getImmediate({identifier:n});if(!s._initialized){let i=vm("firestore");i&&WR(s,...i)}return s}function sh(r){if(r._terminated)throw new B(N.FAILED_PRECONDITION,"The client has already been terminated.");return r._firestoreClient||HR(r),r._firestoreClient}function HR(r){var e,t,n;let s=r._freezeSettings(),i=(function(u,c,h,f){return new dc(u,c,h,f.host,f.ssl,f.experimentalForceLongPolling,f.experimentalAutoDetectLongPolling,Jy(f.experimentalLongPollingOptions),f.useFetchStreams,f.isUsingEmulator)})(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 Cl(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 sr=class r{constructor(e){this._byteString=e}static fromBase64String(e){try{return new r(Ve.fromBase64String(e))}catch(t){throw new B(N.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+t)}}static fromUint8Array(e){return new r(Ve.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)}toJSON(){return{type:r._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(ni(e,r._jsonSchema))return r.fromBase64String(e.bytes)}};sr._jsonSchemaVersion="firestore/bytes/1.0",sr._jsonSchema={type:ye("string",sr._jsonSchemaVersion),bytes:ye("string")};var Kn=class{constructor(...e){for(let t=0;t<e.length;++t)if(e[t].length===0)throw new B(N.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new qe(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}};var ri=class{constructor(e){this._methodName=e}};var ir=class r{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new B(N.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new B(N.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}_compareTo(e){return Q(this._lat,e._lat)||Q(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:r._jsonSchemaVersion}}static fromJSON(e){if(ni(e,r._jsonSchema))return new r(e.latitude,e.longitude)}};ir._jsonSchemaVersion="firestore/geoPoint/1.0",ir._jsonSchema={type:ye("string",ir._jsonSchemaVersion),latitude:ye("number"),longitude:ye("number")};var or=class r{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)}toJSON(){return{type:r._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(ni(e,r._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every((t=>typeof t=="number")))return new r(e.vectorValues);throw new B(N.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}};or._jsonSchemaVersion="firestore/vectorValue/1.0",or._jsonSchema={type:ye("string",or._jsonSchemaVersion),vectorValues:ye("object")};var QR=/^__.*__$/,Ol=class{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return this.fieldMask!==null?new pt(e,this.data,this.fieldMask,t,this.fieldTransforms):new Or(e,this.data,t,this.fieldTransforms)}},ua=class{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new pt(e,this.data,this.fieldMask,t,this.fieldTransforms)}};function Zy(r){switch(r){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw z(40011,{Ec:r})}}var Dl=class r{constructor(e,t,n,s,i,o){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=s,i===void 0&&this.Ac(),this.fieldTransforms=i||[],this.fieldMask=o||[]}get path(){return this.settings.path}get Ec(){return this.settings.Ec}Rc(e){return new r(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Vc(e){var t;let n=(t=this.path)===null||t===void 0?void 0:t.child(e),s=this.Rc({path:n,mc:!1});return s.fc(e),s}gc(e){var t;let n=(t=this.path)===null||t===void 0?void 0:t.child(e),s=this.Rc({path:n,mc:!1});return s.Ac(),s}yc(e){return this.Rc({path:void 0,mc:!0})}wc(e){return la(e,this.settings.methodName,this.settings.Sc||!1,this.path,this.settings.bc)}contains(e){return this.fieldMask.find((t=>e.isPrefixOf(t)))!==void 0||this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))!==void 0}Ac(){if(this.path)for(let e=0;e<this.path.length;e++)this.fc(this.path.get(e))}fc(e){if(e.length===0)throw this.wc("Document fields must not be empty");if(Zy(this.Ec)&&QR.test(e))throw this.wc('Document fields cannot begin and end with "__"')}},Nl=class{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||_a(e)}Dc(e,t,n,s=!1){return new Dl({Ec:e,methodName:t,bc:n,path:qe.emptyPath(),mc:!1,Sc:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function e_(r){let e=r._freezeSettings(),t=_a(r._databaseId);return new Nl(r._databaseId,!!e.ignoreUndefinedProperties,t)}function JR(r,e,t,n,s,i={}){let o=r.Dc(i.merge||i.mergeFields?2:0,e,t,s);ih("Data must be an object, but it was:",o,n);let u=t_(n,o),c,h;if(i.merge)c=new We(o.fieldMask),h=o.fieldTransforms;else if(i.mergeFields){let f=[];for(let p of i.mergeFields){let m=Vl(e,p,t);if(!o.contains(m))throw new B(N.INVALID_ARGUMENT,`Field '${m}' is specified in your field mask but missing from your input data.`);n_(f,m)||f.push(m)}c=new We(f),h=o.fieldTransforms.filter((p=>c.covers(p.field)))}else c=null,h=o.fieldTransforms;return new Ol(new $e(u),c,h)}var ca=class r extends ri{_toFieldTransform(e){if(e.Ec!==2)throw e.Ec===1?e.wc(`${this._methodName}() can only appear at the top level of your update data`):e.wc(`${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 XR(r,e,t,n){let s=r.Dc(1,e,t);ih("Data must be an object, but it was:",s,n);let i=[],o=$e.empty();dr(n,((c,h)=>{let f=oh(e,c,t);h=It(h);let p=s.gc(f);if(h instanceof ca)i.push(f);else{let m=Ea(h,p);m!=null&&(i.push(f),o.set(f,m))}}));let u=new We(i);return new ua(o,u,s.fieldTransforms)}function YR(r,e,t,n,s,i){let o=r.Dc(1,e,t),u=[Vl(e,n,t)],c=[s];if(i.length%2!=0)throw new B(N.INVALID_ARGUMENT,`Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let m=0;m<i.length;m+=2)u.push(Vl(e,i[m])),c.push(i[m+1]);let h=[],f=$e.empty();for(let m=u.length-1;m>=0;--m)if(!n_(h,u[m])){let y=u[m],T=c[m];T=It(T);let R=o.gc(y);if(T instanceof ca)h.push(y);else{let I=Ea(T,R);I!=null&&(h.push(y),f.set(y,I))}}let p=new We(h);return new ua(f,p,o.fieldTransforms)}function Ea(r,e){if(r_(r=It(r)))return ih("Unsupported field value:",e,r),t_(r,e);if(r instanceof ri)return(function(n,s){if(!Zy(s.Ec))throw s.wc(`${n._methodName}() can only be used with update() and set()`);if(!s.path)throw s.wc(`${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.mc&&e.Ec!==4)throw e.wc("Nested arrays are not supported");return(function(n,s){let i=[],o=0;for(let u of n){let c=Ea(u,s.yc(o));c==null&&(c={nullValue:"NULL_VALUE"}),i.push(c),o++}return{arrayValue:{values:i}}})(r,e)}return(function(n,s){if((n=It(n))===null)return{nullValue:"NULL_VALUE"};if(typeof n=="number")return Lx(s.serializer,n);if(typeof n=="boolean")return{booleanValue:n};if(typeof n=="string")return{stringValue:n};if(n instanceof Date){let i=_e.fromDate(n);return{timestampValue:zo(s.serializer,i)}}if(n instanceof _e){let i=new _e(n.seconds,1e3*Math.floor(n.nanoseconds/1e3));return{timestampValue:zo(s.serializer,i)}}if(n instanceof ir)return{geoPointValue:{latitude:n.latitude,longitude:n.longitude}};if(n instanceof sr)return{bytesValue:Sy(s.serializer,n._byteString)};if(n instanceof xe){let i=s.databaseId,o=n.firestore._databaseId;if(!o.isEqual(i))throw s.wc(`Document reference is for database ${o.projectId}/${o.database} but should be for database ${i.projectId}/${i.database}`);return{referenceValue:Hl(n.firestore._databaseId||s.databaseId,n._key.path)}}if(n instanceof or)return(function(o,u){return{mapValue:{fields:{[$l]:{stringValue:ql},[Dn]:{arrayValue:{values:o.toArray().map((h=>{if(typeof h!="number")throw u.wc("VectorValues must only contain numeric values.");return Wl(u.serializer,h)}))}}}}}})(n,s);throw s.wc(`Unsupported field value: ${Ml(n)}`)})(r,e)}function t_(r,e){let t={};return Yg(r)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):dr(r,((n,s)=>{let i=Ea(s,e.Vc(n));i!=null&&(t[n]=i)})),{mapValue:{fields:t}}}function r_(r){return!(typeof r!="object"||r===null||r instanceof Array||r instanceof Date||r instanceof _e||r instanceof ir||r instanceof sr||r instanceof xe||r instanceof ri||r instanceof or)}function ih(r,e,t){if(!r_(t)||!Fg(t)){let n=Ml(t);throw n==="an object"?e.wc(r+" a custom object"):e.wc(r+" "+n)}}function Vl(r,e,t){if((e=It(e))instanceof Kn)return e._internalPath;if(typeof e=="string")return oh(r,e);throw la("Field path arguments must be of type string or ",r,!1,void 0,t)}var ZR=new RegExp("[~\\*/\\[\\]]");function oh(r,e,t){if(e.search(ZR)>=0)throw la(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,r,!1,void 0,t);try{return new Kn(...e.split("."))._internalPath}catch{throw la(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,r,!1,void 0,t)}}function la(r,e,t,n,s){let i=n&&!n.isEmpty(),o=s!==void 0,u=`Function ${e}() called with invalid data`;t&&(u+=" (via `toFirestore()`)"),u+=". ";let c="";return(i||o)&&(c+=" (found",i&&(c+=` in field ${n}`),o&&(c+=` in document ${s}`),c+=")"),new B(N.INVALID_ARGUMENT,u+r+c)}function n_(r,e){return r.some((t=>t.isEqual(e)))}var ha=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 xe(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new Ll(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(s_("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t)}}},Ll=class extends ha{data(){return super.data()}};function s_(r,e){return typeof e=="string"?oh(r,e):e instanceof Kn?e._internalPath:e._delegate._internalPath}function eP(r){if(r.limitType==="L"&&r.explicitOrderBy.length===0)throw new B(N.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}var Fl=class{convertValue(e,t="none"){switch(ur(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(kt(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 z(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let n={};return dr(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[Dn].arrayValue)===null||n===void 0?void 0:n.values)===null||s===void 0?void 0:s.map((o=>ae(o.doubleValue)));return new or(i)}convertGeoPoint(e){return new ir(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=pa(e);return n==null?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Ws(e));default:return null}}convertTimestamp(e){let t=Ct(e);return new _e(t.seconds,t.nanos)}convertDocumentKey(e,t){let n=pe.fromString(e);te(ky(n),9688,{name:e});let s=new Fo(n.get(1),n.get(3)),i=new K(n.popFirst(5));return s.isEqual(t)||Pt(`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 tP(r,e,t){let n;return n=r?t&&(t.merge||t.mergeFields)?r.toFirestore(e,t):r.toFirestore(e):e,n}var Ar=class{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}},xr=class r extends ha{constructor(e,t,n,s,i,o){super(e,t,n,s,o),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(s_("DocumentSnapshot.get",e));if(n!==null)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new B(N.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e=this._document,t={};return t.type=r._jsonSchemaVersion,t.bundle="",t.bundleSource="DocumentSnapshot",t.bundleName=this._key.toString(),!e||!e.isValidDocument()||!e.isFoundDocument()?t:(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),t.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),t)}};xr._jsonSchemaVersion="firestore/documentSnapshot/1.0",xr._jsonSchema={type:ye("string",xr._jsonSchemaVersion),bundleSource:ye("string","DocumentSnapshot"),bundleName:ye("string"),bundle:ye("string")};var Pn=class extends xr{data(e={}){return super.data(e)}},Cn=class r{constructor(e,t,n,s){this._firestore=e,this._userDataWriter=t,this._snapshot=s,this.metadata=new Ar(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 Ar(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 B(N.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 o=0;return s._snapshot.docChanges.map((u=>{let c=new Pn(s._firestore,s._userDataWriter,u.doc.key,u.doc,new Ar(s._snapshot.mutatedKeys.has(u.doc.key),s._snapshot.fromCache),s.query.converter);return u.doc,{type:"added",doc:c,oldIndex:-1,newIndex:o++}}))}{let o=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 Ar(s._snapshot.mutatedKeys.has(u.doc.key),s._snapshot.fromCache),s.query.converter),h=-1,f=-1;return u.type!==0&&(h=o.indexOf(u.doc.key),o=o.delete(u.doc.key)),u.type!==1&&(o=o.add(u.doc),f=o.indexOf(u.doc.key)),{type:rP(u.type),doc:c,oldIndex:h,newIndex:f}}))}})(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new B(N.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=r._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=zs.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let t=[],n=[],s=[];return this.docs.forEach((i=>{i._document!==null&&(t.push(i._document),n.push(this._userDataWriter.convertObjectMap(i._document.data.value.mapValue.fields,"previous")),s.push(i.ref.path))})),e.bundle=(this._firestore,this.query._query,e.bundleName,"NOT SUPPORTED"),e}};function rP(r){switch(r){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return z(61501,{type:r})}}function ah(r){r=ut(r,xe);let e=ut(r.firestore,hr);return GR(sh(e),r._key).then((t=>a_(e,r,t)))}Cn._jsonSchemaVersion="firestore/querySnapshot/1.0",Cn._jsonSchema={type:ye("string",Cn._jsonSchemaVersion),bundleSource:ye("string","QuerySnapshot"),bundleName:ye("string"),bundle:ye("string")};var da=class extends Fl{constructor(e){super(),this.firestore=e}convertBytes(e){return new sr(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new xe(this.firestore,null,t)}};function uh(r,e,t){r=ut(r,xe);let n=ut(r.firestore,hr),s=tP(r.converter,e,t);return o_(n,[JR(e_(n),"setDoc",r._key,s,r.converter!==null,t).toMutation(r._key,nr.none())])}function ch(r,e,t,...n){r=ut(r,xe);let s=ut(r.firestore,hr),i=e_(s),o;return o=typeof(e=It(e))=="string"||e instanceof Kn?YR(i,"updateDoc",r._key,e,t,n):XR(i,"updateDoc",r._key,e),o_(s,[o.toMutation(r._key,nr.exists(!0))])}function i_(r,...e){var t,n,s;r=It(r);let i={includeMetadataChanges:!1,source:"default"},o=0;typeof e[o]!="object"||Ng(e[o])||(i=e[o++]);let u={includeMetadataChanges:i.includeMetadataChanges,source:i.source};if(Ng(e[o])){let p=e[o];e[o]=(t=p.next)===null||t===void 0?void 0:t.bind(p),e[o+1]=(n=p.error)===null||n===void 0?void 0:n.bind(p),e[o+2]=(s=p.complete)===null||s===void 0?void 0:s.bind(p)}let c,h,f;if(r instanceof xe)h=ut(r.firestore,hr),f=ma(r._key.path),c={next:p=>{e[o]&&e[o](a_(h,r,p))},error:e[o+1],complete:e[o+2]};else{let p=ut(r,oa);h=ut(p.firestore,hr),f=p._query;let m=new da(h);c={next:y=>{e[o]&&e[o](new Cn(h,m,p,y))},error:e[o+1],complete:e[o+2]},eP(r._query)}return(function(m,y,T,R){let I=new sa(R),k=new ta(y,I,T);return m.asyncQueue.enqueueAndForget((async()=>By(await kl(m),k))),()=>{I.Ou(),m.asyncQueue.enqueueAndForget((async()=>$y(await kl(m),k)))}})(sh(h),f,u,c)}function o_(r,e){return(function(n,s){let i=new at;return n.asyncQueue.enqueueAndForget((async()=>LR(await KR(n),s,i))),i.promise})(sh(r),e)}function a_(r,e,t){let n=t.docs.get(e._key),s=new da(r);return new xr(r,s,e._key,n,new Ar(t.hasPendingWrites,t.fromCache),e.converter)}(function(e,t=!0){(function(s){Gn=s})(Um),Ls(new St("firestore",((n,{instanceIdentifier:s,options:i})=>{let o=n.getProvider("app").getImmediate(),u=new hr(new ic(n.getProvider("auth-internal")),new uc(o,n.getProvider("app-check-internal")),(function(h,f){if(!Object.prototype.hasOwnProperty.apply(h.options,["projectId"]))throw new B(N.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Fo(h.options.projectId,f)})(o,s),o);return i=Object.assign({useFetchStreams:t},i),u._setSettings(i),u}),"PUBLIC").setMultipleInstances(!0)),rr(Gm,Wm,e),rr(Gm,Wm,"esm2017")})();function Vr(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}function u_(r,e,t,n){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function u(f){try{h(n.next(f))}catch(p){o(p)}}function c(f){try{h(n.throw(f))}catch(p){o(p)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})}var c_=r=>r?(...e)=>r(...e):(...e)=>fetch(...e);var Jn=class extends Error{constructor(e,t="FunctionsError",n){super(e),this.name=t,this.context=n}},oi=class extends Jn{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Xn=class extends Jn{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Yn=class extends Jn{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},ai;(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"})(ai||(ai={}));var ui=class{constructor(e,{headers:t={},customFetch:n,region:s=ai.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=c_(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return u_(this,arguments,void 0,function*(t,n={}){var s;let i,o;try{let{headers:u,method:c,body:h,signal:f,timeout:p}=n,m={},{region:y}=n;y||(y=this.region);let T=new URL(`${this.url}/${t}`);y&&y!=="any"&&(m["x-region"]=y,T.searchParams.set("forceFunctionRegion",y));let R;h&&(u&&!Object.prototype.hasOwnProperty.call(u,"Content-Type")||!u)?typeof Blob!="undefined"&&h instanceof Blob||h instanceof ArrayBuffer?(m["Content-Type"]="application/octet-stream",R=h):typeof h=="string"?(m["Content-Type"]="text/plain",R=h):typeof FormData!="undefined"&&h instanceof FormData?R=h:(m["Content-Type"]="application/json",R=JSON.stringify(h)):h&&typeof h!="string"&&!(typeof Blob!="undefined"&&h instanceof Blob)&&!(h instanceof ArrayBuffer)&&!(typeof FormData!="undefined"&&h instanceof FormData)?R=JSON.stringify(h):R=h;let I=f;p&&(o=new AbortController,i=setTimeout(()=>o.abort(),p),f?(I=o.signal,f.addEventListener("abort",()=>o.abort())):I=o.signal);let k=yield this.fetch(T.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},m),this.headers),u),body:R,signal:I}).catch(H=>{throw new oi(H)}),O=k.headers.get("x-relay-error");if(O&&O==="true")throw new Xn(k);if(!k.ok)throw new Yn(k);let D=((s=k.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),j;return D==="application/json"?j=yield k.json():D==="application/octet-stream"||D==="application/pdf"?j=yield k.blob():D==="text/event-stream"?j=k:D==="multipart/form-data"?j=yield k.formData():j=yield k.text(),{data:j,error:null,response:k}}catch(u){return{data:null,error:u,response:u instanceof Yn||u instanceof Xn?u.context:void 0}}finally{i&&clearTimeout(i)}})}};var d_=class extends Error{constructor(r){super(r.message),this.name="PostgrestError",this.details=r.details,this.hint=r.hint,this.code=r.code}},nP=class{constructor(r){var e,t,n;this.shouldThrowOnError=!1,this.method=r.method,this.url=r.url,this.headers=new Headers(r.headers),this.schema=r.schema,this.body=r.body,this.shouldThrowOnError=(e=r.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=r.signal,this.isMaybeSingle=(t=r.isMaybeSingle)!==null&&t!==void 0?t:!1,this.urlLengthLimit=(n=r.urlLengthLimit)!==null&&n!==void 0?n:8e3,r.fetch?this.fetch=r.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(r,e){return this.headers=new Headers(this.headers),this.headers.set(r,e),this}then(r,e){var t=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("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=>{let o=null,u=null,c=null,h=i.status,f=i.statusText;if(i.ok){var p,m;if(t.method!=="HEAD"){var y;let k=await i.text();k===""||(t.headers.get("Accept")==="text/csv"||t.headers.get("Accept")&&(!((y=t.headers.get("Accept"))===null||y===void 0)&&y.includes("application/vnd.pgrst.plan+text"))?u=k:u=JSON.parse(k))}let R=(p=t.headers.get("Prefer"))===null||p===void 0?void 0:p.match(/count=(exact|planned|estimated)/),I=(m=i.headers.get("content-range"))===null||m===void 0?void 0:m.split("/");R&&I&&I.length>1&&(c=parseInt(I[1])),t.isMaybeSingle&&t.method==="GET"&&Array.isArray(u)&&(u.length>1?(o={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,c=null,h=406,f="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{var T;let R=await i.text();try{o=JSON.parse(R),Array.isArray(o)&&i.status===404&&(u=[],o=null,h=200,f="OK")}catch{i.status===404&&R===""?(h=204,f="No Content"):o={message:R}}if(o&&t.isMaybeSingle&&(!(o==null||(T=o.details)===null||T===void 0)&&T.includes("0 rows"))&&(o=null,h=200,f="OK"),o&&t.shouldThrowOnError)throw new d_(o)}return{error:o,data:u,count:c,status:h,statusText:f}});return this.shouldThrowOnError||(s=s.catch(i=>{var o;let u="",c="",h="",f=i==null?void 0:i.cause;if(f){var p,m,y,T;let k=(p=f==null?void 0:f.message)!==null&&p!==void 0?p:"",O=(m=f==null?void 0:f.code)!==null&&m!==void 0?m:"";u=`${(y=i==null?void 0:i.name)!==null&&y!==void 0?y:"FetchError"}: ${i==null?void 0:i.message}`,u+=`
|
|
21
|
+
)`}copy(e,t){let n=new r;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}};var aa=class{constructor(){this.ga=new de(q.comparator)}track(e){let t=e.doc.key,n=this.ga.get(t);n?e.type!==0&&n.type===3?this.ga=this.ga.insert(t,e):e.type===3&&n.type!==1?this.ga=this.ga.insert(t,{type:n.type,doc:e.doc}):e.type===2&&n.type===2?this.ga=this.ga.insert(t,{type:2,doc:e.doc}):e.type===2&&n.type===0?this.ga=this.ga.insert(t,{type:0,doc:e.doc}):e.type===1&&n.type===0?this.ga=this.ga.remove(t):e.type===1&&n.type===2?this.ga=this.ga.insert(t,{type:1,doc:n.doc}):e.type===0&&n.type===1?this.ga=this.ga.insert(t,{type:2,doc:e.doc}):K(63341,{Vt:e,pa:n}):this.ga=this.ga.insert(t,e)}ya(){let e=[];return this.ga.inorderTraversal(((t,n)=>{e.push(n)})),e}},Fr=class r{constructor(e,t,n,s,i,o,u,c,l){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=s,this.mutatedKeys=i,this.fromCache=o,this.syncStateChanged=u,this.excludesMetadataChanges=c,this.hasCachedResults=l}static fromInitialDocuments(e,t,n,s,i){let o=[];return t.forEach((u=>{o.push({type:0,doc:u})})),new r(e,t,ni.emptySet(t),o,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)&&Ea(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 El=class{constructor(){this.wa=void 0,this.Sa=[]}ba(){return this.Sa.some((e=>e.Da()))}},Tl=class{constructor(){this.queries=gg(),this.onlineState="Unknown",this.Ca=new Set}terminate(){(function(t,n){let s=W(t),i=s.queries;s.queries=gg(),i.forEach(((o,u)=>{for(let c of u.Sa)c.onError(n)}))})(this,new B(O.ABORTED,"Firestore shutting down"))}};function gg(){return new Vt((r=>iy(r)),Ea)}async function Ly(r,e){let t=W(r),n=3,s=e.query,i=t.queries.get(s);i?!i.ba()&&e.Da()&&(n=2):(i=new El,n=e.Da()?0:1);try{switch(n){case 0:i.wa=await t.onListen(s,!0);break;case 1:i.wa=await t.onListen(s,!1);break;case 2:await t.onFirstRemoteStoreListen(s)}}catch(o){let u=Jl(o,`Initialization of query '${Rn(e.query)}' failed`);return void e.onError(u)}t.queries.set(s,i),i.Sa.push(e),e.va(t.onlineState),i.wa&&e.Fa(i.wa)&&Ql(t)}async function Fy(r,e){let t=W(r),n=e.query,s=3,i=t.queries.get(n);if(i){let o=i.Sa.indexOf(e);o>=0&&(i.Sa.splice(o,1),i.Sa.length===0?s=e.Da()?0:1:!i.ba()&&e.Da()&&(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 mR(r,e){let t=W(r),n=!1;for(let s of e){let i=s.query,o=t.queries.get(i);if(o){for(let u of o.Sa)u.Fa(s)&&(n=!0);o.wa=s}}n&&Ql(t)}function gR(r,e,t){let n=W(r),s=n.queries.get(e);if(s)for(let i of s.Sa)i.onError(t);n.queries.delete(e)}function Ql(r){r.Ca.forEach((e=>{e.next()}))}var Il,yg;(yg=Il||(Il={})).Ma="default",yg.Cache="cache";var ua=class{constructor(e,t,n){this.query=e,this.xa=t,this.Oa=!1,this.Na=null,this.onlineState="Unknown",this.options=n||{}}Fa(e){if(!this.options.includeMetadataChanges){let n=[];for(let s of e.docChanges)s.type!==3&&n.push(s);e=new Fr(e.query,e.docs,e.oldDocs,n,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Oa?this.Ba(e)&&(this.xa.next(e),t=!0):this.La(e,this.onlineState)&&(this.ka(e),t=!0),this.Na=e,t}onError(e){this.xa.error(e)}va(e){this.onlineState=e;let t=!1;return this.Na&&!this.Oa&&this.La(this.Na,e)&&(this.ka(this.Na),t=!0),t}La(e,t){if(!e.fromCache||!this.Da())return!0;let n=t!=="Offline";return(!this.options.qa||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||t==="Offline")}Ba(e){if(e.docChanges.length>0)return!0;let t=this.Na&&this.Na.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&this.options.includeMetadataChanges===!0}ka(e){e=Fr.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Oa=!0,this.xa.next(e)}Da(){return this.options.source!==Il.Cache}};var ca=class{constructor(e){this.key=e}},la=class{constructor(e){this.key=e}},Al=class{constructor(e,t){this.query=e,this.Za=t,this.Xa=null,this.hasCachedResults=!1,this.current=!1,this.Ya=Q(),this.mutatedKeys=Q(),this.eu=oy(e),this.tu=new ni(this.eu)}get nu(){return this.Za}ru(e,t){let n=t?t.iu:new aa,s=t?t.tu:this.tu,i=t?t.mutatedKeys:this.mutatedKeys,o=s,u=!1,c=this.query.limitType==="F"&&s.size===this.query.limit?s.last():null,l=this.query.limitType==="L"&&s.size===this.query.limit?s.first():null;if(e.inorderTraversal(((f,p)=>{let g=s.get(f),y=Ta(this.query,p)?p:null,I=!!g&&this.mutatedKeys.has(g.key),R=!!y&&(y.hasLocalMutations||this.mutatedKeys.has(y.key)&&y.hasCommittedMutations),A=!1;g&&y?g.data.isEqual(y.data)?I!==R&&(n.track({type:3,doc:y}),A=!0):this.su(g,y)||(n.track({type:2,doc:y}),A=!0,(c&&this.eu(y,c)>0||l&&this.eu(y,l)<0)&&(u=!0)):!g&&y?(n.track({type:0,doc:y}),A=!0):g&&!y&&(n.track({type:1,doc:g}),A=!0,(c||l)&&(u=!0)),A&&(y?(o=o.add(y),i=R?i.add(f):i.delete(f)):(o=o.delete(f),i=i.delete(f)))})),this.query.limit!==null)for(;o.size>this.query.limit;){let f=this.query.limitType==="F"?o.last():o.first();o=o.delete(f.key),i=i.delete(f.key),n.track({type:1,doc:f})}return{tu:o,iu:n,bs:u,mutatedKeys:i}}su(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,s){let i=this.tu;this.tu=e.tu,this.mutatedKeys=e.mutatedKeys;let o=e.iu.ya();o.sort(((f,p)=>(function(y,I){let R=A=>{switch(A){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return K(20277,{Vt:A})}};return R(y)-R(I)})(f.type,p.type)||this.eu(f.doc,p.doc))),this.ou(n),s=s!=null?s:!1;let u=t&&!s?this._u():[],c=this.Ya.size===0&&this.current&&!s?1:0,l=c!==this.Xa;return this.Xa=c,o.length!==0||l?{snapshot:new Fr(this.query,e.tu,i,o,e.mutatedKeys,c===0,l,!1,!!n&&n.resumeToken.approximateByteSize()>0),au:u}:{au:u}}va(e){return this.current&&e==="Offline"?(this.current=!1,this.applyChanges({tu:this.tu,iu:new aa,mutatedKeys:this.mutatedKeys,bs:!1},!1)):{au:[]}}uu(e){return!this.Za.has(e)&&!!this.tu.has(e)&&!this.tu.get(e).hasLocalMutations}ou(e){e&&(e.addedDocuments.forEach((t=>this.Za=this.Za.add(t))),e.modifiedDocuments.forEach((t=>{})),e.removedDocuments.forEach((t=>this.Za=this.Za.delete(t))),this.current=e.current)}_u(){if(!this.current)return[];let e=this.Ya;this.Ya=Q(),this.tu.forEach((n=>{this.uu(n.key)&&(this.Ya=this.Ya.add(n.key))}));let t=[];return e.forEach((n=>{this.Ya.has(n)||t.push(new la(n))})),this.Ya.forEach((n=>{e.has(n)||t.push(new ca(n))})),t}cu(e){this.Za=e.ks,this.Ya=Q();let t=this.ru(e.documents);return this.applyChanges(t,!0)}lu(){return Fr.fromInitialDocuments(this.query,this.tu,this.mutatedKeys,this.Xa===0,this.hasCachedResults)}},Yl="SyncEngine",Sl=class{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}},xl=class{constructor(e){this.key=e,this.hu=!1}},Rl=class{constructor(e,t,n,s,i,o){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=s,this.currentUser=i,this.maxConcurrentLimboResolutions=o,this.Pu={},this.Tu=new Vt((u=>iy(u)),Ea),this.Eu=new Map,this.Iu=new Set,this.Ru=new de(q.comparator),this.Au=new Map,this.Vu=new ri,this.du={},this.mu=new Map,this.fu=ti.ar(),this.onlineState="Unknown",this.gu=void 0}get isPrimaryClient(){return this.gu===!0}};async function yR(r,e,t=!0){let n=qy(r),s,i=n.Tu.get(e);return i?(n.sharedClientState.addLocalQueryTarget(i.targetId),s=i.view.lu()):s=await My(n,e,t,!0),s}async function _R(r,e){let t=qy(r);await My(t,e,!0,!1)}async function My(r,e,t,n){let s=await Zx(r.localStore,ht(e)),i=s.targetId,o=r.sharedClientState.addLocalQueryTarget(i,t),u;return n&&(u=await wR(r,e,i,o==="current",s.resumeToken)),r.isPrimaryClient&&t&&Cy(r.remoteStore,s),u}async function wR(r,e,t,n,s){r.pu=(p,g,y)=>(async function(R,A,k,D){let N=A.view.ru(k);N.bs&&(N=await dg(R.localStore,A.query,!1).then((({documents:E})=>A.view.ru(E,N))));let U=D&&D.targetChanges.get(A.targetId),z=D&&D.targetMismatches.get(A.targetId)!=null,F=A.view.applyChanges(N,R.isPrimaryClient,U,z);return wg(R,A.targetId,F.au),F.snapshot})(r,p,g,y);let i=await dg(r.localStore,e,!0),o=new Al(e,i.ks),u=o.ru(i.documents),c=Zs.createSynthesizedTargetChangeForCurrentChange(t,n&&r.onlineState!=="Offline",s),l=o.applyChanges(u,r.isPrimaryClient,c);wg(r,t,l.au);let f=new Sl(e,t,o);return r.Tu.set(e,f),r.Eu.has(t)?r.Eu.get(t).push(e):r.Eu.set(t,[e]),l.snapshot}async function vR(r,e,t){let n=W(r),s=n.Tu.get(e),i=n.Eu.get(s.targetId);if(i.length>1)return n.Eu.set(s.targetId,i.filter((o=>!Ea(o,e)))),void n.Tu.delete(e);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(s.targetId),n.sharedClientState.isActiveQueryTarget(s.targetId)||await cl(n.localStore,s.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(s.targetId),t&&Kl(n.remoteStore,s.targetId),Pl(n,s.targetId)})).catch(Yn)):(Pl(n,s.targetId),await cl(n.localStore,s.targetId,!0))}async function bR(r,e){let t=W(r),n=t.Tu.get(e),s=t.Eu.get(n.targetId);t.isPrimaryClient&&s.length===1&&(t.sharedClientState.removeLocalQueryTarget(n.targetId),Kl(t.remoteStore,n.targetId))}async function ER(r,e,t){let n=PR(r);try{let s=await(function(o,u){let c=W(o),l=ge.now(),f=u.reduce(((y,I)=>y.add(I.key)),Q()),p,g;return c.persistence.runTransaction("Locally write mutations","readwrite",(y=>{let I=Lt(),R=Q();return c.xs.getEntries(y,f).next((A=>{I=A,I.forEach(((k,D)=>{D.isValidDocument()||(R=R.add(k))}))})).next((()=>c.localDocuments.getOverlayedDocuments(y,I))).next((A=>{p=A;let k=[];for(let D of u){let N=Ax(D,p.get(D.key).overlayedDocument);N!=null&&k.push(new gt(D.key,N,Xg(N.value.mapValue),Pt.exists(!0)))}return c.mutationQueue.addMutationBatch(y,l,k,u)})).next((A=>{g=A;let k=A.applyToLocalDocumentSet(p,R);return c.documentOverlayCache.saveOverlays(y,A.batchId,k)}))})).then((()=>({batchId:g.batchId,changes:uy(p)})))})(n.localStore,e);n.sharedClientState.addPendingMutation(s.batchId),(function(o,u,c){let l=o.du[o.currentUser.toKey()];l||(l=new de(Y)),l=l.insert(u,c),o.du[o.currentUser.toKey()]=l})(n,s.batchId,t),await li(n,s.changes),await Aa(n.remoteStore)}catch(s){let i=Jl(s,"Failed to persist write");t.reject(i)}}async function jy(r,e){let t=W(r);try{let n=await Qx(t.localStore,e);e.targetChanges.forEach(((s,i)=>{let o=t.Au.get(i);o&&(te(s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size<=1,22616),s.addedDocuments.size>0?o.hu=!0:s.modifiedDocuments.size>0?te(o.hu,14607):s.removedDocuments.size>0&&(te(o.hu,42227),o.hu=!1))})),await li(t,n,e)}catch(n){await Yn(n)}}function _g(r,e,t){let n=W(r);if(n.isPrimaryClient&&t===0||!n.isPrimaryClient&&t===1){let s=[];n.Tu.forEach(((i,o)=>{let u=o.view.va(e);u.snapshot&&s.push(u.snapshot)})),(function(o,u){let c=W(o);c.onlineState=u;let l=!1;c.queries.forEach(((f,p)=>{for(let g of p.Sa)g.va(u)&&(l=!0)})),l&&Ql(c)})(n.eventManager,e),s.length&&n.Pu.H_(s),n.onlineState=e,n.isPrimaryClient&&n.sharedClientState.setOnlineState(e)}}async function TR(r,e,t){let n=W(r);n.sharedClientState.updateQueryState(e,"rejected",t);let s=n.Au.get(e),i=s&&s.key;if(i){let o=new de(q.comparator);o=o.insert(i,Ze.newNoDocument(i,H.min()));let u=Q().add(i),c=new Wo(H.min(),new Map,new de(Y),o,u);await jy(n,c),n.Ru=n.Ru.remove(i),n.Au.delete(e),Xl(n)}else await cl(n.localStore,e,!1).then((()=>Pl(n,e,t))).catch(Yn)}async function IR(r,e){let t=W(r),n=e.batch.batchId;try{let s=await Jx(t.localStore,e);By(t,n,null),Uy(t,n),t.sharedClientState.updateMutationState(n,"acknowledged"),await li(t,s)}catch(s){await Yn(s)}}async function AR(r,e,t){let n=W(r);try{let s=await(function(o,u){let c=W(o);return c.persistence.runTransaction("Reject batch","readwrite-primary",(l=>{let f;return c.mutationQueue.lookupMutationBatch(l,u).next((p=>(te(p!==null,37113),f=p.keys(),c.mutationQueue.removeMutationBatch(l,p)))).next((()=>c.mutationQueue.performConsistencyCheck(l))).next((()=>c.documentOverlayCache.removeOverlaysForBatchId(l,f,u))).next((()=>c.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(l,f))).next((()=>c.localDocuments.getDocuments(l,f)))}))})(n.localStore,e);By(n,e,t),Uy(n,e),n.sharedClientState.updateMutationState(e,"rejected",t),await li(n,s)}catch(s){await Yn(s)}}function Uy(r,e){(r.mu.get(e)||[]).forEach((t=>{t.resolve()})),r.mu.delete(e)}function By(r,e,t){let n=W(r),s=n.du[n.currentUser.toKey()];if(s){let i=s.get(e);i&&(t?i.reject(t):i.resolve(),s=s.remove(e)),n.du[n.currentUser.toKey()]=s}}function Pl(r,e,t=null){r.sharedClientState.removeLocalQueryTarget(e);for(let n of r.Eu.get(e))r.Tu.delete(n),t&&r.Pu.yu(n,t);r.Eu.delete(e),r.isPrimaryClient&&r.Vu.Gr(e).forEach((n=>{r.Vu.containsKey(n)||$y(r,n)}))}function $y(r,e){r.Iu.delete(e.path.canonicalString());let t=r.Ru.get(e);t!==null&&(Kl(r.remoteStore,t),r.Ru=r.Ru.remove(e),r.Au.delete(t),Xl(r))}function wg(r,e,t){for(let n of t)n instanceof ca?(r.Vu.addReference(n.key,e),SR(r,n)):n instanceof la?(M(Yl,"Document no longer in limbo: "+n.key),r.Vu.removeReference(n.key,e),r.Vu.containsKey(n.key)||$y(r,n.key)):K(19791,{wu:n})}function SR(r,e){let t=e.key,n=t.path.canonicalString();r.Ru.get(t)||r.Iu.has(n)||(M(Yl,"New document in limbo: "+t),r.Iu.add(n),Xl(r))}function Xl(r){for(;r.Iu.size>0&&r.Ru.size<r.maxConcurrentLimboResolutions;){let e=r.Iu.values().next().value;r.Iu.delete(e);let t=new q(he.fromString(e)),n=r.fu.next();r.Au.set(n,new xl(t)),r.Ru=r.Ru.insert(t,n),Cy(r.remoteStore,new ei(ht(ai(t.path)),n,"TargetPurposeLimboResolution",Vn.ce))}}async function li(r,e,t){let n=W(r),s=[],i=[],o=[];n.Tu.isEmpty()||(n.Tu.forEach(((u,c)=>{o.push(n.pu(c,e,t).then((l=>{var f;if((l||t)&&n.isPrimaryClient){let p=l?!l.fromCache:(f=t==null?void 0:t.targetChanges.get(c.targetId))==null?void 0:f.current;n.sharedClientState.updateQueryState(c.targetId,p?"current":"not-current")}if(l){s.push(l);let p=il.Is(c.targetId,l);i.push(p)}})))})),await Promise.all(o),n.Pu.H_(s),await(async function(c,l){let f=W(c);try{await f.persistence.runTransaction("notifyLocalViewChanges","readwrite",(p=>V.forEach(l,(g=>V.forEach(g.Ts,(y=>f.persistence.referenceDelegate.addReference(p,g.targetId,y))).next((()=>V.forEach(g.Es,(y=>f.persistence.referenceDelegate.removeReference(p,g.targetId,y)))))))))}catch(p){if(!Xn(p))throw p;M(zl,"Failed to update sequence numbers: "+p)}for(let p of l){let g=p.targetId;if(!p.fromCache){let y=f.vs.get(g),I=y.snapshotVersion,R=y.withLastLimboFreeSnapshotVersion(I);f.vs=f.vs.insert(g,R)}}})(n.localStore,i))}async function xR(r,e){let t=W(r);if(!t.currentUser.isEqual(e)){M(Yl,"User change. New user:",e.toKey());let n=await Ry(t.localStore,e);t.currentUser=e,(function(i,o){i.mu.forEach((u=>{u.forEach((c=>{c.reject(new B(O.CANCELLED,o))}))})),i.mu.clear()})(t,"'waitForPendingWrites' promise is rejected due to a user change."),t.sharedClientState.handleUserChange(e,n.removedBatchIds,n.addedBatchIds),await li(t,n.Ns)}}function RR(r,e){let t=W(r),n=t.Au.get(e);if(n&&n.hu)return Q().add(n.key);{let s=Q(),i=t.Eu.get(e);if(!i)return s;for(let o of i){let u=t.Tu.get(o);s=s.unionWith(u.view.nu)}return s}}function qy(r){let e=W(r);return e.remoteStore.remoteSyncer.applyRemoteEvent=jy.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=RR.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=TR.bind(null,e),e.Pu.H_=mR.bind(null,e.eventManager),e.Pu.yu=gR.bind(null,e.eventManager),e}function PR(r){let e=W(r);return e.remoteStore.remoteSyncer.applySuccessfulWrite=IR.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=AR.bind(null,e),e}var Mr=class{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=ui(e.databaseInfo.databaseId),this.sharedClientState=this.Du(e),this.persistence=this.Cu(e),await this.persistence.start(),this.localStore=this.vu(e),this.gcScheduler=this.Fu(e,this.localStore),this.indexBackfillerScheduler=this.Mu(e,this.localStore)}Fu(e,t){return null}Mu(e,t){return null}vu(e){return Hx(this.persistence,new al,e.initialUser,this.serializer)}Cu(e){return new Zo(sl.Vi,this.serializer)}Du(e){return new ll}async terminate(){var e,t;(e=this.gcScheduler)==null||e.stop(),(t=this.indexBackfillerScheduler)==null||t.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}};Mr.provider={build:()=>new Mr};var ha=class extends Mr{constructor(e){super(),this.cacheSizeBytes=e}Fu(e,t){te(this.persistence.referenceDelegate instanceof ea,46915);let n=this.persistence.referenceDelegate.garbageCollector;return new Kc(n,e.asyncQueue,t)}Cu(e){let t=this.cacheSizeBytes!==void 0?Ke.withCacheSize(this.cacheSizeBytes):Ke.DEFAULT;return new Zo((n=>ea.Vi(n,t)),this.serializer)}};var zn=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=>_g(this.syncEngine,n,1),this.remoteStore.remoteSyncer.handleCredentialChange=xR.bind(null,this.syncEngine),await pR(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return(function(){return new Tl})()}createDatastore(e){let t=ui(e.databaseInfo.databaseId),n=rR(e.databaseInfo);return nR(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return(function(n,s,i,o,u){return new vl(n,s,i,o,u)})(this.localStore,this.datastore,e.asyncQueue,(t=>_g(this.syncEngine,t,0)),(function(){return ra.v()?new ra:new hl})())}createSyncEngine(e,t){return(function(s,i,o,u,c,l,f){let p=new Rl(s,i,o,u,c,l);return f&&(p.gu=!0),p})(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e,t;await(async function(s){let i=W(s);M(Lr,"RemoteStore shutting down."),i.Ia.add(5),await ci(i),i.Aa.shutdown(),i.Va.set("Unknown")})(this.remoteStore),(e=this.datastore)==null||e.terminate(),(t=this.eventManager)==null||t.terminate()}};zn.provider={build:()=>new zn};var da=class{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Ou(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Ou(this.observer.error,e):kt("Uncaught Error in snapshot listener:",e.toString()))}Nu(){this.muted=!0}Ou(e,t){setTimeout((()=>{this.muted||e(t)}),0)}};var hr="FirestoreClient",Cl=class{constructor(e,t,n,s,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this._databaseInfo=s,this.user=Se.UNAUTHENTICATED,this.clientId=Pr.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,(async o=>{M(hr,"Received user=",o.uid),await this.authCredentialListener(o),this.user=o})),this.appCheckCredentials.start(n,(o=>(M(hr,"Received new app check token=",o),this.appCheckCredentialListener(o,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 ct;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 cc(r,e){r.asyncQueue.verifyOperationInProgress(),M(hr,"Initializing OfflineComponentProvider");let t=r.configuration;await e.initialize(t);let n=t.initialUser;r.setCredentialChangeListener((async s=>{n.isEqual(s)||(await Ry(e.localStore,s),n=s)})),e.persistence.setDatabaseDeletedListener((()=>r.terminate())),r._offlineComponents=e}async function vg(r,e){r.asyncQueue.verifyOperationInProgress();let t=await CR(r);M(hr,"Initializing OnlineComponentProvider"),await e.initialize(t,r.configuration),r.setCredentialChangeListener((n=>mg(e.remoteStore,n))),r.setAppCheckTokenChangeListener(((n,s)=>mg(e.remoteStore,s))),r._onlineComponents=e}async function CR(r){if(!r._offlineComponents)if(r._uninitializedComponentsProvider){M(hr,"Using user provided OfflineComponentProvider");try{await cc(r,r._uninitializedComponentsProvider._offline)}catch(e){let t=e;if(!(function(s){return s.name==="FirebaseError"?s.code===O.FAILED_PRECONDITION||s.code===O.UNIMPLEMENTED:!(typeof DOMException!="undefined"&&s instanceof DOMException)||s.code===22||s.code===20||s.code===11})(t))throw t;Ot("Error using user provided cache. Falling back to memory cache: "+t),await cc(r,new Mr)}}else M(hr,"Using default OfflineComponentProvider"),await cc(r,new ha(void 0));return r._offlineComponents}async function zy(r){return r._onlineComponents||(r._uninitializedComponentsProvider?(M(hr,"Using user provided OnlineComponentProvider"),await vg(r,r._uninitializedComponentsProvider._online)):(M(hr,"Using default OnlineComponentProvider"),await vg(r,new zn))),r._onlineComponents}function kR(r){return zy(r).then((e=>e.syncEngine))}async function kl(r){let e=await zy(r),t=e.eventManager;return t.onListen=yR.bind(null,e.syncEngine),t.onUnlisten=vR.bind(null,e.syncEngine),t.onFirstRemoteStoreListen=_R.bind(null,e.syncEngine),t.onLastRemoteStoreUnlisten=bR.bind(null,e.syncEngine),t}function Ky(r,e,t,n){let s=new da(n),i=new ua(e,s,t);return r.asyncQueue.enqueueAndForget((async()=>Ly(await kl(r),i))),()=>{s.Nu(),r.asyncQueue.enqueueAndForget((async()=>Fy(await kl(r),i)))}}function Gy(r,e,t={}){let n=new ct;return r.asyncQueue.enqueueAndForget((async()=>(function(i,o,u,c,l){let f=new da({next:g=>{f.Nu(),o.enqueueAndForget((()=>Fy(i,p)));let y=g.docs.has(u);!y&&g.fromCache?l.reject(new B(O.UNAVAILABLE,"Failed to get document because the client is offline.")):y&&g.fromCache&&c&&c.source==="server"?l.reject(new B(O.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.)')):l.resolve(g)},error:g=>l.reject(g)}),p=new ua(ai(u.path),f,{includeMetadataChanges:!0,qa:!0});return Ly(i,p)})(await kl(r),r.asyncQueue,e,t,n))),n.promise}function Wy(r,e){let t=new ct;return r.asyncQueue.enqueueAndForget((async()=>ER(await kR(r),e,t))),t.promise}function Hy(r){let e={};return r.timeoutSeconds!==void 0&&(e.timeoutSeconds=r.timeoutSeconds),e}var OR="ComponentProvider",bg=new Map;function DR(r,e,t,n,s){return new mc(r,e,t,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,Hy(s.experimentalLongPollingOptions),s.useFetchStreams,s.isUsingEmulator,n)}var Jy="firestore.googleapis.com",Eg=!0,fa=class{constructor(e){var t,n;if(e.host===void 0){if(e.ssl!==void 0)throw new B(O.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=Jy,this.ssl=Eg}else this.host=e.host,this.ssl=(t=e.ssl)!=null?t:Eg;if(this.isUsingEmulator=e.emulatorOptions!==void 0,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e.cacheSizeBytes===void 0)this.cacheSizeBytes=xy;else{if(e.cacheSizeBytes!==-1&&e.cacheSizeBytes<Kx)throw new B(O.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}xg("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=Hy((n=e.experimentalLongPollingOptions)!=null?n:{}),(function(i){if(i.timeoutSeconds!==void 0){if(isNaN(i.timeoutSeconds))throw new B(O.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (must not be NaN)`);if(i.timeoutSeconds<5)throw new B(O.INVALID_ARGUMENT,`invalid long polling timeout: ${i.timeoutSeconds} (minimum allowed value is 5)`);if(i.timeoutSeconds>30)throw new B(O.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}},si=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 fa({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new B(O.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 B(O.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 fa(e),this._emulatorOptions=e.emulatorOptions||{},e.credentials!==void 0&&(this._authCredentials=(function(n){if(!n)return new Lo;switch(n.type){case"firstParty":return new dc(n.sessionIndex||"0",n.iamToken||null,n.authTokenFactory||null);case"provider":return n.client;default:throw new B(O.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}})(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask==="notTerminated"&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){this._terminateTask==="notTerminated"?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return(function(t){let n=bg.get(t);n&&(M(OR,"Removing Datastore"),bg.delete(t),n.terminate())})(this),Promise.resolve()}};function Qy(r,e,t,n={}){var l;r=We(r,si);let s=Lu(e),i=r._getSettings(),o={...i,emulatorOptions:r._getEmulatorOptions()},u=`${e}:${t}`;s&&vm(`https://${u}`),i.host!==Jy&&i.host!==u&&Ot("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let c={...i,host:u,ssl:s,emulatorOptions:n};if(!Ir(c,o)&&(r._setSettings(c),n.mockUserToken)){let f,p;if(typeof n.mockUserToken=="string")f=n.mockUserToken,p=Se.MOCK_USER;else{f=gm(n.mockUserToken,(l=r._app)==null?void 0:l.options.projectId);let g=n.mockUserToken.sub||n.mockUserToken.user_id;if(!g)throw new B(O.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");p=new Se(g)}r._authCredentials=new lc(new Vo(f,p))}}var Kn=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)}},Ee=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 Gn(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new r(this.firestore,e,this._key)}toJSON(){return{type:r._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,t,n){if(Qn(t,r._jsonSchema))return new r(e,n||null,new q(he.fromString(t.referencePath)))}};Ee._jsonSchemaVersion="firestore/documentReference/1.0",Ee._jsonSchema={type:me("string",Ee._jsonSchemaVersion),referencePath:me("string")};var Gn=class r extends Kn{constructor(e,t,n){super(e,t,ai(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 Ee(this.firestore,null,new q(e))}withConverter(e){return new r(this.firestore,e,this._path)}};function es(r,e,...t){if(r=at(r),arguments.length===1&&(e=Pr.newId()),$S("doc","path",e),r instanceof si){let n=he.fromString(e,...t);return $m(n),new Ee(r,null,new q(n))}{if(!(r instanceof Ee||r instanceof Gn))throw new B(O.INVALID_ARGUMENT,"Expected first argument to doc() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let n=r._path.child(he.fromString(e,...t));return $m(n),new Ee(r.firestore,r instanceof Gn?r.converter:null,new q(n))}}var Tg="AsyncQueue",pa=class{constructor(e=Promise.resolve()){this.Yu=[],this.ec=!1,this.tc=[],this.nc=null,this.rc=!1,this.sc=!1,this.oc=[],this.M_=new sa(this,"async_queue_retry"),this._c=()=>{let n=uc();n&&M(Tg,"Visibility state changed to "+n.visibilityState),this.M_.w_()},this.ac=e;let t=uc();t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",this._c)}get isShuttingDown(){return this.ec}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.uc(),this.cc(e)}enterRestrictedMode(e){if(!this.ec){this.ec=!0,this.sc=e||!1;let t=uc();t&&typeof t.removeEventListener=="function"&&t.removeEventListener("visibilitychange",this._c)}}enqueue(e){if(this.uc(),this.ec)return new Promise((()=>{}));let t=new ct;return this.cc((()=>this.ec&&this.sc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.Yu.push(e),this.lc())))}async lc(){if(this.Yu.length!==0){try{await this.Yu[0](),this.Yu.shift(),this.M_.reset()}catch(e){if(!Xn(e))throw e;M(Tg,"Operation failed with retryable error: "+e)}this.Yu.length>0&&this.M_.p_((()=>this.lc()))}}cc(e){let t=this.ac.then((()=>(this.rc=!0,e().catch((n=>{throw this.nc=n,this.rc=!1,kt("INTERNAL UNHANDLED ERROR: ",Ig(n)),n})).then((n=>(this.rc=!1,n))))));return this.ac=t,t}enqueueAfterDelay(e,t,n){this.uc(),this.oc.indexOf(e)>-1&&(t=0);let s=bl.createAndSchedule(this,e,t,n,(i=>this.hc(i)));return this.tc.push(s),s}uc(){this.nc&&K(47125,{Pc:Ig(this.nc)})}verifyOperationInProgress(){}async Tc(){let e;do e=this.ac,await e;while(e!==this.ac)}Ec(e){for(let t of this.tc)if(t.timerId===e)return!0;return!1}Ic(e){return this.Tc().then((()=>{this.tc.sort(((t,n)=>t.targetTimeMs-n.targetTimeMs));for(let t of this.tc)if(t.skipDelay(),e!=="all"&&t.timerId===e)break;return this.Tc()}))}Rc(e){this.oc.push(e)}hc(e){let t=this.tc.indexOf(e);this.tc.splice(t,1)}};function Ig(r){let e=r.message||"";return r.stack&&(e=r.stack.includes(r.message)?r.stack:r.message+`
|
|
22
|
+
`+r.stack),e}var yt=class extends si{constructor(e,t,n,s){super(e,t,n,s),this.type="firestore",this._queue=new pa,this._persistenceKey=(s==null?void 0:s.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new pa(e),this._firestoreClient=void 0,await e}}};function Zl(r,e){let t=typeof r=="object"?r:Lm(),n=typeof r=="string"?r:e||zo,s=Dm(t,"firestore").getImmediate({identifier:n});if(!s._initialized){let i=mm("firestore");i&&Qy(s,...i)}return s}function hi(r){if(r._terminated)throw new B(O.FAILED_PRECONDITION,"The client has already been terminated.");return r._firestoreClient||NR(r),r._firestoreClient}function NR(r){var n,s,i,o;let e=r._freezeSettings(),t=DR(r._databaseId,((n=r._app)==null?void 0:n.options.appId)||"",r._persistenceKey,(s=r._app)==null?void 0:s.options.apiKey,e);r._componentsProvider||(i=e.localCache)!=null&&i._offlineComponentProvider&&((o=e.localCache)!=null&&o._onlineComponentProvider)&&(r._componentsProvider={_offline:e.localCache._offlineComponentProvider,_online:e.localCache._onlineComponentProvider}),r._firestoreClient=new Cl(r._authCredentials,r._appCheckCredentials,r._queue,t,r._componentsProvider&&(function(c){let l=c==null?void 0:c._online.build();return{_offline:c==null?void 0:c._offline.build(l),_online:l}})(r._componentsProvider))}var ft=class r{constructor(e){this._byteString=e}static fromBase64String(e){try{return new r(Pe.fromBase64String(e))}catch(t){throw new B(O.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)}toJSON(){return{type:r._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(Qn(e,r._jsonSchema))return r.fromBase64String(e.bytes)}};ft._jsonSchemaVersion="firestore/bytes/1.0",ft._jsonSchema={type:me("string",ft._jsonSchemaVersion),bytes:me("string")};var jr=class{constructor(...e){for(let t=0;t<e.length;++t)if(e[t].length===0)throw new B(O.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 Wn=class{constructor(e){this._methodName=e}};var Ct=class r{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new B(O.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new B(O.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}_compareTo(e){return Y(this._lat,e._lat)||Y(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:r._jsonSchemaVersion}}static fromJSON(e){if(Qn(e,r._jsonSchema))return new r(e.latitude,e.longitude)}};Ct._jsonSchemaVersion="firestore/geoPoint/1.0",Ct._jsonSchema={type:me("string",Ct._jsonSchemaVersion),latitude:me("number"),longitude:me("number")};var pt=class r{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)}toJSON(){return{type:r._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(Qn(e,r._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every((t=>typeof t=="number")))return new r(e.vectorValues);throw new B(O.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}};pt._jsonSchemaVersion="firestore/vectorValue/1.0",pt._jsonSchema={type:me("string",pt._jsonSchemaVersion),vectorValues:me("object")};var VR=/^__.*__$/,Ol=class{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return this.fieldMask!==null?new gt(e,this.data,this.fieldMask,t,this.fieldTransforms):new Vr(e,this.data,t,this.fieldTransforms)}},ma=class{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new gt(e,this.data,this.fieldMask,t,this.fieldTransforms)}};function Yy(r){switch(r){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw K(40011,{dataSource:r})}}var Dl=class r{constructor(e,t,n,s,i,o){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=s,i===void 0&&this.Ac(),this.fieldTransforms=i||[],this.fieldMask=o||[]}get path(){return this.settings.path}get dataSource(){return this.settings.dataSource}i(e){return new r({...this.settings,...e},this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}dc(e){var s;let t=(s=this.path)==null?void 0:s.child(e),n=this.i({path:t,arrayElement:!1});return n.mc(e),n}fc(e){var s;let t=(s=this.path)==null?void 0:s.child(e),n=this.i({path:t,arrayElement:!1});return n.Ac(),n}gc(e){return this.i({path:void 0,arrayElement:!0})}yc(e){return ya(e,this.settings.methodName,this.settings.hasConverter||!1,this.path,this.settings.targetDoc)}contains(e){return this.fieldMask.find((t=>e.isPrefixOf(t)))!==void 0||this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))!==void 0}Ac(){if(this.path)for(let e=0;e<this.path.length;e++)this.mc(this.path.get(e))}mc(e){if(e.length===0)throw this.yc("Document fields must not be empty");if(Yy(this.dataSource)&&VR.test(e))throw this.yc('Document fields cannot begin and end with "__"')}},Nl=class{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||ui(e)}A(e,t,n,s=!1){return new Dl({dataSource:e,methodName:t,targetDoc:n,path:Be.emptyPath(),arrayElement:!1,hasConverter:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function eh(r){let e=r._freezeSettings(),t=ui(r._databaseId);return new Nl(r._databaseId,!!e.ignoreUndefinedProperties,t)}function Xy(r,e,t,n,s,i={}){let o=r.A(i.merge||i.mergeFields?2:0,e,t,s);th("Data must be an object, but it was:",o,n);let u=t_(n,o),c,l;if(i.merge)c=new Ge(o.fieldMask),l=o.fieldTransforms;else if(i.mergeFields){let f=[];for(let p of i.mergeFields){let g=Hn(e,p,t);if(!o.contains(g))throw new B(O.INVALID_ARGUMENT,`Field '${g}' is specified in your field mask but missing from your input data.`);n_(f,g)||f.push(g)}c=new Ge(f),l=o.fieldTransforms.filter((p=>c.covers(p.field)))}else c=null,l=o.fieldTransforms;return new Ol(new Ue(u),c,l)}var ga=class r extends Wn{_toFieldTransform(e){if(e.dataSource!==2)throw e.dataSource===1?e.yc(`${this._methodName}() can only appear at the top level of your update data`):e.yc(`${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 Zy(r,e,t,n){let s=r.A(1,e,t);th("Data must be an object, but it was:",s,n);let i=[],o=Ue.empty();dr(n,((c,l)=>{let f=rh(e,c,t);l=at(l);let p=s.fc(f);if(l instanceof ga)i.push(f);else{let g=Sa(l,p);g!=null&&(i.push(f),o.set(f,g))}}));let u=new Ge(i);return new ma(o,u,s.fieldTransforms)}function e_(r,e,t,n,s,i){let o=r.A(1,e,t),u=[Hn(e,n,t)],c=[s];if(i.length%2!=0)throw new B(O.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(Hn(e,i[g])),c.push(i[g+1]);let l=[],f=Ue.empty();for(let g=u.length-1;g>=0;--g)if(!n_(l,u[g])){let y=u[g],I=c[g];I=at(I);let R=o.fc(y);if(I instanceof ga)l.push(y);else{let A=Sa(I,R);A!=null&&(l.push(y),f.set(y,A))}}let p=new Ge(l);return new ma(f,p,o.fieldTransforms)}function Sa(r,e){if(r_(r=at(r)))return th("Unsupported field value:",e,r),t_(r,e);if(r instanceof Wn)return(function(n,s){if(!Yy(s.dataSource))throw s.yc(`${n._methodName}() can only be used with update() and set()`);if(!s.path)throw s.yc(`${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.arrayElement&&e.dataSource!==4)throw e.yc("Nested arrays are not supported");return(function(n,s){let i=[],o=0;for(let u of n){let c=Sa(u,s.gc(o));c==null&&(c={nullValue:"NULL_VALUE"}),i.push(c),o++}return{arrayValue:{values:i}}})(r,e)}return(function(n,s){if((n=at(n))===null)return{nullValue:"NULL_VALUE"};if(typeof n=="number")return vx(s.serializer,n);if(typeof n=="boolean")return{booleanValue:n};if(typeof n=="string")return{stringValue:n};if(n instanceof Date){let i=ge.fromDate(n);return{timestampValue:Yo(s.serializer,i)}}if(n instanceof ge){let i=new ge(n.seconds,1e3*Math.floor(n.nanoseconds/1e3));return{timestampValue:Yo(s.serializer,i)}}if(n instanceof Ct)return{geoPointValue:{latitude:n.latitude,longitude:n.longitude}};if(n instanceof ft)return{bytesValue:_y(s.serializer,n._byteString)};if(n instanceof Ee){let i=s.databaseId,o=n.firestore._databaseId;if(!o.isEqual(i))throw s.yc(`Document reference is for database ${o.projectId}/${o.database} but should be for database ${i.projectId}/${i.database}`);return{referenceValue:ql(n.firestore._databaseId||s.databaseId,n._key.path)}}if(n instanceof pt)return(function(o,u){let c=o instanceof pt?o.toArray():o;return{mapValue:{fields:{[Fl]:{stringValue:Ml},[Ln]:{arrayValue:{values:c.map((f=>{if(typeof f!="number")throw u.yc("VectorValues must only contain numeric values.");return $l(u.serializer,f)}))}}}}}})(n,s);if(Ay(n))return n._toProto(s.serializer);throw s.yc(`Unsupported field value: ${_a(n)}`)})(r,e)}function t_(r,e){let t={};return qg(r)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):dr(r,((n,s)=>{let i=Sa(s,e.dc(n));i!=null&&(t[n]=i)})),{mapValue:{fields:t}}}function r_(r){return!(typeof r!="object"||r===null||r instanceof Array||r instanceof Date||r instanceof ge||r instanceof Ct||r instanceof ft||r instanceof Ee||r instanceof Wn||r instanceof pt||Ay(r))}function th(r,e,t){if(!r_(t)||!Rg(t)){let n=_a(t);throw n==="an object"?e.yc(r+" a custom object"):e.yc(r+" "+n)}}function Hn(r,e,t){if((e=at(e))instanceof jr)return e._internalPath;if(typeof e=="string")return rh(r,e);throw ya("Field path arguments must be of type string or ",r,!1,void 0,t)}var LR=new RegExp("[~\\*/\\[\\]]");function rh(r,e,t){if(e.search(LR)>=0)throw ya(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`,r,!1,void 0,t);try{return new jr(...e.split("."))._internalPath}catch{throw ya(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,r,!1,void 0,t)}}function ya(r,e,t,n,s){let i=n&&!n.isEmpty(),o=s!==void 0,u=`Function ${e}() called with invalid data`;t&&(u+=" (via `toFirestore()`)"),u+=". ";let c="";return(i||o)&&(c+=" (found",i&&(c+=` in field ${n}`),o&&(c+=` in document ${s}`),c+=")"),new B(O.INVALID_ARGUMENT,u+r+c)}function n_(r,e){return r.some((t=>t.isEqual(e)))}var ii=class{convertValue(e,t="none"){switch(cr(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(Nt(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 K(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let n={};return dr(e,((s,i)=>{n[s]=this.convertValue(i,t)})),n}convertVectorValue(e){var n,s,i;let t=(i=(s=(n=e.fields)==null?void 0:n[Ln].arrayValue)==null?void 0:s.values)==null?void 0:i.map((o=>ae(o.doubleValue)));return new pt(t)}convertGeoPoint(e){return new Ct(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=ba(e);return n==null?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Js(e));default:return null}}convertTimestamp(e){let t=Dt(e);return new ge(t.seconds,t.nanos)}convertDocumentKey(e,t){let n=he.fromString(e);te(Iy(n),9688,{name:e});let s=new Qs(n.get(1),n.get(3)),i=new q(n.popFirst(5));return s.isEqual(t)||kt(`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}};var oi=class extends ii{constructor(e){super(),this.firestore=e}convertBytes(e){return new ft(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new Ee(this.firestore,null,t)}};var s_="@firebase/firestore",i_="4.13.0";function o_(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 xa=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 Ee(this._firestore,this._converter,this._key)}exists(){return this._document!==null}data(){if(this._document){if(this._converter){let e=new nh(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}_fieldsProto(){var e,t;return(t=(e=this._document)==null?void 0:e.data.clone().value.mapValue.fields)!=null?t:void 0}get(e){if(this._document){let t=this._document.data.field(Hn("DocumentSnapshot.get",e));if(t!==null)return this._userDataWriter.convertValue(t)}}},nh=class extends xa{data(){return super.data()}};function UR(r){if(r.limitType==="L"&&r.explicitOrderBy.length===0)throw new B(O.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}function BR(r,e,t){let n;return n=r?t&&(t.merge||t.mergeFields)?r.toFirestore(e,t):r.toFirestore(e):e,n}var Br=class{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}},$r=class r extends xa{constructor(e,t,n,s,i,o){super(e,t,n,s,o),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let t=new ts(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(Hn("DocumentSnapshot.get",e));if(n!==null)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new B(O.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e=this._document,t={};return t.type=r._jsonSchemaVersion,t.bundle="",t.bundleSource="DocumentSnapshot",t.bundleName=this._key.toString(),!e||!e.isValidDocument()||!e.isFoundDocument()?t:(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),t.bundle=(this._firestore,this.ref.path,"NOT SUPPORTED"),t)}};$r._jsonSchemaVersion="firestore/documentSnapshot/1.0",$r._jsonSchema={type:me("string",$r._jsonSchemaVersion),bundleSource:me("string","DocumentSnapshot"),bundleName:me("string"),bundle:me("string")};var ts=class extends $r{data(e={}){return super.data(e)}},rs=class r{constructor(e,t,n,s){this._firestore=e,this._userDataWriter=t,this._snapshot=s,this.metadata=new Br(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 ts(this._firestore,this._userDataWriter,n.key,n,new Br(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 B(O.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 o=0;return s._snapshot.docChanges.map((u=>{let c=new ts(s._firestore,s._userDataWriter,u.doc.key,u.doc,new Br(s._snapshot.mutatedKeys.has(u.doc.key),s._snapshot.fromCache),s.query.converter);return u.doc,{type:"added",doc:c,oldIndex:-1,newIndex:o++}}))}{let o=s._snapshot.oldDocs;return s._snapshot.docChanges.filter((u=>i||u.type!==3)).map((u=>{let c=new ts(s._firestore,s._userDataWriter,u.doc.key,u.doc,new Br(s._snapshot.mutatedKeys.has(u.doc.key),s._snapshot.fromCache),s.query.converter),l=-1,f=-1;return u.type!==0&&(l=o.indexOf(u.doc.key),o=o.delete(u.doc.key)),u.type!==1&&(o=o.add(u.doc),f=o.indexOf(u.doc.key)),{type:$R(u.type),doc:c,oldIndex:l,newIndex:f}}))}})(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new B(O.FAILED_PRECONDITION,"QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=r._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=Pr.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let t=[],n=[],s=[];return this.docs.forEach((i=>{i._document!==null&&(t.push(i._document),n.push(this._userDataWriter.convertObjectMap(i._document.data.value.mapValue.fields,"previous")),s.push(i.ref.path))})),e.bundle=(this._firestore,this.query._query,e.bundleName,"NOT SUPPORTED"),e}};function $R(r){switch(r){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return K(61501,{type:r})}}rs._jsonSchemaVersion="firestore/querySnapshot/1.0",rs._jsonSchema={type:me("string",rs._jsonSchemaVersion),bundleSource:me("string","QuerySnapshot"),bundleName:me("string"),bundle:me("string")};function sh(r){r=We(r,Ee);let e=We(r.firestore,yt),t=hi(e);return Gy(t,r._key).then((n=>c_(e,r,n)))}function ih(r,e,t){r=We(r,Ee);let n=We(r.firestore,yt),s=BR(r.converter,e,t),i=eh(n);return u_(n,[Xy(i,"setDoc",r._key,s,r.converter!==null,t).toMutation(r._key,Pt.none())])}function oh(r,e,t,...n){r=We(r,Ee);let s=We(r.firestore,yt),i=eh(s),o;return o=typeof(e=at(e))=="string"||e instanceof jr?e_(i,"updateDoc",r._key,e,t,n):Zy(i,"updateDoc",r._key,e),u_(s,[o.toMutation(r._key,Pt.exists(!0))])}function a_(r,...e){var l,f,p;r=at(r);let t={includeMetadataChanges:!1,source:"default"},n=0;typeof e[n]!="object"||o_(e[n])||(t=e[n++]);let s={includeMetadataChanges:t.includeMetadataChanges,source:t.source};if(o_(e[n])){let g=e[n];e[n]=(l=g.next)==null?void 0:l.bind(g),e[n+1]=(f=g.error)==null?void 0:f.bind(g),e[n+2]=(p=g.complete)==null?void 0:p.bind(g)}let i,o,u;if(r instanceof Ee)o=We(r.firestore,yt),u=ai(r._key.path),i={next:g=>{e[n]&&e[n](c_(o,r,g))},error:e[n+1],complete:e[n+2]};else{let g=We(r,Kn);o=We(g.firestore,yt),u=g._query;let y=new oi(o);i={next:I=>{e[n]&&e[n](new rs(o,y,g,I))},error:e[n+1],complete:e[n+2]},UR(r._query)}let c=hi(o);return Ky(c,u,s,i)}function u_(r,e){let t=hi(r);return Wy(t,e)}function c_(r,e,t){let n=t.docs.get(e._key),s=new oi(r);return new $r(r,s,e._key,n,new Br(t.hasPendingWrites,t.fromCache),e.converter)}(function(e,t=!0){Ag(Vm),js(new At("firestore",((n,{instanceIdentifier:s,options:i})=>{let o=n.getProvider("app").getImmediate(),u=new yt(new Fo(n.getProvider("auth-internal")),new jo(o,n.getProvider("app-check-internal")),Hg(o,s),o);return i={useFetchStreams:t,...i},u._setSettings(i),u}),"PUBLIC").setMultipleInstances(!0)),ur(s_,i_,e),ur(s_,i_,"esm2020")})();function qr(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}function l_(r,e,t,n){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function u(f){try{l(n.next(f))}catch(p){o(p)}}function c(f){try{l(n.throw(f))}catch(p){o(p)}}function l(f){f.done?i(f.value):s(f.value).then(u,c)}l((n=n.apply(r,e||[])).next())})}var h_=r=>r?(...e)=>r(...e):(...e)=>fetch(...e);var ns=class extends Error{constructor(e,t="FunctionsError",n){super(e),this.name=t,this.context=n}},di=class extends ns{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},ss=class extends ns{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},is=class extends ns{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},fi;(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"})(fi||(fi={}));var pi=class{constructor(e,{headers:t={},customFetch:n,region:s=fi.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=h_(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return l_(this,arguments,void 0,function*(t,n={}){var s;let i,o;try{let{headers:u,method:c,body:l,signal:f,timeout:p}=n,g={},{region:y}=n;y||(y=this.region);let I=new URL(`${this.url}/${t}`);y&&y!=="any"&&(g["x-region"]=y,I.searchParams.set("forceFunctionRegion",y));let R;l&&(u&&!Object.prototype.hasOwnProperty.call(u,"Content-Type")||!u)?typeof Blob!="undefined"&&l instanceof Blob||l instanceof ArrayBuffer?(g["Content-Type"]="application/octet-stream",R=l):typeof l=="string"?(g["Content-Type"]="text/plain",R=l):typeof FormData!="undefined"&&l instanceof FormData?R=l:(g["Content-Type"]="application/json",R=JSON.stringify(l)):l&&typeof l!="string"&&!(typeof Blob!="undefined"&&l instanceof Blob)&&!(l instanceof ArrayBuffer)&&!(typeof FormData!="undefined"&&l instanceof FormData)?R=JSON.stringify(l):R=l;let A=f;p&&(o=new AbortController,i=setTimeout(()=>o.abort(),p),f?(A=o.signal,f.addEventListener("abort",()=>o.abort())):A=o.signal);let k=yield this.fetch(I.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},g),this.headers),u),body:R,signal:A}).catch(z=>{throw new di(z)}),D=k.headers.get("x-relay-error");if(D&&D==="true")throw new ss(k);if(!k.ok)throw new is(k);let N=((s=k.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),U;return N==="application/json"?U=yield k.json():N==="application/octet-stream"||N==="application/pdf"?U=yield k.blob():N==="text/event-stream"?U=k:N==="multipart/form-data"?U=yield k.formData():U=yield k.text(),{data:U,error:null,response:k}}catch(u){return{data:null,error:u,response:u instanceof is||u instanceof ss?u.context:void 0}}finally{i&&clearTimeout(i)}})}};var p_=class extends Error{constructor(r){super(r.message),this.name="PostgrestError",this.details=r.details,this.hint=r.hint,this.code=r.code}},qR=class{constructor(r){var e,t,n;this.shouldThrowOnError=!1,this.method=r.method,this.url=r.url,this.headers=new Headers(r.headers),this.schema=r.schema,this.body=r.body,this.shouldThrowOnError=(e=r.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=r.signal,this.isMaybeSingle=(t=r.isMaybeSingle)!==null&&t!==void 0?t:!1,this.urlLengthLimit=(n=r.urlLengthLimit)!==null&&n!==void 0?n:8e3,r.fetch?this.fetch=r.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(r,e){return this.headers=new Headers(this.headers),this.headers.set(r,e),this}then(r,e){var t=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("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=>{let o=null,u=null,c=null,l=i.status,f=i.statusText;if(i.ok){var p,g;if(t.method!=="HEAD"){var y;let k=await i.text();k===""||(t.headers.get("Accept")==="text/csv"||t.headers.get("Accept")&&(!((y=t.headers.get("Accept"))===null||y===void 0)&&y.includes("application/vnd.pgrst.plan+text"))?u=k:u=JSON.parse(k))}let R=(p=t.headers.get("Prefer"))===null||p===void 0?void 0:p.match(/count=(exact|planned|estimated)/),A=(g=i.headers.get("content-range"))===null||g===void 0?void 0:g.split("/");R&&A&&A.length>1&&(c=parseInt(A[1])),t.isMaybeSingle&&t.method==="GET"&&Array.isArray(u)&&(u.length>1?(o={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,c=null,l=406,f="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{var I;let R=await i.text();try{o=JSON.parse(R),Array.isArray(o)&&i.status===404&&(u=[],o=null,l=200,f="OK")}catch{i.status===404&&R===""?(l=204,f="No Content"):o={message:R}}if(o&&t.isMaybeSingle&&(!(o==null||(I=o.details)===null||I===void 0)&&I.includes("0 rows"))&&(o=null,l=200,f="OK"),o&&t.shouldThrowOnError)throw new p_(o)}return{error:o,data:u,count:c,status:l,statusText:f}});return this.shouldThrowOnError||(s=s.catch(i=>{var o;let u="",c="",l="",f=i==null?void 0:i.cause;if(f){var p,g,y,I;let k=(p=f==null?void 0:f.message)!==null&&p!==void 0?p:"",D=(g=f==null?void 0:f.code)!==null&&g!==void 0?g:"";u=`${(y=i==null?void 0:i.name)!==null&&y!==void 0?y:"FetchError"}: ${i==null?void 0:i.message}`,u+=`
|
|
37
23
|
|
|
38
|
-
Caused by: ${(
|
|
39
|
-
${f.stack}`)}else{var R;u=(R=i==null?void 0:i.stack)!==null&&R!==void 0?R:""}let I=this.url.toString().length;return(i==null?void 0:i.name)==="AbortError"||(i==null?void 0:i.code)==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",I>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${I} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((f==null?void 0:f.name)==="HeadersOverflowError"||(f==null?void 0:f.code)==="UND_ERR_HEADERS_OVERFLOW")&&(h="",c="HTTP headers exceeded server limits (typically 16KB)",I>this.urlLengthLimit&&(c+=`. Your request URL is ${I} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(o=i==null?void 0:i.name)!==null&&o!==void 0?o:"FetchError"}: ${i==null?void 0:i.message}`,details:u,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),s.then(r,e)}returns(){return this}overrideTypes(){return this}},sP=class extends nP{select(r){let e=!1,t=(r!=null?r:"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",t),this.headers.append("Prefer","return=representation"),this}order(r,{ascending:e=!0,nullsFirst:t,foreignTable:n,referencedTable:s=n}={}){let i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${r}.${e?"asc":"desc"}${t===void 0?"":t?".nullsfirst":".nullslast"}`),this}limit(r,{foreignTable:e,referencedTable:t=e}={}){let n=typeof t=="undefined"?"limit":`${t}.limit`;return this.url.searchParams.set(n,`${r}`),this}range(r,e,{foreignTable:t,referencedTable:n=t}={}){let s=typeof n=="undefined"?"offset":`${n}.offset`,i=typeof n=="undefined"?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${r}`),this.url.searchParams.set(i,`${e-r+1}`),this}abortSignal(r){return this.signal=r,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:r=!1,verbose:e=!1,settings:t=!1,buffers:n=!1,wal:s=!1,format:i="text"}={}){var o;let u=[r?"analyze":null,e?"verbose":null,t?"settings":null,n?"buffers":null,s?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${u};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(r){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${r}`),this}},l_=new RegExp("[,()]"),Zn=class extends sP{eq(r,e){return this.url.searchParams.append(r,`eq.${e}`),this}neq(r,e){return this.url.searchParams.append(r,`neq.${e}`),this}gt(r,e){return this.url.searchParams.append(r,`gt.${e}`),this}gte(r,e){return this.url.searchParams.append(r,`gte.${e}`),this}lt(r,e){return this.url.searchParams.append(r,`lt.${e}`),this}lte(r,e){return this.url.searchParams.append(r,`lte.${e}`),this}like(r,e){return this.url.searchParams.append(r,`like.${e}`),this}likeAllOf(r,e){return this.url.searchParams.append(r,`like(all).{${e.join(",")}}`),this}likeAnyOf(r,e){return this.url.searchParams.append(r,`like(any).{${e.join(",")}}`),this}ilike(r,e){return this.url.searchParams.append(r,`ilike.${e}`),this}ilikeAllOf(r,e){return this.url.searchParams.append(r,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(r,e){return this.url.searchParams.append(r,`ilike(any).{${e.join(",")}}`),this}regexMatch(r,e){return this.url.searchParams.append(r,`match.${e}`),this}regexIMatch(r,e){return this.url.searchParams.append(r,`imatch.${e}`),this}is(r,e){return this.url.searchParams.append(r,`is.${e}`),this}isDistinct(r,e){return this.url.searchParams.append(r,`isdistinct.${e}`),this}in(r,e){let t=Array.from(new Set(e)).map(n=>typeof n=="string"&&l_.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(r,`in.(${t})`),this}notIn(r,e){let t=Array.from(new Set(e)).map(n=>typeof n=="string"&&l_.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(r,`not.in.(${t})`),this}contains(r,e){return typeof e=="string"?this.url.searchParams.append(r,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(r,`cs.{${e.join(",")}}`):this.url.searchParams.append(r,`cs.${JSON.stringify(e)}`),this}containedBy(r,e){return typeof e=="string"?this.url.searchParams.append(r,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(r,`cd.{${e.join(",")}}`):this.url.searchParams.append(r,`cd.${JSON.stringify(e)}`),this}rangeGt(r,e){return this.url.searchParams.append(r,`sr.${e}`),this}rangeGte(r,e){return this.url.searchParams.append(r,`nxl.${e}`),this}rangeLt(r,e){return this.url.searchParams.append(r,`sl.${e}`),this}rangeLte(r,e){return this.url.searchParams.append(r,`nxr.${e}`),this}rangeAdjacent(r,e){return this.url.searchParams.append(r,`adj.${e}`),this}overlaps(r,e){return typeof e=="string"?this.url.searchParams.append(r,`ov.${e}`):this.url.searchParams.append(r,`ov.{${e.join(",")}}`),this}textSearch(r,e,{config:t,type:n}={}){let s="";n==="plain"?s="pl":n==="phrase"?s="ph":n==="websearch"&&(s="w");let i=t===void 0?"":`(${t})`;return this.url.searchParams.append(r,`${s}fts${i}.${e}`),this}match(r){return Object.entries(r).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(r,e,t){return this.url.searchParams.append(r,`not.${e}.${t}`),this}or(r,{foreignTable:e,referencedTable:t=e}={}){let n=t?`${t}.or`:"or";return this.url.searchParams.append(n,`(${r})`),this}filter(r,e,t){return this.url.searchParams.append(r,`${e}.${t}`),this}},iP=class{constructor(r,{headers:e={},schema:t,fetch:n,urlLengthLimit:s=8e3}){this.url=r,this.headers=new Headers(e),this.schema=t,this.fetch=n,this.urlLengthLimit=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(r,e){let{head:t=!1,count:n}=e!=null?e:{},s=t?"HEAD":"GET",i=!1,o=(r!=null?r:"*").split("").map(h=>/\s/.test(h)&&!i?"":(h==='"'&&(i=!i),h)).join(""),{url:u,headers:c}=this.cloneRequestState();return u.searchParams.set("select",o),n&&c.append("Prefer",`count=${n}`),new Zn({method:s,url:u,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(r,{count:e,defaultToNull:t=!0}={}){var n;let s="POST",{url:i,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),t||o.append("Prefer","missing=default"),Array.isArray(r)){let u=r.reduce((c,h)=>c.concat(Object.keys(h)),[]);if(u.length>0){let c=[...new Set(u)].map(h=>`"${h}"`);i.searchParams.set("columns",c.join(","))}}return new Zn({method:s,url:i,headers:o,schema:this.schema,body:r,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(r,{onConflict:e,ignoreDuplicates:t=!1,count:n,defaultToNull:s=!0}={}){var i;let o="POST",{url:u,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${t?"ignore":"merge"}-duplicates`),e!==void 0&&u.searchParams.set("on_conflict",e),n&&c.append("Prefer",`count=${n}`),s||c.append("Prefer","missing=default"),Array.isArray(r)){let h=r.reduce((f,p)=>f.concat(Object.keys(p)),[]);if(h.length>0){let f=[...new Set(h)].map(p=>`"${p}"`);u.searchParams.set("columns",f.join(","))}}return new Zn({method:o,url:u,headers:c,schema:this.schema,body:r,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(r,{count:e}={}){var t;let n="PATCH",{url:s,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Zn({method:n,url:s,headers:i,schema:this.schema,body:r,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:r}={}){var e;let t="DELETE",{url:n,headers:s}=this.cloneRequestState();return r&&s.append("Prefer",`count=${r}`),new Zn({method:t,url:n,headers:s,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function ci(r){"@babel/helpers - typeof";return ci=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ci(r)}function oP(r,e){if(ci(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e||"default");if(ci(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function aP(r){var e=oP(r,"string");return ci(e)=="symbol"?e:e+""}function uP(r,e,t){return(e=aP(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function h_(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,n)}return t}function Ta(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?h_(Object(t),!0).forEach(function(n){uP(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):h_(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var f_=class p_{constructor(e,{headers:t={},schema:n,fetch:s,timeout:i,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new Headers(t),this.schemaName=n,this.urlLengthLimit=o;let u=s!=null?s:globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,h)=>{let f=new AbortController,p=setTimeout(()=>f.abort(),i),m=h==null?void 0:h.signal;if(m){if(m.aborted)return clearTimeout(p),u(c,h);let y=()=>{clearTimeout(p),f.abort()};return m.addEventListener("abort",y,{once:!0}),u(c,Ta(Ta({},h),{},{signal:f.signal})).finally(()=>{clearTimeout(p),m.removeEventListener("abort",y)})}return u(c,Ta(Ta({},h),{},{signal:f.signal})).finally(()=>clearTimeout(p))}:this.fetch=u}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new iP(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new p_(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,t={},{head:n=!1,get:s=!1,count:i}={}){var o;let u,c=new URL(`${this.url}/rpc/${e}`),h,f=y=>y!==null&&typeof y=="object"&&(!Array.isArray(y)||y.some(f)),p=n&&Object.values(t).some(f);p?(u="POST",h=t):n||s?(u=n?"HEAD":"GET",Object.entries(t).filter(([y,T])=>T!==void 0).map(([y,T])=>[y,Array.isArray(T)?`{${T.join(",")}}`:`${T}`]).forEach(([y,T])=>{c.searchParams.append(y,T)})):(u="POST",h=t);let m=new Headers(this.headers);return p?m.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&m.set("Prefer",`count=${i}`),new Zn({method:u,url:c,headers:m,schema:this.schemaName,body:h,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};var lh=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket!="undefined")return{type:"native",constructor:WebSocket};if(typeof globalThis!="undefined"&&typeof globalThis.WebSocket!="undefined")return{type:"native",constructor:globalThis.WebSocket};if(typeof global!="undefined"&&typeof global.WebSocket!="undefined")return{type:"native",constructor:global.WebSocket};if(typeof globalThis!="undefined"&&typeof globalThis.WebSocketPair!="undefined"&&typeof globalThis.WebSocket=="undefined")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis!="undefined"&&globalThis.EdgeRuntime||typeof navigator!="undefined"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let t=globalThis.process;if(t){let n=t.versions;if(n&&n.node){let s=n.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket!="undefined"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
24
|
+
Caused by: ${(I=f==null?void 0:f.name)!==null&&I!==void 0?I:"Error"}: ${k}`,D&&(u+=` (${D})`),f!=null&&f.stack&&(u+=`
|
|
25
|
+
${f.stack}`)}else{var R;u=(R=i==null?void 0:i.stack)!==null&&R!==void 0?R:""}let A=this.url.toString().length;return(i==null?void 0:i.name)==="AbortError"||(i==null?void 0:i.code)==="ABORT_ERR"?(l="",c="Request was aborted (timeout or manual cancellation)",A>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${A} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((f==null?void 0:f.name)==="HeadersOverflowError"||(f==null?void 0:f.code)==="UND_ERR_HEADERS_OVERFLOW")&&(l="",c="HTTP headers exceeded server limits (typically 16KB)",A>this.urlLengthLimit&&(c+=`. Your request URL is ${A} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(o=i==null?void 0:i.name)!==null&&o!==void 0?o:"FetchError"}: ${i==null?void 0:i.message}`,details:u,hint:c,code:l},data:null,count:null,status:0,statusText:""}})),s.then(r,e)}returns(){return this}overrideTypes(){return this}},zR=class extends qR{select(r){let e=!1,t=(r!=null?r:"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",t),this.headers.append("Prefer","return=representation"),this}order(r,{ascending:e=!0,nullsFirst:t,foreignTable:n,referencedTable:s=n}={}){let i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${r}.${e?"asc":"desc"}${t===void 0?"":t?".nullsfirst":".nullslast"}`),this}limit(r,{foreignTable:e,referencedTable:t=e}={}){let n=typeof t=="undefined"?"limit":`${t}.limit`;return this.url.searchParams.set(n,`${r}`),this}range(r,e,{foreignTable:t,referencedTable:n=t}={}){let s=typeof n=="undefined"?"offset":`${n}.offset`,i=typeof n=="undefined"?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${r}`),this.url.searchParams.set(i,`${e-r+1}`),this}abortSignal(r){return this.signal=r,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:r=!1,verbose:e=!1,settings:t=!1,buffers:n=!1,wal:s=!1,format:i="text"}={}){var o;let u=[r?"analyze":null,e?"verbose":null,t?"settings":null,n?"buffers":null,s?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${u};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(r){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${r}`),this}},d_=new RegExp("[,()]"),os=class extends zR{eq(r,e){return this.url.searchParams.append(r,`eq.${e}`),this}neq(r,e){return this.url.searchParams.append(r,`neq.${e}`),this}gt(r,e){return this.url.searchParams.append(r,`gt.${e}`),this}gte(r,e){return this.url.searchParams.append(r,`gte.${e}`),this}lt(r,e){return this.url.searchParams.append(r,`lt.${e}`),this}lte(r,e){return this.url.searchParams.append(r,`lte.${e}`),this}like(r,e){return this.url.searchParams.append(r,`like.${e}`),this}likeAllOf(r,e){return this.url.searchParams.append(r,`like(all).{${e.join(",")}}`),this}likeAnyOf(r,e){return this.url.searchParams.append(r,`like(any).{${e.join(",")}}`),this}ilike(r,e){return this.url.searchParams.append(r,`ilike.${e}`),this}ilikeAllOf(r,e){return this.url.searchParams.append(r,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(r,e){return this.url.searchParams.append(r,`ilike(any).{${e.join(",")}}`),this}regexMatch(r,e){return this.url.searchParams.append(r,`match.${e}`),this}regexIMatch(r,e){return this.url.searchParams.append(r,`imatch.${e}`),this}is(r,e){return this.url.searchParams.append(r,`is.${e}`),this}isDistinct(r,e){return this.url.searchParams.append(r,`isdistinct.${e}`),this}in(r,e){let t=Array.from(new Set(e)).map(n=>typeof n=="string"&&d_.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(r,`in.(${t})`),this}notIn(r,e){let t=Array.from(new Set(e)).map(n=>typeof n=="string"&&d_.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(r,`not.in.(${t})`),this}contains(r,e){return typeof e=="string"?this.url.searchParams.append(r,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(r,`cs.{${e.join(",")}}`):this.url.searchParams.append(r,`cs.${JSON.stringify(e)}`),this}containedBy(r,e){return typeof e=="string"?this.url.searchParams.append(r,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(r,`cd.{${e.join(",")}}`):this.url.searchParams.append(r,`cd.${JSON.stringify(e)}`),this}rangeGt(r,e){return this.url.searchParams.append(r,`sr.${e}`),this}rangeGte(r,e){return this.url.searchParams.append(r,`nxl.${e}`),this}rangeLt(r,e){return this.url.searchParams.append(r,`sl.${e}`),this}rangeLte(r,e){return this.url.searchParams.append(r,`nxr.${e}`),this}rangeAdjacent(r,e){return this.url.searchParams.append(r,`adj.${e}`),this}overlaps(r,e){return typeof e=="string"?this.url.searchParams.append(r,`ov.${e}`):this.url.searchParams.append(r,`ov.{${e.join(",")}}`),this}textSearch(r,e,{config:t,type:n}={}){let s="";n==="plain"?s="pl":n==="phrase"?s="ph":n==="websearch"&&(s="w");let i=t===void 0?"":`(${t})`;return this.url.searchParams.append(r,`${s}fts${i}.${e}`),this}match(r){return Object.entries(r).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(r,e,t){return this.url.searchParams.append(r,`not.${e}.${t}`),this}or(r,{foreignTable:e,referencedTable:t=e}={}){let n=t?`${t}.or`:"or";return this.url.searchParams.append(n,`(${r})`),this}filter(r,e,t){return this.url.searchParams.append(r,`${e}.${t}`),this}},KR=class{constructor(r,{headers:e={},schema:t,fetch:n,urlLengthLimit:s=8e3}){this.url=r,this.headers=new Headers(e),this.schema=t,this.fetch=n,this.urlLengthLimit=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(r,e){let{head:t=!1,count:n}=e!=null?e:{},s=t?"HEAD":"GET",i=!1,o=(r!=null?r:"*").split("").map(l=>/\s/.test(l)&&!i?"":(l==='"'&&(i=!i),l)).join(""),{url:u,headers:c}=this.cloneRequestState();return u.searchParams.set("select",o),n&&c.append("Prefer",`count=${n}`),new os({method:s,url:u,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(r,{count:e,defaultToNull:t=!0}={}){var n;let s="POST",{url:i,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),t||o.append("Prefer","missing=default"),Array.isArray(r)){let u=r.reduce((c,l)=>c.concat(Object.keys(l)),[]);if(u.length>0){let c=[...new Set(u)].map(l=>`"${l}"`);i.searchParams.set("columns",c.join(","))}}return new os({method:s,url:i,headers:o,schema:this.schema,body:r,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(r,{onConflict:e,ignoreDuplicates:t=!1,count:n,defaultToNull:s=!0}={}){var i;let o="POST",{url:u,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${t?"ignore":"merge"}-duplicates`),e!==void 0&&u.searchParams.set("on_conflict",e),n&&c.append("Prefer",`count=${n}`),s||c.append("Prefer","missing=default"),Array.isArray(r)){let l=r.reduce((f,p)=>f.concat(Object.keys(p)),[]);if(l.length>0){let f=[...new Set(l)].map(p=>`"${p}"`);u.searchParams.set("columns",f.join(","))}}return new os({method:o,url:u,headers:c,schema:this.schema,body:r,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(r,{count:e}={}){var t;let n="PATCH",{url:s,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new os({method:n,url:s,headers:i,schema:this.schema,body:r,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:r}={}){var e;let t="DELETE",{url:n,headers:s}=this.cloneRequestState();return r&&s.append("Prefer",`count=${r}`),new os({method:t,url:n,headers:s,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function mi(r){"@babel/helpers - typeof";return mi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},mi(r)}function GR(r,e){if(mi(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e||"default");if(mi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function WR(r){var e=GR(r,"string");return mi(e)=="symbol"?e:e+""}function HR(r,e,t){return(e=WR(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function f_(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,n)}return t}function Ra(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?f_(Object(t),!0).forEach(function(n){HR(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):f_(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var m_=class g_{constructor(e,{headers:t={},schema:n,fetch:s,timeout:i,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new Headers(t),this.schemaName=n,this.urlLengthLimit=o;let u=s!=null?s:globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,l)=>{let f=new AbortController,p=setTimeout(()=>f.abort(),i),g=l==null?void 0:l.signal;if(g){if(g.aborted)return clearTimeout(p),u(c,l);let y=()=>{clearTimeout(p),f.abort()};return g.addEventListener("abort",y,{once:!0}),u(c,Ra(Ra({},l),{},{signal:f.signal})).finally(()=>{clearTimeout(p),g.removeEventListener("abort",y)})}return u(c,Ra(Ra({},l),{},{signal:f.signal})).finally(()=>clearTimeout(p))}:this.fetch=u}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new KR(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new g_(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,t={},{head:n=!1,get:s=!1,count:i}={}){var o;let u,c=new URL(`${this.url}/rpc/${e}`),l,f=y=>y!==null&&typeof y=="object"&&(!Array.isArray(y)||y.some(f)),p=n&&Object.values(t).some(f);p?(u="POST",l=t):n||s?(u=n?"HEAD":"GET",Object.entries(t).filter(([y,I])=>I!==void 0).map(([y,I])=>[y,Array.isArray(I)?`{${I.join(",")}}`:`${I}`]).forEach(([y,I])=>{c.searchParams.append(y,I)})):(u="POST",l=t);let g=new Headers(this.headers);return p?g.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&g.set("Prefer",`count=${i}`),new os({method:u,url:c,headers:g,schema:this.schemaName,body:l,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};var ah=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket!="undefined")return{type:"native",constructor:WebSocket};if(typeof globalThis!="undefined"&&typeof globalThis.WebSocket!="undefined")return{type:"native",constructor:globalThis.WebSocket};if(typeof global!="undefined"&&typeof global.WebSocket!="undefined")return{type:"native",constructor:global.WebSocket};if(typeof globalThis!="undefined"&&typeof globalThis.WebSocketPair!="undefined"&&typeof globalThis.WebSocket=="undefined")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis!="undefined"&&globalThis.EdgeRuntime||typeof navigator!="undefined"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let t=globalThis.process;if(t){let n=t.versions;if(n&&n.node){let s=n.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket!="undefined"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
40
26
|
import ws from "ws"
|
|
41
27
|
new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`
|
|
42
28
|
|
|
43
|
-
Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){let n=this.getWebSocketConstructor();return new n(e,t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}},hh=lh;var m_="2.97.0";var g_=`realtime-js/${m_}`,y_="1.0.0",dh="2.0.0",fh=dh;var li=1e4,__=1e3,v_=100,Nt;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(Nt||(Nt={}));var ve;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(ve||(ve={}));var ze;(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"})(ze||(ze={}));var Ia;(function(r){r.websocket="websocket"})(Ia||(Ia={}));var fr;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(fr||(fr={}));var hi=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e!=null?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return t(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer((t=e.payload)===null||t===void 0?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,n;let s=(n=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,n;let s=(n=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,t,n){var s,i;let o=e.topic,u=(s=e.ref)!==null&&s!==void 0?s:"",c=(i=e.join_ref)!==null&&i!==void 0?i:"",h=e.payload.event,f=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},p=Object.keys(f).length===0?"":JSON.stringify(f);if(c.length>255)throw new Error(`joinRef length ${c.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`ref length ${u.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`userEvent length ${h.length} exceeds maximum of 255`);if(p.length>255)throw new Error(`metadata length ${p.length} exceeds maximum of 255`);let m=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+u.length+o.length+h.length+p.length,y=new ArrayBuffer(this.HEADER_LENGTH+m),T=new DataView(y),R=0;T.setUint8(R++,this.KINDS.userBroadcastPush),T.setUint8(R++,c.length),T.setUint8(R++,u.length),T.setUint8(R++,o.length),T.setUint8(R++,h.length),T.setUint8(R++,p.length),T.setUint8(R++,t),Array.from(c,k=>T.setUint8(R++,k.charCodeAt(0))),Array.from(u,k=>T.setUint8(R++,k.charCodeAt(0))),Array.from(o,k=>T.setUint8(R++,k.charCodeAt(0))),Array.from(h,k=>T.setUint8(R++,k.charCodeAt(0))),Array.from(p,k=>T.setUint8(R++,k.charCodeAt(0)));var I=new Uint8Array(y.byteLength+n.byteLength);return I.set(new Uint8Array(y),0),I.set(new Uint8Array(n),y.byteLength),I.buffer}decode(e,t){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return t(n)}if(typeof e=="string"){let n=JSON.parse(e),[s,i,o,u,c]=n;return t({join_ref:s,ref:i,topic:o,event:u,payload:c})}return t({})}_binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),s=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,t,s)}}_decodeUserBroadcast(e,t,n){let s=t.getUint8(1),i=t.getUint8(2),o=t.getUint8(3),u=t.getUint8(4),c=this.HEADER_LENGTH+4,h=n.decode(e.slice(c,c+s));c=c+s;let f=n.decode(e.slice(c,c+i));c=c+i;let p=n.decode(e.slice(c,c+o));c=c+o;let m=e.slice(c,e.byteLength),y=u===this.JSON_ENCODING?JSON.parse(n.decode(m)):m,T={type:this.BROADCAST_EVENT,event:f,payload:y};return o>0&&(T.meta=JSON.parse(p)),{join_ref:null,ref:null,topic:h,event:this.BROADCAST_EVENT,payload:T}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||((t=e==null?void 0:e.constructor)===null||t===void 0?void 0:t.name)==="ArrayBuffer"}_pick(e,t){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>t.includes(n)))}};var Lr=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),this.timer=void 0}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 mh=(r,e,t={})=>{var n;let s=(n=t.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=cP(o,r,e,s),i),{}):{}},cP=(r,e,t,n)=>{let s=e.find(u=>u.name===r),i=s==null?void 0:s.type,o=t[r];return i&&!n.includes(i)?w_(i,o):ph(o)},w_=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return fP(e,t)}switch(r){case se.bool:return lP(e);case se.float4:case se.float8:case se.int2:case se.int4:case se.int8:case se.numeric:case se.oid:return hP(e);case se.json:case se.jsonb:return dP(e);case se.timestamp:return pP(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 ph(e);default:return ph(e)}},ph=r=>r,lP=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},hP=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},dP=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch{return r}return r},fP=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,n=r[t];if(r[0]==="{"&&n==="}"){let i,o=r.slice(1,t);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(u=>w_(e,u))}return r},pP=r=>typeof r=="string"?r.replace(" ","T"):r,Sa=r=>{let e=new URL(r);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var Fr=class{constructor(e,t,n={},s=li){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 gh;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(gh||(gh={}));var es=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,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:o,onSync:u}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,s,i,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,i,o)}),this.pendingDiffs=[],u()}),this.channel._on(n.diff,{},s=>{let{onJoin:i,onLeave:o,onSync:u}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=r.syncDiff(this.state,s,i,o),u())}),this.onJoin((s,i,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:o})}),this.onLeave((s,i,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,n,s){let i=this.cloneDeep(e),o=this.transformState(t),u={},c={};return this.map(i,(h,f)=>{o[h]||(c[h]=f)}),this.map(o,(h,f)=>{let p=i[h];if(p){let m=f.map(I=>I.presence_ref),y=p.map(I=>I.presence_ref),T=f.filter(I=>y.indexOf(I.presence_ref)<0),R=p.filter(I=>m.indexOf(I.presence_ref)<0);T.length>0&&(u[h]=T),R.length>0&&(c[h]=R)}else u[h]=f}),this.syncDiff(i,{joins:u,leaves:c},n,s)}static syncDiff(e,t,n,s){let{joins:i,leaves:o}={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 p=e[u].map(y=>y.presence_ref),m=f.filter(y=>p.indexOf(y.presence_ref)<0);e[u].unshift(...m)}n(u,f,c)}),this.map(o,(u,c)=>{let h=e[u];if(!h)return;let f=c.map(p=>p.presence_ref);h=h.filter(p=>f.indexOf(p.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 yh;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(yh||(yh={}));var ts;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(ts||(ts={}));var mt;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(mt||(mt={}));var rs=class r{constructor(e,t={config:{}},n){var s,i;if(this.topic=e,this.params=t,this.socket=n,this.bindings={},this.state=ve.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new Fr(this,ze.join,this.params,this.timeout),this.rejoinTimer=new Lr(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=ve.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=ve.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=ve.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=ve.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=ve.errored,this.rejoinTimer.scheduleTimeout())}),this._on(ze.reply,{},(o,u)=>{this._trigger(this._replyEventName(u),o)}),this.presence=new es(this),this.broadcastEndpointURL=Sa(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var n,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==ve.closed){let{config:{broadcast:o,presence:u,private:c}}=this.params,h=(s=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(y=>y.filter))!==null&&s!==void 0?s:[],f=!!this.bindings[ts.PRESENCE]&&this.bindings[ts.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,p={},m={broadcast:o,presence:Object.assign(Object.assign({},u),{enabled:f}),postgres_changes:h,private:c};this.socket.accessTokenValue&&(p.access_token=this.socket.accessTokenValue),this._onError(y=>e==null?void 0:e(mt.CHANNEL_ERROR,y)),this._onClose(()=>e==null?void 0:e(mt.CLOSED)),this.updateJoinPayload(Object.assign({config:m},p)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:y})=>{var T;if(this.socket._isManualToken()||this.socket.setAuth(),y===void 0){e==null||e(mt.SUBSCRIBED);return}else{let R=this.bindings.postgres_changes,I=(T=R==null?void 0:R.length)!==null&&T!==void 0?T:0,k=[];for(let O=0;O<I;O++){let D=R[O],{filter:{event:j,schema:H,table:F,filter:E}}=D,_=y&&y[O];if(_&&_.event===j&&r.isFilterValueEqual(_.schema,H)&&r.isFilterValueEqual(_.table,F)&&r.isFilterValueEqual(_.filter,E))k.push(Object.assign(Object.assign({},D),{id:_.id}));else{this.unsubscribe(),this.state=ve.errored,e==null||e(mt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=k,e&&e(mt.SUBSCRIBED);return}}).receive("error",y=>{this.state=ve.errored,e==null||e(mt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(y).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(mt.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.state===ve.joined&&e===ts.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,n)}async httpSend(e,t,n={}){var s;if(t==null)return Promise.reject("Payload is required for httpSend()");let i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},u=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(s=n.timeout)!==null&&s!==void 0?s:this.timeout);if(u.status===202)return{success:!0};let c=u.statusText;try{let h=await u.json();c=h.error||h.message||c}catch{}return Promise.reject(new Error(c))}async send(e,t={}){var n,s;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:i,payload:o}=e,u={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(u.Authorization=`Bearer ${this.socket.accessTokenValue}`);let c={method:"POST",headers:u,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,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 o,u,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(u=(o=this.params)===null||o===void 0?void 0:o.config)===null||u===void 0?void 0:u.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),h.receive("ok",()=>i("ok")),h.receive("error",()=>i("error")),h.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=ve.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(ze.close,"leave",this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(s=>{n=new Fr(this,ze.leave,{},e),n.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),n.send(),this._canPush()||n.trigger("ok",{})}).finally(()=>{n==null||n.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=ve.closed,this.bindings={}}async _fetchWithTimeout(e,t,n){let s=new AbortController,i=setTimeout(()=>s.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(i),o}_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 Fr(this,e,t,n);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>v_){let t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload))}}_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 o=e.toLocaleLowerCase(),{close:u,error:c,leave:h,join:f}=ze;if(n&&[u,c,h,f].indexOf(o)>=0&&n!==this._joinRef())return;let m=this._onMessage(o,t,n);if(t&&!m)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(y=>{var T,R,I;return((T=y.filter)===null||T===void 0?void 0:T.event)==="*"||((I=(R=y.filter)===null||R===void 0?void 0:R.event)===null||I===void 0?void 0:I.toLocaleLowerCase())===o}).map(y=>y.callback(m,n)):(i=this.bindings[o])===null||i===void 0||i.filter(y=>{var T,R,I,k,O,D;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in y){let j=y.id,H=(T=y.filter)===null||T===void 0?void 0:T.event;return j&&((R=t.ids)===null||R===void 0?void 0:R.includes(j))&&(H==="*"||(H==null?void 0:H.toLocaleLowerCase())===((I=t.data)===null||I===void 0?void 0:I.type.toLocaleLowerCase()))}else{let j=(O=(k=y==null?void 0:y.filter)===null||k===void 0?void 0:k.event)===null||O===void 0?void 0:O.toLocaleLowerCase();return j==="*"||j===((D=t==null?void 0:t.event)===null||D===void 0?void 0:D.toLocaleLowerCase())}else return y.type.toLocaleLowerCase()===o}).map(y=>{if(typeof m=="object"&&"ids"in m){let T=m.data,{schema:R,table:I,commit_timestamp:k,type:O,errors:D}=T;m=Object.assign(Object.assign({},{schema:R,table:I,commit_timestamp:k,eventType:O,new:{},old:{},errors:D}),this._getPayloadRecords(T))}y.callback(m,n)})}_isClosed(){return this.state===ve.closed}_isJoined(){return this.state===ve.joined}_isJoining(){return this.state===ve.joining}_isLeaving(){return this.state===ve.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,n){let s=e.toLocaleLowerCase(),i={type:s,filter:t,callback:n};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,t){let n=e.toLocaleLowerCase();return this.bindings[n]&&(this.bindings[n]=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}static isFilterValueEqual(e,t){let n=e!=null?e:void 0,s=t!=null?t:void 0;return n===s}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(ze.close,{},e)}_onError(e){this._on(ze.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=ve.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=mh(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=mh(e.columns,e.old_record)),t}};var _h=()=>{},Aa={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},gP=[1e3,2e3,5e3,1e4],yP=1e4,_P=`
|
|
29
|
+
Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){let n=this.getWebSocketConstructor();return new n(e,t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}},uh=ah;var y_="2.99.1";var __=`realtime-js/${y_}`,w_="1.0.0",ch="2.0.0",lh=ch;var gi=1e4,v_=1e3,b_=100,Ft;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(Ft||(Ft={}));var ve;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(ve||(ve={}));var qe;(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"})(qe||(qe={}));var Pa;(function(r){r.websocket="websocket"})(Pa||(Pa={}));var fr;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(fr||(fr={}));var yi=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e!=null?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return t(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer((t=e.payload)===null||t===void 0?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,n;let s=(n=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,n;let s=(n=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,t,n){var s,i;let o=e.topic,u=(s=e.ref)!==null&&s!==void 0?s:"",c=(i=e.join_ref)!==null&&i!==void 0?i:"",l=e.payload.event,f=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},p=Object.keys(f).length===0?"":JSON.stringify(f);if(c.length>255)throw new Error(`joinRef length ${c.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`ref length ${u.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`userEvent length ${l.length} exceeds maximum of 255`);if(p.length>255)throw new Error(`metadata length ${p.length} exceeds maximum of 255`);let g=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+u.length+o.length+l.length+p.length,y=new ArrayBuffer(this.HEADER_LENGTH+g),I=new DataView(y),R=0;I.setUint8(R++,this.KINDS.userBroadcastPush),I.setUint8(R++,c.length),I.setUint8(R++,u.length),I.setUint8(R++,o.length),I.setUint8(R++,l.length),I.setUint8(R++,p.length),I.setUint8(R++,t),Array.from(c,k=>I.setUint8(R++,k.charCodeAt(0))),Array.from(u,k=>I.setUint8(R++,k.charCodeAt(0))),Array.from(o,k=>I.setUint8(R++,k.charCodeAt(0))),Array.from(l,k=>I.setUint8(R++,k.charCodeAt(0))),Array.from(p,k=>I.setUint8(R++,k.charCodeAt(0)));var A=new Uint8Array(y.byteLength+n.byteLength);return A.set(new Uint8Array(y),0),A.set(new Uint8Array(n),y.byteLength),A.buffer}decode(e,t){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return t(n)}if(typeof e=="string"){let n=JSON.parse(e),[s,i,o,u,c]=n;return t({join_ref:s,ref:i,topic:o,event:u,payload:c})}return t({})}_binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),s=new TextDecoder;if(n===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s)}_decodeUserBroadcast(e,t,n){let s=t.getUint8(1),i=t.getUint8(2),o=t.getUint8(3),u=t.getUint8(4),c=this.HEADER_LENGTH+4,l=n.decode(e.slice(c,c+s));c=c+s;let f=n.decode(e.slice(c,c+i));c=c+i;let p=n.decode(e.slice(c,c+o));c=c+o;let g=e.slice(c,e.byteLength),y=u===this.JSON_ENCODING?JSON.parse(n.decode(g)):g,I={type:this.BROADCAST_EVENT,event:f,payload:y};return o>0&&(I.meta=JSON.parse(p)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:I}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||((t=e==null?void 0:e.constructor)===null||t===void 0?void 0:t.name)==="ArrayBuffer"}_pick(e,t){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>t.includes(n)))}};var zr=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),this.timer=void 0}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 dh=(r,e,t={})=>{var n;let s=(n=t.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=JR(o,r,e,s),i),{}):{}},JR=(r,e,t,n)=>{let s=e.find(u=>u.name===r),i=s==null?void 0:s.type,o=t[r];return i&&!n.includes(i)?E_(i,o):hh(o)},E_=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return ZR(e,t)}switch(r){case se.bool:return QR(e);case se.float4:case se.float8:case se.int2:case se.int4:case se.int8:case se.numeric:case se.oid:return YR(e);case se.json:case se.jsonb:return XR(e);case se.timestamp:return eP(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 hh(e);default:return hh(e)}},hh=r=>r,QR=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},YR=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},XR=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch{return r}return r},ZR=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,n=r[t];if(r[0]==="{"&&n==="}"){let i,o=r.slice(1,t);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(u=>E_(e,u))}return r},eP=r=>typeof r=="string"?r.replace(" ","T"):r,Ca=r=>{let e=new URL(r);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var Kr=class{constructor(e,t,n={},s=gi){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 fh;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(fh||(fh={}));var as=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,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:o,onSync:u}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,s,i,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,i,o)}),this.pendingDiffs=[],u()}),this.channel._on(n.diff,{},s=>{let{onJoin:i,onLeave:o,onSync:u}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=r.syncDiff(this.state,s,i,o),u())}),this.onJoin((s,i,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:o})}),this.onLeave((s,i,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,n,s){let i=this.cloneDeep(e),o=this.transformState(t),u={},c={};return this.map(i,(l,f)=>{o[l]||(c[l]=f)}),this.map(o,(l,f)=>{let p=i[l];if(p){let g=f.map(A=>A.presence_ref),y=p.map(A=>A.presence_ref),I=f.filter(A=>y.indexOf(A.presence_ref)<0),R=p.filter(A=>g.indexOf(A.presence_ref)<0);I.length>0&&(u[l]=I),R.length>0&&(c[l]=R)}else u[l]=f}),this.syncDiff(i,{joins:u,leaves:c},n,s)}static syncDiff(e,t,n,s){let{joins:i,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return n||(n=()=>{}),s||(s=()=>{}),this.map(i,(u,c)=>{var l;let f=(l=e[u])!==null&&l!==void 0?l:[];if(e[u]=this.cloneDeep(c),f.length>0){let p=e[u].map(y=>y.presence_ref),g=f.filter(y=>p.indexOf(y.presence_ref)<0);e[u].unshift(...g)}n(u,f,c)}),this.map(o,(u,c)=>{let l=e[u];if(!l)return;let f=c.map(p=>p.presence_ref);l=l.filter(p=>f.indexOf(p.presence_ref)<0),e[u]=l,s(u,l,c),l.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 ph;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(ph||(ph={}));var us;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(us||(us={}));var _t;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(_t||(_t={}));var cs=class r{constructor(e,t={config:{}},n){var s,i;if(this.topic=e,this.params=t,this.socket=n,this.bindings={},this.state=ve.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new Kr(this,qe.join,this.params,this.timeout),this.rejoinTimer=new zr(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=ve.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=ve.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=ve.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=ve.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=ve.errored,this.rejoinTimer.scheduleTimeout())}),this._on(qe.reply,{},(o,u)=>{this._trigger(this._replyEventName(u),o)}),this.presence=new as(this),this.broadcastEndpointURL=Ca(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var n,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==ve.closed){let{config:{broadcast:o,presence:u,private:c}}=this.params,l=(s=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(y=>y.filter))!==null&&s!==void 0?s:[],f=!!this.bindings[us.PRESENCE]&&this.bindings[us.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,p={},g={broadcast:o,presence:Object.assign(Object.assign({},u),{enabled:f}),postgres_changes:l,private:c};this.socket.accessTokenValue&&(p.access_token=this.socket.accessTokenValue),this._onError(y=>e==null?void 0:e(_t.CHANNEL_ERROR,y)),this._onClose(()=>e==null?void 0:e(_t.CLOSED)),this.updateJoinPayload(Object.assign({config:g},p)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:y})=>{var I;if(this.socket._isManualToken()||this.socket.setAuth(),y===void 0){e==null||e(_t.SUBSCRIBED);return}else{let R=this.bindings.postgres_changes,A=(I=R==null?void 0:R.length)!==null&&I!==void 0?I:0,k=[];for(let D=0;D<A;D++){let N=R[D],{filter:{event:U,schema:z,table:F,filter:E}}=N,_=y&&y[D];if(_&&_.event===U&&r.isFilterValueEqual(_.schema,z)&&r.isFilterValueEqual(_.table,F)&&r.isFilterValueEqual(_.filter,E))k.push(Object.assign(Object.assign({},N),{id:_.id}));else{this.unsubscribe(),this.state=ve.errored,e==null||e(_t.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=k,e&&e(_t.SUBSCRIBED);return}}).receive("error",y=>{this.state=ve.errored,e==null||e(_t.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(y).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(_t.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.state===ve.joined&&e===us.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,n)}async httpSend(e,t,n={}){var s;if(t==null)return Promise.reject("Payload is required for httpSend()");let i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},u=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(s=n.timeout)!==null&&s!==void 0?s:this.timeout);if(u.status===202)return{success:!0};let c=u.statusText;try{let l=await u.json();c=l.error||l.message||c}catch{}return Promise.reject(new Error(c))}async send(e,t={}){var n,s;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:i,payload:o}=e,u={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(u.Authorization=`Bearer ${this.socket.accessTokenValue}`);let c={method:"POST",headers:u,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{let l=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(n=t.timeout)!==null&&n!==void 0?n:this.timeout);return await((s=l.body)===null||s===void 0?void 0:s.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,u,c;let l=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(u=(o=this.params)===null||o===void 0?void 0:o.config)===null||u===void 0?void 0:u.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),l.receive("ok",()=>i("ok")),l.receive("error",()=>i("error")),l.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=ve.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(qe.close,"leave",this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(s=>{n=new Kr(this,qe.leave,{},e),n.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),n.send(),this._canPush()||n.trigger("ok",{})}).finally(()=>{n==null||n.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=ve.closed,this.bindings={}}async _fetchWithTimeout(e,t,n){let s=new AbortController,i=setTimeout(()=>s.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(i),o}_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 Kr(this,e,t,n);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>b_){let t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload))}}_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 o=e.toLocaleLowerCase(),{close:u,error:c,leave:l,join:f}=qe;if(n&&[u,c,l,f].indexOf(o)>=0&&n!==this._joinRef())return;let g=this._onMessage(o,t,n);if(t&&!g)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(y=>{var I,R,A;return((I=y.filter)===null||I===void 0?void 0:I.event)==="*"||((A=(R=y.filter)===null||R===void 0?void 0:R.event)===null||A===void 0?void 0:A.toLocaleLowerCase())===o}).map(y=>y.callback(g,n)):(i=this.bindings[o])===null||i===void 0||i.filter(y=>{var I,R,A,k,D,N;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in y){let U=y.id,z=(I=y.filter)===null||I===void 0?void 0:I.event;return U&&((R=t.ids)===null||R===void 0?void 0:R.includes(U))&&(z==="*"||(z==null?void 0:z.toLocaleLowerCase())===((A=t.data)===null||A===void 0?void 0:A.type.toLocaleLowerCase()))}else{let U=(D=(k=y==null?void 0:y.filter)===null||k===void 0?void 0:k.event)===null||D===void 0?void 0:D.toLocaleLowerCase();return U==="*"||U===((N=t==null?void 0:t.event)===null||N===void 0?void 0:N.toLocaleLowerCase())}else return y.type.toLocaleLowerCase()===o}).map(y=>{if(typeof g=="object"&&"ids"in g){let I=g.data,{schema:R,table:A,commit_timestamp:k,type:D,errors:N}=I;g=Object.assign(Object.assign({},{schema:R,table:A,commit_timestamp:k,eventType:D,new:{},old:{},errors:N}),this._getPayloadRecords(I))}y.callback(g,n)})}_isClosed(){return this.state===ve.closed}_isJoined(){return this.state===ve.joined}_isJoining(){return this.state===ve.joining}_isLeaving(){return this.state===ve.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,n){let s=e.toLocaleLowerCase(),i={type:s,filter:t,callback:n};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,t){let n=e.toLocaleLowerCase();return this.bindings[n]&&(this.bindings[n]=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}static isFilterValueEqual(e,t){let n=e!=null?e:void 0,s=t!=null?t:void 0;return n===s}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(qe.close,{},e)}_onError(e){this._on(qe.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=ve.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=dh(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=dh(e.columns,e.old_record)),t}};var mh=()=>{},ka={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},rP=[1e3,2e3,5e3,1e4],nP=1e4,sP=`
|
|
44
30
|
addEventListener("message", (e) => {
|
|
45
31
|
if (e.data.event === "start") {
|
|
46
32
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
47
33
|
}
|
|
48
|
-
});`,
|
|
34
|
+
});`,ls=class{constructor(e,t){var n;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=gi,this.transport=null,this.heartbeatIntervalMs=ka.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=mh,this.ref=0,this.reconnectTimer=null,this.vsn=lh,this.logger=mh,this.conn=null,this.sendBuffer=[],this.serializer=new yi,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((n=t==null?void 0:t.params)===null||n===void 0)&&n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Pa.websocket}`,this.httpEndpoint=Ca(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t==null?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=uh.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");let t=e.message;throw t.includes("Node.js")?new Error(`${t}
|
|
49
35
|
|
|
50
36
|
To use Realtime in Node.js, you need to provide a WebSocket implementation:
|
|
51
37
|
|
|
@@ -58,24 +44,24 @@ Option 2: Install and provide the "ws" package:
|
|
|
58
44
|
const client = new RealtimeClient(url, {
|
|
59
45
|
...options,
|
|
60
46
|
transport: ws
|
|
61
|
-
})`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){let n=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,t!=null?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}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.channels=[],this.disconnect(),e}log(e,t,n){this.logger(e,t,n)}connectionState(){switch(this.conn&&this.conn.readyState){case Nt.connecting:return fr.Connecting;case Nt.open:return fr.Open;case Nt.closing:return fr.Closing;default:return fr.Closed}}isConnected(){return this.connectionState()===fr.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){let n=`realtime:${e}`,s=this.getChannels().find(i=>i.topic===n);if(s)return s;{let i=new rs(`realtime:${e}`,t,this);return this.channels.push(i),i}}push(e){let{topic:t,event:n,payload:s,ref:i}=e,o=()=>{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()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(__,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},Aa.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}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.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply"&&t.ref&&t.ref===this.pendingHeartbeatRef){let h=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error",h)}catch(f){this.log("error","error in heartbeat callback",f)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}let{topic:n,event:s,payload:i,ref:o}=t,u=o?`(${o})`:"",c=i.status||"";this.log("receive",`${c} ${n} ${s} ${u}`.trim(),i),this.channels.filter(h=>h._isMember(n)).forEach(h=>h._trigger(s,i,o)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in 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),this.conn.readyState===Nt.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===Nt.open||this.conn.readyState===Nt.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(t=>{this.log("error","error waiting for auth on connect",t),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){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._terminateWorker()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(t){this.log("error","error in heartbeat callback",t)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(ze.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([_P],{type:"application/javascript"});t=URL.createObjectURL(n)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,n=!1;if(e)t=e,n=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),t=this.accessTokenValue}else t=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(s=>{let i={access_token:t,version:g_};t&&s.updateJoinPayload(i),s.joinedOnce&&s._isJoined()&&s._push(ze.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(n=>{try{n(t)}catch(s){this.log("error",`error in ${e} callback`,s)}})}catch(n){this.log("error",`error triggering ${e} callbacks`,n)}}_setupReconnectionTimer(){this.reconnectTimer=new Lr(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Aa.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,n,s,i,o,u,c,h,f,p,m,y;switch(this.transport=(t=e==null?void 0:e.transport)!==null&&t!==void 0?t:null,this.timeout=(n=e==null?void 0:e.timeout)!==null&&n!==void 0?n:li,this.heartbeatIntervalMs=(s=e==null?void 0:e.heartbeatIntervalMs)!==null&&s!==void 0?s:Aa.HEARTBEAT_INTERVAL,this.worker=(i=e==null?void 0:e.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=e==null?void 0:e.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(u=e==null?void 0:e.heartbeatCallback)!==null&&u!==void 0?u:_h,this.vsn=(c=e==null?void 0:e.vsn)!==null&&c!==void 0?c:fh,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(h=e==null?void 0:e.reconnectAfterMs)!==null&&h!==void 0?h:(T=>gP[T-1]||yP),this.vsn){case y_:this.encode=(f=e==null?void 0:e.encode)!==null&&f!==void 0?f:((T,R)=>R(JSON.stringify(T))),this.decode=(p=e==null?void 0:e.decode)!==null&&p!==void 0?p:((T,R)=>R(JSON.parse(T)));break;case dh:this.encode=(m=e==null?void 0:e.encode)!==null&&m!==void 0?m:this.serializer.encode.bind(this.serializer),this.decode=(y=e==null?void 0:e.decode)!==null&&y!==void 0?y:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window!="undefined"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}};var di=class extends Error{constructor(r,e){var t;super(r),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&((t=e.icebergType)==null?void 0:t.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function vP(r,e,t){let n=new URL(e,r);if(t)for(let[s,i]of Object.entries(t))i!==void 0&&n.searchParams.set(s,i);return n.toString()}async function wP(r){return!r||r.type==="none"?{}:r.type==="bearer"?{Authorization:`Bearer ${r.token}`}:r.type==="header"?{[r.name]:r.value}:r.type==="custom"?await r.getHeaders():{}}function bP(r){var t;let e=(t=r.fetchImpl)!=null?t:globalThis.fetch;return{async request({method:n,path:s,query:i,body:o,headers:u}){var T;let c=vP(r.baseUrl,s,i),h=await wP(r.auth),f=await e(c,{method:n,headers:{...o?{"Content-Type":"application/json"}:{},...h,...u},body:o?JSON.stringify(o):void 0}),p=await f.text(),m=(f.headers.get("content-type")||"").includes("application/json"),y=m&&p?JSON.parse(p):p;if(!f.ok){let R=m?y:void 0,I=R==null?void 0:R.error;throw new di((T=I==null?void 0:I.message)!=null?T:`Request failed with status ${f.status}`,{status:f.status,icebergType:I==null?void 0:I.type,icebergCode:I==null?void 0:I.code,details:R})}return{status:f.status,headers:f.headers,data:y}}}}function xa(r){return r.join("")}var EP=class{constructor(r,e=""){this.client=r,this.prefix=e}async listNamespaces(r){let e=r?{parent:xa(r.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(r,e){let t={namespace:r.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:t})).data}async dropNamespace(r){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${xa(r.namespace)}`})}async loadNamespaceMetadata(r){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${xa(r.namespace)}`})).data.properties}}async namespaceExists(r){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${xa(r.namespace)}`}),!0}catch(e){if(e instanceof di&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(r,e){try{return await this.createNamespace(r,e)}catch(t){if(t instanceof di&&t.status===409)return;throw t}}};function ss(r){return r.join("")}var TP=class{constructor(r,e="",t){this.client=r,this.prefix=e,this.accessDelegation=t}async listTables(r){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ss(r.namespace)}/tables`})).data.identifiers}async createTable(r,e){let t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${ss(r.namespace)}/tables`,body:e,headers:t})).data.metadata}async updateTable(r,e){let t=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${ss(r.namespace)}/tables/${r.name}`,body:e});return{"metadata-location":t.data["metadata-location"],metadata:t.data.metadata}}async dropTable(r,e){var t;await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ss(r.namespace)}/tables/${r.name}`,query:{purgeRequested:String((t=e==null?void 0:e.purge)!=null?t:!1)}})}async loadTable(r){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ss(r.namespace)}/tables/${r.name}`,headers:e})).data.metadata}async tableExists(r){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ss(r.namespace)}/tables/${r.name}`,headers:e}),!0}catch(t){if(t instanceof di&&t.status===404)return!1;throw t}}async createTableIfNotExists(r,e){try{return await this.createTable(r,e)}catch(t){if(t instanceof di&&t.status===409)return await this.loadTable({namespace:r.namespace,name:e.name});throw t}}},b_=class{constructor(r){var n;let e="v1";r.catalogName&&(e+=`/${r.catalogName}`);let t=r.baseUrl.endsWith("/")?r.baseUrl:`${r.baseUrl}/`;this.client=bP({baseUrl:t,auth:r.auth,fetchImpl:r.fetch}),this.accessDelegation=(n=r.accessDelegation)==null?void 0:n.join(","),this.namespaceOps=new EP(this.client,e),this.tableOps=new TP(this.client,e,this.accessDelegation)}async listNamespaces(r){return this.namespaceOps.listNamespaces(r)}async createNamespace(r,e){return this.namespaceOps.createNamespace(r,e)}async dropNamespace(r){await this.namespaceOps.dropNamespace(r)}async loadNamespaceMetadata(r){return this.namespaceOps.loadNamespaceMetadata(r)}async listTables(r){return this.tableOps.listTables(r)}async createTable(r,e){return this.tableOps.createTable(r,e)}async updateTable(r,e){return this.tableOps.updateTable(r,e)}async dropTable(r,e){await this.tableOps.dropTable(r,e)}async loadTable(r){return this.tableOps.loadTable(r)}async namespaceExists(r){return this.namespaceOps.namespaceExists(r)}async tableExists(r){return this.tableOps.tableExists(r)}async createNamespaceIfNotExists(r,e){return this.namespaceOps.createNamespaceIfNotExists(r,e)}async createTableIfNotExists(r,e){return this.tableOps.createTableIfNotExists(r,e)}};var Pa=class extends Error{constructor(r,e="storage",t,n){super(r),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=t,this.statusCode=n}};function Ca(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Ra=class extends Pa{constructor(r,e,t,n="storage"){super(r,n,e,t),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=t}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},S_=class extends Pa{constructor(r,e,t="storage"){super(r,t),this.name=t==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var IP=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),SP=r=>{if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)},vh=r=>{if(Array.isArray(r))return r.map(t=>vh(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]=vh(n)}),e},AP=r=>!r||typeof r!="string"||r.length===0||r.length>100||r.trim()!==r||r.includes("/")||r.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(r);function pi(r){"@babel/helpers - typeof";return pi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},pi(r)}function xP(r,e){if(pi(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e||"default");if(pi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function RP(r){var e=xP(r,"string");return pi(e)=="symbol"?e:e+""}function PP(r,e,t){return(e=RP(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function E_(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,n)}return t}function q(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?E_(Object(t),!0).forEach(function(n){PP(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):E_(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var T_=r=>{var e;return r.msg||r.message||r.error_description||(typeof r.error=="string"?r.error:(e=r.error)===null||e===void 0?void 0:e.message)||JSON.stringify(r)},CP=async(r,e,t,n)=>{if(r&&typeof r=="object"&&"status"in r&&"ok"in r&&typeof r.status=="number"&&!(t!=null&&t.noResolveJson)){let s=r,i=s.status||500;if(typeof s.json=="function")s.json().then(o=>{let u=(o==null?void 0:o.statusCode)||(o==null?void 0:o.code)||i+"";e(new Ra(T_(o),i,u,n))}).catch(()=>{if(n==="vectors"){let o=i+"";e(new Ra(s.statusText||`HTTP ${i} error`,i,o,n))}else{let o=i+"";e(new Ra(s.statusText||`HTTP ${i} error`,i,o,n))}});else{let o=i+"";e(new Ra(s.statusText||`HTTP ${i} error`,i,o,n))}}else e(new S_(T_(r),r,n))},kP=(r,e,t,n)=>{let s={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"||r==="HEAD"||!n?q(q({},s),t):(SP(n)?(s.headers=q({"Content-Type":"application/json"},e==null?void 0:e.headers),s.body=JSON.stringify(n)):s.body=n,e!=null&&e.duplex&&(s.duplex=e.duplex),q(q({},s),t))};async function fi(r,e,t,n,s,i,o){return new Promise((u,c)=>{r(t,kP(e,n,s,i)).then(h=>{if(!h.ok)throw h;if(n!=null&&n.noResolveJson)return h;if(o==="vectors"){let f=h.headers.get("content-type");if(h.headers.get("content-length")==="0"||h.status===204)return{};if(!f||!f.includes("application/json"))return{}}return h.json()}).then(h=>u(h)).catch(h=>CP(h,c,n,o))})}function A_(r="storage"){return{get:async(e,t,n,s)=>fi(e,"GET",t,n,s,void 0,r),post:async(e,t,n,s,i)=>fi(e,"POST",t,s,i,n,r),put:async(e,t,n,s,i)=>fi(e,"PUT",t,s,i,n,r),head:async(e,t,n,s)=>fi(e,"HEAD",t,q(q({},n),{},{noResolveJson:!0}),s,void 0,r),remove:async(e,t,n,s,i)=>fi(e,"DELETE",t,s,i,n,r)}}var OP=A_("storage"),{get:mi,post:rt,put:wh,head:DP,remove:bh}=OP,Ke=A_("vectors"),is=class{constructor(r,e={},t,n="storage"){this.shouldThrowOnError=!1,this.url=r,this.headers=e,this.fetch=IP(t),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(r,e){return this.headers=q(q({},this.headers),{},{[r]:e}),this}async handleOperation(r){var e=this;try{return{data:await r(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ca(t))return{data:null,error:t};throw t}}},NP=class{constructor(r,e){this.downloadFn=r,this.shouldThrowOnError=e}then(r,e){return this.execute().then(r,e)}async execute(){var r=this;try{return{data:(await r.downloadFn()).body,error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Ca(e))return{data:null,error:e};throw e}}},x_;x_=Symbol.toStringTag;var VP=class{constructor(r,e){this.downloadFn=r,this.shouldThrowOnError=e,this[x_]="BlobDownloadBuilder",this.promise=null}asStream(){return new NP(this.downloadFn,this.shouldThrowOnError)}then(r,e){return this.getPromise().then(r,e)}catch(r){return this.getPromise().catch(r)}finally(r){return this.getPromise().finally(r)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var r=this;try{return{data:await(await r.downloadFn()).blob(),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Ca(e))return{data:null,error:e};throw e}}},LP={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},I_={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},FP=class extends is{constructor(r,e={},t,n){super(r,e,n,"storage"),this.bucketId=t}async uploadOrUpdate(r,e,t,n){var s=this;return s.handleOperation(async()=>{let i,o=q(q({},I_),n),u=q(q({},s.headers),r==="POST"&&{"x-upsert":String(o.upsert)}),c=o.metadata;typeof Blob!="undefined"&&t instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),c&&i.append("metadata",s.encodeMetadata(c)),i.append("",t)):typeof FormData!="undefined"&&t instanceof FormData?(i=t,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),c&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(c))):(i=t,u["cache-control"]=`max-age=${o.cacheControl}`,u["content-type"]=o.contentType,c&&(u["x-metadata"]=s.toBase64(s.encodeMetadata(c))),(typeof ReadableStream!="undefined"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),n!=null&&n.headers&&(u=q(q({},u),n.headers));let h=s._removeEmptyFolders(e),f=s._getFinalPath(h),p=await(r=="PUT"?wh:rt)(s.fetch,`${s.url}/object/${f}`,i,q({headers:u},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{path:h,id:p.Id,fullPath:p.Key}})}async upload(r,e,t){return this.uploadOrUpdate("POST",r,e,t)}async uploadToSignedUrl(r,e,t,n){var s=this;let i=s._removeEmptyFolders(r),o=s._getFinalPath(i),u=new URL(s.url+`/object/upload/sign/${o}`);return u.searchParams.set("token",e),s.handleOperation(async()=>{let c,h=q({upsert:I_.upsert},n),f=q(q({},s.headers),{"x-upsert":String(h.upsert)});return typeof Blob!="undefined"&&t instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",t)):typeof FormData!="undefined"&&t instanceof FormData?(c=t,c.append("cacheControl",h.cacheControl)):(c=t,f["cache-control"]=`max-age=${h.cacheControl}`,f["content-type"]=h.contentType),{path:i,fullPath:(await wh(s.fetch,u.toString(),c,{headers:f})).Key}})}async createSignedUploadUrl(r,e){var t=this;return t.handleOperation(async()=>{let n=t._getFinalPath(r),s=q({},t.headers);e!=null&&e.upsert&&(s["x-upsert"]="true");let i=await rt(t.fetch,`${t.url}/object/upload/sign/${n}`,{},{headers:s}),o=new URL(t.url+i.url),u=o.searchParams.get("token");if(!u)throw new Pa("No token returned by API");return{signedUrl:o.toString(),path:r,token:u}})}async update(r,e,t){return this.uploadOrUpdate("PUT",r,e,t)}async move(r,e,t){var n=this;return n.handleOperation(async()=>await rt(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:r,destinationKey:e,destinationBucket:t==null?void 0:t.destinationBucket},{headers:n.headers}))}async copy(r,e,t){var n=this;return n.handleOperation(async()=>({path:(await rt(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:r,destinationKey:e,destinationBucket:t==null?void 0:t.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(r,e,t){var n=this;return n.handleOperation(async()=>{let s=n._getFinalPath(r),i=await rt(n.fetch,`${n.url}/object/sign/${s}`,q({expiresIn:e},t!=null&&t.transform?{transform:t.transform}:{}),{headers:n.headers}),o=t!=null&&t.download?`&download=${t.download===!0?"":t.download}`:"";return{signedUrl:encodeURI(`${n.url}${i.signedURL}${o}`)}})}async createSignedUrls(r,e,t){var n=this;return n.handleOperation(async()=>{let s=await rt(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:r},{headers:n.headers}),i=t!=null&&t.download?`&download=${t.download===!0?"":t.download}`:"";return s.map(o=>q(q({},o),{},{signedUrl:o.signedURL?encodeURI(`${n.url}${o.signedURL}${i}`):null}))})}download(r,e,t){let n=typeof(e==null?void 0:e.transform)!="undefined"?"render/image/authenticated":"object",s=this.transformOptsToQueryString((e==null?void 0:e.transform)||{}),i=s?`?${s}`:"",o=this._getFinalPath(r),u=()=>mi(this.fetch,`${this.url}/${n}/${o}${i}`,{headers:this.headers,noResolveJson:!0},t);return new VP(u,this.shouldThrowOnError)}async info(r){var e=this;let t=e._getFinalPath(r);return e.handleOperation(async()=>vh(await mi(e.fetch,`${e.url}/object/info/${t}`,{headers:e.headers})))}async exists(r){var e=this;let t=e._getFinalPath(r);try{return await DP(e.fetch,`${e.url}/object/${t}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(Ca(n)&&n instanceof S_){let s=n.originalError;if([400,404].includes(s==null?void 0:s.status))return{data:!1,error:n}}throw n}}getPublicUrl(r,e){let t=this._getFinalPath(r),n=[],s=e!=null&&e.download?`download=${e.download===!0?"":e.download}`:"";s!==""&&n.push(s);let i=typeof(e==null?void 0:e.transform)!="undefined"?"render/image":"object",o=this.transformOptsToQueryString((e==null?void 0:e.transform)||{});o!==""&&n.push(o);let u=n.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${t}${u}`)}}}async remove(r){var e=this;return e.handleOperation(async()=>await bh(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:r},{headers:e.headers}))}async list(r,e,t){var n=this;return n.handleOperation(async()=>{let s=q(q(q({},LP),e),{},{prefix:r||""});return await rt(n.fetch,`${n.url}/object/list/${n.bucketId}`,s,{headers:n.headers},t)})}async listV2(r,e){var t=this;return t.handleOperation(async()=>{let n=q({},r);return await rt(t.fetch,`${t.url}/object/list-v2/${t.bucketId}`,n,{headers:t.headers},e)})}encodeMetadata(r){return JSON.stringify(r)}toBase64(r){return typeof Buffer!="undefined"?Buffer.from(r).toString("base64"):btoa(r)}_getFinalPath(r){return`${this.bucketId}/${r.replace(/^\/+/,"")}`}_removeEmptyFolders(r){return r.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(r){let e=[];return r.width&&e.push(`width=${r.width}`),r.height&&e.push(`height=${r.height}`),r.resize&&e.push(`resize=${r.resize}`),r.format&&e.push(`format=${r.format}`),r.quality&&e.push(`quality=${r.quality}`),e.join("&")}},jP="2.97.0",gi={"X-Client-Info":`storage-js/${jP}`},MP=class extends is{constructor(r,e={},t,n){let s=new URL(r);n!=null&&n.useNewHostname&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase."));let i=s.href.replace(/\/$/,""),o=q(q({},gi),e);super(i,o,t,"storage")}async listBuckets(r){var e=this;return e.handleOperation(async()=>{let t=e.listBucketOptionsToQueryString(r);return await mi(e.fetch,`${e.url}/bucket${t}`,{headers:e.headers})})}async getBucket(r){var e=this;return e.handleOperation(async()=>await mi(e.fetch,`${e.url}/bucket/${r}`,{headers:e.headers}))}async createBucket(r,e={public:!1}){var t=this;return t.handleOperation(async()=>await rt(t.fetch,`${t.url}/bucket`,{id:r,name:r,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:t.headers}))}async updateBucket(r,e){var t=this;return t.handleOperation(async()=>await wh(t.fetch,`${t.url}/bucket/${r}`,{id:r,name:r,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:t.headers}))}async emptyBucket(r){var e=this;return e.handleOperation(async()=>await rt(e.fetch,`${e.url}/bucket/${r}/empty`,{},{headers:e.headers}))}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await bh(e.fetch,`${e.url}/bucket/${r}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(r){let e={};return r&&("limit"in r&&(e.limit=String(r.limit)),"offset"in r&&(e.offset=String(r.offset)),r.search&&(e.search=r.search),r.sortColumn&&(e.sortColumn=r.sortColumn),r.sortOrder&&(e.sortOrder=r.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},UP=class extends is{constructor(r,e={},t){let n=r.replace(/\/$/,""),s=q(q({},gi),e);super(n,s,t,"storage")}async createBucket(r){var e=this;return e.handleOperation(async()=>await rt(e.fetch,`${e.url}/bucket`,{name:r},{headers:e.headers}))}async listBuckets(r){var e=this;return e.handleOperation(async()=>{let t=new URLSearchParams;(r==null?void 0:r.limit)!==void 0&&t.set("limit",r.limit.toString()),(r==null?void 0:r.offset)!==void 0&&t.set("offset",r.offset.toString()),r!=null&&r.sortColumn&&t.set("sortColumn",r.sortColumn),r!=null&&r.sortOrder&&t.set("sortOrder",r.sortOrder),r!=null&&r.search&&t.set("search",r.search);let n=t.toString(),s=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await mi(e.fetch,s,{headers:e.headers})})}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await bh(e.fetch,`${e.url}/bucket/${r}`,{},{headers:e.headers}))}from(r){var e=this;if(!AP(r))throw new Pa("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let t=new b_({baseUrl:this.url,catalogName:r,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(t,{get(s,i){let o=s[i];return typeof o!="function"?o:async(...u)=>{try{return{data:await o.apply(s,u),error:null}}catch(c){if(n)throw c;return{data:null,error:c}}}}})}},BP=class extends is{constructor(r,e={},t){let n=r.replace(/\/$/,""),s=q(q({},gi),{},{"Content-Type":"application/json"},e);super(n,s,t,"vectors")}async createIndex(r){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/CreateIndex`,r,{headers:e.headers})||{})}async getIndex(r,e){var t=this;return t.handleOperation(async()=>await Ke.post(t.fetch,`${t.url}/GetIndex`,{vectorBucketName:r,indexName:e},{headers:t.headers}))}async listIndexes(r){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/ListIndexes`,r,{headers:e.headers}))}async deleteIndex(r,e){var t=this;return t.handleOperation(async()=>await Ke.post(t.fetch,`${t.url}/DeleteIndex`,{vectorBucketName:r,indexName:e},{headers:t.headers})||{})}},$P=class extends is{constructor(r,e={},t){let n=r.replace(/\/$/,""),s=q(q({},gi),{},{"Content-Type":"application/json"},e);super(n,s,t,"vectors")}async putVectors(r){var e=this;if(r.vectors.length<1||r.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/PutVectors`,r,{headers:e.headers})||{})}async getVectors(r){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/GetVectors`,r,{headers:e.headers}))}async listVectors(r){var e=this;if(r.segmentCount!==void 0){if(r.segmentCount<1||r.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(r.segmentIndex!==void 0&&(r.segmentIndex<0||r.segmentIndex>=r.segmentCount))throw new Error(`segmentIndex must be between 0 and ${r.segmentCount-1}`)}return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/ListVectors`,r,{headers:e.headers}))}async queryVectors(r){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/QueryVectors`,r,{headers:e.headers}))}async deleteVectors(r){var e=this;if(r.keys.length<1||r.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/DeleteVectors`,r,{headers:e.headers})||{})}},qP=class extends is{constructor(r,e={},t){let n=r.replace(/\/$/,""),s=q(q({},gi),{},{"Content-Type":"application/json"},e);super(n,s,t,"vectors")}async createBucket(r){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:r},{headers:e.headers})||{})}async getBucket(r){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:r},{headers:e.headers}))}async listBuckets(r={}){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/ListVectorBuckets`,r,{headers:e.headers}))}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:r},{headers:e.headers})||{})}},zP=class extends qP{constructor(r,e={}){super(r,e.headers||{},e.fetch)}from(r){return new KP(this.url,this.headers,r,this.fetch)}async createBucket(r){var e=()=>super.createBucket,t=this;return e().call(t,r)}async getBucket(r){var e=()=>super.getBucket,t=this;return e().call(t,r)}async listBuckets(r={}){var e=()=>super.listBuckets,t=this;return e().call(t,r)}async deleteBucket(r){var e=()=>super.deleteBucket,t=this;return e().call(t,r)}},KP=class extends BP{constructor(r,e,t,n){super(r,e,n),this.vectorBucketName=t}async createIndex(r){var e=()=>super.createIndex,t=this;return e().call(t,q(q({},r),{},{vectorBucketName:t.vectorBucketName}))}async listIndexes(r={}){var e=()=>super.listIndexes,t=this;return e().call(t,q(q({},r),{},{vectorBucketName:t.vectorBucketName}))}async getIndex(r){var e=()=>super.getIndex,t=this;return e().call(t,t.vectorBucketName,r)}async deleteIndex(r){var e=()=>super.deleteIndex,t=this;return e().call(t,t.vectorBucketName,r)}index(r){return new GP(this.url,this.headers,this.vectorBucketName,r,this.fetch)}},GP=class extends $P{constructor(r,e,t,n,s){super(r,e,s),this.vectorBucketName=t,this.indexName=n}async putVectors(r){var e=()=>super.putVectors,t=this;return e().call(t,q(q({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(r){var e=()=>super.getVectors,t=this;return e().call(t,q(q({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(r={}){var e=()=>super.listVectors,t=this;return e().call(t,q(q({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(r){var e=()=>super.queryVectors,t=this;return e().call(t,q(q({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(r){var e=()=>super.deleteVectors,t=this;return e().call(t,q(q({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},R_=class extends MP{constructor(r,e={},t,n){super(r,e,t,n)}from(r){return new FP(this.url,this.headers,r,this.fetch)}get vectors(){return new zP(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new UP(this.url+"/iceberg",this.headers,this.fetch)}};var ka="2.97.0";var jr=30*1e3,Oa=3,Da=Oa*jr,P_="http://localhost:9999",C_="supabase.auth.token";var k_={"X-Client-Info":`gotrue-js/${ka}`};var yi="X-Supabase-Api-Version",Eh={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},O_=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,D_=600*1e3;var pr=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=n}};function U(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Na=class extends pr{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}};function N_(r){return U(r)&&r.name==="AuthApiError"}var He=class extends pr{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},nt=class extends pr{constructor(e,t,n,s){super(e,n,s),this.name=t,this.status=n}},Re=class extends nt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function La(r){return U(r)&&r.name==="AuthSessionMissingError"}var Vt=class extends nt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Mr=class extends nt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Ur=class extends nt{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 U(r)&&r.name==="AuthImplicitGrantRedirectError"}var _i=class extends nt{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}}},Va=class extends nt{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}};var os=class extends nt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Fa(r){return U(r)&&r.name==="AuthRetryableFetchError"}var vi=class extends nt{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}};var Br=class extends nt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var ja="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),L_=`
|
|
62
|
-
\r=`.split(""),WP=(()=>{let r=new Array(128);for(let e=0;e<r.length;e+=1)r[e]=-1;for(let e=0;e<L_.length;e+=1)r[L_[e].charCodeAt(0)]=-2;for(let e=0;e<ja.length;e+=1)r[ja[e].charCodeAt(0)]=e;return r})();function F_(r,e,t){if(r!==null)for(e.queue=e.queue<<8|r,e.queuedBits+=8;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;t(ja[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;t(ja[n]),e.queuedBits-=6}}function j_(r,e,t){let n=WP[r];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(r)}"`)}}function Th(r){let e=[],t=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{JP(o,n,t)};for(let o=0;o<r.length;o+=1)j_(r.charCodeAt(o),s,i);return e.join("")}function HP(r,e){if(r<=127){e(r);return}else if(r<=2047){e(192|r>>6),e(128|r&63);return}else if(r<=65535){e(224|r>>12),e(128|r>>6&63),e(128|r&63);return}else if(r<=1114111){e(240|r>>18),e(128|r>>12&63),e(128|r>>6&63),e(128|r&63);return}throw new Error(`Unrecognized Unicode codepoint: ${r.toString(16)}`)}function QP(r,e){for(let t=0;t<r.length;t+=1){let n=r.charCodeAt(t);if(n>55295&&n<=56319){let s=(n-55296)*1024&65535;n=(r.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}HP(n,e)}}function JP(r,e,t){if(e.utf8seq===0){if(r<=127){t(r);return}for(let n=1;n<6;n+=1)if((r>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=r&31;else if(e.utf8seq===3)e.codepoint=r&15;else if(e.utf8seq===4)e.codepoint=r&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(r<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|r&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function mr(r){let e=[],t={queue:0,queuedBits:0},n=s=>{e.push(s)};for(let s=0;s<r.length;s+=1)j_(r.charCodeAt(s),t,n);return new Uint8Array(e)}function M_(r){let e=[];return QP(r,t=>e.push(t)),new Uint8Array(e)}function Lt(r){let e=[],t={queue:0,queuedBits:0},n=s=>{e.push(s)};return r.forEach(s=>F_(s,t,n)),F_(null,t,n),e.join("")}function U_(r){return Math.round(Date.now()/1e3)+r}function B_(){return Symbol("auth-callback")}var be=()=>typeof window!="undefined"&&typeof document!="undefined",$r={tested:!1,writable:!1},Ma=()=>{if(!be())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if($r.tested)return $r.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),$r.tested=!0,$r.writable=!0}catch{$r.tested=!0,$r.writable=!1}return $r.writable};function $_(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 Ua=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),q_=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",qr=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},gr=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Se=async(r,e)=>{await r.removeItem(e)},wi=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};wi.promiseConstructor=Promise;function bi(r){let e=r.split(".");if(e.length!==3)throw new Br("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!O_.test(e[n]))throw new Br("JWT not in base64url format");return{header:JSON.parse(Th(e[0])),payload:JSON.parse(Th(e[1])),signature:mr(e[2]),raw:{header:e[0],payload:e[1]}}}async function z_(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 o=await r(i);if(!e(i,null,o)){n(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function XP(r){return("0"+r.toString(16)).substr(-2)}function YP(){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,XP).join("")}async function ZP(r){let t=new TextEncoder().encode(r),n=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(n);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function eC(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 ZP(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function zr(r,e,t=!1){let n=YP(),s=n;t&&(s+="/PASSWORD_RECOVERY"),await qr(r,`${e}-code-verifier`,s);let i=await eC(n);return[i,n===i?"plain":"s256"]}var tC=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function G_(r){let e=r.headers.get(yi);if(!e||!e.match(tC))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function W_(r){if(!r)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(r<=e)throw new Error("JWT has expired")}function H_(r){switch(r){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var rC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Kr(r){if(!rC.test(r))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ba(){let r={};return new Proxy(r,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){let n=t.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Q_(r,e){return new Proxy(r,{get:(t,n,s)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){let i=n.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,n,s)}return!e.value&&typeof n=="string"&&(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."),e.value=!0),Reflect.get(t,n,s)}})}function Ih(r){return JSON.parse(JSON.stringify(r))}var Gr=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),nC=[502,503,504];async function J_(r){var e;if(!q_(r))throw new os(Gr(r),0);if(nC.includes(r.status))throw new os(Gr(r),r.status);let t;try{t=await r.json()}catch(i){throw new He(Gr(i),i)}let n,s=G_(r);if(s&&s.getTime()>=Eh["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 vi(Gr(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Re}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,o)=>i&&typeof o=="string",!0))throw new vi(Gr(t),r.status,t.weak_password.reasons);throw new Na(Gr(t),r.status||500,n)}var sC=(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 $(r,e,t,n){var s;let i=Object.assign({},n==null?void 0:n.headers);i[yi]||(i[yi]=Eh["2024-01-01"].name),n!=null&&n.jwt&&(i.Authorization=`Bearer ${n.jwt}`);let o=(s=n==null?void 0:n.query)!==null&&s!==void 0?s:{};n!=null&&n.redirectTo&&(o.redirect_to=n.redirectTo);let u=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await iC(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 iC(r,e,t,n,s,i){let o=sC(e,n,s,i),u;try{u=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new os(Gr(c),0)}if(u.ok||await J_(u),n!=null&&n.noResolveJson)return u;try{return await u.json()}catch(c){await J_(c)}}function Qe(r){var e;let t=null;oC(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=U_(r.expires_in)));let n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:n},error:null}}function Sh(r){let e=Qe(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 gt(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function X_(r){return{data:r,error:null}}function Y_(r){let{action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i}=r,o=Vr(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({},o);return{data:{properties:u,user:c},error:null}}function Ah(r){return r}function oC(r){return r.access_token&&r.refresh_token&&r.expires_in}var $a=["global","local","others"];var Wr=class{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=Ua(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=$a[0]){if($a.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${$a.join(", ")}`);try{return await $(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,t={}){try{return await $(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:gt})}catch(n){if(U(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:t}=e,n=Vr(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 $(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Y_,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(U(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await $(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:gt})}catch(t){if(U(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,n,s,i,o,u,c;try{let h={nextPage:null,lastPage:0,total:0},f=await $(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:Ah});if(f.error)throw f.error;let p=await f.json(),m=(o=f.headers.get("x-total-count"))!==null&&o!==void 0?o:0,y=(c=(u=f.headers.get("link"))===null||u===void 0?void 0:u.split(","))!==null&&c!==void 0?c:[];return y.length>0&&(y.forEach(T=>{let R=parseInt(T.split(";")[0].split("=")[1].substring(0,1)),I=JSON.parse(T.split(";")[1].split("=")[1]);h[`${I}Page`]=R}),h.total=parseInt(m)),{data:Object.assign(Object.assign({},p),h),error:null}}catch(h){if(U(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){Kr(e);try{return await $(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:gt})}catch(t){if(U(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Kr(e);try{return await $(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:gt})}catch(n){if(U(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,t=!1){Kr(e);try{return await $(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:gt})}catch(n){if(U(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){Kr(e.userId);try{let{data:t,error:n}=await $(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(U(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Kr(e.userId),Kr(e.id);try{return{data:await $(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,n,s,i,o,u,c;try{let h={nextPage:null,lastPage:0,total:0},f=await $(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{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:Ah});if(f.error)throw f.error;let p=await f.json(),m=(o=f.headers.get("x-total-count"))!==null&&o!==void 0?o:0,y=(c=(u=f.headers.get("link"))===null||u===void 0?void 0:u.split(","))!==null&&c!==void 0?c:[];return y.length>0&&(y.forEach(T=>{let R=parseInt(T.split(";")[0].split("=")[1].substring(0,1)),I=JSON.parse(T.split(";")[1].split("=")[1]);h[`${I}Page`]=R}),h.total=parseInt(m)),{data:Object.assign(Object.assign({},p),h),error:null}}catch(h){if(U(h))return{data:{clients:[]},error:h};throw h}}async _createOAuthClient(e){try{return await $(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(U(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await $(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(U(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await $(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(U(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await $(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await $(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(U(t))return{data:null,error:t};throw t}}};function xh(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}var Hr={debug:!!(globalThis&&Ma()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Ei=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Ti=class extends Ei{};async function Rh(r,e,t){Hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let n=new globalThis.AbortController;e>0&&setTimeout(()=>{n.abort(),Hr.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await Promise.resolve();try{return await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){Hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,s.name);try{return await t()}finally{Hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,s.name)}}else{if(e===0)throw Hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Ti(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Hr.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()}})}catch(s){throw(s==null?void 0:s.name)==="AbortError"?new Ti(`Acquiring an exclusive Navigator LockManager lock "${r}" timed out waiting ${e}ms`):s}}function Z_(){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)}}function Ph(r){if(!/^0x[a-fA-F0-9]{40}$/.test(r))throw new Error(`@supabase/auth-js: Address "${r}" is invalid.`);return r.toLowerCase()}function ev(r){return parseInt(r,16)}function tv(r){let e=new TextEncoder().encode(r);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function rv(r){var e;let{chainId:t,domain:n,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:u,requestId:c,resources:h,scheme:f,uri:p,version:m}=r;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!p)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(m!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${m}`);if(!((e=r.statement)===null||e===void 0)&&e.includes(`
|
|
63
|
-
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${r.statement}`)}let y=
|
|
64
|
-
`:"",
|
|
47
|
+
})`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){let n=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,t!=null?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}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.channels=[],this.disconnect(),e}log(e,t,n){this.logger(e,t,n)}connectionState(){switch(this.conn&&this.conn.readyState){case Ft.connecting:return fr.Connecting;case Ft.open:return fr.Open;case Ft.closing:return fr.Closing;default:return fr.Closed}}isConnected(){return this.connectionState()===fr.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){let n=`realtime:${e}`,s=this.getChannels().find(i=>i.topic===n);if(s)return s;{let i=new cs(`realtime:${e}`,t,this);return this.channels.push(i),i}}push(e){let{topic:t,event:n,payload:s,ref:i}=e,o=()=>{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()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(v_,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},ka.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}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.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply"&&t.ref&&t.ref===this.pendingHeartbeatRef){let l=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error",l)}catch(f){this.log("error","error in heartbeat callback",f)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}let{topic:n,event:s,payload:i,ref:o}=t,u=o?`(${o})`:"",c=i.status||"";this.log("receive",`${c} ${n} ${s} ${u}`.trim(),i),this.channels.filter(l=>l._isMember(n)).forEach(l=>l._trigger(s,i,o)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in 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),this.conn.readyState===Ft.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===Ft.open||this.conn.readyState===Ft.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.accessTokenValue&&(this.channels.forEach(t=>{t.updateJoinPayload({access_token:this.accessTokenValue})}),this.sendBuffer=[],this.channels.forEach(t=>{t._isJoining()&&(t.joinPush.sent=!1,t.joinPush.send())})),this.flushSendBuffer()}).catch(t=>{this.log("error","error waiting for auth on connect",t),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){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._terminateWorker()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(t){this.log("error","error in heartbeat callback",t)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(qe.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([sP],{type:"application/javascript"});t=URL.createObjectURL(n)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,n=!1;if(e)t=e,n=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),t=this.accessTokenValue}else t=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(s=>{let i={access_token:t,version:__};t&&s.updateJoinPayload(i),s.joinedOnce&&s._isJoined()&&s._push(qe.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(n=>{try{n(t)}catch(s){this.log("error",`error in ${e} callback`,s)}})}catch(n){this.log("error",`error triggering ${e} callbacks`,n)}}_setupReconnectionTimer(){this.reconnectTimer=new zr(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},ka.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,n,s,i,o,u,c,l,f,p,g,y;switch(this.transport=(t=e==null?void 0:e.transport)!==null&&t!==void 0?t:null,this.timeout=(n=e==null?void 0:e.timeout)!==null&&n!==void 0?n:gi,this.heartbeatIntervalMs=(s=e==null?void 0:e.heartbeatIntervalMs)!==null&&s!==void 0?s:ka.HEARTBEAT_INTERVAL,this.worker=(i=e==null?void 0:e.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=e==null?void 0:e.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(u=e==null?void 0:e.heartbeatCallback)!==null&&u!==void 0?u:mh,this.vsn=(c=e==null?void 0:e.vsn)!==null&&c!==void 0?c:lh,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(l=e==null?void 0:e.reconnectAfterMs)!==null&&l!==void 0?l:(I=>rP[I-1]||nP),this.vsn){case w_:this.encode=(f=e==null?void 0:e.encode)!==null&&f!==void 0?f:((I,R)=>R(JSON.stringify(I))),this.decode=(p=e==null?void 0:e.decode)!==null&&p!==void 0?p:((I,R)=>R(JSON.parse(I)));break;case ch:this.encode=(g=e==null?void 0:e.encode)!==null&&g!==void 0?g:this.serializer.encode.bind(this.serializer),this.decode=(y=e==null?void 0:e.decode)!==null&&y!==void 0?y:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window!="undefined"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}};var _i=class extends Error{constructor(r,e){var t;super(r),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&((t=e.icebergType)==null?void 0:t.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function iP(r,e,t){let n=new URL(e,r);if(t)for(let[s,i]of Object.entries(t))i!==void 0&&n.searchParams.set(s,i);return n.toString()}async function oP(r){return!r||r.type==="none"?{}:r.type==="bearer"?{Authorization:`Bearer ${r.token}`}:r.type==="header"?{[r.name]:r.value}:r.type==="custom"?await r.getHeaders():{}}function aP(r){var t;let e=(t=r.fetchImpl)!=null?t:globalThis.fetch;return{async request({method:n,path:s,query:i,body:o,headers:u}){var I;let c=iP(r.baseUrl,s,i),l=await oP(r.auth),f=await e(c,{method:n,headers:{...o?{"Content-Type":"application/json"}:{},...l,...u},body:o?JSON.stringify(o):void 0}),p=await f.text(),g=(f.headers.get("content-type")||"").includes("application/json"),y=g&&p?JSON.parse(p):p;if(!f.ok){let R=g?y:void 0,A=R==null?void 0:R.error;throw new _i((I=A==null?void 0:A.message)!=null?I:`Request failed with status ${f.status}`,{status:f.status,icebergType:A==null?void 0:A.type,icebergCode:A==null?void 0:A.code,details:R})}return{status:f.status,headers:f.headers,data:y}}}}function Oa(r){return r.join("")}var uP=class{constructor(r,e=""){this.client=r,this.prefix=e}async listNamespaces(r){let e=r?{parent:Oa(r.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(r,e){let t={namespace:r.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:t})).data}async dropNamespace(r){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Oa(r.namespace)}`})}async loadNamespaceMetadata(r){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Oa(r.namespace)}`})).data.properties}}async namespaceExists(r){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Oa(r.namespace)}`}),!0}catch(e){if(e instanceof _i&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(r,e){try{return await this.createNamespace(r,e)}catch(t){if(t instanceof _i&&t.status===409)return;throw t}}};function hs(r){return r.join("")}var cP=class{constructor(r,e="",t){this.client=r,this.prefix=e,this.accessDelegation=t}async listTables(r){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${hs(r.namespace)}/tables`})).data.identifiers}async createTable(r,e){let t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${hs(r.namespace)}/tables`,body:e,headers:t})).data.metadata}async updateTable(r,e){let t=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${hs(r.namespace)}/tables/${r.name}`,body:e});return{"metadata-location":t.data["metadata-location"],metadata:t.data.metadata}}async dropTable(r,e){var t;await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${hs(r.namespace)}/tables/${r.name}`,query:{purgeRequested:String((t=e==null?void 0:e.purge)!=null?t:!1)}})}async loadTable(r){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${hs(r.namespace)}/tables/${r.name}`,headers:e})).data.metadata}async tableExists(r){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${hs(r.namespace)}/tables/${r.name}`,headers:e}),!0}catch(t){if(t instanceof _i&&t.status===404)return!1;throw t}}async createTableIfNotExists(r,e){try{return await this.createTable(r,e)}catch(t){if(t instanceof _i&&t.status===409)return await this.loadTable({namespace:r.namespace,name:e.name});throw t}}},T_=class{constructor(r){var n;let e="v1";r.catalogName&&(e+=`/${r.catalogName}`);let t=r.baseUrl.endsWith("/")?r.baseUrl:`${r.baseUrl}/`;this.client=aP({baseUrl:t,auth:r.auth,fetchImpl:r.fetch}),this.accessDelegation=(n=r.accessDelegation)==null?void 0:n.join(","),this.namespaceOps=new uP(this.client,e),this.tableOps=new cP(this.client,e,this.accessDelegation)}async listNamespaces(r){return this.namespaceOps.listNamespaces(r)}async createNamespace(r,e){return this.namespaceOps.createNamespace(r,e)}async dropNamespace(r){await this.namespaceOps.dropNamespace(r)}async loadNamespaceMetadata(r){return this.namespaceOps.loadNamespaceMetadata(r)}async listTables(r){return this.tableOps.listTables(r)}async createTable(r,e){return this.tableOps.createTable(r,e)}async updateTable(r,e){return this.tableOps.updateTable(r,e)}async dropTable(r,e){await this.tableOps.dropTable(r,e)}async loadTable(r){return this.tableOps.loadTable(r)}async namespaceExists(r){return this.namespaceOps.namespaceExists(r)}async tableExists(r){return this.tableOps.tableExists(r)}async createNamespaceIfNotExists(r,e){return this.namespaceOps.createNamespaceIfNotExists(r,e)}async createTableIfNotExists(r,e){return this.tableOps.createTableIfNotExists(r,e)}};var Da=class extends Error{constructor(r,e="storage",t,n){super(r),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=t,this.statusCode=n}};function Na(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var vi=class extends Da{constructor(r,e,t,n="storage"){super(r,n,e,t),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=t}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},x_=class extends Da{constructor(r,e,t="storage"){super(r,t),this.name=t==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var lP=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),hP=r=>{if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)},gh=r=>{if(Array.isArray(r))return r.map(t=>gh(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]=gh(n)}),e},dP=r=>!r||typeof r!="string"||r.length===0||r.length>100||r.trim()!==r||r.includes("/")||r.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(r);function bi(r){"@babel/helpers - typeof";return bi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},bi(r)}function fP(r,e){if(bi(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e||"default");if(bi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function pP(r){var e=fP(r,"string");return bi(e)=="symbol"?e:e+""}function mP(r,e,t){return(e=pP(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function I_(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,n)}return t}function G(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?I_(Object(t),!0).forEach(function(n){mP(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):I_(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var A_=r=>{var e;return r.msg||r.message||r.error_description||(typeof r.error=="string"?r.error:(e=r.error)===null||e===void 0?void 0:e.message)||JSON.stringify(r)},gP=async(r,e,t,n)=>{if(r&&typeof r=="object"&&"status"in r&&"ok"in r&&typeof r.status=="number"){let s=r,i=s.status||500;if(typeof s.json=="function")s.json().then(o=>{let u=(o==null?void 0:o.statusCode)||(o==null?void 0:o.code)||i+"";e(new vi(A_(o),i,u,n))}).catch(()=>{if(n==="vectors"){let o=i+"";e(new vi(s.statusText||`HTTP ${i} error`,i,o,n))}else{let o=i+"";e(new vi(s.statusText||`HTTP ${i} error`,i,o,n))}});else{let o=i+"";e(new vi(s.statusText||`HTTP ${i} error`,i,o,n))}}else e(new x_(A_(r),r,n))},yP=(r,e,t,n)=>{let s={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"||r==="HEAD"||!n?G(G({},s),t):(hP(n)?(s.headers=G({"Content-Type":"application/json"},e==null?void 0:e.headers),s.body=JSON.stringify(n)):s.body=n,e!=null&&e.duplex&&(s.duplex=e.duplex),G(G({},s),t))};async function wi(r,e,t,n,s,i,o){return new Promise((u,c)=>{r(t,yP(e,n,s,i)).then(l=>{if(!l.ok)throw l;if(n!=null&&n.noResolveJson)return l;if(o==="vectors"){let f=l.headers.get("content-type");if(l.headers.get("content-length")==="0"||l.status===204)return{};if(!f||!f.includes("application/json"))return{}}return l.json()}).then(l=>u(l)).catch(l=>gP(l,c,n,o))})}function R_(r="storage"){return{get:async(e,t,n,s)=>wi(e,"GET",t,n,s,void 0,r),post:async(e,t,n,s,i)=>wi(e,"POST",t,s,i,n,r),put:async(e,t,n,s,i)=>wi(e,"PUT",t,s,i,n,r),head:async(e,t,n,s)=>wi(e,"HEAD",t,G(G({},n),{},{noResolveJson:!0}),s,void 0,r),remove:async(e,t,n,s,i)=>wi(e,"DELETE",t,s,i,n,r)}}var _P=R_("storage"),{get:Ei,post:tt,put:yh,head:wP,remove:_h}=_P,ze=R_("vectors"),ds=class{constructor(r,e={},t,n="storage"){this.shouldThrowOnError=!1,this.url=r,this.headers=e,this.fetch=lP(t),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(r,e){return this.headers=G(G({},this.headers),{},{[r]:e}),this}async handleOperation(r){var e=this;try{return{data:await r(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Na(t))return{data:null,error:t};throw t}}},vP=class{constructor(r,e){this.downloadFn=r,this.shouldThrowOnError=e}then(r,e){return this.execute().then(r,e)}async execute(){var r=this;try{return{data:(await r.downloadFn()).body,error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Na(e))return{data:null,error:e};throw e}}},P_;P_=Symbol.toStringTag;var bP=class{constructor(r,e){this.downloadFn=r,this.shouldThrowOnError=e,this[P_]="BlobDownloadBuilder",this.promise=null}asStream(){return new vP(this.downloadFn,this.shouldThrowOnError)}then(r,e){return this.getPromise().then(r,e)}catch(r){return this.getPromise().catch(r)}finally(r){return this.getPromise().finally(r)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var r=this;try{return{data:await(await r.downloadFn()).blob(),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Na(e))return{data:null,error:e};throw e}}},EP={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},S_={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},TP=class extends ds{constructor(r,e={},t,n){super(r,e,n,"storage"),this.bucketId=t}async uploadOrUpdate(r,e,t,n){var s=this;return s.handleOperation(async()=>{let i,o=G(G({},S_),n),u=G(G({},s.headers),r==="POST"&&{"x-upsert":String(o.upsert)}),c=o.metadata;typeof Blob!="undefined"&&t instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),c&&i.append("metadata",s.encodeMetadata(c)),i.append("",t)):typeof FormData!="undefined"&&t instanceof FormData?(i=t,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),c&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(c))):(i=t,u["cache-control"]=`max-age=${o.cacheControl}`,u["content-type"]=o.contentType,c&&(u["x-metadata"]=s.toBase64(s.encodeMetadata(c))),(typeof ReadableStream!="undefined"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),n!=null&&n.headers&&(u=G(G({},u),n.headers));let l=s._removeEmptyFolders(e),f=s._getFinalPath(l),p=await(r=="PUT"?yh:tt)(s.fetch,`${s.url}/object/${f}`,i,G({headers:u},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{path:l,id:p.Id,fullPath:p.Key}})}async upload(r,e,t){return this.uploadOrUpdate("POST",r,e,t)}async uploadToSignedUrl(r,e,t,n){var s=this;let i=s._removeEmptyFolders(r),o=s._getFinalPath(i),u=new URL(s.url+`/object/upload/sign/${o}`);return u.searchParams.set("token",e),s.handleOperation(async()=>{let c,l=G({upsert:S_.upsert},n),f=G(G({},s.headers),{"x-upsert":String(l.upsert)});return typeof Blob!="undefined"&&t instanceof Blob?(c=new FormData,c.append("cacheControl",l.cacheControl),c.append("",t)):typeof FormData!="undefined"&&t instanceof FormData?(c=t,c.append("cacheControl",l.cacheControl)):(c=t,f["cache-control"]=`max-age=${l.cacheControl}`,f["content-type"]=l.contentType),{path:i,fullPath:(await yh(s.fetch,u.toString(),c,{headers:f})).Key}})}async createSignedUploadUrl(r,e){var t=this;return t.handleOperation(async()=>{let n=t._getFinalPath(r),s=G({},t.headers);e!=null&&e.upsert&&(s["x-upsert"]="true");let i=await tt(t.fetch,`${t.url}/object/upload/sign/${n}`,{},{headers:s}),o=new URL(t.url+i.url),u=o.searchParams.get("token");if(!u)throw new Da("No token returned by API");return{signedUrl:o.toString(),path:r,token:u}})}async update(r,e,t){return this.uploadOrUpdate("PUT",r,e,t)}async move(r,e,t){var n=this;return n.handleOperation(async()=>await tt(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:r,destinationKey:e,destinationBucket:t==null?void 0:t.destinationBucket},{headers:n.headers}))}async copy(r,e,t){var n=this;return n.handleOperation(async()=>({path:(await tt(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:r,destinationKey:e,destinationBucket:t==null?void 0:t.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(r,e,t){var n=this;return n.handleOperation(async()=>{let s=n._getFinalPath(r),i=await tt(n.fetch,`${n.url}/object/sign/${s}`,G({expiresIn:e},t!=null&&t.transform?{transform:t.transform}:{}),{headers:n.headers}),o=t!=null&&t.download?`&download=${t.download===!0?"":t.download}`:"",u=t!=null&&t.transform&&i.signedURL.includes("/object/sign/")?i.signedURL.replace("/object/sign/","/render/image/sign/"):i.signedURL;return{signedUrl:encodeURI(`${n.url}${u}${o}`)}})}async createSignedUrls(r,e,t){var n=this;return n.handleOperation(async()=>{let s=await tt(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:r},{headers:n.headers}),i=t!=null&&t.download?`&download=${t.download===!0?"":t.download}`:"";return s.map(o=>G(G({},o),{},{signedUrl:o.signedURL?encodeURI(`${n.url}${o.signedURL}${i}`):null}))})}download(r,e,t){let n=typeof(e==null?void 0:e.transform)!="undefined"?"render/image/authenticated":"object",s=this.transformOptsToQueryString((e==null?void 0:e.transform)||{}),i=s?`?${s}`:"",o=this._getFinalPath(r),u=()=>Ei(this.fetch,`${this.url}/${n}/${o}${i}`,{headers:this.headers,noResolveJson:!0},t);return new bP(u,this.shouldThrowOnError)}async info(r){var e=this;let t=e._getFinalPath(r);return e.handleOperation(async()=>gh(await Ei(e.fetch,`${e.url}/object/info/${t}`,{headers:e.headers})))}async exists(r){var e=this;let t=e._getFinalPath(r);try{return await wP(e.fetch,`${e.url}/object/${t}`,{headers:e.headers}),{data:!0,error:null}}catch(s){if(e.shouldThrowOnError)throw s;if(Na(s)){var n;let i=s instanceof vi?s.status:s instanceof x_?(n=s.originalError)===null||n===void 0?void 0:n.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:s}}throw s}}getPublicUrl(r,e){let t=this._getFinalPath(r),n=[],s=e!=null&&e.download?`download=${e.download===!0?"":e.download}`:"";s!==""&&n.push(s);let i=typeof(e==null?void 0:e.transform)!="undefined"?"render/image":"object",o=this.transformOptsToQueryString((e==null?void 0:e.transform)||{});o!==""&&n.push(o);let u=n.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${t}${u}`)}}}async remove(r){var e=this;return e.handleOperation(async()=>await _h(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:r},{headers:e.headers}))}async list(r,e,t){var n=this;return n.handleOperation(async()=>{let s=G(G(G({},EP),e),{},{prefix:r||""});return await tt(n.fetch,`${n.url}/object/list/${n.bucketId}`,s,{headers:n.headers},t)})}async listV2(r,e){var t=this;return t.handleOperation(async()=>{let n=G({},r);return await tt(t.fetch,`${t.url}/object/list-v2/${t.bucketId}`,n,{headers:t.headers},e)})}encodeMetadata(r){return JSON.stringify(r)}toBase64(r){return typeof Buffer!="undefined"?Buffer.from(r).toString("base64"):btoa(r)}_getFinalPath(r){return`${this.bucketId}/${r.replace(/^\/+/,"")}`}_removeEmptyFolders(r){return r.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(r){let e=[];return r.width&&e.push(`width=${r.width}`),r.height&&e.push(`height=${r.height}`),r.resize&&e.push(`resize=${r.resize}`),r.format&&e.push(`format=${r.format}`),r.quality&&e.push(`quality=${r.quality}`),e.join("&")}},IP="2.99.1",Ti={"X-Client-Info":`storage-js/${IP}`},AP=class extends ds{constructor(r,e={},t,n){let s=new URL(r);n!=null&&n.useNewHostname&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase."));let i=s.href.replace(/\/$/,""),o=G(G({},Ti),e);super(i,o,t,"storage")}async listBuckets(r){var e=this;return e.handleOperation(async()=>{let t=e.listBucketOptionsToQueryString(r);return await Ei(e.fetch,`${e.url}/bucket${t}`,{headers:e.headers})})}async getBucket(r){var e=this;return e.handleOperation(async()=>await Ei(e.fetch,`${e.url}/bucket/${r}`,{headers:e.headers}))}async createBucket(r,e={public:!1}){var t=this;return t.handleOperation(async()=>await tt(t.fetch,`${t.url}/bucket`,{id:r,name:r,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:t.headers}))}async updateBucket(r,e){var t=this;return t.handleOperation(async()=>await yh(t.fetch,`${t.url}/bucket/${r}`,{id:r,name:r,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:t.headers}))}async emptyBucket(r){var e=this;return e.handleOperation(async()=>await tt(e.fetch,`${e.url}/bucket/${r}/empty`,{},{headers:e.headers}))}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await _h(e.fetch,`${e.url}/bucket/${r}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(r){let e={};return r&&("limit"in r&&(e.limit=String(r.limit)),"offset"in r&&(e.offset=String(r.offset)),r.search&&(e.search=r.search),r.sortColumn&&(e.sortColumn=r.sortColumn),r.sortOrder&&(e.sortOrder=r.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},SP=class extends ds{constructor(r,e={},t){let n=r.replace(/\/$/,""),s=G(G({},Ti),e);super(n,s,t,"storage")}async createBucket(r){var e=this;return e.handleOperation(async()=>await tt(e.fetch,`${e.url}/bucket`,{name:r},{headers:e.headers}))}async listBuckets(r){var e=this;return e.handleOperation(async()=>{let t=new URLSearchParams;(r==null?void 0:r.limit)!==void 0&&t.set("limit",r.limit.toString()),(r==null?void 0:r.offset)!==void 0&&t.set("offset",r.offset.toString()),r!=null&&r.sortColumn&&t.set("sortColumn",r.sortColumn),r!=null&&r.sortOrder&&t.set("sortOrder",r.sortOrder),r!=null&&r.search&&t.set("search",r.search);let n=t.toString(),s=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await Ei(e.fetch,s,{headers:e.headers})})}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await _h(e.fetch,`${e.url}/bucket/${r}`,{},{headers:e.headers}))}from(r){var e=this;if(!dP(r))throw new Da("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let t=new T_({baseUrl:this.url,catalogName:r,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(t,{get(s,i){let o=s[i];return typeof o!="function"?o:async(...u)=>{try{return{data:await o.apply(s,u),error:null}}catch(c){if(n)throw c;return{data:null,error:c}}}}})}},xP=class extends ds{constructor(r,e={},t){let n=r.replace(/\/$/,""),s=G(G({},Ti),{},{"Content-Type":"application/json"},e);super(n,s,t,"vectors")}async createIndex(r){var e=this;return e.handleOperation(async()=>await ze.post(e.fetch,`${e.url}/CreateIndex`,r,{headers:e.headers})||{})}async getIndex(r,e){var t=this;return t.handleOperation(async()=>await ze.post(t.fetch,`${t.url}/GetIndex`,{vectorBucketName:r,indexName:e},{headers:t.headers}))}async listIndexes(r){var e=this;return e.handleOperation(async()=>await ze.post(e.fetch,`${e.url}/ListIndexes`,r,{headers:e.headers}))}async deleteIndex(r,e){var t=this;return t.handleOperation(async()=>await ze.post(t.fetch,`${t.url}/DeleteIndex`,{vectorBucketName:r,indexName:e},{headers:t.headers})||{})}},RP=class extends ds{constructor(r,e={},t){let n=r.replace(/\/$/,""),s=G(G({},Ti),{},{"Content-Type":"application/json"},e);super(n,s,t,"vectors")}async putVectors(r){var e=this;if(r.vectors.length<1||r.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await ze.post(e.fetch,`${e.url}/PutVectors`,r,{headers:e.headers})||{})}async getVectors(r){var e=this;return e.handleOperation(async()=>await ze.post(e.fetch,`${e.url}/GetVectors`,r,{headers:e.headers}))}async listVectors(r){var e=this;if(r.segmentCount!==void 0){if(r.segmentCount<1||r.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(r.segmentIndex!==void 0&&(r.segmentIndex<0||r.segmentIndex>=r.segmentCount))throw new Error(`segmentIndex must be between 0 and ${r.segmentCount-1}`)}return e.handleOperation(async()=>await ze.post(e.fetch,`${e.url}/ListVectors`,r,{headers:e.headers}))}async queryVectors(r){var e=this;return e.handleOperation(async()=>await ze.post(e.fetch,`${e.url}/QueryVectors`,r,{headers:e.headers}))}async deleteVectors(r){var e=this;if(r.keys.length<1||r.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await ze.post(e.fetch,`${e.url}/DeleteVectors`,r,{headers:e.headers})||{})}},PP=class extends ds{constructor(r,e={},t){let n=r.replace(/\/$/,""),s=G(G({},Ti),{},{"Content-Type":"application/json"},e);super(n,s,t,"vectors")}async createBucket(r){var e=this;return e.handleOperation(async()=>await ze.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:r},{headers:e.headers})||{})}async getBucket(r){var e=this;return e.handleOperation(async()=>await ze.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:r},{headers:e.headers}))}async listBuckets(r={}){var e=this;return e.handleOperation(async()=>await ze.post(e.fetch,`${e.url}/ListVectorBuckets`,r,{headers:e.headers}))}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await ze.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:r},{headers:e.headers})||{})}},CP=class extends PP{constructor(r,e={}){super(r,e.headers||{},e.fetch)}from(r){return new kP(this.url,this.headers,r,this.fetch)}async createBucket(r){var e=()=>super.createBucket,t=this;return e().call(t,r)}async getBucket(r){var e=()=>super.getBucket,t=this;return e().call(t,r)}async listBuckets(r={}){var e=()=>super.listBuckets,t=this;return e().call(t,r)}async deleteBucket(r){var e=()=>super.deleteBucket,t=this;return e().call(t,r)}},kP=class extends xP{constructor(r,e,t,n){super(r,e,n),this.vectorBucketName=t}async createIndex(r){var e=()=>super.createIndex,t=this;return e().call(t,G(G({},r),{},{vectorBucketName:t.vectorBucketName}))}async listIndexes(r={}){var e=()=>super.listIndexes,t=this;return e().call(t,G(G({},r),{},{vectorBucketName:t.vectorBucketName}))}async getIndex(r){var e=()=>super.getIndex,t=this;return e().call(t,t.vectorBucketName,r)}async deleteIndex(r){var e=()=>super.deleteIndex,t=this;return e().call(t,t.vectorBucketName,r)}index(r){return new OP(this.url,this.headers,this.vectorBucketName,r,this.fetch)}},OP=class extends RP{constructor(r,e,t,n,s){super(r,e,s),this.vectorBucketName=t,this.indexName=n}async putVectors(r){var e=()=>super.putVectors,t=this;return e().call(t,G(G({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(r){var e=()=>super.getVectors,t=this;return e().call(t,G(G({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(r={}){var e=()=>super.listVectors,t=this;return e().call(t,G(G({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(r){var e=()=>super.queryVectors,t=this;return e().call(t,G(G({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(r){var e=()=>super.deleteVectors,t=this;return e().call(t,G(G({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},C_=class extends AP{constructor(r,e={},t,n){super(r,e,t,n)}from(r){return new TP(this.url,this.headers,r,this.fetch)}get vectors(){return new CP(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new SP(this.url+"/iceberg",this.headers,this.fetch)}};var Va="2.99.1";var Gr=30*1e3,La=3,Fa=La*Gr,k_="http://localhost:9999",O_="supabase.auth.token";var D_={"X-Client-Info":`gotrue-js/${Va}`};var Ii="X-Supabase-Api-Version",wh={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},N_=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,V_=600*1e3;var pr=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=n}};function j(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Ma=class extends pr{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}};function L_(r){return j(r)&&r.name==="AuthApiError"}var He=class extends pr{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},rt=class extends pr{constructor(e,t,n,s){super(e,n,s),this.name=t,this.status=n}},Ce=class extends rt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function Ua(r){return j(r)&&r.name==="AuthSessionMissingError"}var Mt=class extends rt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Wr=class extends rt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Hr=class extends rt{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 F_(r){return j(r)&&r.name==="AuthImplicitGrantRedirectError"}var Ai=class extends rt{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}}},ja=class extends rt{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}};var fs=class extends rt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Ba(r){return j(r)&&r.name==="AuthRetryableFetchError"}var Si=class extends rt{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}};var Jr=class extends rt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var $a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),M_=`
|
|
48
|
+
\r=`.split(""),DP=(()=>{let r=new Array(128);for(let e=0;e<r.length;e+=1)r[e]=-1;for(let e=0;e<M_.length;e+=1)r[M_[e].charCodeAt(0)]=-2;for(let e=0;e<$a.length;e+=1)r[$a[e].charCodeAt(0)]=e;return r})();function j_(r,e,t){if(r!==null)for(e.queue=e.queue<<8|r,e.queuedBits+=8;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;t($a[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;t($a[n]),e.queuedBits-=6}}function U_(r,e,t){let n=DP[r];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(r)}"`)}}function vh(r){let e=[],t=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{LP(o,n,t)};for(let o=0;o<r.length;o+=1)U_(r.charCodeAt(o),s,i);return e.join("")}function NP(r,e){if(r<=127){e(r);return}else if(r<=2047){e(192|r>>6),e(128|r&63);return}else if(r<=65535){e(224|r>>12),e(128|r>>6&63),e(128|r&63);return}else if(r<=1114111){e(240|r>>18),e(128|r>>12&63),e(128|r>>6&63),e(128|r&63);return}throw new Error(`Unrecognized Unicode codepoint: ${r.toString(16)}`)}function VP(r,e){for(let t=0;t<r.length;t+=1){let n=r.charCodeAt(t);if(n>55295&&n<=56319){let s=(n-55296)*1024&65535;n=(r.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}NP(n,e)}}function LP(r,e,t){if(e.utf8seq===0){if(r<=127){t(r);return}for(let n=1;n<6;n+=1)if((r>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=r&31;else if(e.utf8seq===3)e.codepoint=r&15;else if(e.utf8seq===4)e.codepoint=r&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(r<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|r&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function mr(r){let e=[],t={queue:0,queuedBits:0},n=s=>{e.push(s)};for(let s=0;s<r.length;s+=1)U_(r.charCodeAt(s),t,n);return new Uint8Array(e)}function B_(r){let e=[];return VP(r,t=>e.push(t)),new Uint8Array(e)}function jt(r){let e=[],t={queue:0,queuedBits:0},n=s=>{e.push(s)};return r.forEach(s=>j_(s,t,n)),j_(null,t,n),e.join("")}function $_(r){return Math.round(Date.now()/1e3)+r}function q_(){return Symbol("auth-callback")}var Te=()=>typeof window!="undefined"&&typeof document!="undefined",Qr={tested:!1,writable:!1},qa=()=>{if(!Te())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Qr.tested)return Qr.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Qr.tested=!0,Qr.writable=!0}catch{Qr.tested=!0,Qr.writable=!1}return Qr.writable};function z_(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 za=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),K_=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",Yr=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},gr=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Re=async(r,e)=>{await r.removeItem(e)},xi=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};xi.promiseConstructor=Promise;function Ri(r){let e=r.split(".");if(e.length!==3)throw new Jr("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!N_.test(e[n]))throw new Jr("JWT not in base64url format");return{header:JSON.parse(vh(e[0])),payload:JSON.parse(vh(e[1])),signature:mr(e[2]),raw:{header:e[0],payload:e[1]}}}async function G_(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function W_(r,e){return new Promise((n,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await r(i);if(!e(i,null,o)){n(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function FP(r){return("0"+r.toString(16)).substr(-2)}function MP(){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,FP).join("")}async function jP(r){let t=new TextEncoder().encode(r),n=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(n);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function UP(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 jP(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Xr(r,e,t=!1){let n=MP(),s=n;t&&(s+="/PASSWORD_RECOVERY"),await Yr(r,`${e}-code-verifier`,s);let i=await UP(n);return[i,n===i?"plain":"s256"]}var BP=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function H_(r){let e=r.headers.get(Ii);if(!e||!e.match(BP))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function J_(r){if(!r)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(r<=e)throw new Error("JWT has expired")}function Q_(r){switch(r){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var $P=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Zr(r){if(!$P.test(r))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ka(){let r={};return new Proxy(r,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){let n=t.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Y_(r,e){return new Proxy(r,{get:(t,n,s)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){let i=n.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,n,s)}return!e.value&&typeof n=="string"&&(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."),e.value=!0),Reflect.get(t,n,s)}})}function bh(r){return JSON.parse(JSON.stringify(r))}var en=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),qP=[502,503,504];async function X_(r){var e;if(!K_(r))throw new fs(en(r),0);if(qP.includes(r.status))throw new fs(en(r),r.status);let t;try{t=await r.json()}catch(i){throw new He(en(i),i)}let n,s=H_(r);if(s&&s.getTime()>=wh["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 Si(en(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Ce}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,o)=>i&&typeof o=="string",!0))throw new Si(en(t),r.status,t.weak_password.reasons);throw new Ma(en(t),r.status||500,n)}var zP=(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 $(r,e,t,n){var s;let i=Object.assign({},n==null?void 0:n.headers);i[Ii]||(i[Ii]=wh["2024-01-01"].name),n!=null&&n.jwt&&(i.Authorization=`Bearer ${n.jwt}`);let o=(s=n==null?void 0:n.query)!==null&&s!==void 0?s:{};n!=null&&n.redirectTo&&(o.redirect_to=n.redirectTo);let u=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await KP(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 KP(r,e,t,n,s,i){let o=zP(e,n,s,i),u;try{u=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new fs(en(c),0)}if(u.ok||await X_(u),n!=null&&n.noResolveJson)return u;try{return await u.json()}catch(c){await X_(c)}}function Je(r){var e;let t=null;GP(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=$_(r.expires_in)));let n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:n},error:null}}function Eh(r){let e=Je(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 wt(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function Z_(r){return{data:r,error:null}}function ew(r){let{action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i}=r,o=qr(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({},o);return{data:{properties:u,user:c},error:null}}function Th(r){return r}function GP(r){return r.access_token&&r.refresh_token&&r.expires_in}var Ga=["global","local","others"];var tn=class{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=za(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,t=Ga[0]){if(Ga.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ga.join(", ")}`);try{return await $(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(j(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,t={}){try{return await $(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:wt})}catch(n){if(j(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:t}=e,n=qr(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 $(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:ew,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(j(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await $(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:wt})}catch(t){if(j(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,n,s,i,o,u,c;try{let l={nextPage:null,lastPage:0,total:0},f=await $(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:Th});if(f.error)throw f.error;let p=await f.json(),g=(o=f.headers.get("x-total-count"))!==null&&o!==void 0?o:0,y=(c=(u=f.headers.get("link"))===null||u===void 0?void 0:u.split(","))!==null&&c!==void 0?c:[];return y.length>0&&(y.forEach(I=>{let R=parseInt(I.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(I.split(";")[1].split("=")[1]);l[`${A}Page`]=R}),l.total=parseInt(g)),{data:Object.assign(Object.assign({},p),l),error:null}}catch(l){if(j(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){Zr(e);try{return await $(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:wt})}catch(t){if(j(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Zr(e);try{return await $(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:wt})}catch(n){if(j(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,t=!1){Zr(e);try{return await $(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:wt})}catch(n){if(j(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){Zr(e.userId);try{let{data:t,error:n}=await $(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(j(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Zr(e.userId),Zr(e.id);try{return{data:await $(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,n,s,i,o,u,c;try{let l={nextPage:null,lastPage:0,total:0},f=await $(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{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:Th});if(f.error)throw f.error;let p=await f.json(),g=(o=f.headers.get("x-total-count"))!==null&&o!==void 0?o:0,y=(c=(u=f.headers.get("link"))===null||u===void 0?void 0:u.split(","))!==null&&c!==void 0?c:[];return y.length>0&&(y.forEach(I=>{let R=parseInt(I.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(I.split(";")[1].split("=")[1]);l[`${A}Page`]=R}),l.total=parseInt(g)),{data:Object.assign(Object.assign({},p),l),error:null}}catch(l){if(j(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(e){try{return await $(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(j(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await $(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(j(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await $(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(j(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await $(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await $(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(j(t))return{data:null,error:t};throw t}}async _listCustomProviders(e){try{let t={};return e!=null&&e.type&&(t.type=e.type),await $(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:n=>{var s;return{data:{providers:(s=n==null?void 0:n.providers)!==null&&s!==void 0?s:[]},error:null}}})}catch(t){if(j(t))return{data:{providers:[]},error:t};throw t}}async _createCustomProvider(e){try{return await $(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(j(t))return{data:null,error:t};throw t}}async _getCustomProvider(e){try{return await $(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(j(t))return{data:null,error:t};throw t}}async _updateCustomProvider(e,t){try{return await $(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(j(n))return{data:null,error:n};throw n}}async _deleteCustomProvider(e){try{return await $(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}}};function Ih(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}var vt={debug:!!(globalThis&&qa()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Pi=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Wa=class extends Pi{};async function Ah(r,e,t){vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let n=new globalThis.AbortController;e>0&&setTimeout(()=>{n.abort(),vt.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await Promise.resolve();try{return await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,s.name);try{return await t()}finally{vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,s.name)}}else{if(e===0)throw vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Wa(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(vt.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()}})}catch(s){if((s==null?void 0:s.name)==="AbortError"&&e>0)return vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",r),console.warn(`@supabase/gotrue-js: Lock "${r}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(r,{mode:"exclusive",steal:!0},async i=>{if(i){vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",r,i.name);try{return await t()}finally{vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",r,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await t()}));throw s}}function tw(){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)}}function Sh(r){if(!/^0x[a-fA-F0-9]{40}$/.test(r))throw new Error(`@supabase/auth-js: Address "${r}" is invalid.`);return r.toLowerCase()}function rw(r){return parseInt(r,16)}function nw(r){let e=new TextEncoder().encode(r);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function sw(r){var e;let{chainId:t,domain:n,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:u,requestId:c,resources:l,scheme:f,uri:p,version:g}=r;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!p)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(g!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${g}`);if(!((e=r.statement)===null||e===void 0)&&e.includes(`
|
|
49
|
+
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${r.statement}`)}let y=Sh(r.address),I=f?`${f}://${n}`:n,R=r.statement?`${r.statement}
|
|
50
|
+
`:"",A=`${I} wants you to sign in with your Ethereum account:
|
|
65
51
|
${y}
|
|
66
52
|
|
|
67
53
|
${R}`,k=`URI: ${p}
|
|
68
|
-
Version: ${
|
|
54
|
+
Version: ${g}
|
|
69
55
|
Chain ID: ${t}${o?`
|
|
70
56
|
Nonce: ${o}`:""}
|
|
71
57
|
Issued At: ${i.toISOString()}`;if(s&&(k+=`
|
|
72
58
|
Expiration Time: ${s.toISOString()}`),u&&(k+=`
|
|
73
59
|
Not Before: ${u.toISOString()}`),c&&(k+=`
|
|
74
|
-
Request ID: ${c}`),
|
|
75
|
-
Resources:`;for(let
|
|
76
|
-
- ${
|
|
77
|
-
${k}`}var ue=class extends Error{constructor({message:e,code:t,cause:n,name:s}){var i;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(i=s!=null?s:n instanceof Error?n.name:void 0)!==null&&i!==void 0?i:"Unknown Error",this.code=t}},Qr=class extends ue{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function nv({error:r,options:e}){var t,n,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ue({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else if(r.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new ue({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:r});if(e.mediation==="conditional"&&((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new ue({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:r});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new ue({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:r})}else{if(r.name==="InvalidStateError")return new ue({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new ue({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="NotSupportedError")return i.pubKeyCredParams.filter(u=>u.type==="public-key").length===0?new ue({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new ue({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:r});if(r.name==="SecurityError"){let o=window.location.hostname;if(Ch(o)){if(i.rp.id!==o)return new ue({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new ue({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:r})}else if(r.name==="UnknownError")return new ue({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}function sv({error:r,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ue({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new ue({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){let n=window.location.hostname;if(Ch(n)){if(t.rpId!==n)return new ue({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new ue({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}var kh=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},aC=new kh;function ov(r){if(!r)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential!="undefined"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(r);let{challenge:e,user:t,excludeCredentials:n}=r,s=Vr(r,["challenge","user","excludeCredentials"]),i=mr(e).buffer,o=Object.assign(Object.assign({},t),{id:mr(t.id).buffer}),u=Object.assign(Object.assign({},s),{challenge:i,user:o});if(n&&n.length>0){u.excludeCredentials=new Array(n.length);for(let c=0;c<n.length;c++){let h=n[c];u.excludeCredentials[c]=Object.assign(Object.assign({},h),{id:mr(h.id).buffer,type:h.type||"public-key",transports:h.transports})}}return u}function av(r){if(!r)throw new Error("Credential request options are required");if(typeof PublicKeyCredential!="undefined"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(r);let{challenge:e,allowCredentials:t}=r,n=Vr(r,["challenge","allowCredentials"]),s=mr(e).buffer,i=Object.assign(Object.assign({},n),{challenge:s});if(t&&t.length>0){i.allowCredentials=new Array(t.length);for(let o=0;o<t.length;o++){let u=t[o];i.allowCredentials[o]=Object.assign(Object.assign({},u),{id:mr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return i}function uv(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();let t=r;return{id:r.id,rawId:r.id,response:{attestationObject:Lt(new Uint8Array(r.response.attestationObject)),clientDataJSON:Lt(new Uint8Array(r.response.clientDataJSON))},type:"public-key",clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function cv(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();let t=r,n=r.getClientExtensionResults(),s=r.response;return{id:r.id,rawId:r.id,response:{authenticatorData:Lt(new Uint8Array(s.authenticatorData)),clientDataJSON:Lt(new Uint8Array(s.clientDataJSON)),signature:Lt(new Uint8Array(s.signature)),userHandle:s.userHandle?Lt(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Ch(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}function iv(){var r,e;return!!(be()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((r=navigator==null?void 0:navigator.credentials)===null||r===void 0?void 0:r.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function uC(r){try{let e=await navigator.credentials.create(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Qr("Browser returned unexpected credential type",e)}:{data:null,error:new Qr("Empty credential response",e)}}catch(e){return{data:null,error:nv({error:e,options:r})}}}async function cC(r){try{let e=await navigator.credentials.get(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Qr("Browser returned unexpected credential type",e)}:{data:null,error:new Qr("Empty credential response",e)}}catch(e){return{data:null,error:sv({error:e,options:r})}}}var lC={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},hC={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function qa(...r){let e=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),n={};for(let s of r)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))n[i]=o;else if(t(o))n[i]=o;else if(e(o)){let u=n[i];e(u)?n[i]=qa(u,o):n[i]=qa(o)}else n[i]=o}return n}function dC(r,e){return qa(lC,r,e||{})}function fC(r,e){return qa(hC,r,e||{})}var za=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:n,signal:s},i){var o;try{let{data:u,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!u)return{data:null,error:c};let h=s!=null?s:aC.createNewAbortSignal();if(u.webauthn.type==="create"){let{user:f}=u.webauthn.credential_options.publicKey;if(!f.name){let p=n;if(p)f.name=`${f.id}:${p}`;else{let y=(await this.client.getUser()).data.user,T=((o=y==null?void 0:y.user_metadata)===null||o===void 0?void 0:o.name)||(y==null?void 0:y.email)||(y==null?void 0:y.id)||"User";f.name=`${f.id}:${T}`}}f.displayName||(f.displayName=f.name)}switch(u.webauthn.type){case"create":{let f=dC(u.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:p,error:m}=await uC({publicKey:f,signal:h});return p?{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:p}},error:null}:{data:null,error:m}}case"request":{let f=fC(u.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:p,error:m}=await cC(Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:f,signal:h}));return p?{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:p}},error:null}:{data:null,error:m}}}}catch(u){return U(u)?{data:null,error:u}:{data:null,error:new He("Unexpected error in challenge",u)}}}async _verify({challengeId:e,factorId:t,webauthn:n}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window!="undefined"?window.location.hostname:void 0,rpOrigins:n=typeof window!="undefined"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new pr("rpId is required for WebAuthn authentication")};try{if(!iv())return{data:null,error:new He("Browser does not support WebAuthn",null)};let{data:o,error:u}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:n},signal:s},{request:i});if(!o)return{data:null,error:u};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:n,credential_response:c.credential_response}})}catch(o){return U(o)?{data:null,error:o}:{data:null,error:new He("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window!="undefined"?window.location.hostname:void 0,rpOrigins:n=typeof window!="undefined"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new pr("rpId is required for WebAuthn registration")};try{if(!iv())return{data:null,error:new He("Browser does not support WebAuthn",null)};let{data:o,error:u}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(f=>{var p;return(p=f.data)===null||p===void 0?void 0:p.all.find(m=>m.factor_type==="webauthn"&&m.friendly_name===e&&m.status!=="unverified")}).then(f=>f?this.client.mfa.unenroll({factorId:f==null?void 0:f.id}):void 0),{data:null,error:u};let{data:c,error:h}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:n},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:n,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:h}}catch(o){return U(o)?{data:null,error:o}:{data:null,error:new He("Unexpected error in register",o)}}}};Z_();var pC={url:P_,storageKey:C_,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:k_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4,skipAutoInitialize:!1};async function lv(r,e,t){return await t()}var as={},Ka=class r{get jwks(){var e,t;return(t=(e=as[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){as[this.storageKey]=Object.assign(Object.assign({},as[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=as[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){as[this.storageKey]=Object.assign(Object.assign({},as[this.storageKey]),{cachedAt:e})}constructor(e){var t,n,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=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;let i=Object.assign(Object.assign({},pC),e);if(this.storageKey=i.storageKey,this.instanceID=(t=r.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,r.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&be()){let o=`${this._logPrefix()} 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.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Wr({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Ua(i.fetch),this.lock=i.lock||lv,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&be()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=Rh:this.lock=lv,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new za(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:Ma()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=xh(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=xh(this.memoryStorage)),be()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(u){this._debug("#broadcastChannel","error",u)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ka}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let t={},n="none";if(be()&&(t=$_(window.location.href),this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce")),be()&&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{error:i}}let{session:o,redirectType:u}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",u),await this._saveSession(o),setTimeout(async()=>{u==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return U(t)?this._returnResult({error:t}):this._returnResult({error:new He("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,s;try{let i=await $(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:Qe}),{data:o,error:u}=i;if(u||!o)return this._returnResult({data:{user:null,session:null},error:u});let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:h,session:c},error:null})}catch(i){if(U(i))return this._returnResult({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:p,options:m}=e,y=null,T=null;this.flowType==="pkce"&&([y,T]=await zr(this.storage,this.storageKey)),i=await $(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m==null?void 0:m.emailRedirectTo,body:{email:f,password:p,data:(t=m==null?void 0:m.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:y,code_challenge_method:T},xform:Qe})}else if("phone"in e){let{phone:f,password:p,options:m}=e;i=await $(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:p,data:(n=m==null?void 0:m.data)!==null&&n!==void 0?n:{},channel:(s=m==null?void 0:m.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken}},xform:Qe})}else throw new Mr("You must provide either an email or phone number and a password");let{data:o,error:u}=i;if(u||!o)return await Se(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:u});let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:h,session:c},error:null})}catch(i){if(await Se(this.storage,`${this.storageKey}-code-verifier`),U(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:u}=e;t=await $(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Sh})}else if("phone"in e){let{phone:i,password:o,options:u}=e;t=await $(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Sh})}else throw new Mr("You must provide either an email or phone number and a password");let{data:n,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!n||!n.session||!n.user){let i=new Vt;return this._returnResult({data:{user:null,session:null},error:i})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:s})}catch(t){if(U(t))return this._returnResult({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(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,n,s,i,o,u,c,h,f,p,m;let y,T;if("message"in e)y=e.message,T=e.signature;else{let{chain:R,wallet:I,statement:k,options:O}=e,D;if(be())if(typeof I=="object")D=I;else{let w=window;if("ethereum"in w&&typeof w.ethereum=="object"&&"request"in w.ethereum&&typeof w.ethereum.request=="function")D=w.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof I!="object"||!(O!=null&&O.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");D=I}let j=new URL((t=O==null?void 0:O.url)!==null&&t!==void 0?t:window.location.href),H=await D.request({method:"eth_requestAccounts"}).then(w=>w).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!H||H.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let F=Ph(H[0]),E=(n=O==null?void 0:O.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!E){let w=await D.request({method:"eth_chainId"});E=ev(w)}let _={domain:j.host,address:F,statement:k,uri:j.href,version:"1",chainId:E,nonce:(s=O==null?void 0:O.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=O==null?void 0:O.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(u=O==null?void 0:O.signInWithEthereum)===null||u===void 0?void 0:u.expirationTime,notBefore:(c=O==null?void 0:O.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(h=O==null?void 0:O.signInWithEthereum)===null||h===void 0?void 0:h.requestId,resources:(f=O==null?void 0:O.signInWithEthereum)===null||f===void 0?void 0:f.resources};y=rv(_),T=await D.request({method:"personal_sign",params:[tv(y),F]})}try{let{data:R,error:I}=await $(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:y,signature:T},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Qe});if(I)throw I;if(!R||!R.session||!R.user){let k=new Vt;return this._returnResult({data:{user:null,session:null},error:k})}return R.session&&(await this._saveSession(R.session),await this._notifyAllSubscribers("SIGNED_IN",R.session)),this._returnResult({data:Object.assign({},R),error:I})}catch(R){if(U(R))return this._returnResult({data:{user:null,session:null},error:R});throw R}}async signInWithSolana(e){var t,n,s,i,o,u,c,h,f,p,m,y;let T,R;if("message"in e)T=e.message,R=e.signature;else{let{chain:I,wallet:k,statement:O,options:D}=e,j;if(be())if(typeof k=="object")j=k;else{let F=window;if("solana"in F&&typeof F.solana=="object"&&("signIn"in F.solana&&typeof F.solana.signIn=="function"||"signMessage"in F.solana&&typeof F.solana.signMessage=="function"))j=F.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof k!="object"||!(D!=null&&D.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");j=k}let H=new URL((t=D==null?void 0:D.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in j&&j.signIn){let F=await j.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},D==null?void 0:D.signInWithSolana),{version:"1",domain:H.host,uri:H.href}),O?{statement:O}:null)),E;if(Array.isArray(F)&&F[0]&&typeof F[0]=="object")E=F[0];else if(F&&typeof F=="object"&&"signedMessage"in F&&"signature"in F)E=F;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in E&&"signature"in E&&(typeof E.signedMessage=="string"||E.signedMessage instanceof Uint8Array)&&E.signature instanceof Uint8Array)T=typeof E.signedMessage=="string"?E.signedMessage:new TextDecoder().decode(E.signedMessage),R=E.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in j)||typeof j.signMessage!="function"||!("publicKey"in j)||typeof j!="object"||!j.publicKey||!("toBase58"in j.publicKey)||typeof j.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");T=[`${H.host} wants you to sign in with your Solana account:`,j.publicKey.toBase58(),...O?["",O,""]:[""],"Version: 1",`URI: ${H.href}`,`Issued At: ${(s=(n=D==null?void 0:D.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=D==null?void 0:D.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${D.signInWithSolana.notBefore}`]:[],...!((o=D==null?void 0:D.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${D.signInWithSolana.expirationTime}`]:[],...!((u=D==null?void 0:D.signInWithSolana)===null||u===void 0)&&u.chainId?[`Chain ID: ${D.signInWithSolana.chainId}`]:[],...!((c=D==null?void 0:D.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${D.signInWithSolana.nonce}`]:[],...!((h=D==null?void 0:D.signInWithSolana)===null||h===void 0)&&h.requestId?[`Request ID: ${D.signInWithSolana.requestId}`]:[],...!((p=(f=D==null?void 0:D.signInWithSolana)===null||f===void 0?void 0:f.resources)===null||p===void 0)&&p.length?["Resources",...D.signInWithSolana.resources.map(E=>`- ${E}`)]:[]].join(`
|
|
78
|
-
`);let F=await j.signMessage(new TextEncoder().encode(T),"utf8");if(!F||!(F instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");R=F}}try{let{data:I,error:k}=await $(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:T,signature:Lt(R)},!((m=e.options)===null||m===void 0)&&m.captchaToken?{gotrue_meta_security:{captcha_token:(y=e.options)===null||y===void 0?void 0:y.captchaToken}}:null),xform:Qe});if(k)throw k;if(!I||!I.session||!I.user){let O=new Vt;return this._returnResult({data:{user:null,session:null},error:O})}return I.session&&(await this._saveSession(I.session),await this._notifyAllSubscribers("SIGNED_IN",I.session)),this._returnResult({data:Object.assign({},I),error:k})}catch(I){if(U(I))return this._returnResult({data:{user:null,session:null},error:I});throw I}}async _exchangeCodeForSession(e){let t=await gr(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{if(!n&&this.flowType==="pkce")throw new Va;let{data:i,error:o}=await $(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Qe});if(await Se(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let u=new Vt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:u})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s!=null?s:null}),error:o})}catch(i){if(await Se(this.storage,`${this.storageKey}-code-verifier`),U(i))return this._returnResult({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:o}=e,u=await $(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:Qe}),{data:c,error:h}=u;if(h)return this._returnResult({data:{user:null,session:null},error:h});if(!c||!c.session||!c.user){let f=new Vt;return this._returnResult({data:{user:null,session:null},error:f})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:h})}catch(t){if(U(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,n,s,i,o;try{if("email"in e){let{email:u,options:c}=e,h=null,f=null;this.flowType==="pkce"&&([h,f]=await zr(this.storage,this.storageKey));let{error:p}=await $(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 this._returnResult({data:{user:null,session:null},error:p})}if("phone"in e){let{phone:u,options:c}=e,{data:h,error:f}=await $(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:(o=c==null?void 0:c.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:h==null?void 0:h.message_id},error:f})}throw new Mr("You must provide either an email or phone number.")}catch(u){if(await Se(this.storage,`${this.storageKey}-code-verifier`),U(u))return this._returnResult({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:o,error:u}=await $(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Qe});if(u)throw u;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=o.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:h,session:c},error:null})}catch(s){if(U(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,n,s,i,o;try{let u=null,c=null;this.flowType==="pkce"&&([u,c]=await zr(this.storage,this.storageKey));let h=await $(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:u,code_challenge_method:c}),headers:this.headers,xform:X_});return!((i=h.data)===null||i===void 0)&&i.url&&be()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(h.data.url),this._returnResult(h)}catch(u){if(await Se(this.storage,`${this.storageKey}-code-verifier`),U(u))return this._returnResult({data:null,error:u});throw u}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,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 Re;let{error:s}=await $(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(U(e))return this._returnResult({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:o}=await $(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 this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:s,options:i}=e,{data:o,error:u}=await $(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:u})}throw new Mr("You must provide either an email or phone number and a type")}catch(t){if(U(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,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 gr(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<Da:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await gr(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Ba()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=Q_(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await $(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:gt}):await this._useSession(async t=>{var n,s,i;let{data:o,error:u}=t;if(u)throw u;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Re}:await $(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:gt})})}catch(t){if(U(t))return La(t)&&(await this._removeSession(),await Se(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,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 Re;let o=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await zr(this.storage,this.storageKey));let{data:h,error:f}=await $(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:o.access_token,xform:gt});if(f)throw f;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await Se(this.storage,`${this.storageKey}-code-verifier`),U(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Re;let t=Date.now()/1e3,n=t,s=!0,i=null,{payload:o}=bi(e.access_token);if(o.exp&&(n=o.exp,s=n<=t),s){let{data:u,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({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)return this._returnResult({data:{user:null,session:null},error: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 this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(U(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var n;if(!e){let{data:o,error:u}=t;if(u)throw u;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new Re;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(U(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!be())throw new Ur("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ur(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 _i("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ur("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 _i("No code detected.");let{data:O,error:D}=await this._exchangeCodeForSession(e.code);if(D)throw D;let j=new URL(window.location.href);return j.searchParams.delete("code"),window.history.replaceState(window.history.state,"",j.toString()),{data:{session:O.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:o,expires_in:u,expires_at:c,token_type:h}=e;if(!i||!u||!o||!h)throw new Ur("No session defined in URL");let f=Math.round(Date.now()/1e3),p=parseInt(u),m=f+p;c&&(m=parseInt(c));let y=m-f;y*1e3<=jr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${y}s, should have been closer to ${p}s`);let T=m-p;f-T>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",T,m,f):f-T<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",T,m,f);let{data:R,error:I}=await this._getUser(i);if(I)throw I;let k={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:p,expires_at:m,refresh_token:o,token_type:h,user:R.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:k,redirectType:e.type},error:null})}catch(n){if(U(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await gr(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,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&&!La(i))return this._returnResult({error:i});let o=(n=s.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:u}=await this.admin.signOut(o,e);if(u&&!(N_(u)&&(u.status===404||u.status===401||u.status===403)||La(u)))return this._returnResult({error:u})}return e!=="others"&&(await this._removeSession(),await Se(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=B_(),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(this.lockAcquireTimeout,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:o}=t;if(o)throw o;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 zr(this.storage,this.storageKey,!0));try{return await $(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(await Se(this.storage,`${this.storageKey}-code-verifier`),U(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:t,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{let{data:n,error:s}=await this._useSession(async i=>{var o,u,c,h,f;let{data:p,error:m}=i;if(m)throw m;let y=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.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 $(this.fetch,"GET",y,{headers:this.headers,jwt:(f=(h=p.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(s)throw s;return be()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),this._returnResult({data:{provider:e.provider,url:n==null?void 0:n.url},error:null})}catch(n){if(U(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var n;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:u,token:c,access_token:h,nonce:f}=e,p=await $(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=i==null?void 0:i.access_token)!==null&&n!==void 0?n:void 0,body:{provider:u,id_token:c,access_token:h,nonce:f,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Qe}),{data:m,error:y}=p;return y?this._returnResult({data:{user:null,session:null},error:y}):!m||!m.session||!m.user?this._returnResult({data:{user:null,session:null},error:new Vt}):(m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("USER_UPDATED",m.session)),this._returnResult({data:m,error:y}))}catch(s){if(await Se(this.storage,`${this.storageKey}-code-verifier`),U(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:o}=t;if(o)throw o;return await $(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(U(t))return this._returnResult({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 z_(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await $(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Qe})),(s,i)=>{let o=200*Math.pow(2,s);return i&&Fa(i)&&Date.now()+o-n<jr})}catch(n){if(this._debug(t,"error",n),U(n))return this._returnResult({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),be()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,t;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let s=await gr(this.storage,this.storageKey);if(s&&this.userStorage){let o=await gr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await qr(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Ba()}else if(s&&!s.user&&!s.user){let o=await gr(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(s.user=o.user,await Se(this.storage,this.storageKey+"-user"),await qr(this.storage,this.storageKey,s)):s.user=Ba()}if(this._debug(n,"session from storage",s),!this._isValidSession(s)){this._debug(n,"session is not valid"),s!==null&&await this._removeSession();return}let i=((t=s.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<Da;if(this._debug(n,`session has${i?"":" not"} expired with margin of ${Da}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Fa(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:u}=await this._getUser(s.access_token);!u&&(o!=null&&o.user)?(s.user=o.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(n,"error",s),console.error(s);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var t,n;if(!e)throw new Re;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new wi;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new Re;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let u={data:i.session,error:null};return this.refreshingDeferred.resolve(u),u}catch(i){if(this._debug(s,"error",i),U(i)){let o={data:null,error:i};return Fa(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}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=[],o=Array.from(this.stateChangeEmitters.values()).map(async u=>{try{await u.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),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 Se(this.storage,`${this.storageKey}-code-verifier`);let t=Object.assign({},e),n=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&t.user&&await qr(this.userStorage,this.storageKey+"-user",{user:t.user});let s=Object.assign({},t);delete s.user;let i=Ih(s);await qr(this.storage,this.storageKey,i)}else{let s=Ih(t);await qr(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Se(this.storage,this.storageKey),await Se(this.storage,this.storageKey+"-code-verifier"),await Se(this.storage,this.storageKey+"-user"),this.userStorage&&await Se(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&be()&&(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(),jr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}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)/jr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${jr}ms, refresh threshold is ${Oa} ticks`),s<=Oa&&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 Ei)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!be()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},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(this.lockAcquireTimeout,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,o]=await zr(this.storage,this.storageKey),u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});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?this._returnResult({data:null,error:i}):await $(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(U(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let u=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:h}=await $(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?this._returnResult({data:null,error:h}):(e.factorType==="totp"&&c.type==="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}`),this._returnResult({data:c,error:null}))})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?uv(e.webauthn.credential_response):cv(e.webauthn.credential_response)})}:{code:e.code}),{data:u,error:c}=await $(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+u.expires_in},u)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:u,error:c}))})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let o=await $(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:u}=o;if(u.type!=="webauthn")return{data:u,error:null};switch(u.webauthn.type){case"create":return{data:Object.assign(Object.assign({},u),{webauthn:Object.assign(Object.assign({},u.webauthn),{credential_options:Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:ov(u.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},u),{webauthn:Object.assign(Object.assign({},u.webauthn),{credential_options:Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:av(u.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}})}async _challengeAndVerify(e){let{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};let s={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=t==null?void 0:t.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,n,s,i;if(e)try{let{payload:y}=bi(e),T=null;y.aal&&(T=y.aal);let R=T,{data:{user:I},error:k}=await this.getUser(e);if(k)return this._returnResult({data:null,error:k});((n=(t=I==null?void 0:I.factors)===null||t===void 0?void 0:t.filter(j=>j.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(R="aal2");let D=y.amr||[];return{data:{currentLevel:T,nextLevel:R,currentAuthenticationMethods:D},error:null}}catch(y){if(U(y))return this._returnResult({data:null,error:y});throw y}let{data:{session:o},error:u}=await this.getSession();if(u)return this._returnResult({data:null,error:u});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=bi(o.access_token),h=null;c.aal&&(h=c.aal);let f=h;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(y=>y.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(f="aal2");let m=c.amr||[];return{data:{currentLevel:h,nextLevel:f,currentAuthenticationMethods:m},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:n},error:s}=t;return s?this._returnResult({data:null,error:s}):n?await $(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Re})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Re});let o=await $(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:u=>({data:u,error:null})});return o.data&&o.data.redirect_url&&be()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Re});let o=await $(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:u=>({data:u,error:null})});return o.data&&o.data.redirect_url&&be()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;return n?this._returnResult({data:null,error:n}):t?await $(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Re})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:n},error:s}=t;return s?this._returnResult({data:null,error:s}):n?(await $(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Re})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(u=>u.kid===e);if(n)return n;let s=Date.now();if(n=this.jwks.keys.find(u=>u.kid===e),n&&this.jwks_cached_at+D_>s)return n;let{data:i,error:o}=await $(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,n=i.keys.find(u=>u.kid===e),!n)?null:n}async getClaims(e,t={}){try{let n=e;if(!n){let{data:y,error:T}=await this.getSession();if(T||!y.session)return this._returnResult({data:null,error:T});n=y.session.access_token}let{header:s,payload:i,signature:o,raw:{header:u,payload:c}}=bi(n);t!=null&&t.allowExpired||W_(i.exp);let h=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t!=null&&t.keys?{keys:t.keys}:t==null?void 0:t.jwks);if(!h){let{error:y}=await this.getUser(n);if(y)throw y;return{data:{claims:i,header:s,signature:o},error:null}}let f=H_(s.alg),p=await crypto.subtle.importKey("jwk",h,f,!0,["verify"]);if(!await crypto.subtle.verify(f,p,o,M_(`${u}.${c}`)))throw new Br("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}};Ka.nextInstanceID={};var Oh=Ka;var mC=Oh,Dh=mC;var gC="2.97.0",Ii="";typeof Deno!="undefined"?Ii="deno":typeof document!="undefined"?Ii="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?Ii="react-native":Ii="node";var yC={"X-Client-Info":`supabase-js-${Ii}/${gC}`},_C={headers:yC},vC={schema:"public"},wC={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},bC={};function Si(r){"@babel/helpers - typeof";return Si=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Si(r)}function EC(r,e){if(Si(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e||"default");if(Si(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function TC(r){var e=EC(r,"string");return Si(e)=="symbol"?e:e+""}function IC(r,e,t){return(e=TC(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function hv(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,n)}return t}function de(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?hv(Object(t),!0).forEach(function(n){IC(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):hv(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var SC=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),AC=()=>Headers,xC=(r,e,t)=>{let n=SC(t),s=AC();return async(i,o)=>{var u;let c=(u=await e())!==null&&u!==void 0?u:r,h=new s(o==null?void 0:o.headers);return h.has("apikey")||h.set("apikey",r),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),n(i,de(de({},o),{},{headers:h}))}};function RC(r){return r.endsWith("/")?r:r+"/"}function PC(r,e){var t,n;let{db:s,auth:i,realtime:o,global:u}=r,{db:c,auth:h,realtime:f,global:p}=e,m={db:de(de({},c),s),auth:de(de({},h),i),realtime:de(de({},f),o),storage:{},global:de(de(de({},p),u),{},{headers:de(de({},(t=p==null?void 0:p.headers)!==null&&t!==void 0?t:{}),(n=u==null?void 0:u.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return r.accessToken?m.accessToken=r.accessToken:delete m.accessToken,m}function CC(r){let e=r==null?void 0:r.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(RC(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var kC=class extends Dh{constructor(r){super(r)}},OC=class{constructor(r,e,t){var n,s;this.supabaseUrl=r,this.supabaseKey=e;let i=CC(r);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);let o=`sb-${i.hostname.split(".")[0]}-auth-token`,u={db:vC,realtime:bC,auth:de(de({},wC),{},{storageKey:o}),global:_C},c=PC(t!=null?t:{},u);if(this.storageKey=(n=c.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(s=c.global.headers)!==null&&s!==void 0?s:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(f,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}});else{var h;this.auth=this._initSupabaseAuthClient((h=c.auth)!==null&&h!==void 0?h:{},this.headers,c.global.fetch)}this.fetch=xC(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(de({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(f=>this.realtime.setAuth(f)).catch(f=>console.warn("Failed to set initial Realtime auth token:",f)),this.rest=new f_(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new R_(this.storageUrl.href,this.headers,this.fetch,t==null?void 0:t.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new ui(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(r){return this.rest.from(r)}schema(r){return this.rest.schema(r)}rpc(r,e={},t={head:!1,get:!1,count:void 0}){return this.rest.rpc(r,e,t)}channel(r,e={config:{}}){return this.realtime.channel(r,e)}getChannels(){return this.realtime.getChannels()}removeChannel(r){return this.realtime.removeChannel(r)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var r=this,e,t;if(r.accessToken)return await r.accessToken();let{data:n}=await r.auth.getSession();return(e=(t=n.session)===null||t===void 0?void 0:t.access_token)!==null&&e!==void 0?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:n,userStorage:s,storageKey:i,flowType:o,lock:u,debug:c,throwOnError:h},f,p){let m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new kC({url:this.authUrl.href,headers:de(de({},m),f),storageKey:i,autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:n,userStorage:s,flowType:o,lock:u,debug:c,throwOnError:h,fetch:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(y=>y.toLowerCase()==="authorization")})}_initRealtimeClient(r){return new ns(this.realtimeUrl.href,de(de({},r),{},{params:de(de({},{apikey:this.supabaseKey}),r==null?void 0:r.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,e)=>{this._handleTokenChanged(r,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(r,e,t){(r==="TOKEN_REFRESHED"||r==="SIGNED_IN")&&this.changedAccessToken!==t?(this.changedAccessToken=t,this.realtime.setAuth(t)):r==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},dv=(r,e,t)=>new OC(r,e,t);function DC(){if(typeof window!="undefined")return!1;let r=globalThis.process;if(!r)return!1;let e=r.version;if(e==null)return!1;let t=e.match(/^v(\d+)\./);return t?parseInt(t[1],10)<=18:!1}DC()&&console.warn("\u26A0\uFE0F Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var vv=yw(yv(),1);var VC=Object.prototype.toString,LC=r=>VC.call(r)==="[object Error]",FC=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Nh(r){if(!(r&&LC(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")?!0:FC.has(t)}var Vh=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}},_v=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Ai(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=vv.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 o=()=>{var f;(f=e.signal)==null||f.removeEventListener("abort",i),s.stop()};s.attempt(async f=>{try{let p=await r(f);o(),t(p)}catch(p){try{if(!(p instanceof Error))throw new TypeError(`Non-error was thrown: "${p}". You should only throw errors.`);if(p instanceof Vh)throw p.originalError;if(p instanceof TypeError&&!Nh(p))throw p;if(_v(p,f,e),await e.shouldRetry(p)||(s.stop(),n(p)),await e.onFailedAttempt(p),!s.retry(p))throw s.mainError()}catch(m){_v(m,f,e),o(),n(m)}}})})}var jC=function(e,t){if(typeof e!="function")throw new Error("First argument to supabasey() must be a callback function");let n={session:null,retries:3,retry:{minTimeout:100,factor:2,randomize:!0,onFailedAttempt:i=>console.info(`[Attempt ${i.attemptNumber}/${i.attemptNumber+i.retriesLeft-1}] failed to run Supabase query`),shouldRetry:i=>(console.log("QUERY SHOULD-RETRY",i),!0)},...t},s=n.session?typeof n.session=="string"?Ee.sessions[n.session]:typeof n.session=="object"?n.session:(()=>{throw new Error(`Unknown session type for supabasey(cb, {session}) - expected Object|String got ${typeof n.session}`)})():(()=>{throw new Error("supabasey(cb, {session}) cannot be empty - specify a session or use bindSession() first")})();return Promise.resolve().then(()=>Ai(()=>e.call(s,s),{...n.retries&&{retries:n.retries},...t.retry})).then(i=>{if(i!=null&&i.error)Ee.throw(i.error);else if(i.data)return i.data}).catch(i=>{throw console.log("Supabasey error:",i),i})},Ee=jC;Ee.bindSession=function(e){if(typeof e=="string"&&!Ee.sessions[e])throw new Error(`Unable to bind to non-existant session "${e}"`);let t=(n,s)=>Ee(n,{session:e,...s});return t.rpc=(n,s,i)=>Ee.rpc(n,s,{session:e,...i}),t};Ee.init=function(e){let t={env:{},init:!0,login:!1,session:"auto",...e},n=t.env,s=t.session=="auto"&&n.SUPABASE_URL?n.SUPABASE_URL:t.session?t.session:(()=>{throw new Error("Sesison should be truthy if using @iebh/supabasey.middleware({session:String})")})(),i=Ee.sessions[s];return Promise.resolve().then(()=>{if(!i)if(t.init){if(!n.SUPABASE_URL||!n.SUPABASE_KEY)throw new Error("Both env.SUPABASE_URL + env.SUPABASE_KEY should be specified to use @iebh/supabasey.middleware(), otherwise disable with {init:false}");i=Ee.sessions[s]=dv(n.SUPABASE_URL,n.SUPABASE_KEY)}else throw new Error("No Supabase session for middleware to work with!")}).then(()=>{if(t.login){if(i.supabaseyIsLoggedIn)return;if(!n.SUPABASE_USER||!n.SUPABASE_PASS)throw new Error("User credentials missing when using @iebh/supabasey.middleware(), provide in env.SUPABASE_USER + ..._PASS");return Ee(o=>o.auth.signInWithPassword({email:n.SUPABASE_USER,password:n.SUPABASE_PASS}),{session:i}).then(()=>i.supabaseyIsLoggedIn=!0)}else return}).then(()=>Ee.bindSession(i))};Ee.middleware=function(e){let t={env:{},injectEnv:!0,...e};return async(n,s,i,o)=>Ee.init({...e,env:i}).then(u=>{t.injectEnv&&(i.supabasey=u)}).catch(u=>Ee.throw(u))};Ee.throw=function(r){throw typeof r=="string"?new Error(r):r instanceof Error?r:/JSON object requested, multiple \(or no\) rows returned$/.test(r.message)?(console.warn("Supabase query resulted in NOT-FOUND:",r.message),console.warn("Supabase raw error",r),new Error("NOT-FOUND")):(console.warn("Supabase query threw",r.message||r||"Unknown error"),new Error(`${(r==null?void 0:r.code)||"UnknownError"}: ${(r==null?void 0:r.message)||"Unknown Supabase error"}`))};Ee.rpc=function(r,e,t){return Ee(async n=>await n.rpc(r,e),t)};Ee.sessions={};var wv=Ee;function MC(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function Ga(r,e){return Array.isArray(r)?r.map(t=>Ga(t,e)):typeof r=="object"?r==null?null:Object.fromEntries(Object.entries(MC(r,e)).map(([t,n])=>[t,Ga(n,e)])):r}var bv={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var Ev={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var Tv={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 Iv={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var Sv={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 Av={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var xv={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var us={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[bv,Ev,Tv,Iv,Sv,Av,xv],circular:!0,symetric:!1},loadedModules:{},loadModules(r){return r.map(e=>{if(ee(e)){if(!e.id)throw new Error("Provided custom module does not expose an `id` property");return us.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=go(e,us.settings),n=us.loadModules(t.modules),s=t.symetric?Ga(r):t.clone?Zt(r):r,i=new Map,o=(u,c)=>{let h=ee(u);if(h&&t.circular){let m=i.get(u);if(m)return er(s,c,{_:"~circular",p:m.join(".")});i.set(u,c)}let f=n.find(m=>m.test(u,c)),p=(!t.depth||c.length<t.depth)&&h;if(f){let m=f.serialize(u,c);if(f.recursive&&p){let y=De(u);t.symetric&&y.sort(),er(s,c,m),y.forEach(T=>o(u[T],c.concat(T)))}else c.length?er(s,c,m):s=m}else if(p){let m=De(u);t.symetric&&m.sort(),m.forEach(y=>o(u[y],c.concat(y)))}};return o(s,[]),t.stringify?JSON.stringify(s):s},deserialize(r,e){let t=go(e,us.settings),n=us.loadModules(t.modules),s=Au(n,"id"),i=t.destringify?JSON.parse(r):t.clone?Zt(r):r,o=(u,c)=>{if(ee(u)&&u._&&typeof u._=="string"&&u._.startsWith("~")&&s[u._]){let h=s[u._].deserialize(u,c);c.length?s[u._].recursive&&ee(h)?(er(i,c,h),De(h).forEach(f=>o(u[f],[...c,f]))):er(i,c,h):i=h}else t.circular&&ee(u)&&u._&&u._=="~circular"?er(i,c,Cs(i,u.p)):(!t.depth||c.length<t.depth)&&ee(u)&&De(u).forEach(h=>o(u[h],c.concat(h)))};return o(i,[]),i}},Wa=us;var Rv="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Pv=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Rv[t[r]&63];return e};var Ft=class r{constructor(e,t){this.throttle=250;this.config={heartbeatInterval:12e4,syncroRegistryUrl:"https://tera-tools.com/api/sync",context:{}};this.isDirty=!1;this._destroyActions=[];this.path=e,Object.assign(this,{...t,config:{...this.config,...t==null?void 0:t.config}}),r.session||(r.session=`syncro_${Pv()}`)}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 Zt(t)},watch(n){}}}static pathSplit(e,t){var o;let n={allowAsterisk:!1,...t},i={...(o=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:o.groups};if(!i||!i.entity||!i.id)throw new Error(`Invalid session path syntax "${e}"`);if(r.SyncroEntities&&!(i.entity in r.SyncroEntities))throw new Error(`Unsupported entity "${e}" -> Entity="${i.entity}"`);return{entity:i.entity,id:i.id,relation:i.relation,fsCollection:i.entity,fsId:i.relation?`${i.id}::${i.relation}`:i.id}}static toFirestore(e={}){return Wa.serialize(e,{...Cv,stringify:!1})}static fromFirestore(e={}){return Wa.deserialize(e,{...Cv,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(o=>r.toFirestoreFields({item:o}).item)}}:i==="object"&&(t[n]={mapValue:{fields:r.toFirestoreFields(s)}})}return t}static fromFirestoreFields(e={}){let t={};for(let n in e){let s=e[n],i=["stringValue","booleanValue","doubleValue","integerValue","timestampValue","mapValue","arrayValue","nullValue"].find(o=>o===Object.keys(s)[0]);if(i)switch(i){case"mapValue":t[n]=r.fromFirestoreFields(s.mapValue.fields||{});break;case"arrayValue":{let o=s.arrayValue.values;t[n]=o?o.map(u=>r.fromFirestoreFields(u)):[];break}case"nullValue":t[n]=null;break;default:t[n]=s[i]}else t[n]=r.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=r.pathSplit(e);return Promise.resolve().then(async()=>ah(ba(r.firestore,t,n))).then(s=>s.exists()?r.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:i,fsId:o}=r.pathSplit(e),u=ba(r.firestore,i,o),c=r.toFirestore(t);return Promise.resolve().then(()=>s.method==="merge"?ch(u,c):uh(u,c)).then(()=>t)}mount(e){let t={initialState:null,retries:5,retryMinTime:250,...e},{fsCollection:n,fsId:s,entity:i}=r.pathSplit(this.path),o,u;return Ai(async()=>{await this.setHeartbeat(!1),this.docRef=ba(r.firestore,n,s);let c=await this.getFirestoreState();if(this.path.startsWith("projects::")&&c&&!yo(c)&&c.users&&!c.type&&!c.name&&!c.created){this.debugError("Zombie state detected (Partial document). Forcing repair...");let f=await fetch(`${this.config.syncroRegistryUrl}/${this.path}?drop=1&force=1`);f.ok?(this.debug("Repair signal sent successfully. Reloading local state..."),c=await this.getFirestoreState()):console.error("[Syncro] Self-healing failed",f.statusText)}if(o=this.getReactive(c),!o.doc||!o.setState||!o.getState||!o.watch)throw new Error("Syncro.getReactive() requires a returned `doc`, `setState()`, `getState()` + `watch()`");this.value=u=o.doc,this.debug("Initial state",{doc:u});let h=i_(this.docRef,f=>{let p=r.fromFirestore(f.data());this.debug("Incoming snapshot",{snapshotData:p}),o.setState(p)});if(this._destroyActions.push(h),yo(u))if(t.initialState)this.debug("Populate initial Syncro state (from provided initialState)"),await this.setFirestoreState(t.initialState,{method:"set"});else{this.debug(`Populate initial Syncro state (from "${i}" Syncro worker)`);let f=await fetch(`${this.config.syncroRegistryUrl}/${this.path}`);if(!f.ok)throw new Error(`Failed to check Syncro "${n}::${s}" status - ${f.statusText}`)}return o.watch(xu(f=>{this.debug("Local change",{newState:f}),this.markDirty(),this.setFirestoreState(f,{method:"merge"})},this.throttle)),await this.setHeartbeat(!0,{immediate:!0}),this},{retries:t.retries,minTimeout:t.retryMinTime,randomize:!0,factor:3,onFailedAttempt:async c=>{this.debugError(`[Attempt ${c.attemptNumber}/${c.attemptNumber+c.retriesLeft-1}] to mount syncro`,c),await this.destroy()}})}async set(e,t,n){let s;if(typeof e=="string")s[e]=t;else if(typeof e=="object")[s,n]=[e,t];else throw new Error("Unknown call signature for set() - call with string+value or object");let i={delta:!0,flush:!0,forceFlush:!1,flushDestroy:!1,...n},o=!1;return i.delta?Object.entries(s).filter(([u,c])=>!Os(this.value[u],c)).forEach(([u,c])=>{o=!0,this.value[u]=c}):(o=!0,Object.assign(this.value,s)),(i.forceFlush||o)&&i.flush&&await this.flush({destroy:i.flushDestroy}),this}setHeartbeat(e=!0,t){let n={immediate:!0,...t};if(clearTimeout(this._heartbeatTimer),e){let s=async()=>{await this.heartbeat(),e&&this.setHeartbeat(!0)};if(this._heartbeatTimer=setTimeout(s,this.config.heartbeatInterval),n.immediate)return this.heartbeat()}}async heartbeat(){this.debug("heartbeat!");try{let e=await fetch(`${this.config.syncroRegistryUrl}/${this.path}/heartbeat`,{method:"post",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:r.session,...this.isDirty&&{dirty:!0}})});e.ok||console.warn(this.path,`Heartbeat failed - ${e.statusText}`,{response:e}),this.isDirty=!1}catch(e){console.warn(this.path,"Heartbeat fetch error",e)}}async setFirestoreState(e,t,n=0){let s={method:"merge",...t};if(!this.docRef)throw new Error("mount() must be called before setting Firestore state");let i=r.toFirestore(e);try{return s.method==="merge"?await ch(this.docRef,i):await uh(this.docRef,i)}catch(o){if(o instanceof et&&o.code==="not-found"){if(n<3)return console.warn("Firebase syncro document does not exist during document update, reinitializing..."),(await fetch(`${this.config.syncroRegistryUrl}/${this.path}?force=1`)).ok||console.error("Failed to reinitialize Syncro"),await this.setFirestoreState(e,t,n+1);console.warn("Max retries exceeded while trying to recover firestore syncro document, throwing error")}throw console.error(`Error during Firestore operation (${s.method}) on doc: ${this.docRef.path}`,o),o}}getFirestoreState(){if(!this.docRef)throw new Error("mount() must be called before getting Firestore state");return ah(this.docRef).then(e=>{var t;return r.fromFirestore((t=e.data())!=null?t:{})})}markDirty(){return this.isDirty=!0,this}flush(e){let t={destroy:!1,...e};return fetch(`${this.config.syncroRegistryUrl}/${this.path}/flush`+(t.destroy?"?destroy=1":"")).then(n=>n.ok?null:Promise.reject(n.statusText||"An error occurred"))}};var Cv={circular:!1,clone:!0,modules:[{id:"~array",recursive:!0,test:r=>Array.isArray(r),serialize:r=>({_:"~array",...r}),deserialize:r=>{let e=Array.from({length:Object.keys(r).length-1});return Object.entries(r).filter(([t])=>t!=="_").forEach(([t,n])=>e[+t]=n),e}},{id:"~function",test:r=>typeof r=="function",serialize:(r,e)=>{throw console.warn("Marshal Warning: Stripping function from path",e.join(".")),new Error("Function serializing is forbidden")},deserialize:(r,e)=>{console.warn("Marshal Warning: Stripping function from path",e.join("."))}},...Wa.settings.modules.filter(r=>r.id!="~function")]};var xi=class{init(){}constructor(e,t){}};var Ri=class extends xi{constructor(){super(...arguments);this.syncros={};this.namespaces={}}async init(t){let n={firebaseApiKey:null,firebaseAuthDomain:null,firebaseProjectId:null,firebaseAppId:null,supabaseUrl:null,supabaseKey:null,...await this.getCredentials(),...t},s=Object.keys(n).filter(i=>i===null);if(s.length>0)throw new Error("Firebase plugin requires mandatory options: "+s.join(", "));Ft.firebase=Gu({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),Ft.firestore=Yy(Ft.firebase),Ft.supabasey=await wv.init({env:{SUPABASE_URL:n.supabaseUrl,SUPABASE_KEY:n.supabaseKey}})}_mountNamespace(t){let n;return Promise.resolve().then(()=>this.requireProject()).then(s=>{let i=t=="_PROJECT"?`projects::${s.id}`:`project_namespaces::${s.id}::${t}`;return n=this.syncros[t]=new Ft(i,{debug:(...o)=>this.debug(`SYNCRO://${i}`,...o),getReactive:this.getReactive}),n.mount()}).then(()=>{this.namespaces[t]=n.value})}_unmountNamespace(t){let n=this.syncros[t];return delete this.namespaces[t],delete this.syncros[t],n?n.destroy():Promise.resolve()}};var Lh=class extends Ri{constructor(){super(...arguments);this.project=null;this.reactiveId=1001}async init(t){let n={app:null,Vue:null,globalName:"$tera",...t};if(!n.Vue)throw new Error("Vue instance to use must be specified in init options as `Vue`");if(this.Vue=n.Vue,!n.app)throw new Error("Vue Root / App instance to use must be specified in init options as `app`");this.app=n.app,n.globalName&&(this.Vue.prototype[n.globalName]=this),await super.init(n),this.project=await this.mountNamespace("_PROJECT")}getReactive(t){let n=this.Vue.observable(t),s=`_teraFy_${this.reactiveId++}`;return this.app[s]=n,{doc:n,setState:i=>{Object.entries(i||{}).filter(([o])=>!Os(n[o],i[o])).forEach(([o,u])=>n[o]=u)},getState:()=>Zt(n),watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Lh as default};
|
|
60
|
+
Request ID: ${c}`),l){let D=`
|
|
61
|
+
Resources:`;for(let N of l){if(!N||typeof N!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${N}`);D+=`
|
|
62
|
+
- ${N}`}k+=D}return`${A}
|
|
63
|
+
${k}`}var ue=class extends Error{constructor({message:e,code:t,cause:n,name:s}){var i;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(i=s!=null?s:n instanceof Error?n.name:void 0)!==null&&i!==void 0?i:"Unknown Error",this.code=t}},rn=class extends ue{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function iw({error:r,options:e}){var t,n,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ue({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else if(r.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new ue({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:r});if(e.mediation==="conditional"&&((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new ue({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:r});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new ue({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:r})}else{if(r.name==="InvalidStateError")return new ue({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new ue({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="NotSupportedError")return i.pubKeyCredParams.filter(u=>u.type==="public-key").length===0?new ue({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new ue({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:r});if(r.name==="SecurityError"){let o=window.location.hostname;if(xh(o)){if(i.rp.id!==o)return new ue({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new ue({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:r})}else if(r.name==="UnknownError")return new ue({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}function ow({error:r,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ue({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new ue({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){let n=window.location.hostname;if(xh(n)){if(t.rpId!==n)return new ue({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new ue({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}var Rh=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},WP=new Rh;function uw(r){if(!r)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential!="undefined"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(r);let{challenge:e,user:t,excludeCredentials:n}=r,s=qr(r,["challenge","user","excludeCredentials"]),i=mr(e).buffer,o=Object.assign(Object.assign({},t),{id:mr(t.id).buffer}),u=Object.assign(Object.assign({},s),{challenge:i,user:o});if(n&&n.length>0){u.excludeCredentials=new Array(n.length);for(let c=0;c<n.length;c++){let l=n[c];u.excludeCredentials[c]=Object.assign(Object.assign({},l),{id:mr(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return u}function cw(r){if(!r)throw new Error("Credential request options are required");if(typeof PublicKeyCredential!="undefined"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(r);let{challenge:e,allowCredentials:t}=r,n=qr(r,["challenge","allowCredentials"]),s=mr(e).buffer,i=Object.assign(Object.assign({},n),{challenge:s});if(t&&t.length>0){i.allowCredentials=new Array(t.length);for(let o=0;o<t.length;o++){let u=t[o];i.allowCredentials[o]=Object.assign(Object.assign({},u),{id:mr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return i}function lw(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();let t=r;return{id:r.id,rawId:r.id,response:{attestationObject:jt(new Uint8Array(r.response.attestationObject)),clientDataJSON:jt(new Uint8Array(r.response.clientDataJSON))},type:"public-key",clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function hw(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();let t=r,n=r.getClientExtensionResults(),s=r.response;return{id:r.id,rawId:r.id,response:{authenticatorData:jt(new Uint8Array(s.authenticatorData)),clientDataJSON:jt(new Uint8Array(s.clientDataJSON)),signature:jt(new Uint8Array(s.signature)),userHandle:s.userHandle?jt(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function xh(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}function aw(){var r,e;return!!(Te()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((r=navigator==null?void 0:navigator.credentials)===null||r===void 0?void 0:r.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function HP(r){try{let e=await navigator.credentials.create(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new rn("Browser returned unexpected credential type",e)}:{data:null,error:new rn("Empty credential response",e)}}catch(e){return{data:null,error:iw({error:e,options:r})}}}async function JP(r){try{let e=await navigator.credentials.get(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new rn("Browser returned unexpected credential type",e)}:{data:null,error:new rn("Empty credential response",e)}}catch(e){return{data:null,error:ow({error:e,options:r})}}}var QP={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},YP={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ha(...r){let e=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),n={};for(let s of r)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))n[i]=o;else if(t(o))n[i]=o;else if(e(o)){let u=n[i];e(u)?n[i]=Ha(u,o):n[i]=Ha(o)}else n[i]=o}return n}function XP(r,e){return Ha(QP,r,e||{})}function ZP(r,e){return Ha(YP,r,e||{})}var Ja=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:n,signal:s},i){var o;try{let{data:u,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!u)return{data:null,error:c};let l=s!=null?s:WP.createNewAbortSignal();if(u.webauthn.type==="create"){let{user:f}=u.webauthn.credential_options.publicKey;if(!f.name){let p=n;if(p)f.name=`${f.id}:${p}`;else{let y=(await this.client.getUser()).data.user,I=((o=y==null?void 0:y.user_metadata)===null||o===void 0?void 0:o.name)||(y==null?void 0:y.email)||(y==null?void 0:y.id)||"User";f.name=`${f.id}:${I}`}}f.displayName||(f.displayName=f.name)}switch(u.webauthn.type){case"create":{let f=XP(u.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:p,error:g}=await HP({publicKey:f,signal:l});return p?{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:p}},error:null}:{data:null,error:g}}case"request":{let f=ZP(u.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:p,error:g}=await JP(Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:f,signal:l}));return p?{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:p}},error:null}:{data:null,error:g}}}}catch(u){return j(u)?{data:null,error:u}:{data:null,error:new He("Unexpected error in challenge",u)}}}async _verify({challengeId:e,factorId:t,webauthn:n}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window!="undefined"?window.location.hostname:void 0,rpOrigins:n=typeof window!="undefined"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new pr("rpId is required for WebAuthn authentication")};try{if(!aw())return{data:null,error:new He("Browser does not support WebAuthn",null)};let{data:o,error:u}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:n},signal:s},{request:i});if(!o)return{data:null,error:u};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:n,credential_response:c.credential_response}})}catch(o){return j(o)?{data:null,error:o}:{data:null,error:new He("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window!="undefined"?window.location.hostname:void 0,rpOrigins:n=typeof window!="undefined"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new pr("rpId is required for WebAuthn registration")};try{if(!aw())return{data:null,error:new He("Browser does not support WebAuthn",null)};let{data:o,error:u}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(f=>{var p;return(p=f.data)===null||p===void 0?void 0:p.all.find(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status!=="unverified")}).then(f=>f?this.client.mfa.unenroll({factorId:f==null?void 0:f.id}):void 0),{data:null,error:u};let{data:c,error:l}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:n},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:n,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:l}}catch(o){return j(o)?{data:null,error:o}:{data:null,error:new He("Unexpected error in register",o)}}}};tw();var eC={url:k_,storageKey:O_,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:D_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function dw(r,e,t){return await t()}var ps={},Qa=class r{get jwks(){var e,t;return(t=(e=ps[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){ps[this.storageKey]=Object.assign(Object.assign({},ps[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=ps[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){ps[this.storageKey]=Object.assign(Object.assign({},ps[this.storageKey]),{cachedAt:e})}constructor(e){var t,n,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=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;let i=Object.assign(Object.assign({},eC),e);if(this.storageKey=i.storageKey,this.instanceID=(t=r.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,r.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&Te()){let o=`${this._logPrefix()} 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.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new tn({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=za(i.fetch),this.lock=i.lock||dw,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&Te()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=Ah:this.lock=dw,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new Ja(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:qa()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Ih(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Ih(this.memoryStorage)),Te()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(u){this._debug("#broadcastChannel","error",u)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Va}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let t={},n="none";if(Te()&&(t=z_(window.location.href),this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce")),Te()&&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),F_(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{error:i}}let{session:o,redirectType:u}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",u),await this._saveSession(o),setTimeout(async()=>{u==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return j(t)?this._returnResult({error:t}):this._returnResult({error:new He("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,s;try{let i=await $(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:Je}),{data:o,error:u}=i;if(u||!o)return this._returnResult({data:{user:null,session:null},error:u});let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(i){if(j(i))return this._returnResult({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:p,options:g}=e,y=null,I=null;this.flowType==="pkce"&&([y,I]=await Xr(this.storage,this.storageKey)),i=await $(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:f,password:p,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:y,code_challenge_method:I},xform:Je})}else if("phone"in e){let{phone:f,password:p,options:g}=e;i=await $(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:p,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:Je})}else throw new Wr("You must provide either an email or phone number and a password");let{data:o,error:u}=i;if(u||!o)return await Re(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:u});let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(i){if(await Re(this.storage,`${this.storageKey}-code-verifier`),j(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:u}=e;t=await $(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Eh})}else if("phone"in e){let{phone:i,password:o,options:u}=e;t=await $(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Eh})}else throw new Wr("You must provide either an email or phone number and a password");let{data:n,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!n||!n.session||!n.user){let i=new Mt;return this._returnResult({data:{user:null,session:null},error:i})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:s})}catch(t){if(j(t))return this._returnResult({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(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,n,s,i,o,u,c,l,f,p,g;let y,I;if("message"in e)y=e.message,I=e.signature;else{let{chain:R,wallet:A,statement:k,options:D}=e,N;if(Te())if(typeof A=="object")N=A;else{let w=window;if("ethereum"in w&&typeof w.ethereum=="object"&&"request"in w.ethereum&&typeof w.ethereum.request=="function")N=w.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof A!="object"||!(D!=null&&D.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");N=A}let U=new URL((t=D==null?void 0:D.url)!==null&&t!==void 0?t:window.location.href),z=await N.request({method:"eth_requestAccounts"}).then(w=>w).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!z||z.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let F=Sh(z[0]),E=(n=D==null?void 0:D.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!E){let w=await N.request({method:"eth_chainId"});E=rw(w)}let _={domain:U.host,address:F,statement:k,uri:U.href,version:"1",chainId:E,nonce:(s=D==null?void 0:D.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=D==null?void 0:D.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(u=D==null?void 0:D.signInWithEthereum)===null||u===void 0?void 0:u.expirationTime,notBefore:(c=D==null?void 0:D.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(l=D==null?void 0:D.signInWithEthereum)===null||l===void 0?void 0:l.requestId,resources:(f=D==null?void 0:D.signInWithEthereum)===null||f===void 0?void 0:f.resources};y=sw(_),I=await N.request({method:"personal_sign",params:[nw(y),F]})}try{let{data:R,error:A}=await $(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:y,signature:I},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:Je});if(A)throw A;if(!R||!R.session||!R.user){let k=new Mt;return this._returnResult({data:{user:null,session:null},error:k})}return R.session&&(await this._saveSession(R.session),await this._notifyAllSubscribers("SIGNED_IN",R.session)),this._returnResult({data:Object.assign({},R),error:A})}catch(R){if(j(R))return this._returnResult({data:{user:null,session:null},error:R});throw R}}async signInWithSolana(e){var t,n,s,i,o,u,c,l,f,p,g,y;let I,R;if("message"in e)I=e.message,R=e.signature;else{let{chain:A,wallet:k,statement:D,options:N}=e,U;if(Te())if(typeof k=="object")U=k;else{let F=window;if("solana"in F&&typeof F.solana=="object"&&("signIn"in F.solana&&typeof F.solana.signIn=="function"||"signMessage"in F.solana&&typeof F.solana.signMessage=="function"))U=F.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof k!="object"||!(N!=null&&N.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");U=k}let z=new URL((t=N==null?void 0:N.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in U&&U.signIn){let F=await U.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},N==null?void 0:N.signInWithSolana),{version:"1",domain:z.host,uri:z.href}),D?{statement:D}:null)),E;if(Array.isArray(F)&&F[0]&&typeof F[0]=="object")E=F[0];else if(F&&typeof F=="object"&&"signedMessage"in F&&"signature"in F)E=F;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in E&&"signature"in E&&(typeof E.signedMessage=="string"||E.signedMessage instanceof Uint8Array)&&E.signature instanceof Uint8Array)I=typeof E.signedMessage=="string"?E.signedMessage:new TextDecoder().decode(E.signedMessage),R=E.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in U)||typeof U.signMessage!="function"||!("publicKey"in U)||typeof U!="object"||!U.publicKey||!("toBase58"in U.publicKey)||typeof U.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");I=[`${z.host} wants you to sign in with your Solana account:`,U.publicKey.toBase58(),...D?["",D,""]:[""],"Version: 1",`URI: ${z.href}`,`Issued At: ${(s=(n=N==null?void 0:N.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=N==null?void 0:N.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${N.signInWithSolana.notBefore}`]:[],...!((o=N==null?void 0:N.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${N.signInWithSolana.expirationTime}`]:[],...!((u=N==null?void 0:N.signInWithSolana)===null||u===void 0)&&u.chainId?[`Chain ID: ${N.signInWithSolana.chainId}`]:[],...!((c=N==null?void 0:N.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${N.signInWithSolana.nonce}`]:[],...!((l=N==null?void 0:N.signInWithSolana)===null||l===void 0)&&l.requestId?[`Request ID: ${N.signInWithSolana.requestId}`]:[],...!((p=(f=N==null?void 0:N.signInWithSolana)===null||f===void 0?void 0:f.resources)===null||p===void 0)&&p.length?["Resources",...N.signInWithSolana.resources.map(E=>`- ${E}`)]:[]].join(`
|
|
64
|
+
`);let F=await U.signMessage(new TextEncoder().encode(I),"utf8");if(!F||!(F instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");R=F}}try{let{data:A,error:k}=await $(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:I,signature:jt(R)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(y=e.options)===null||y===void 0?void 0:y.captchaToken}}:null),xform:Je});if(k)throw k;if(!A||!A.session||!A.user){let D=new Mt;return this._returnResult({data:{user:null,session:null},error:D})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:k})}catch(A){if(j(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e){let t=await gr(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{if(!n&&this.flowType==="pkce")throw new ja;let{data:i,error:o}=await $(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Je});if(await Re(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let u=new Mt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:u})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s!=null?s:null}),error:o})}catch(i){if(await Re(this.storage,`${this.storageKey}-code-verifier`),j(i))return this._returnResult({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:o}=e,u=await $(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:Je}),{data:c,error:l}=u;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!c||!c.session||!c.user){let f=new Mt;return this._returnResult({data:{user:null,session:null},error:f})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:l})}catch(t){if(j(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,n,s,i,o;try{if("email"in e){let{email:u,options:c}=e,l=null,f=null;this.flowType==="pkce"&&([l,f]=await Xr(this.storage,this.storageKey));let{error:p}=await $(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:l,code_challenge_method:f},redirectTo:c==null?void 0:c.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:p})}if("phone"in e){let{phone:u,options:c}=e,{data:l,error:f}=await $(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:(o=c==null?void 0:c.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:l==null?void 0:l.message_id},error:f})}throw new Wr("You must provide either an email or phone number.")}catch(u){if(await Re(this.storage,`${this.storageKey}-code-verifier`),j(u))return this._returnResult({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:o,error:u}=await $(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Je});if(u)throw u;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(s){if(j(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,n,s,i,o;try{let u=null,c=null;this.flowType==="pkce"&&([u,c]=await Xr(this.storage,this.storageKey));let l=await $(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:u,code_challenge_method:c}),headers:this.headers,xform:Z_});return!((i=l.data)===null||i===void 0)&&i.url&&Te()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(u){if(await Re(this.storage,`${this.storageKey}-code-verifier`),j(u))return this._returnResult({data:null,error:u});throw u}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,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 Ce;let{error:s}=await $(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(j(e))return this._returnResult({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:o}=await $(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 this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:s,options:i}=e,{data:o,error:u}=await $(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:u})}throw new Wr("You must provide either an email or phone number and a type")}catch(t){if(j(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,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 gr(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<Fa:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await gr(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Ka()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=Y_(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await $(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:wt}):await this._useSession(async t=>{var n,s,i;let{data:o,error:u}=t;if(u)throw u;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Ce}:await $(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:wt})})}catch(t){if(j(t))return Ua(t)&&(await this._removeSession(),await Re(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,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 Ce;let o=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await Xr(this.storage,this.storageKey));let{data:l,error:f}=await $(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:o.access_token,xform:wt});if(f)throw f;return o.user=l.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await Re(this.storage,`${this.storageKey}-code-verifier`),j(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Ce;let t=Date.now()/1e3,n=t,s=!0,i=null,{payload:o}=Ri(e.access_token);if(o.exp&&(n=o.exp,s=n<=t),s){let{data:u,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({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)return this._returnResult({data:{user:null,session:null},error: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 this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(j(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var n;if(!e){let{data:o,error:u}=t;if(u)throw u;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new Ce;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(j(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!Te())throw new Hr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Hr(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 Ai("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Hr("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 Ai("No code detected.");let{data:D,error:N}=await this._exchangeCodeForSession(e.code);if(N)throw N;let U=new URL(window.location.href);return U.searchParams.delete("code"),window.history.replaceState(window.history.state,"",U.toString()),{data:{session:D.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:o,expires_in:u,expires_at:c,token_type:l}=e;if(!i||!u||!o||!l)throw new Hr("No session defined in URL");let f=Math.round(Date.now()/1e3),p=parseInt(u),g=f+p;c&&(g=parseInt(c));let y=g-f;y*1e3<=Gr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${y}s, should have been closer to ${p}s`);let I=g-p;f-I>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",I,g,f):f-I<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",I,g,f);let{data:R,error:A}=await this._getUser(i);if(A)throw A;let k={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:p,expires_at:g,refresh_token:o,token_type:l,user:R.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:k,redirectType:e.type},error:null})}catch(n){if(j(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await gr(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,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&&!Ua(i))return this._returnResult({error:i});let o=(n=s.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:u}=await this.admin.signOut(o,e);if(u&&!(L_(u)&&(u.status===404||u.status===401||u.status===403)||Ua(u)))return this._returnResult({error:u})}return e!=="others"&&(await this._removeSession(),await Re(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=q_(),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(this.lockAcquireTimeout,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:o}=t;if(o)throw o;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 Xr(this.storage,this.storageKey,!0));try{return await $(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(await Re(this.storage,`${this.storageKey}-code-verifier`),j(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:t,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(j(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{let{data:n,error:s}=await this._useSession(async i=>{var o,u,c,l,f;let{data:p,error:g}=i;if(g)throw g;let y=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.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 $(this.fetch,"GET",y,{headers:this.headers,jwt:(f=(l=p.session)===null||l===void 0?void 0:l.access_token)!==null&&f!==void 0?f:void 0})});if(s)throw s;return Te()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),this._returnResult({data:{provider:e.provider,url:n==null?void 0:n.url},error:null})}catch(n){if(j(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var n;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:u,token:c,access_token:l,nonce:f}=e,p=await $(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=i==null?void 0:i.access_token)!==null&&n!==void 0?n:void 0,body:{provider:u,id_token:c,access_token:l,nonce:f,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Je}),{data:g,error:y}=p;return y?this._returnResult({data:{user:null,session:null},error:y}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new Mt}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:y}))}catch(s){if(await Re(this.storage,`${this.storageKey}-code-verifier`),j(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:o}=t;if(o)throw o;return await $(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(j(t))return this._returnResult({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 W_(async s=>(s>0&&await G_(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await $(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Je})),(s,i)=>{let o=200*Math.pow(2,s);return i&&Ba(i)&&Date.now()+o-n<Gr})}catch(n){if(this._debug(t,"error",n),j(n))return this._returnResult({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),Te()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,t;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let s=await gr(this.storage,this.storageKey);if(s&&this.userStorage){let o=await gr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await Yr(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Ka()}else if(s&&!s.user&&!s.user){let o=await gr(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(s.user=o.user,await Re(this.storage,this.storageKey+"-user"),await Yr(this.storage,this.storageKey,s)):s.user=Ka()}if(this._debug(n,"session from storage",s),!this._isValidSession(s)){this._debug(n,"session is not valid"),s!==null&&await this._removeSession();return}let i=((t=s.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<Fa;if(this._debug(n,`session has${i?"":" not"} expired with margin of ${Fa}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Ba(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:u}=await this._getUser(s.access_token);!u&&(o!=null&&o.user)?(s.user=o.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(n,"error",s),console.error(s);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var t,n;if(!e)throw new Ce;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new xi;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new Ce;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let u={data:i.session,error:null};return this.refreshingDeferred.resolve(u),u}catch(i){if(this._debug(s,"error",i),j(i)){let o={data:null,error:i};return Ba(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}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=[],o=Array.from(this.stateChangeEmitters.values()).map(async u=>{try{await u.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),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 Re(this.storage,`${this.storageKey}-code-verifier`);let t=Object.assign({},e),n=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&t.user&&await Yr(this.userStorage,this.storageKey+"-user",{user:t.user});let s=Object.assign({},t);delete s.user;let i=bh(s);await Yr(this.storage,this.storageKey,i)}else{let s=bh(t);await Yr(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Re(this.storage,this.storageKey),await Re(this.storage,this.storageKey+"-code-verifier"),await Re(this.storage,this.storageKey+"-user"),this.userStorage&&await Re(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Te()&&(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(),Gr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}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)/Gr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Gr}ms, refresh threshold is ${La} ticks`),s<=La&&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()"),!Te()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},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(this.lockAcquireTimeout,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,o]=await Xr(this.storage,this.storageKey),u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});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?this._returnResult({data:null,error:i}):await $(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(j(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let u=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:l}=await $(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 l?this._returnResult({data:null,error:l}):(e.factorType==="totp"&&c.type==="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}`),this._returnResult({data:c,error:null}))})}catch(t){if(j(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?lw(e.webauthn.credential_response):hw(e.webauthn.credential_response)})}:{code:e.code}),{data:u,error:c}=await $(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+u.expires_in},u)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:u,error:c}))})}catch(t){if(j(t))return this._returnResult({data:null,error:t});throw t}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let o=await $(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:u}=o;if(u.type!=="webauthn")return{data:u,error:null};switch(u.webauthn.type){case"create":return{data:Object.assign(Object.assign({},u),{webauthn:Object.assign(Object.assign({},u.webauthn),{credential_options:Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:uw(u.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},u),{webauthn:Object.assign(Object.assign({},u.webauthn),{credential_options:Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:cw(u.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(j(t))return this._returnResult({data:null,error:t});throw t}})}async _challengeAndVerify(e){let{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};let s={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=t==null?void 0:t.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,n,s,i;if(e)try{let{payload:y}=Ri(e),I=null;y.aal&&(I=y.aal);let R=I,{data:{user:A},error:k}=await this.getUser(e);if(k)return this._returnResult({data:null,error:k});((n=(t=A==null?void 0:A.factors)===null||t===void 0?void 0:t.filter(U=>U.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(R="aal2");let N=y.amr||[];return{data:{currentLevel:I,nextLevel:R,currentAuthenticationMethods:N},error:null}}catch(y){if(j(y))return this._returnResult({data:null,error:y});throw y}let{data:{session:o},error:u}=await this.getSession();if(u)return this._returnResult({data:null,error:u});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Ri(o.access_token),l=null;c.aal&&(l=c.aal);let f=l;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(y=>y.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(f="aal2");let g=c.amr||[];return{data:{currentLevel:l,nextLevel:f,currentAuthenticationMethods:g},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:n},error:s}=t;return s?this._returnResult({data:null,error:s}):n?await $(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Ce})})}catch(t){if(j(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Ce});let o=await $(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:u=>({data:u,error:null})});return o.data&&o.data.redirect_url&&Te()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(j(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Ce});let o=await $(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:u=>({data:u,error:null})});return o.data&&o.data.redirect_url&&Te()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(j(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;return n?this._returnResult({data:null,error:n}):t?await $(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Ce})})}catch(e){if(j(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:n},error:s}=t;return s?this._returnResult({data:null,error:s}):n?(await $(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Ce})})}catch(t){if(j(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(u=>u.kid===e);if(n)return n;let s=Date.now();if(n=this.jwks.keys.find(u=>u.kid===e),n&&this.jwks_cached_at+V_>s)return n;let{data:i,error:o}=await $(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,n=i.keys.find(u=>u.kid===e),!n)?null:n}async getClaims(e,t={}){try{let n=e;if(!n){let{data:y,error:I}=await this.getSession();if(I||!y.session)return this._returnResult({data:null,error:I});n=y.session.access_token}let{header:s,payload:i,signature:o,raw:{header:u,payload:c}}=Ri(n);t!=null&&t.allowExpired||J_(i.exp);let l=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t!=null&&t.keys?{keys:t.keys}:t==null?void 0:t.jwks);if(!l){let{error:y}=await this.getUser(n);if(y)throw y;return{data:{claims:i,header:s,signature:o},error:null}}let f=Q_(s.alg),p=await crypto.subtle.importKey("jwk",l,f,!0,["verify"]);if(!await crypto.subtle.verify(f,p,o,B_(`${u}.${c}`)))throw new Jr("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(n){if(j(n))return this._returnResult({data:null,error:n});throw n}}};Qa.nextInstanceID={};var Ph=Qa;var tC=Ph,Ch=tC;var rC="2.99.1",Ci="";typeof Deno!="undefined"?Ci="deno":typeof document!="undefined"?Ci="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?Ci="react-native":Ci="node";var nC={"X-Client-Info":`supabase-js-${Ci}/${rC}`},sC={headers:nC},iC={schema:"public"},oC={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},aC={};function ki(r){"@babel/helpers - typeof";return ki=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ki(r)}function uC(r,e){if(ki(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e||"default");if(ki(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function cC(r){var e=uC(r,"string");return ki(e)=="symbol"?e:e+""}function lC(r,e,t){return(e=cC(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function fw(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,n)}return t}function fe(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?fw(Object(t),!0).forEach(function(n){lC(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):fw(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var hC=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),dC=()=>Headers,fC=(r,e,t)=>{let n=hC(t),s=dC();return async(i,o)=>{var u;let c=(u=await e())!==null&&u!==void 0?u:r,l=new s(o==null?void 0:o.headers);return l.has("apikey")||l.set("apikey",r),l.has("Authorization")||l.set("Authorization",`Bearer ${c}`),n(i,fe(fe({},o),{},{headers:l}))}};function pC(r){return r.endsWith("/")?r:r+"/"}function mC(r,e){var t,n;let{db:s,auth:i,realtime:o,global:u}=r,{db:c,auth:l,realtime:f,global:p}=e,g={db:fe(fe({},c),s),auth:fe(fe({},l),i),realtime:fe(fe({},f),o),storage:{},global:fe(fe(fe({},p),u),{},{headers:fe(fe({},(t=p==null?void 0:p.headers)!==null&&t!==void 0?t:{}),(n=u==null?void 0:u.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return r.accessToken?g.accessToken=r.accessToken:delete g.accessToken,g}function gC(r){let e=r==null?void 0:r.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(pC(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var yC=class extends Ch{constructor(r){super(r)}},_C=class{constructor(r,e,t){var n,s;this.supabaseUrl=r,this.supabaseKey=e;let i=gC(r);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);let o=`sb-${i.hostname.split(".")[0]}-auth-token`,u={db:iC,realtime:aC,auth:fe(fe({},oC),{},{storageKey:o}),global:sC},c=mC(t!=null?t:{},u);if(this.storageKey=(n=c.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(s=c.global.headers)!==null&&s!==void 0?s:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(f,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}});else{var l;this.auth=this._initSupabaseAuthClient((l=c.auth)!==null&&l!==void 0?l:{},this.headers,c.global.fetch)}this.fetch=fC(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(fe({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(f=>this.realtime.setAuth(f)).catch(f=>console.warn("Failed to set initial Realtime auth token:",f)),this.rest=new m_(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new C_(this.storageUrl.href,this.headers,this.fetch,t==null?void 0:t.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new pi(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(r){return this.rest.from(r)}schema(r){return this.rest.schema(r)}rpc(r,e={},t={head:!1,get:!1,count:void 0}){return this.rest.rpc(r,e,t)}channel(r,e={config:{}}){return this.realtime.channel(r,e)}getChannels(){return this.realtime.getChannels()}removeChannel(r){return this.realtime.removeChannel(r)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var r=this,e,t;if(r.accessToken)return await r.accessToken();let{data:n}=await r.auth.getSession();return(e=(t=n.session)===null||t===void 0?void 0:t.access_token)!==null&&e!==void 0?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:n,userStorage:s,storageKey:i,flowType:o,lock:u,debug:c,throwOnError:l},f,p){let g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new yC({url:this.authUrl.href,headers:fe(fe({},g),f),storageKey:i,autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:n,userStorage:s,flowType:o,lock:u,debug:c,throwOnError:l,fetch:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(y=>y.toLowerCase()==="authorization")})}_initRealtimeClient(r){return new ls(this.realtimeUrl.href,fe(fe({},r),{},{params:fe(fe({},{apikey:this.supabaseKey}),r==null?void 0:r.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,e)=>{this._handleTokenChanged(r,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(r,e,t){(r==="TOKEN_REFRESHED"||r==="SIGNED_IN")&&this.changedAccessToken!==t?(this.changedAccessToken=t,this.realtime.setAuth(t)):r==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},pw=(r,e,t)=>new _C(r,e,t);function wC(){if(typeof window!="undefined")return!1;let r=globalThis.process;if(!r)return!1;let e=r.version;if(e==null)return!1;let t=e.match(/^v(\d+)\./);return t?parseInt(t[1],10)<=18:!1}wC()&&console.warn("\u26A0\uFE0F Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var vC=Object.prototype.toString,bC=r=>vC.call(r)==="[object Error]",EC=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function kh(r){if(!(r&&bC(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:EC.has(t)}function TC(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Ya(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var Oh=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}};function IC(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(t-1));return s=Math.min(s,e.maxTimeout),s}function mw(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function AC({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:s}){var y,I,R,A,k;let i=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(i instanceof Oh)throw i.originalError;let o=Number.isFinite(s.retries)?Math.max(0,s.retries-t):s.retries,u=(y=s.maxRetryTime)!=null?y:Number.POSITIVE_INFINITY,c=Object.freeze({error:i,attemptNumber:e,retriesLeft:o,retriesConsumed:t});if(await s.onFailedAttempt(c),mw(n,u)<=0)throw i;let l=await s.shouldConsumeRetry(c),f=mw(n,u);if(f<=0||o<=0)throw i;if(i instanceof TypeError&&!kh(i)){if(l)throw i;return(I=s.signal)==null||I.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw i;if(!l)return(R=s.signal)==null||R.throwIfAborted(),!1;let p=IC(t,s),g=Math.min(p,f);return(A=s.signal)==null||A.throwIfAborted(),g>0&&await new Promise((D,N)=>{var F,E;let U=()=>{var _;clearTimeout(z),(_=s.signal)==null||_.removeEventListener("abort",U),N(s.signal.reason)},z=setTimeout(()=>{var _;(_=s.signal)==null||_.removeEventListener("abort",U),D()},g);s.unref&&((F=z.unref)==null||F.call(z)),(E=s.signal)==null||E.addEventListener("abort",U,{once:!0})}),(k=s.signal)==null||k.throwIfAborted(),!0}async function Oi(r,e={}){var i,o,u,c,l,f,p,g,y,I,R,A;if(e={...e},TC(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");(i=e.retries)!=null||(e.retries=10),(o=e.factor)!=null||(e.factor=2),(u=e.minTimeout)!=null||(e.minTimeout=1e3),(c=e.maxTimeout)!=null||(e.maxTimeout=Number.POSITIVE_INFINITY),(l=e.maxRetryTime)!=null||(e.maxRetryTime=Number.POSITIVE_INFINITY),(f=e.randomize)!=null||(e.randomize=!1),(p=e.onFailedAttempt)!=null||(e.onFailedAttempt=()=>{}),(g=e.shouldRetry)!=null||(e.shouldRetry=()=>!0),(y=e.shouldConsumeRetry)!=null||(e.shouldConsumeRetry=()=>!0),Ya("factor",e.factor,{min:0,allowInfinity:!1}),Ya("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Ya("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Ya("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),(I=e.signal)==null||I.throwIfAborted();let t=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{(R=e.signal)==null||R.throwIfAborted();let k=await r(t);return(A=e.signal)==null||A.throwIfAborted(),k}catch(k){await AC({error:k,attemptNumber:t,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var SC=function(e,t){if(typeof e!="function")throw new Error("First argument to supabasey() must be a callback function");let n={session:null,retries:3,retry:{minTimeout:100,factor:2,randomize:!0,onFailedAttempt:i=>console.info(`[Attempt ${i.attemptNumber}/${i.attemptNumber+i.retriesLeft-1}] failed to run Supabase query`),shouldRetry:i=>(console.log("QUERY SHOULD-RETRY",i),!0)},...t},s=n.session?typeof n.session=="string"?Ie.sessions[n.session]:typeof n.session=="object"?n.session:(()=>{throw new Error(`Unknown session type for supabasey(cb, {session}) - expected Object|String got ${typeof n.session}`)})():(()=>{throw new Error("supabasey(cb, {session}) cannot be empty - specify a session or use bindSession() first")})();return Promise.resolve().then(()=>Oi(()=>e.call(s,s),{...n.retries&&{retries:n.retries},...t.retry})).then(i=>{if(i!=null&&i.error)Ie.throw(i.error);else if(i.data)return i.data}).catch(i=>{throw console.log("Supabasey error:",i),i})},Ie=SC;Ie.bindSession=function(e){if(typeof e=="string"&&!Ie.sessions[e])throw new Error(`Unable to bind to non-existant session "${e}"`);let t=(n,s)=>Ie(n,{session:e,...s});return t.rpc=(n,s,i)=>Ie.rpc(n,s,{session:e,...i}),t};Ie.init=function(e){let t={env:{},init:!0,login:!1,session:"auto",...e},n=t.env,s=t.session=="auto"&&n.SUPABASE_URL?n.SUPABASE_URL:t.session?t.session:(()=>{throw new Error("Sesison should be truthy if using @iebh/supabasey.middleware({session:String})")})(),i=Ie.sessions[s];return Promise.resolve().then(()=>{if(!i)if(t.init){if(!n.SUPABASE_URL||!n.SUPABASE_KEY)throw new Error("Both env.SUPABASE_URL + env.SUPABASE_KEY should be specified to use @iebh/supabasey.middleware(), otherwise disable with {init:false}");i=Ie.sessions[s]=pw(n.SUPABASE_URL,n.SUPABASE_KEY)}else throw new Error("No Supabase session for middleware to work with!")}).then(()=>{if(t.login){if(i.supabaseyIsLoggedIn)return;if(!n.SUPABASE_USER||!n.SUPABASE_PASS)throw new Error("User credentials missing when using @iebh/supabasey.middleware(), provide in env.SUPABASE_USER + ..._PASS");return Ie(o=>o.auth.signInWithPassword({email:n.SUPABASE_USER,password:n.SUPABASE_PASS}),{session:i}).then(()=>i.supabaseyIsLoggedIn=!0)}else return}).then(()=>Ie.bindSession(i))};Ie.middleware=function(e){let t={env:{},injectEnv:!0,...e};return async(n,s,i,o)=>Ie.init({...e,env:i}).then(u=>{t.injectEnv&&(i.supabasey=u)}).catch(u=>Ie.throw(u))};Ie.throw=function(r){throw typeof r=="string"?new Error(r):r instanceof Error?r:/JSON object requested, multiple \(or no\) rows returned$/.test(r.message)?(console.warn("Supabase query resulted in NOT-FOUND:",r.message),console.warn("Supabase raw error",r),new Error("NOT-FOUND")):(console.warn("Supabase query threw",r.message||r||"Unknown error"),new Error(`${(r==null?void 0:r.code)||"UnknownError"}: ${(r==null?void 0:r.message)||"Unknown Supabase error"}`))};Ie.rpc=function(r,e,t){return Ie(async n=>await n.rpc(r,e),t)};Ie.sessions={};var gw=Ie;function xC(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function Xa(r,e){return Array.isArray(r)?r.map(t=>Xa(t,e)):typeof r=="object"?r==null?null:Object.fromEntries(Object.entries(xC(r,e)).map(([t,n])=>[t,Xa(n,e)])):r}var yw={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var _w={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var ww={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 vw={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var bw={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 Ew={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var Tw={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var ms={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[yw,_w,ww,vw,bw,Ew,Tw],circular:!0,symetric:!1},loadedModules:{},loadModules(r){return r.map(e=>{if(ee(e)){if(!e.id)throw new Error("Provided custom module does not expose an `id` property");return ms.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=bo(e,ms.settings),n=ms.loadModules(t.modules),s=t.symetric?Xa(r):t.clone?ir(r):r,i=new Map,o=(u,c)=>{let l=ee(u);if(l&&t.circular){let g=i.get(u);if(g)return or(s,c,{_:"~circular",p:g.join(".")});i.set(u,c)}let f=n.find(g=>g.test(u,c)),p=(!t.depth||c.length<t.depth)&&l;if(f){let g=f.serialize(u,c);if(f.recursive&&p){let y=Oe(u);t.symetric&&y.sort(),or(s,c,g),y.forEach(I=>o(u[I],c.concat(I)))}else c.length?or(s,c,g):s=g}else if(p){let g=Oe(u);t.symetric&&g.sort(),g.forEach(y=>o(u[y],c.concat(y)))}};return o(s,[]),t.stringify?JSON.stringify(s):s},deserialize(r,e){let t=bo(e,ms.settings),n=ms.loadModules(t.modules),s=Cu(n,"id"),i=t.destringify?JSON.parse(r):t.clone?ir(r):r,o=(u,c)=>{if(ee(u)&&u._&&typeof u._=="string"&&u._.startsWith("~")&&s[u._]){let l=s[u._].deserialize(u,c);c.length?s[u._].recursive&&ee(l)?(or(i,c,l),Oe(l).forEach(f=>o(u[f],[...c,f]))):or(i,c,l):i=l}else t.circular&&ee(u)&&u._&&u._=="~circular"?or(i,c,Ns(i,u.p)):(!t.depth||c.length<t.depth)&&ee(u)&&Oe(u).forEach(l=>o(u[l],c.concat(l)))};return o(i,[]),i}},Za=ms;var Iw="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Aw=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Iw[t[r]&63];return e};var Ut=class r{constructor(e,t){this.throttle=250;this.config={heartbeatInterval:12e4,syncroRegistryUrl:"https://tera-tools.com/api/sync",context:{}};this.isDirty=!1;this._destroyActions=[];this.path=e,Object.assign(this,{...t,config:{...this.config,...t==null?void 0:t.config}}),r.session||(r.session=`syncro_${Aw()}`)}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 ir(t)},watch(n){}}}static pathSplit(e,t){var o;let n={allowAsterisk:!1,...t},i={...(o=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:o.groups};if(!i||!i.entity||!i.id)throw new Error(`Invalid session path syntax "${e}"`);if(r.SyncroEntities&&!(i.entity in r.SyncroEntities))throw new Error(`Unsupported entity "${e}" -> Entity="${i.entity}"`);return{entity:i.entity,id:i.id,relation:i.relation,fsCollection:i.entity,fsId:i.relation?`${i.id}::${i.relation}`:i.id}}static toFirestore(e={}){return Za.serialize(e,{...Sw,stringify:!1})}static fromFirestore(e={}){return Za.deserialize(e,{...Sw,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(o=>r.toFirestoreFields({item:o}).item)}}:i==="object"&&(t[n]={mapValue:{fields:r.toFirestoreFields(s)}})}return t}static fromFirestoreFields(e={}){let t={};for(let n in e){let s=e[n],i=["stringValue","booleanValue","doubleValue","integerValue","timestampValue","mapValue","arrayValue","nullValue"].find(o=>o===Object.keys(s)[0]);if(i)switch(i){case"mapValue":t[n]=r.fromFirestoreFields(s.mapValue.fields||{});break;case"arrayValue":{let o=s.arrayValue.values;t[n]=o?o.map(u=>r.fromFirestoreFields(u)):[];break}case"nullValue":t[n]=null;break;default:t[n]=s[i]}else t[n]=r.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=r.pathSplit(e);return Promise.resolve().then(async()=>sh(es(r.firestore,t,n))).then(s=>s.exists()?r.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:i,fsId:o}=r.pathSplit(e),u=es(r.firestore,i,o),c=r.toFirestore(t);return Promise.resolve().then(()=>s.method==="merge"?oh(u,c):ih(u,c)).then(()=>t)}mount(e){let t={initialState:null,retries:5,retryMinTime:250,...e},{fsCollection:n,fsId:s,entity:i}=r.pathSplit(this.path),o,u;return Oi(async()=>{await this.setHeartbeat(!1),this.docRef=es(r.firestore,n,s);let c=await this.getFirestoreState();if(this.path.startsWith("projects::")&&c&&!Eo(c)&&c.users&&!c.type&&!c.name&&!c.created){this.debugError("Zombie state detected (Partial document). Forcing repair...");let f=await fetch(`${this.config.syncroRegistryUrl}/${this.path}?drop=1&force=1`);f.ok?(this.debug("Repair signal sent successfully. Reloading local state..."),c=await this.getFirestoreState()):console.error("[Syncro] Self-healing failed",f.statusText)}if(o=this.getReactive(c),!o.doc||!o.setState||!o.getState||!o.watch)throw new Error("Syncro.getReactive() requires a returned `doc`, `setState()`, `getState()` + `watch()`");this.value=u=o.doc,this.debug("Initial state",{doc:u});let l=a_(this.docRef,f=>{let p=r.fromFirestore(f.data());this.debug("Incoming snapshot",{snapshotData:p}),o.setState(p)});if(this._destroyActions.push(l),Eo(u))if(t.initialState)this.debug("Populate initial Syncro state (from provided initialState)"),await this.setFirestoreState(t.initialState,{method:"set"});else{this.debug(`Populate initial Syncro state (from "${i}" Syncro worker)`);let f=await fetch(`${this.config.syncroRegistryUrl}/${this.path}`);if(!f.ok)throw new Error(`Failed to check Syncro "${n}::${s}" status - ${f.statusText}`)}return o.watch(ku(f=>{this.debug("Local change",{newState:f}),this.markDirty(),this.setFirestoreState(f,{method:"merge"})},this.throttle)),await this.setHeartbeat(!0,{immediate:!0}),this},{retries:t.retries,minTimeout:t.retryMinTime,randomize:!0,factor:3,onFailedAttempt:async c=>{this.debugError(`[Attempt ${c.attemptNumber}/${c.attemptNumber+c.retriesLeft-1}] to mount syncro`,c),await this.destroy()}})}async set(e,t,n){let s;if(typeof e=="string")s[e]=t;else if(typeof e=="object")[s,n]=[e,t];else throw new Error("Unknown call signature for set() - call with string+value or object");let i={delta:!0,flush:!0,forceFlush:!1,flushDestroy:!1,...n},o=!1;return i.delta?Object.entries(s).filter(([u,c])=>!Ls(this.value[u],c)).forEach(([u,c])=>{o=!0,this.value[u]=c}):(o=!0,Object.assign(this.value,s)),(i.forceFlush||o)&&i.flush&&await this.flush({destroy:i.flushDestroy}),this}setHeartbeat(e=!0,t){let n={immediate:!0,...t};if(clearTimeout(this._heartbeatTimer),e){let s=async()=>{await this.heartbeat(),e&&this.setHeartbeat(!0)};if(this._heartbeatTimer=setTimeout(s,this.config.heartbeatInterval),n.immediate)return this.heartbeat()}}async heartbeat(){this.debug("heartbeat!");try{let e=await fetch(`${this.config.syncroRegistryUrl}/${this.path}/heartbeat`,{method:"post",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:r.session,...this.isDirty&&{dirty:!0}})});e.ok||console.warn(this.path,`Heartbeat failed - ${e.statusText}`,{response:e}),this.isDirty=!1}catch(e){console.warn(this.path,"Heartbeat fetch error",e)}}async setFirestoreState(e,t,n=0){let s={method:"merge",...t};if(!this.docRef)throw new Error("mount() must be called before setting Firestore state");let i=r.toFirestore(e);try{return s.method==="merge"?await oh(this.docRef,i):await ih(this.docRef,i)}catch(o){if(o instanceof Xe&&o.code==="not-found"){if(n<3)return console.warn("Firebase syncro document does not exist during document update, reinitializing..."),(await fetch(`${this.config.syncroRegistryUrl}/${this.path}?force=1`)).ok||console.error("Failed to reinitialize Syncro"),await this.setFirestoreState(e,t,n+1);console.warn("Max retries exceeded while trying to recover firestore syncro document, throwing error")}throw console.error(`Error during Firestore operation (${s.method}) on doc: ${this.docRef.path}`,o),o}}getFirestoreState(){if(!this.docRef)throw new Error("mount() must be called before getting Firestore state");return sh(this.docRef).then(e=>{var t;return r.fromFirestore((t=e.data())!=null?t:{})})}markDirty(){return this.isDirty=!0,this}flush(e){let t={destroy:!1,...e};return fetch(`${this.config.syncroRegistryUrl}/${this.path}/flush`+(t.destroy?"?destroy=1":"")).then(n=>n.ok?null:Promise.reject(n.statusText||"An error occurred"))}};var Sw={circular:!1,clone:!0,modules:[{id:"~array",recursive:!0,test:r=>Array.isArray(r),serialize:r=>({_:"~array",...r}),deserialize:r=>{let e=Array.from({length:Object.keys(r).length-1});return Object.entries(r).filter(([t])=>t!=="_").forEach(([t,n])=>e[+t]=n),e}},{id:"~function",test:r=>typeof r=="function",serialize:(r,e)=>{throw console.warn("Marshal Warning: Stripping function from path",e.join(".")),new Error("Function serializing is forbidden")},deserialize:(r,e)=>{console.warn("Marshal Warning: Stripping function from path",e.join("."))}},...Za.settings.modules.filter(r=>r.id!="~function")]};var Di=class{init(){}constructor(e,t){}};var Ni=class extends Di{constructor(){super(...arguments);this.syncros={};this.namespaces={}}async init(t){let n={firebaseApiKey:null,firebaseAuthDomain:null,firebaseProjectId:null,firebaseAppId:null,supabaseUrl:null,supabaseKey:null,...await this.getCredentials(),...t},s=Object.keys(n).filter(i=>i===null);if(s.length>0)throw new Error("Firebase plugin requires mandatory options: "+s.join(", "));Ut.firebase=Yu({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),Ut.firestore=Zl(Ut.firebase),Ut.supabasey=await gw.init({env:{SUPABASE_URL:n.supabaseUrl,SUPABASE_KEY:n.supabaseKey}})}_mountNamespace(t){let n;return Promise.resolve().then(()=>this.requireProject()).then(s=>{let i=t=="_PROJECT"?`projects::${s.id}`:`project_namespaces::${s.id}::${t}`;return n=this.syncros[t]=new Ut(i,{debug:(...o)=>this.debug(`SYNCRO://${i}`,...o),getReactive:this.getReactive}),n.mount()}).then(()=>{this.namespaces[t]=n.value})}_unmountNamespace(t){let n=this.syncros[t];return delete this.namespaces[t],delete this.syncros[t],n?n.destroy():Promise.resolve()}};var Dh=class extends Ni{constructor(){super(...arguments);this.project=null;this.reactiveId=1001}async init(t){let n={app:null,Vue:null,globalName:"$tera",...t};if(!n.Vue)throw new Error("Vue instance to use must be specified in init options as `Vue`");if(this.Vue=n.Vue,!n.app)throw new Error("Vue Root / App instance to use must be specified in init options as `app`");this.app=n.app,n.globalName&&(this.Vue.prototype[n.globalName]=this),await super.init(n),this.project=await this.mountNamespace("_PROJECT")}getReactive(t){let n=this.Vue.observable(t),s=`_teraFy_${this.reactiveId++}`;return this.app[s]=n,{doc:n,setState:i=>{Object.entries(i||{}).filter(([o])=>!Ls(n[o],i[o])).forEach(([o,u])=>n[o]=u)},getState:()=>ir(n),watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Dh as default};
|
|
79
65
|
/*! Bundled license information:
|
|
80
66
|
|
|
81
67
|
lodash-es/lodash.js:
|
|
@@ -89,31 +75,32 @@ lodash-es/lodash.js:
|
|
|
89
75
|
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
|
|
90
76
|
*)
|
|
91
77
|
|
|
92
|
-
@firebase/util/dist/index.
|
|
93
|
-
@firebase/util/dist/index.
|
|
94
|
-
@firebase/util/dist/index.
|
|
95
|
-
@firebase/util/dist/index.
|
|
96
|
-
@firebase/util/dist/index.
|
|
97
|
-
@firebase/util/dist/index.
|
|
98
|
-
@firebase/util/dist/index.
|
|
99
|
-
@firebase/util/dist/index.
|
|
100
|
-
@firebase/util/dist/index.
|
|
101
|
-
@firebase/util/dist/index.
|
|
102
|
-
@firebase/logger/dist/esm/index.
|
|
103
|
-
@firebase/firestore/dist/
|
|
104
|
-
@firebase/firestore/dist/
|
|
105
|
-
@firebase/firestore/dist/
|
|
106
|
-
@firebase/firestore/dist/
|
|
107
|
-
@firebase/firestore/dist/
|
|
108
|
-
@firebase/firestore/dist/
|
|
109
|
-
@firebase/firestore/dist/
|
|
110
|
-
@firebase/firestore/dist/
|
|
111
|
-
@firebase/firestore/dist/
|
|
112
|
-
@firebase/firestore/dist/
|
|
113
|
-
@firebase/firestore/dist/
|
|
114
|
-
@firebase/firestore/dist/
|
|
115
|
-
@firebase/firestore/dist/
|
|
116
|
-
@firebase/firestore/dist/
|
|
78
|
+
@firebase/util/dist/index.esm.js:
|
|
79
|
+
@firebase/util/dist/index.esm.js:
|
|
80
|
+
@firebase/util/dist/index.esm.js:
|
|
81
|
+
@firebase/util/dist/index.esm.js:
|
|
82
|
+
@firebase/util/dist/index.esm.js:
|
|
83
|
+
@firebase/util/dist/index.esm.js:
|
|
84
|
+
@firebase/util/dist/index.esm.js:
|
|
85
|
+
@firebase/util/dist/index.esm.js:
|
|
86
|
+
@firebase/util/dist/index.esm.js:
|
|
87
|
+
@firebase/util/dist/index.esm.js:
|
|
88
|
+
@firebase/logger/dist/esm/index.esm.js:
|
|
89
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
90
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
91
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
92
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
93
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
94
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
95
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
96
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
97
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
98
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
99
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
100
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
101
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
102
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
103
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
117
104
|
(**
|
|
118
105
|
* @license
|
|
119
106
|
* Copyright 2017 Google LLC
|
|
@@ -131,15 +118,16 @@ lodash-es/lodash.js:
|
|
|
131
118
|
* limitations under the License.
|
|
132
119
|
*)
|
|
133
120
|
|
|
134
|
-
@firebase/util/dist/index.
|
|
135
|
-
@firebase/util/dist/index.
|
|
136
|
-
@firebase/firestore/dist/
|
|
137
|
-
@firebase/firestore/dist/
|
|
138
|
-
@firebase/firestore/dist/
|
|
139
|
-
@firebase/firestore/dist/
|
|
140
|
-
@firebase/firestore/dist/
|
|
141
|
-
@firebase/firestore/dist/index.
|
|
142
|
-
@firebase/firestore/dist/index.
|
|
121
|
+
@firebase/util/dist/index.esm.js:
|
|
122
|
+
@firebase/util/dist/index.esm.js:
|
|
123
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
124
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
125
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
126
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
127
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
128
|
+
@firebase/firestore/dist/index.esm.js:
|
|
129
|
+
@firebase/firestore/dist/index.esm.js:
|
|
130
|
+
@firebase/firestore/dist/index.esm.js:
|
|
143
131
|
(**
|
|
144
132
|
* @license
|
|
145
133
|
* Copyright 2022 Google LLC
|
|
@@ -157,7 +145,7 @@ lodash-es/lodash.js:
|
|
|
157
145
|
* limitations under the License.
|
|
158
146
|
*)
|
|
159
147
|
|
|
160
|
-
@firebase/util/dist/index.
|
|
148
|
+
@firebase/util/dist/index.esm.js:
|
|
161
149
|
(**
|
|
162
150
|
* @license
|
|
163
151
|
* Copyright 2017 Google LLC
|
|
@@ -176,7 +164,7 @@ lodash-es/lodash.js:
|
|
|
176
164
|
*)
|
|
177
165
|
(**
|
|
178
166
|
* @license
|
|
179
|
-
* Copyright
|
|
167
|
+
* Copyright 2021 Google LLC
|
|
180
168
|
*
|
|
181
169
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
182
170
|
* you may not use this file except in compliance with the License.
|
|
@@ -190,9 +178,18 @@ lodash-es/lodash.js:
|
|
|
190
178
|
* See the License for the specific language governing permissions and
|
|
191
179
|
* limitations under the License.
|
|
192
180
|
*)
|
|
181
|
+
|
|
182
|
+
@firebase/util/dist/index.esm.js:
|
|
183
|
+
@firebase/component/dist/esm/index.esm.js:
|
|
184
|
+
@firebase/app/dist/esm/index.esm.js:
|
|
185
|
+
@firebase/app/dist/esm/index.esm.js:
|
|
186
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
187
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
188
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
189
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
193
190
|
(**
|
|
194
191
|
* @license
|
|
195
|
-
* Copyright
|
|
192
|
+
* Copyright 2019 Google LLC
|
|
196
193
|
*
|
|
197
194
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
198
195
|
* you may not use this file except in compliance with the License.
|
|
@@ -207,17 +204,23 @@ lodash-es/lodash.js:
|
|
|
207
204
|
* limitations under the License.
|
|
208
205
|
*)
|
|
209
206
|
|
|
210
|
-
@firebase/util/dist/index.
|
|
211
|
-
|
|
212
|
-
@firebase/
|
|
213
|
-
@firebase/
|
|
214
|
-
@firebase/firestore/dist/
|
|
215
|
-
@firebase/firestore/dist/
|
|
216
|
-
@firebase/firestore/dist/
|
|
217
|
-
@firebase/firestore/dist/
|
|
207
|
+
@firebase/util/dist/index.esm.js:
|
|
208
|
+
firebase/app/dist/esm/index.esm.js:
|
|
209
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
210
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
211
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
212
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
213
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
214
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
215
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
216
|
+
@firebase/firestore/dist/index.esm.js:
|
|
217
|
+
@firebase/firestore/dist/index.esm.js:
|
|
218
|
+
@firebase/firestore/dist/index.esm.js:
|
|
219
|
+
@firebase/firestore/dist/index.esm.js:
|
|
220
|
+
@firebase/firestore/dist/index.esm.js:
|
|
218
221
|
(**
|
|
219
222
|
* @license
|
|
220
|
-
* Copyright
|
|
223
|
+
* Copyright 2020 Google LLC
|
|
221
224
|
*
|
|
222
225
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
223
226
|
* you may not use this file except in compliance with the License.
|
|
@@ -232,25 +235,10 @@ lodash-es/lodash.js:
|
|
|
232
235
|
* limitations under the License.
|
|
233
236
|
*)
|
|
234
237
|
|
|
235
|
-
@firebase/util/dist/index.
|
|
236
|
-
firebase/app/dist/esm/index.esm.js:
|
|
237
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
238
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
239
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
240
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
241
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
242
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
243
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
244
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
245
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
246
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
247
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
248
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
249
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
250
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
238
|
+
@firebase/util/dist/index.esm.js:
|
|
251
239
|
(**
|
|
252
240
|
* @license
|
|
253
|
-
* Copyright
|
|
241
|
+
* Copyright 2021 Google LLC
|
|
254
242
|
*
|
|
255
243
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
256
244
|
* you may not use this file except in compliance with the License.
|
|
@@ -264,12 +252,9 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
264
252
|
* See the License for the specific language governing permissions and
|
|
265
253
|
* limitations under the License.
|
|
266
254
|
*)
|
|
267
|
-
|
|
268
|
-
@firebase/util/dist/index.esm2017.js:
|
|
269
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
270
255
|
(**
|
|
271
256
|
* @license
|
|
272
|
-
* Copyright
|
|
257
|
+
* Copyright 2025 Google LLC
|
|
273
258
|
*
|
|
274
259
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
275
260
|
* you may not use this file except in compliance with the License.
|
|
@@ -284,7 +269,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
284
269
|
* limitations under the License.
|
|
285
270
|
*)
|
|
286
271
|
|
|
287
|
-
@firebase/app/dist/esm/index.
|
|
272
|
+
@firebase/app/dist/esm/index.esm.js:
|
|
288
273
|
(**
|
|
289
274
|
* @license
|
|
290
275
|
* Copyright 2019 Google LLC
|
|
@@ -318,7 +303,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
318
303
|
* limitations under the License.
|
|
319
304
|
*)
|
|
320
305
|
|
|
321
|
-
@firebase/app/dist/esm/index.
|
|
306
|
+
@firebase/app/dist/esm/index.esm.js:
|
|
322
307
|
(**
|
|
323
308
|
* @license
|
|
324
309
|
* Copyright 2021 Google LLC
|
|
@@ -364,23 +349,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
364
349
|
SPDX-License-Identifier: Apache-2.0
|
|
365
350
|
*)
|
|
366
351
|
|
|
367
|
-
@firebase/firestore/dist/
|
|
368
|
-
(**
|
|
369
|
-
* @license
|
|
370
|
-
* Copyright 2020 Google LLC
|
|
371
|
-
*
|
|
372
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
373
|
-
* you may not use this file except in compliance with the License.
|
|
374
|
-
* You may obtain a copy of the License at
|
|
375
|
-
*
|
|
376
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
377
|
-
*
|
|
378
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
379
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
380
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
381
|
-
* See the License for the specific language governing permissions and
|
|
382
|
-
* limitations under the License.
|
|
383
|
-
*)
|
|
352
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
384
353
|
(**
|
|
385
354
|
* @license
|
|
386
355
|
* Copyright 2017 Google LLC
|
|
@@ -397,8 +366,6 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
397
366
|
* See the License for the specific language governing permissions and
|
|
398
367
|
* limitations under the License.
|
|
399
368
|
*)
|
|
400
|
-
|
|
401
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
402
369
|
(**
|
|
403
370
|
* @license
|
|
404
371
|
* Copyright 2020 Google LLC
|
|
@@ -415,9 +382,15 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
415
382
|
* See the License for the specific language governing permissions and
|
|
416
383
|
* limitations under the License.
|
|
417
384
|
*)
|
|
385
|
+
|
|
386
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
387
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
388
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
389
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
390
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
418
391
|
(**
|
|
419
392
|
* @license
|
|
420
|
-
* Copyright
|
|
393
|
+
* Copyright 2020 Google LLC
|
|
421
394
|
*
|
|
422
395
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
423
396
|
* you may not use this file except in compliance with the License.
|
|
@@ -448,7 +421,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
448
421
|
* limitations under the License.
|
|
449
422
|
*)
|
|
450
423
|
|
|
451
|
-
@firebase/firestore/dist/
|
|
424
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
452
425
|
(**
|
|
453
426
|
* @license
|
|
454
427
|
* Copyright 2025 Google LLC
|
|
@@ -498,14 +471,10 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
498
471
|
* limitations under the License.
|
|
499
472
|
*)
|
|
500
473
|
|
|
501
|
-
@firebase/firestore/dist/
|
|
502
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
503
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
504
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
505
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
474
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
506
475
|
(**
|
|
507
476
|
* @license
|
|
508
|
-
* Copyright
|
|
477
|
+
* Copyright 2018 Google LLC
|
|
509
478
|
*
|
|
510
479
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
511
480
|
* you may not use this file except in compliance with the License.
|
|
@@ -536,10 +505,10 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
536
505
|
* limitations under the License.
|
|
537
506
|
*)
|
|
538
507
|
|
|
539
|
-
@firebase/firestore/dist/
|
|
508
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
540
509
|
(**
|
|
541
510
|
* @license
|
|
542
|
-
* Copyright
|
|
511
|
+
* Copyright 2020 Google LLC
|
|
543
512
|
*
|
|
544
513
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
545
514
|
* you may not use this file except in compliance with the License.
|
|
@@ -555,7 +524,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
555
524
|
*)
|
|
556
525
|
(**
|
|
557
526
|
* @license
|
|
558
|
-
* Copyright
|
|
527
|
+
* Copyright 2023 Google LLC
|
|
559
528
|
*
|
|
560
529
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
561
530
|
* you may not use this file except in compliance with the License.
|
|
@@ -570,10 +539,11 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
570
539
|
* limitations under the License.
|
|
571
540
|
*)
|
|
572
541
|
|
|
573
|
-
@firebase/firestore/dist/
|
|
542
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
543
|
+
@firebase/firestore/dist/index.esm.js:
|
|
574
544
|
(**
|
|
575
545
|
* @license
|
|
576
|
-
* Copyright
|
|
546
|
+
* Copyright 2017 Google LLC
|
|
577
547
|
*
|
|
578
548
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
579
549
|
* you may not use this file except in compliance with the License.
|
|
@@ -589,7 +559,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
589
559
|
*)
|
|
590
560
|
(**
|
|
591
561
|
* @license
|
|
592
|
-
* Copyright
|
|
562
|
+
* Copyright 2022 Google LLC
|
|
593
563
|
*
|
|
594
564
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
595
565
|
* you may not use this file except in compliance with the License.
|
|
@@ -604,7 +574,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
604
574
|
* limitations under the License.
|
|
605
575
|
*)
|
|
606
576
|
|
|
607
|
-
@firebase/firestore/dist/
|
|
577
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
608
578
|
(**
|
|
609
579
|
* @license
|
|
610
580
|
* Copyright 2017 Google LLC
|
|
@@ -623,7 +593,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
623
593
|
*)
|
|
624
594
|
(**
|
|
625
595
|
* @license
|
|
626
|
-
* Copyright
|
|
596
|
+
* Copyright 2020 Google LLC
|
|
627
597
|
*
|
|
628
598
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
629
599
|
* you may not use this file except in compliance with the License.
|
|
@@ -637,11 +607,9 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
637
607
|
* See the License for the specific language governing permissions and
|
|
638
608
|
* limitations under the License.
|
|
639
609
|
*)
|
|
640
|
-
|
|
641
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
642
610
|
(**
|
|
643
611
|
* @license
|
|
644
|
-
* Copyright
|
|
612
|
+
* Copyright 2018 Google LLC
|
|
645
613
|
*
|
|
646
614
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
647
615
|
* you may not use this file except in compliance with the License.
|
|
@@ -655,9 +623,11 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
655
623
|
* See the License for the specific language governing permissions and
|
|
656
624
|
* limitations under the License.
|
|
657
625
|
*)
|
|
626
|
+
|
|
627
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
658
628
|
(**
|
|
659
629
|
* @license
|
|
660
|
-
* Copyright
|
|
630
|
+
* Copyright 2017 Google LLC
|
|
661
631
|
*
|
|
662
632
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
663
633
|
* you may not use this file except in compliance with the License.
|
|
@@ -673,7 +643,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
673
643
|
*)
|
|
674
644
|
(**
|
|
675
645
|
* @license
|
|
676
|
-
* Copyright
|
|
646
|
+
* Copyright 2022 Google LLC
|
|
677
647
|
*
|
|
678
648
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
679
649
|
* you may not use this file except in compliance with the License.
|
|
@@ -687,11 +657,9 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
687
657
|
* See the License for the specific language governing permissions and
|
|
688
658
|
* limitations under the License.
|
|
689
659
|
*)
|
|
690
|
-
|
|
691
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
692
660
|
(**
|
|
693
661
|
* @license
|
|
694
|
-
* Copyright
|
|
662
|
+
* Copyright 2023 Google LLC
|
|
695
663
|
*
|
|
696
664
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
697
665
|
* you may not use this file except in compliance with the License.
|
|
@@ -705,9 +673,11 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
705
673
|
* See the License for the specific language governing permissions and
|
|
706
674
|
* limitations under the License.
|
|
707
675
|
*)
|
|
676
|
+
|
|
677
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
708
678
|
(**
|
|
709
679
|
* @license
|
|
710
|
-
* Copyright
|
|
680
|
+
* Copyright 2017 Google LLC
|
|
711
681
|
*
|
|
712
682
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
713
683
|
* you may not use this file except in compliance with the License.
|
|
@@ -738,10 +708,10 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
738
708
|
* limitations under the License.
|
|
739
709
|
*)
|
|
740
710
|
|
|
741
|
-
@firebase/firestore/dist/
|
|
711
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
742
712
|
(**
|
|
743
713
|
* @license
|
|
744
|
-
* Copyright
|
|
714
|
+
* Copyright 2023 Google LLC
|
|
745
715
|
*
|
|
746
716
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
747
717
|
* you may not use this file except in compliance with the License.
|
|
@@ -757,7 +727,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
757
727
|
*)
|
|
758
728
|
(**
|
|
759
729
|
* @license
|
|
760
|
-
* Copyright
|
|
730
|
+
* Copyright 2022 Google LLC
|
|
761
731
|
*
|
|
762
732
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
763
733
|
* you may not use this file except in compliance with the License.
|
|
@@ -773,7 +743,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
773
743
|
*)
|
|
774
744
|
(**
|
|
775
745
|
* @license
|
|
776
|
-
* Copyright
|
|
746
|
+
* Copyright 2017 Google LLC
|
|
777
747
|
*
|
|
778
748
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
779
749
|
* you may not use this file except in compliance with the License.
|
|
@@ -788,7 +758,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
788
758
|
* limitations under the License.
|
|
789
759
|
*)
|
|
790
760
|
|
|
791
|
-
@firebase/firestore/dist/
|
|
761
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
792
762
|
(**
|
|
793
763
|
* @license
|
|
794
764
|
* Copyright 2024 Google LLC
|
|
@@ -806,7 +776,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
806
776
|
* limitations under the License.
|
|
807
777
|
*)
|
|
808
778
|
|
|
809
|
-
@firebase/firestore/dist/
|
|
779
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
810
780
|
(**
|
|
811
781
|
* @license
|
|
812
782
|
* Copyright 2021 Google LLC
|
|
@@ -840,7 +810,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
840
810
|
* limitations under the License.
|
|
841
811
|
*)
|
|
842
812
|
|
|
843
|
-
@firebase/firestore/dist/
|
|
813
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
844
814
|
(**
|
|
845
815
|
* @license
|
|
846
816
|
* Copyright 2018 Google LLC
|
|
@@ -874,7 +844,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
874
844
|
* limitations under the License.
|
|
875
845
|
*)
|
|
876
846
|
|
|
877
|
-
@firebase/firestore/dist/
|
|
847
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
878
848
|
(**
|
|
879
849
|
* @license
|
|
880
850
|
* Copyright 2017 Google LLC
|
|
@@ -940,7 +910,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
940
910
|
* limitations under the License.
|
|
941
911
|
*)
|
|
942
912
|
|
|
943
|
-
@firebase/firestore/dist/
|
|
913
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
944
914
|
(**
|
|
945
915
|
* @license
|
|
946
916
|
* Copyright 2017 Google LLC
|
|
@@ -1006,7 +976,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
1006
976
|
* limitations under the License.
|
|
1007
977
|
*)
|
|
1008
978
|
|
|
1009
|
-
@firebase/firestore/dist/
|
|
979
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
1010
980
|
(**
|
|
1011
981
|
* @license
|
|
1012
982
|
* Copyright 2018 Google LLC
|
|
@@ -1024,7 +994,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
1024
994
|
* limitations under the License.
|
|
1025
995
|
*)
|
|
1026
996
|
|
|
1027
|
-
@firebase/firestore/dist/
|
|
997
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
1028
998
|
(**
|
|
1029
999
|
* @license
|
|
1030
1000
|
* Copyright 2019 Google LLC
|
|
@@ -1090,7 +1060,9 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
1090
1060
|
* limitations under the License.
|
|
1091
1061
|
*)
|
|
1092
1062
|
|
|
1093
|
-
@firebase/firestore/dist/
|
|
1063
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
1064
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
1065
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
1094
1066
|
(**
|
|
1095
1067
|
* @license
|
|
1096
1068
|
* Copyright 2025 Google LLC
|
|
@@ -1108,7 +1080,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
1108
1080
|
* limitations under the License.
|
|
1109
1081
|
*)
|
|
1110
1082
|
|
|
1111
|
-
@firebase/firestore/dist/
|
|
1083
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
1112
1084
|
(**
|
|
1113
1085
|
* @license
|
|
1114
1086
|
* Copyright 2023 Google LLC
|
|
@@ -1142,7 +1114,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
1142
1114
|
* limitations under the License.
|
|
1143
1115
|
*)
|
|
1144
1116
|
|
|
1145
|
-
@firebase/firestore/dist/
|
|
1117
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
1146
1118
|
(**
|
|
1147
1119
|
* @license
|
|
1148
1120
|
* Copyright 2020 Google LLC
|
|
@@ -1161,7 +1133,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
1161
1133
|
*)
|
|
1162
1134
|
(**
|
|
1163
1135
|
* @license
|
|
1164
|
-
* Copyright
|
|
1136
|
+
* Copyright 2017 Google LLC
|
|
1165
1137
|
*
|
|
1166
1138
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1167
1139
|
* you may not use this file except in compliance with the License.
|
|
@@ -1175,11 +1147,9 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
1175
1147
|
* See the License for the specific language governing permissions and
|
|
1176
1148
|
* limitations under the License.
|
|
1177
1149
|
*)
|
|
1178
|
-
|
|
1179
|
-
@firebase/firestore/dist/index.esm2017.js:
|
|
1180
1150
|
(**
|
|
1181
1151
|
* @license
|
|
1182
|
-
* Copyright
|
|
1152
|
+
* Copyright 2024 Google LLC
|
|
1183
1153
|
*
|
|
1184
1154
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1185
1155
|
* you may not use this file except in compliance with the License.
|
|
@@ -1193,9 +1163,11 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
1193
1163
|
* See the License for the specific language governing permissions and
|
|
1194
1164
|
* limitations under the License.
|
|
1195
1165
|
*)
|
|
1166
|
+
|
|
1167
|
+
@firebase/firestore/dist/common-edb5d170.esm.js:
|
|
1196
1168
|
(**
|
|
1197
1169
|
* @license
|
|
1198
|
-
* Copyright
|
|
1170
|
+
* Copyright 2020 Google LLC
|
|
1199
1171
|
*
|
|
1200
1172
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1201
1173
|
* you may not use this file except in compliance with the License.
|
|
@@ -1226,7 +1198,7 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
1226
1198
|
* limitations under the License.
|
|
1227
1199
|
*)
|
|
1228
1200
|
|
|
1229
|
-
@firebase/firestore/dist/index.
|
|
1201
|
+
@firebase/firestore/dist/index.esm.js:
|
|
1230
1202
|
(**
|
|
1231
1203
|
* @license
|
|
1232
1204
|
* Copyright 2025 Google LLC
|
|
@@ -1260,8 +1232,26 @@ firebase/app/dist/esm/index.esm.js:
|
|
|
1260
1232
|
* limitations under the License.
|
|
1261
1233
|
*)
|
|
1262
1234
|
|
|
1263
|
-
@firebase/firestore/dist/index.
|
|
1264
|
-
|
|
1235
|
+
@firebase/firestore/dist/index.esm.js:
|
|
1236
|
+
(**
|
|
1237
|
+
* @license
|
|
1238
|
+
* Copyright 2021 Google LLC
|
|
1239
|
+
*
|
|
1240
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
1241
|
+
* you may not use this file except in compliance with the License.
|
|
1242
|
+
* You may obtain a copy of the License at
|
|
1243
|
+
*
|
|
1244
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
1245
|
+
*
|
|
1246
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
1247
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
1248
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1249
|
+
* See the License for the specific language governing permissions and
|
|
1250
|
+
* limitations under the License.
|
|
1251
|
+
*)
|
|
1252
|
+
|
|
1253
|
+
@firebase/firestore/dist/index.esm.js:
|
|
1254
|
+
@firebase/firestore/dist/index.esm.js:
|
|
1265
1255
|
(**
|
|
1266
1256
|
* @license
|
|
1267
1257
|
* Copyright 2023 Google LLC
|