ss-chatbot-widget 0.0.2 → 0.0.3

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.
@@ -172,6 +172,6 @@ Error: ${O}`)}}return d()}case de.MESSAGES_SNAPSHOT:{let S=await ln(r,a,s,(w,_,O
172
172
  `:""}${a}${u?`
173
173
  `:""})`}}function I8(e){return e!=null&&typeof e=="object"&&"$id"in e&&e.$id!=null&&"$ref"in e&&typeof e.$ref=="string"&&(!("$db"in e)||"$db"in e&&typeof e.$db=="string")}class Ls extends Kr{get _bsontype(){return"DBRef"}collection;oid;db;fields;constructor(t,n,r,a){super();const s=t.split(".");s.length===2&&(r=s.shift(),t=s.shift()),this.collection=t,this.oid=n,this.db=r,this.fields=a||{}}get namespace(){return this.collection}set namespace(t){this.collection=t}toJSON(){const t=Object.assign({$ref:this.collection,$id:this.oid},this.fields);return this.db!=null&&(t.$db=this.db),t}toExtendedJSON(t){t=t||{};let n={$ref:this.collection,$id:this.oid};return t.legacy||(this.db&&(n.$db=this.db),n=Object.assign(n,this.fields)),n}static fromExtendedJSON(t){const n=Object.assign({},t);return delete n.$ref,delete n.$id,delete n.$db,new Ls(t.$ref,t.$id,t.$db,n)}inspect(t,n,r){r??=Rr;const a=[r(this.namespace,n),r(this.oid,n),...this.db?[r(this.db,n)]:[],...Object.keys(this.fields).length>0?[r(this.fields,n)]:[]];return a[1]=r===Rr?`new ObjectId(${a[1]})`:a[1],`new DBRef(${a.join(", ")})`}}function a_(e){if(e==="")return e;let t=0;const n=e[t]==="-",r=e[t]==="+";(r||n)&&(t+=1);let a=!1;for(;t<e.length&&e[t]==="0";++t)a=!0;return a?`${n?"-":""}${e.length===t?"0":e.slice(t)}`:r?e.slice(1):e}function M8(e,t){t=t??10;const n="0123456789abcdefghijklmnopqrstuvwxyz".slice(0,t);return new RegExp(`[^-+${n}]`,"i").test(e)?!1:e}let Wr;try{Wr=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}const s_=65536,D8=1<<24,Ps=s_*s_,l_=Ps*Ps,u_=l_/2,c_={},f_={},B8=20,z8=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;class K extends Kr{get _bsontype(){return"Long"}get __isLong__(){return!0}high;low;unsigned;constructor(t=0,n,r){super();const a=typeof n=="boolean"?n:!!r,s=typeof n=="number"?n:0,u=typeof t=="string"?K.fromString(t,a):typeof t=="bigint"?K.fromBigInt(t,a):{low:t|0,high:s|0,unsigned:a};this.low=u.low,this.high=u.high,this.unsigned=u.unsigned}static TWO_PWR_24=K.fromInt(D8);static MAX_UNSIGNED_VALUE=K.fromBits(-1,-1,!0);static ZERO=K.fromInt(0);static UZERO=K.fromInt(0,!0);static ONE=K.fromInt(1);static UONE=K.fromInt(1,!0);static NEG_ONE=K.fromInt(-1);static MAX_VALUE=K.fromBits(-1,2147483647,!1);static MIN_VALUE=K.fromBits(0,-2147483648,!1);static fromBits(t,n,r){return new K(t,n,r)}static fromInt(t,n){let r,a,s;return n?(t>>>=0,(s=0<=t&&t<256)&&(a=f_[t],a)?a:(r=K.fromBits(t,(t|0)<0?-1:0,!0),s&&(f_[t]=r),r)):(t|=0,(s=-128<=t&&t<128)&&(a=c_[t],a)?a:(r=K.fromBits(t,t<0?-1:0,!1),s&&(c_[t]=r),r))}static fromNumber(t,n){if(isNaN(t))return n?K.UZERO:K.ZERO;if(n){if(t<0)return K.UZERO;if(t>=l_)return K.MAX_UNSIGNED_VALUE}else{if(t<=-u_)return K.MIN_VALUE;if(t+1>=u_)return K.MAX_VALUE}return t<0?K.fromNumber(-t,n).neg():K.fromBits(t%Ps|0,t/Ps|0,n)}static fromBigInt(t,n){const r=0xffffffffn,a=32n;return new K(Number(t&r),Number(t>>a&r),n)}static _fromString(t,n,r){if(t.length===0)throw new ve("empty string");if(r<2||36<r)throw new ve("radix");let a;if((a=t.indexOf("-"))>0)throw new ve("interior hyphen");if(a===0)return K._fromString(t.substring(1),n,r).neg();const s=K.fromNumber(Math.pow(r,8));let u=K.ZERO;for(let f=0;f<t.length;f+=8){const d=Math.min(8,t.length-f),p=parseInt(t.substring(f,f+d),r);if(d<8){const m=K.fromNumber(Math.pow(r,d));u=u.mul(m).add(K.fromNumber(p))}else u=u.mul(s),u=u.add(K.fromNumber(p))}return u.unsigned=n,u}static fromStringStrict(t,n,r){let a=!1;if(typeof n=="number"?(r=n,n=!1):a=!!n,r??=10,t.trim()!==t)throw new ve(`Input: '${t}' contains leading and/or trailing whitespace`);if(!M8(t,r))throw new ve(`Input: '${t}' contains invalid characters for radix: ${r}`);const s=a_(t),u=K._fromString(s,a,r);if(u.toString(r).toLowerCase()!==s.toLowerCase())throw new ve(`Input: ${t} is not representable as ${u.unsigned?"an unsigned":"a signed"} 64-bit Long ${r!=null?`with radix: ${r}`:""}`);return u}static fromString(t,n,r){let a=!1;return typeof n=="number"?(r=n,n=!1):a=!!n,r??=10,t==="NaN"&&r<24||(t==="Infinity"||t==="+Infinity"||t==="-Infinity")&&r<35?K.ZERO:K._fromString(t,a,r)}static fromBytes(t,n,r){return r?K.fromBytesLE(t,n):K.fromBytesBE(t,n)}static fromBytesLE(t,n){return new K(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,n)}static fromBytesBE(t,n){return new K(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],n)}static isLong(t){return t!=null&&typeof t=="object"&&"__isLong__"in t&&t.__isLong__===!0}static fromValue(t,n){return typeof t=="number"?K.fromNumber(t,n):typeof t=="string"?K.fromString(t,n):K.fromBits(t.low,t.high,typeof n=="boolean"?n:t.unsigned)}add(t){K.isLong(t)||(t=K.fromValue(t));const n=this.high>>>16,r=this.high&65535,a=this.low>>>16,s=this.low&65535,u=t.high>>>16,f=t.high&65535,d=t.low>>>16,p=t.low&65535;let m=0,y=0,b=0,v=0;return v+=s+p,b+=v>>>16,v&=65535,b+=a+d,y+=b>>>16,b&=65535,y+=r+f,m+=y>>>16,y&=65535,m+=n+u,m&=65535,K.fromBits(b<<16|v,m<<16|y,this.unsigned)}and(t){return K.isLong(t)||(t=K.fromValue(t)),K.fromBits(this.low&t.low,this.high&t.high,this.unsigned)}compare(t){if(K.isLong(t)||(t=K.fromValue(t)),this.eq(t))return 0;const n=this.isNegative(),r=t.isNegative();return n&&!r?-1:!n&&r?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1}comp(t){return this.compare(t)}divide(t){if(K.isLong(t)||(t=K.fromValue(t)),t.isZero())throw new ve("division by zero");if(Wr){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;const s=(this.unsigned?Wr.div_u:Wr.div_s)(this.low,this.high,t.low,t.high);return K.fromBits(s,Wr.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?K.UZERO:K.ZERO;let n,r,a;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return K.UZERO;if(t.gt(this.shru(1)))return K.UONE;a=K.UZERO}else{if(this.eq(K.MIN_VALUE))return t.eq(K.ONE)||t.eq(K.NEG_ONE)?K.MIN_VALUE:t.eq(K.MIN_VALUE)?K.ONE:(n=this.shr(1).div(t).shl(1),n.eq(K.ZERO)?t.isNegative()?K.ONE:K.NEG_ONE:(r=this.sub(t.mul(n)),a=n.add(r.div(t)),a));if(t.eq(K.MIN_VALUE))return this.unsigned?K.UZERO:K.ZERO;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();a=K.ZERO}for(r=this;r.gte(t);){n=Math.max(1,Math.floor(r.toNumber()/t.toNumber()));const s=Math.ceil(Math.log(n)/Math.LN2),u=s<=48?1:Math.pow(2,s-48);let f=K.fromNumber(n),d=f.mul(t);for(;d.isNegative()||d.gt(r);)n-=u,f=K.fromNumber(n,this.unsigned),d=f.mul(t);f.isZero()&&(f=K.ONE),a=a.add(f),r=r.sub(d)}return a}div(t){return this.divide(t)}equals(t){return K.isLong(t)||(t=K.fromValue(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low}eq(t){return this.equals(t)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative())return this.eq(K.MIN_VALUE)?64:this.neg().getNumBitsAbs();const t=this.high!==0?this.high:this.low;let n;for(n=31;n>0&&(t&1<<n)===0;n--);return this.high!==0?n+33:n+1}greaterThan(t){return this.comp(t)>0}gt(t){return this.greaterThan(t)}greaterThanOrEqual(t){return this.comp(t)>=0}gte(t){return this.greaterThanOrEqual(t)}ge(t){return this.greaterThanOrEqual(t)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(t){return this.comp(t)<0}lt(t){return this.lessThan(t)}lessThanOrEqual(t){return this.comp(t)<=0}lte(t){return this.lessThanOrEqual(t)}modulo(t){if(K.isLong(t)||(t=K.fromValue(t)),Wr){const n=(this.unsigned?Wr.rem_u:Wr.rem_s)(this.low,this.high,t.low,t.high);return K.fromBits(n,Wr.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))}mod(t){return this.modulo(t)}rem(t){return this.modulo(t)}multiply(t){if(this.isZero())return K.ZERO;if(K.isLong(t)||(t=K.fromValue(t)),Wr){const E=Wr.mul(this.low,this.high,t.low,t.high);return K.fromBits(E,Wr.get_high(),this.unsigned)}if(t.isZero())return K.ZERO;if(this.eq(K.MIN_VALUE))return t.isOdd()?K.MIN_VALUE:K.ZERO;if(t.eq(K.MIN_VALUE))return this.isOdd()?K.MIN_VALUE:K.ZERO;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(K.TWO_PWR_24)&&t.lt(K.TWO_PWR_24))return K.fromNumber(this.toNumber()*t.toNumber(),this.unsigned);const n=this.high>>>16,r=this.high&65535,a=this.low>>>16,s=this.low&65535,u=t.high>>>16,f=t.high&65535,d=t.low>>>16,p=t.low&65535;let m=0,y=0,b=0,v=0;return v+=s*p,b+=v>>>16,v&=65535,b+=a*p,y+=b>>>16,b&=65535,b+=s*d,y+=b>>>16,b&=65535,y+=r*p,m+=y>>>16,y&=65535,y+=a*d,m+=y>>>16,y&=65535,y+=s*f,m+=y>>>16,y&=65535,m+=n*p+r*d+a*f+s*u,m&=65535,K.fromBits(b<<16|v,m<<16|y,this.unsigned)}mul(t){return this.multiply(t)}negate(){return!this.unsigned&&this.eq(K.MIN_VALUE)?K.MIN_VALUE:this.not().add(K.ONE)}neg(){return this.negate()}not(){return K.fromBits(~this.low,~this.high,this.unsigned)}notEquals(t){return!this.equals(t)}neq(t){return this.notEquals(t)}ne(t){return this.notEquals(t)}or(t){return K.isLong(t)||(t=K.fromValue(t)),K.fromBits(this.low|t.low,this.high|t.high,this.unsigned)}shiftLeft(t){return K.isLong(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?K.fromBits(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):K.fromBits(0,this.low<<t-32,this.unsigned)}shl(t){return this.shiftLeft(t)}shiftRight(t){return K.isLong(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?K.fromBits(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):K.fromBits(this.high>>t-32,this.high>=0?0:-1,this.unsigned)}shr(t){return this.shiftRight(t)}shiftRightUnsigned(t){if(K.isLong(t)&&(t=t.toInt()),t&=63,t===0)return this;{const n=this.high;if(t<32){const r=this.low;return K.fromBits(r>>>t|n<<32-t,n>>>t,this.unsigned)}else return t===32?K.fromBits(n,0,this.unsigned):K.fromBits(n>>>t-32,0,this.unsigned)}}shr_u(t){return this.shiftRightUnsigned(t)}shru(t){return this.shiftRightUnsigned(t)}subtract(t){return K.isLong(t)||(t=K.fromValue(t)),this.add(t.neg())}sub(t){return this.subtract(t)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){return this.unsigned?(this.high>>>0)*Ps+(this.low>>>0):this.high*Ps+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(t){return t?this.toBytesLE():this.toBytesBE()}toBytesLE(){const t=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]}toBytesBE(){const t=this.high,n=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,n>>>24,n>>>16&255,n>>>8&255,n&255]}toSigned(){return this.unsigned?K.fromBits(this.low,this.high,!1):this}toString(t){if(t=t||10,t<2||36<t)throw new ve("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(K.MIN_VALUE)){const s=K.fromNumber(t),u=this.div(s),f=u.mul(s).sub(this);return u.toString(t)+f.toInt().toString(t)}else return"-"+this.neg().toString(t);const n=K.fromNumber(Math.pow(t,6),this.unsigned);let r=this,a="";for(;;){const s=r.div(n);let f=(r.sub(s.mul(n)).toInt()>>>0).toString(t);if(r=s,r.isZero())return f+a;for(;f.length<6;)f="0"+f;a=""+f+a}}toUnsigned(){return this.unsigned?this:K.fromBits(this.low,this.high,!0)}xor(t){return K.isLong(t)||(t=K.fromValue(t)),K.fromBits(this.low^t.low,this.high^t.high,this.unsigned)}eqz(){return this.isZero()}le(t){return this.lessThanOrEqual(t)}toExtendedJSON(t){return t&&t.relaxed?this.toNumber():{$numberLong:this.toString()}}static fromExtendedJSON(t,n){const{useBigInt64:r=!1,relaxed:a=!0}={...n};if(t.$numberLong.length>B8)throw new ve("$numberLong string is too long");if(!z8.test(t.$numberLong))throw new ve(`$numberLong string "${t.$numberLong}" is in an invalid format`);if(r){const u=BigInt(t.$numberLong);return BigInt.asIntN(64,u)}const s=K.fromString(t.$numberLong);return a?s.toNumber():s}inspect(t,n,r){r??=Rr;const a=r(this.toString(),n),s=this.unsigned?`, ${r(this.unsigned,n)}`:"";return`new Long(${a}${s})`}}const L8=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,P8=/^(\+|-)?(Infinity|inf)$/i,$8=/^(\+|-)?NaN$/i,$s=6111,Iu=-6176,d_=6176,p_=34,ny=Le.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),h_=Le.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),m_=Le.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse()),U8=/^([-+])?(\d+)?$/,j8=31,g_=16383,H8=30,V8=31;function y_(e){return!isNaN(parseInt(e,10))}function F8(e){const t=K.fromNumber(1e9);let n=K.fromNumber(0);if(!e.parts[0]&&!e.parts[1]&&!e.parts[2]&&!e.parts[3])return{quotient:e,rem:n};for(let r=0;r<=3;r++)n=n.shiftLeft(32),n=n.add(new K(e.parts[r],0)),e.parts[r]=n.div(t).low,n=n.modulo(t);return{quotient:e,rem:n}}function q8(e,t){if(!e&&!t)return{high:K.fromNumber(0),low:K.fromNumber(0)};const n=e.shiftRightUnsigned(32),r=new K(e.getLowBits(),0),a=t.shiftRightUnsigned(32),s=new K(t.getLowBits(),0);let u=n.multiply(a),f=n.multiply(s);const d=r.multiply(a);let p=r.multiply(s);return u=u.add(f.shiftRightUnsigned(32)),f=new K(f.getLowBits(),0).add(d).add(p.shiftRightUnsigned(32)),u=u.add(f.shiftRightUnsigned(32)),p=f.shiftLeft(32).add(new K(p.getLowBits(),0)),{high:u,low:p}}function G8(e,t){const n=e.high>>>0,r=t.high>>>0;if(n<r)return!0;if(n===r){const a=e.low>>>0,s=t.low>>>0;if(a<s)return!0}return!1}function mi(e,t){throw new ve(`"${e}" is not a valid Decimal128 string - ${t}`)}class Nr extends Kr{get _bsontype(){return"Decimal128"}bytes;constructor(t){if(super(),typeof t=="string")this.bytes=Nr.fromString(t).bytes;else if(t instanceof Uint8Array||kd(t)){if(t.byteLength!==16)throw new ve("Decimal128 must take a Buffer of 16 bytes");this.bytes=t}else throw new ve("Decimal128 must take a Buffer or string")}static fromString(t){return Nr._fromString(t,{allowRounding:!1})}static fromStringWithRounding(t){return Nr._fromString(t,{allowRounding:!0})}static _fromString(t,n){let r=!1,a=!1,s=!1,u=!1,f=0,d=0,p=0,m=0,y=0;const b=[0];let v=0,E=0,S=0,w=0,_=new K(0,0),O=new K(0,0),T=0,C=0;if(t.length>=7e3)throw new ve(""+t+" not a valid Decimal128 string");const N=t.match(L8),k=t.match(P8),z=t.match($8);if(!N&&!k&&!z||t.length===0)throw new ve(""+t+" not a valid Decimal128 string");if(N){const F=N[2],A=N[4],X=N[5],$=N[6];A&&$===void 0&&mi(t,"missing exponent power"),A&&F===void 0&&mi(t,"missing exponent base"),A===void 0&&(X||$)&&mi(t,"missing e before exponent")}if((t[C]==="+"||t[C]==="-")&&(a=!0,r=t[C++]==="-"),!y_(t[C])&&t[C]!=="."){if(t[C]==="i"||t[C]==="I")return new Nr(r?h_:m_);if(t[C]==="N")return new Nr(ny)}for(;y_(t[C])||t[C]===".";){if(t[C]==="."){s&&mi(t,"contains multiple periods"),s=!0,C=C+1;continue}v<p_&&(t[C]!=="0"||u)&&(u||(y=d),u=!0,b[E++]=parseInt(t[C],10),v=v+1),u&&(p=p+1),s&&(m=m+1),d=d+1,C=C+1}if(s&&!d)throw new ve(""+t+" not a valid Decimal128 string");if(t[C]==="e"||t[C]==="E"){const F=t.substr(++C).match(U8);if(!F||!F[2])return new Nr(ny);w=parseInt(F[0],10),C=C+F[0].length}if(t[C])return new Nr(ny);if(!v)b[0]=0,p=1,v=1,f=0;else if(S=v-1,f=p,f!==1)for(;t[y+f-1+Number(a)+Number(s)]==="0";)f=f-1;for(w<=m&&m>w+16384?w=Iu:w=w-m;w>$s;){if(S=S+1,S>=p_){if(f===0){w=$s;break}mi(t,"overflow")}w=w-1}if(n.allowRounding){for(;w<Iu||v<p;){if(S===0&&f<v){w=Iu,f=0;break}if(v<p?p=p-1:S=S-1,w<$s)w=w+1;else{if(b.join("").match(/^0+$/)){w=$s;break}mi(t,"overflow")}}if(S+1<f){let F=d;s&&(y=y+1,F=F+1),a&&(y=y+1,F=F+1);const A=parseInt(t[y+S+1],10);let X=0;if(A>=5&&(X=1,A===5)){X=b[S]%2===1?1:0;for(let $=y+S+2;$<F;$++)if(parseInt(t[$],10)){X=1;break}}if(X){let $=S;for(;$>=0&&++b[$]>9;$--)if(b[$]=0,$===0)if(w<$s)w=w+1,b[$]=1;else return new Nr(r?h_:m_)}}}else{for(;w<Iu||v<p;){if(S===0){if(f===0){w=Iu;break}mi(t,"exponent underflow")}v<p?(t[p-1+Number(a)+Number(s)]!=="0"&&f!==0&&mi(t,"inexact rounding"),p=p-1):(b[S]!==0&&mi(t,"inexact rounding"),S=S-1),w<$s?w=w+1:mi(t,"overflow")}S+1<f&&(s&&(y=y+1),a&&(y=y+1),parseInt(t[y+S+1],10)!==0&&mi(t,"inexact rounding"))}if(_=K.fromNumber(0),O=K.fromNumber(0),f===0)_=K.fromNumber(0),O=K.fromNumber(0);else if(S<17){let F=0;for(O=K.fromNumber(b[F++]),_=new K(0,0);F<=S;F++)O=O.multiply(K.fromNumber(10)),O=O.add(K.fromNumber(b[F]))}else{let F=0;for(_=K.fromNumber(b[F++]);F<=S-17;F++)_=_.multiply(K.fromNumber(10)),_=_.add(K.fromNumber(b[F]));for(O=K.fromNumber(b[F++]);F<=S;F++)O=O.multiply(K.fromNumber(10)),O=O.add(K.fromNumber(b[F]))}const H=q8(_,K.fromString("100000000000000000"));H.low=H.low.add(O),G8(H.low,O)&&(H.high=H.high.add(K.fromNumber(1))),T=w+d_;const j={low:K.fromNumber(0),high:K.fromNumber(0)};H.high.shiftRightUnsigned(49).and(K.fromNumber(1)).equals(K.fromNumber(1))?(j.high=j.high.or(K.fromNumber(3).shiftLeft(61)),j.high=j.high.or(K.fromNumber(T).and(K.fromNumber(16383).shiftLeft(47))),j.high=j.high.or(H.high.and(K.fromNumber(0x7fffffffffff)))):(j.high=j.high.or(K.fromNumber(T&16383).shiftLeft(49)),j.high=j.high.or(H.high.and(K.fromNumber(562949953421311)))),j.low=H.low,r&&(j.high=j.high.or(K.fromString("9223372036854775808")));const G=Le.allocateUnsafe(16);return C=0,G[C++]=j.low.low&255,G[C++]=j.low.low>>8&255,G[C++]=j.low.low>>16&255,G[C++]=j.low.low>>24&255,G[C++]=j.low.high&255,G[C++]=j.low.high>>8&255,G[C++]=j.low.high>>16&255,G[C++]=j.low.high>>24&255,G[C++]=j.high.low&255,G[C++]=j.high.low>>8&255,G[C++]=j.high.low>>16&255,G[C++]=j.high.low>>24&255,G[C++]=j.high.high&255,G[C++]=j.high.high>>8&255,G[C++]=j.high.high>>16&255,G[C++]=j.high.high>>24&255,new Nr(G)}toString(){let t,n=0;const r=new Array(36);for(let C=0;C<r.length;C++)r[C]=0;let a=0,s=!1,u,f={parts:[0,0,0,0]},d,p;const m=[];a=0;const y=this.bytes,b=y[a++]|y[a++]<<8|y[a++]<<16|y[a++]<<24,v=y[a++]|y[a++]<<8|y[a++]<<16|y[a++]<<24,E=y[a++]|y[a++]<<8|y[a++]<<16|y[a++]<<24,S=y[a++]|y[a++]<<8|y[a++]<<16|y[a++]<<24;a=0,{low:new K(b,v),high:new K(E,S)}.high.lessThan(K.ZERO)&&m.push("-");const _=S>>26&j8;if(_>>3===3){if(_===H8)return m.join("")+"Infinity";if(_===V8)return"NaN";t=S>>15&g_,u=8+(S>>14&1)}else u=S>>14&7,t=S>>17&g_;const O=t-d_;if(f.parts[0]=(S&16383)+((u&15)<<14),f.parts[1]=E,f.parts[2]=v,f.parts[3]=b,f.parts[0]===0&&f.parts[1]===0&&f.parts[2]===0&&f.parts[3]===0)s=!0;else for(p=3;p>=0;p--){let C=0;const N=F8(f);if(f=N.quotient,C=N.rem.low,!!C)for(d=8;d>=0;d--)r[p*9+d]=C%10,C=Math.floor(C/10)}if(s)n=1,r[a]=0;else for(n=36;!r[a];)n=n-1,a=a+1;const T=n-1+O;if(T>=34||T<=-7||O>0){if(n>34)return m.push("0"),O>0?m.push(`E+${O}`):O<0&&m.push(`E${O}`),m.join("");m.push(`${r[a++]}`),n=n-1,n&&m.push(".");for(let C=0;C<n;C++)m.push(`${r[a++]}`);m.push("E"),T>0?m.push(`+${T}`):m.push(`${T}`)}else if(O>=0)for(let C=0;C<n;C++)m.push(`${r[a++]}`);else{let C=n+O;if(C>0)for(let N=0;N<C;N++)m.push(`${r[a++]}`);else m.push("0");for(m.push(".");C++<0;)m.push("0");for(let N=0;N<n-Math.max(C-1,0);N++)m.push(`${r[a++]}`)}return m.join("")}toJSON(){return{$numberDecimal:this.toString()}}toExtendedJSON(){return{$numberDecimal:this.toString()}}static fromExtendedJSON(t){return Nr.fromString(t.$numberDecimal)}inspect(t,n,r){return r??=Rr,`new Decimal128(${r(this.toString(),n)})`}}class Ji extends Kr{get _bsontype(){return"Double"}value;constructor(t){super(),t instanceof Number&&(t=t.valueOf()),this.value=+t}static fromString(t){const n=Number(t);if(t==="NaN")return new Ji(NaN);if(t==="Infinity")return new Ji(1/0);if(t==="-Infinity")return new Ji(-1/0);if(!Number.isFinite(n))throw new ve(`Input: ${t} is not representable as a Double`);if(t.trim()!==t)throw new ve(`Input: '${t}' contains whitespace`);if(t==="")throw new ve("Input is an empty string");if(/[^-0-9.+eE]/.test(t))throw new ve(`Input: '${t}' is not in decimal or exponential notation`);return new Ji(n)}valueOf(){return this.value}toJSON(){return this.value}toString(t){return this.value.toString(t)}toExtendedJSON(t){return t&&(t.legacy||t.relaxed&&isFinite(this.value))?this.value:Object.is(Math.sign(this.value),-0)?{$numberDouble:"-0.0"}:{$numberDouble:Number.isInteger(this.value)?this.value.toFixed(1):this.value.toString()}}static fromExtendedJSON(t,n){const r=parseFloat(t.$numberDouble);return n&&n.relaxed?r:new Ji(r)}inspect(t,n,r){return r??=Rr,`new Double(${r(this.value,n)})`}}class Us extends Kr{get _bsontype(){return"Int32"}value;constructor(t){super(),t instanceof Number&&(t=t.valueOf()),this.value=+t|0}static fromString(t){const n=a_(t),r=Number(t);if(Qg<r)throw new ve(`Input: '${t}' is larger than the maximum value for Int32`);if(Jg>r)throw new ve(`Input: '${t}' is smaller than the minimum value for Int32`);if(Number.isSafeInteger(r)){if(r.toString()!==n)throw new ve(`Input: '${t}' is not a valid Int32 string`)}else throw new ve(`Input: '${t}' is not a safe integer`);return new Us(r)}valueOf(){return this.value}toString(t){return this.value.toString(t)}toJSON(){return this.value}toExtendedJSON(t){return t&&(t.relaxed||t.legacy)?this.value:{$numberInt:this.value.toString()}}static fromExtendedJSON(t,n){return n&&n.relaxed?parseInt(t.$numberInt,10):new Us(t.$numberInt)}inspect(t,n,r){return r??=Rr,`new Int32(${r(this.value,n)})`}}class Od extends Kr{get _bsontype(){return"MaxKey"}toExtendedJSON(){return{$maxKey:1}}static fromExtendedJSON(){return new Od}inspect(){return"new MaxKey()"}}class Rd extends Kr{get _bsontype(){return"MinKey"}toExtendedJSON(){return{$minKey:1}}static fromExtendedJSON(){return new Rd}inspect(){return"new MinKey()"}}let Na=null;const Mu=new WeakMap;class En extends Kr{get _bsontype(){return"ObjectId"}static index=Math.floor(Math.random()*16777215);static cacheHexString;buffer;constructor(t){super();let n;if(typeof t=="object"&&t&&"id"in t){if(typeof t.id!="string"&&!ArrayBuffer.isView(t.id))throw new ve("Argument passed in must have an id that is of type string or Buffer");"toHexString"in t&&typeof t.toHexString=="function"?n=Le.fromHex(t.toHexString()):n=t.id}else n=t;if(n==null)this.buffer=En.generate();else if(ArrayBuffer.isView(n)&&n.byteLength===12)this.buffer=Le.toLocalBufferType(n);else if(typeof n=="string")if(En.validateHexString(n))this.buffer=Le.fromHex(n),En.cacheHexString&&Mu.set(this,n);else throw new ve("input must be a 24 character hex string, 12 byte Uint8Array, or an integer");else throw new ve("Argument passed in does not match the accepted types")}get id(){return this.buffer}set id(t){this.buffer=t,En.cacheHexString&&Mu.set(this,Le.toHex(t))}static validateHexString(t){if(t?.length!==24)return!1;for(let n=0;n<24;n++){const r=t.charCodeAt(n);if(!(r>=48&&r<=57||r>=97&&r<=102||r>=65&&r<=70))return!1}return!0}toHexString(){if(En.cacheHexString){const n=Mu.get(this);if(n)return n}const t=Le.toHex(this.id);return En.cacheHexString&&Mu.set(this,t),t}static getInc(){return En.index=(En.index+1)%16777215}static generate(t){typeof t!="number"&&(t=Math.floor(Date.now()/1e3));const n=En.getInc(),r=Le.allocateUnsafe(12);return Ra.setInt32BE(r,0,t),Na===null&&(Na=Le.randomBytes(5)),r[4]=Na[0],r[5]=Na[1],r[6]=Na[2],r[7]=Na[3],r[8]=Na[4],r[11]=n&255,r[10]=n>>8&255,r[9]=n>>16&255,r}toString(t){return t==="base64"?Le.toBase64(this.id):t==="hex"?this.toHexString():this.toHexString()}toJSON(){return this.toHexString()}static is(t){return t!=null&&typeof t=="object"&&"_bsontype"in t&&t._bsontype==="ObjectId"}equals(t){if(t==null)return!1;if(En.is(t))return this.buffer[11]===t.buffer[11]&&Le.equals(this.buffer,t.buffer);if(typeof t=="string")return t.toLowerCase()===this.toHexString();if(typeof t=="object"&&typeof t.toHexString=="function"){const n=t.toHexString(),r=this.toHexString();return typeof n=="string"&&n.toLowerCase()===r}return!1}getTimestamp(){const t=new Date,n=Ra.getUint32BE(this.buffer,0);return t.setTime(Math.floor(n)*1e3),t}static createPk(){return new En}serializeInto(t,n){return t[n]=this.buffer[0],t[n+1]=this.buffer[1],t[n+2]=this.buffer[2],t[n+3]=this.buffer[3],t[n+4]=this.buffer[4],t[n+5]=this.buffer[5],t[n+6]=this.buffer[6],t[n+7]=this.buffer[7],t[n+8]=this.buffer[8],t[n+9]=this.buffer[9],t[n+10]=this.buffer[10],t[n+11]=this.buffer[11],12}static createFromTime(t){const n=Le.allocate(12);for(let r=11;r>=4;r--)n[r]=0;return Ra.setInt32BE(n,0,t),new En(n)}static createFromHexString(t){if(t?.length!==24)throw new ve("hex string must be 24 characters");return new En(Le.fromHex(t))}static createFromBase64(t){if(t?.length!==16)throw new ve("base64 string must be 16 characters");return new En(Le.fromBase64(t))}static isValid(t){if(t==null)return!1;if(typeof t=="string")return En.validateHexString(t);try{return new En(t),!0}catch{return!1}}toExtendedJSON(){return this.toHexString?{$oid:this.toHexString()}:{$oid:this.toString("hex")}}static fromExtendedJSON(t){return new En(t.$oid)}isCached(){return En.cacheHexString&&Mu.has(this)}inspect(t,n,r){return r??=Rr,`new ObjectId(${r(this.toHexString(),n)})`}}function Y8(e){return e.split("").sort().join("")}class eo extends Kr{get _bsontype(){return"BSONRegExp"}pattern;options;constructor(t,n){if(super(),this.pattern=t,this.options=Y8(n??""),this.pattern.indexOf("\0")!==-1)throw new ve(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);if(this.options.indexOf("\0")!==-1)throw new ve(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);for(let r=0;r<this.options.length;r++)if(!(this.options[r]==="i"||this.options[r]==="m"||this.options[r]==="x"||this.options[r]==="l"||this.options[r]==="s"||this.options[r]==="u"))throw new ve(`The regular expression option [${this.options[r]}] is not supported`)}static parseOptions(t){return t?t.split("").sort().join(""):""}toExtendedJSON(t){return t=t||{},t.legacy?{$regex:this.pattern,$options:this.options}:{$regularExpression:{pattern:this.pattern,options:this.options}}}static fromExtendedJSON(t){if("$regex"in t)if(typeof t.$regex!="string"){if(t.$regex._bsontype==="BSONRegExp")return t}else return new eo(t.$regex,eo.parseOptions(t.$options));if("$regularExpression"in t)return new eo(t.$regularExpression.pattern,eo.parseOptions(t.$regularExpression.options));throw new ve(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(t)}`)}inspect(t,n,r){const a=b8(n)??(f=>f);r??=Rr;const s=a(r(this.pattern),"regexp"),u=a(r(this.options),"regexp");return`new BSONRegExp(${s}, ${u})`}}class Nd extends Kr{get _bsontype(){return"BSONSymbol"}value;constructor(t){super(),this.value=t}valueOf(){return this.value}toString(){return this.value}toJSON(){return this.value}toExtendedJSON(){return{$symbol:this.value}}static fromExtendedJSON(t){return new Nd(t.$symbol)}inspect(t,n,r){return r??=Rr,`new BSONSymbol(${r(this.value,n)})`}}const X8=K;class $o extends X8{get _bsontype(){return"Timestamp"}get[o_](){return"Timestamp"}static MAX_VALUE=K.MAX_UNSIGNED_VALUE;get i(){return this.low>>>0}get t(){return this.high>>>0}constructor(t){if(t==null)super(0,0,!0);else if(typeof t=="bigint")super(t,!0);else if(K.isLong(t))super(t.low,t.high,!0);else if(typeof t=="object"&&"t"in t&&"i"in t){if(typeof t.t!="number"&&(typeof t.t!="object"||t.t._bsontype!=="Int32"))throw new ve("Timestamp constructed from { t, i } must provide t as a number");if(typeof t.i!="number"&&(typeof t.i!="object"||t.i._bsontype!=="Int32"))throw new ve("Timestamp constructed from { t, i } must provide i as a number");const n=Number(t.t),r=Number(t.i);if(n<0||Number.isNaN(n))throw new ve("Timestamp constructed from { t, i } must provide a positive t");if(r<0||Number.isNaN(r))throw new ve("Timestamp constructed from { t, i } must provide a positive i");if(n>4294967295)throw new ve("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");if(r>4294967295)throw new ve("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");super(r,n,!0)}else throw new ve("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}toJSON(){return{$timestamp:this.toString()}}static fromInt(t){return new $o(K.fromInt(t,!0))}static fromNumber(t){return new $o(K.fromNumber(t,!0))}static fromBits(t,n){return new $o({i:t,t:n})}static fromString(t,n){return new $o(K.fromString(t,!0,n))}toExtendedJSON(){return{$timestamp:{t:this.t,i:this.i}}}static fromExtendedJSON(t){const n=K.isLong(t.$timestamp.i)?t.$timestamp.i.getLowBitsUnsigned():t.$timestamp.i,r=K.isLong(t.$timestamp.t)?t.$timestamp.t.getLowBitsUnsigned():t.$timestamp.t;return new $o({t:r,i:n})}inspect(t,n,r){r??=Rr;const a=r(this.t,n),s=r(this.i,n);return`new Timestamp({ t: ${a}, i: ${s} })`}}K.fromNumber(S8),K.fromNumber(x8);function Z8(e){return e!=null&&typeof e=="object"&&"_bsontype"in e&&typeof e._bsontype=="string"}const K8={$oid:En,$binary:dt,$uuid:dt,$symbol:Nd,$numberInt:Us,$numberDecimal:Nr,$numberDouble:Ji,$numberLong:K,$minKey:Rd,$maxKey:Od,$regex:eo,$regularExpression:eo,$timestamp:$o};function v_(e,t={}){if(typeof e=="number"){const r=e<=Qg&&e>=Jg,a=e<=Kw&&e>=Ww;if(t.relaxed||t.legacy)return e;if(Number.isInteger(e)&&!Object.is(e,-0)){if(r)return new Us(e);if(a)return t.useBigInt64?BigInt(e):K.fromNumber(e)}return new Ji(e)}if(e==null||typeof e!="object")return e;if(e.$undefined)return null;const n=Object.keys(e).filter(r=>r.startsWith("$")&&e[r]!=null);for(let r=0;r<n.length;r++){const a=K8[n[r]];if(a)return a.fromExtendedJSON(e,t)}if(e.$date!=null){const r=e.$date,a=new Date;if(t.legacy)if(typeof r=="number")a.setTime(r);else if(typeof r=="string")a.setTime(Date.parse(r));else if(typeof r=="bigint")a.setTime(Number(r));else throw new Jw(`Unrecognized type for EJSON date: ${typeof r}`);else if(typeof r=="string")a.setTime(Date.parse(r));else if(K.isLong(r))a.setTime(r.toNumber());else if(typeof r=="number"&&t.relaxed)a.setTime(r);else if(typeof r=="bigint")a.setTime(Number(r));else throw new Jw(`Unrecognized type for EJSON date: ${typeof r}`);return a}if(e.$code!=null){const r=Object.assign({},e);return e.$scope&&(r.$scope=v_(e.$scope)),Nu.fromExtendedJSON(e)}if(I8(e)||e.$dbPointer){const r=e.$ref?e:e.$dbPointer;if(r instanceof Ls)return r;const a=Object.keys(r).filter(u=>u.startsWith("$"));let s=!0;if(a.forEach(u=>{["$ref","$id","$db"].indexOf(u)===-1&&(s=!1)}),s)return Ls.fromExtendedJSON(r)}return e}function W8(e,t){return e.map((n,r)=>{t.seenObjects.push({propertyName:`index ${r}`,obj:null});try{return to(n,t)}finally{t.seenObjects.pop()}})}function b_(e){const t=e.toISOString();return e.getUTCMilliseconds()!==0?t:t.slice(0,-5)+"Z"}function to(e,t){if(e instanceof Map||Xw(e)){const n=Object.create(null);for(const[r,a]of e){if(typeof r!="string")throw new ve("Can only serialize maps with string keys");n[r]=a}return to(n,t)}if((typeof e=="object"||typeof e=="function")&&e!==null){const n=t.seenObjects.findIndex(r=>r.obj===e);if(n!==-1){const r=t.seenObjects.map(m=>m.propertyName),a=r.slice(0,n).map(m=>`${m} -> `).join(""),s=r[n],u=" -> "+r.slice(n+1,r.length-1).map(m=>`${m} -> `).join(""),f=r[r.length-1],d=" ".repeat(a.length+s.length/2),p="-".repeat(u.length+(s.length+f.length)/2-1);throw new ve(`Converting circular structure to EJSON:
174
174
  ${a}${s}${u}${f}
175
- ${d}\\${p}/`)}t.seenObjects[t.seenObjects.length-1].obj=e}if(Array.isArray(e))return W8(e,t);if(e===void 0)return null;if(e instanceof Date||v8(e)){const n=e.getTime(),r=n>-1&&n<2534023188e5;return t.legacy?t.relaxed&&r?{$date:e.getTime()}:{$date:b_(e)}:t.relaxed&&r?{$date:b_(e)}:{$date:{$numberLong:e.getTime().toString()}}}if(typeof e=="number"&&(!t.relaxed||!isFinite(e))){if(Number.isInteger(e)&&!Object.is(e,-0)){if(e>=Jg&&e<=Qg)return{$numberInt:e.toString()};if(e>=Ww&&e<=Kw)return{$numberLong:e.toString()}}return{$numberDouble:Object.is(e,-0)?"-0.0":e.toString()}}if(typeof e=="bigint")return t.relaxed?Number(BigInt.asIntN(64,e)):{$numberLong:BigInt.asIntN(64,e).toString()};if(e instanceof RegExp||y8(e)){let n=e.flags;if(n===void 0){const a=e.toString().match(/[gimuy]*$/);a&&(n=a[0])}return new eo(e.source,n).toExtendedJSON(t)}return e!=null&&typeof e=="object"?J8(e,t):e}const Q8={Binary:e=>new dt(e.value(),e.sub_type),Code:e=>new Nu(e.code,e.scope),DBRef:e=>new Ls(e.collection||e.namespace,e.oid,e.db,e.fields),Decimal128:e=>new Nr(e.bytes),Double:e=>new Ji(e.value),Int32:e=>new Us(e.value),Long:e=>K.fromBits(e.low!=null?e.low:e.low_,e.low!=null?e.high:e.high_,e.low!=null?e.unsigned:e.unsigned_),MaxKey:()=>new Od,MinKey:()=>new Rd,ObjectId:e=>new En(e),BSONRegExp:e=>new eo(e.pattern,e.options),BSONSymbol:e=>new Nd(e.value),Timestamp:e=>$o.fromBits(e.low,e.high)};function J8(e,t){if(e==null||typeof e!="object")throw new ve("not an object instance");const n=e._bsontype;if(typeof n>"u"){const r={};for(const a of Object.keys(e)){t.seenObjects.push({propertyName:a,obj:null});try{const s=to(e[a],t);a==="__proto__"?Object.defineProperty(r,a,{value:s,writable:!0,enumerable:!0,configurable:!0}):r[a]=s}finally{t.seenObjects.pop()}}return r}else{if(e!=null&&typeof e=="object"&&typeof e._bsontype=="string"&&e[Zw]!==Wg)throw new E8;if(Z8(e)){let r=e;if(typeof r.toExtendedJSON!="function"){const a=Q8[e._bsontype];if(!a)throw new ve("Unrecognized or invalid _bsontype: "+e._bsontype);r=a(r)}return n==="Code"&&r.scope?r=new Nu(r.code,to(r.scope,t)):n==="DBRef"&&r.oid&&(r=new Ls(to(r.collection,t),to(r.oid,t),to(r.db,t),to(r.fields,t))),r.toExtendedJSON(t)}else throw new ve("_bsontype must be a string, but was: "+typeof n)}}function S_(e,t){const n={useBigInt64:t?.useBigInt64??!1,relaxed:t?.relaxed??!0,legacy:t?.legacy??!1};return JSON.parse(e,(r,a)=>{if(r.indexOf("\0")!==-1)throw new ve(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(r)}`);return v_(a,n)})}function x_(e,t,n,r){n!=null&&typeof n=="object"&&(r=n,n=0),t!=null&&typeof t=="object"&&!Array.isArray(t)&&(r=t,t=void 0,n=0);const a=Object.assign({relaxed:!0,legacy:!1},r,{seenObjects:[{propertyName:"(root)",obj:null}]}),s=to(e,a);return JSON.stringify(s,t,n)}function eU(e,t){return t=t||{},JSON.parse(x_(e,t))}function tU(e,t){return t=t||{},S_(JSON.stringify(e),t)}const Du=Object.create(null);Du.parse=S_,Du.stringify=x_,Du.serialize=eU,Du.deserialize=tU,Object.freeze(Du);const un={double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:255,maxKey:127};function ry(e,t){try{return Ra.getNonnegativeInt32LE(e,t)}catch(n){throw new Lo("BSON size cannot be negative",t,{cause:n})}}function iy(e,t){let n=t;for(;e[n]!==0;n++);if(n===e.length-1)throw new Lo("Null terminator not found",t);return n}function nU(e,t=0){if(t??=0,e.length<5)throw new Lo(`Input must be at least 5 bytes, got ${e.length} bytes`,t);const n=ry(e,t);if(n>e.length-t)throw new Lo(`Parsed documentSize (${n} bytes) does not match input length (${e.length} bytes)`,t);if(e[t+n-1]!==0)throw new Lo("BSON documents must end in 0x00",t+n);const r=[];let a=t+4;for(;a<=n+t;){const s=e[a];if(a+=1,s===0){if(a-t!==n)throw new Lo("Invalid 0x00 type byte",a);break}const u=a,f=iy(e,a)-u;a+=f+1;let d;if(s===un.double||s===un.long||s===un.date||s===un.timestamp)d=8;else if(s===un.int)d=4;else if(s===un.objectId)d=12;else if(s===un.decimal)d=16;else if(s===un.bool)d=1;else if(s===un.null||s===un.undefined||s===un.maxKey||s===un.minKey)d=0;else if(s===un.regex)d=iy(e,iy(e,a)+1)+1-a;else if(s===un.object||s===un.array||s===un.javascriptWithScope)d=ry(e,a);else if(s===un.string||s===un.binData||s===un.dbPointer||s===un.javascript||s===un.symbol)d=ry(e,a)+4,s===un.binData&&(d+=1),s===un.dbPointer&&(d+=12);else throw new Lo(`Invalid 0x${s.toString(16).padStart(2,"0")} type byte`,a);if(d>n)throw new Lo("value reports length larger than document",a);r.push([s,u,f,a,d]),a+=d}return r}const Id=Object.create(null);Id.parseToElements=nU,Id.ByteUtils=Le,Id.NumberUtils=Ra,Object.freeze(Id);const rU=1024*1024*17;Le.allocate(rU);const iU=({directive:e,setDirective:t})=>{if(!e)return null;const[n,r]=I.useState(null),a=I.useCallback(s=>{p8(s).then(u=>{const f=u.events;if(f.length==0)return null;let d=f[0];const p=JSON.parse(d.value);if(d.value=p,d.value.kind==pi.OperationValidationFailed){r(d);return}t(d)}).catch(()=>t(null))},[e]);switch(e.value.kind){case pi.verificationForm:return e.value?.payload?.channels?.includes("email")?L.jsx(d8,{send:a,cancel:()=>t(null)}):L.jsx(u8,{send:a});case pi.OtpForm:const s=e?.value?.payload;return L.jsx(h8,{valueRecieved:s,failedValidationOperation:n,send:a,cancel:()=>t(null)});case pi.OperationError:return L.jsx(Tr,{color:"error",children:e.value.payload.message});case pi.OperationSuccess:const u={id:new Jn().toString(),role:"assistant",text:e.value.payload?.message,sentAt:void 0,seen:!1,status:void 0,errorText:void 0};return L.jsxs(pn,{sx:{display:"flex",justifyContent:"flex-start",gap:1,mb:1.2,overflowAnchor:"none"},children:[L.jsx(Yw,{msg:u,isMe:!1}),L.jsx(Gw,{msg:u,isMe:!1,showSeenIndicator:!1,isSeen:!1,send:()=>null})]});default:return null}},oU=()=>L.jsxs(pn,{sx:{display:"flex",alignItems:"flex-end",gap:1,mb:1.2},children:[L.jsx(bf,{sx:{width:30,height:30,bgcolor:"primary.main"},children:L.jsx(pg,{sx:{fontSize:18}})}),L.jsxs(pn,{sx:{px:1.4,py:1.1,borderRadius:3,border:"1px solid",borderColor:"divider",bgcolor:"background.paper",boxShadow:"0 10px 30px rgba(0,0,0,.10)",display:"flex",alignItems:"center",gap:.6},children:[L.jsx(pn,{sx:{width:6,height:6,borderRadius:999,bgcolor:"text.secondary",animation:"dot 1.1s infinite ease-in-out","@keyframes dot":{"0%, 80%, 100%":{transform:"scale(0.6)",opacity:.4},"40%":{transform:"scale(1)",opacity:1}}}}),L.jsx(pn,{sx:{width:6,height:6,borderRadius:999,bgcolor:"text.secondary",animation:"dot 1.1s infinite ease-in-out",animationDelay:"0.15s","@keyframes dot":{"0%, 80%, 100%":{transform:"scale(0.6)",opacity:.4},"40%":{transform:"scale(1)",opacity:1}}}}),L.jsx(pn,{sx:{width:6,height:6,borderRadius:999,bgcolor:"text.secondary",animation:"dot 1.1s infinite ease-in-out",animationDelay:"0.3s","@keyframes dot":{"0%, 80%, 100%":{transform:"scale(0.6)",opacity:.4},"40%":{transform:"scale(1)",opacity:1}}}})]})]}),aU={display:"flex",flexDirection:"column",flex:1,minHeight:0,overflow:"auto",px:1.5,pt:1.5,backgroundImage:"radial-gradient(circle at 20% 10%, rgba(25,118,210,.10), transparent 45%),radial-gradient(circle at 80% 20%, rgba(156,39,176,.10), transparent 50%),radial-gradient(circle at 40% 90%, rgba(0,200,83,.08), transparent 45%)","&::-webkit-scrollbar":{width:10},"&::-webkit-scrollbar-thumb":{backgroundColor:"rgba(0,0,0,.18)",borderRadius:999,border:"3px solid transparent",backgroundClip:"content-box"}};function sU({msgs:e,isMessageSeen:t,send:n,sending:r,items:a,endRef:s,directive:u,setDirective:f}){return L.jsxs(pn,{sx:aU,children:[L.jsx(l8,{msgs:e,isMessageSeen:t,reSend:n}),L.jsx("div",{style:{paddingBottom:2},children:r&&L.jsx(oU,{})}),a.map(d=>L.jsx(qB,{error:d.message,onClose:()=>yd.getState().remove(d.id)},d.id)),L.jsx(iU,{directive:u,setDirective:f}),L.jsx(x4,{ref:s,href:"https://x-bot.ro",target:"_blank",rel:"noreferrer",underline:"none",sx:{pb:1,marginTop:"auto",alignSelf:"center",fontSize:12,color:"text.secondary",opacity:.75,"&:hover":{opacity:1,color:"text.primary"},justifyContent:"center"},children:"Chat oferit de X-bot.ro"})]})}function lU({inputRef:e,input:t,sending:n,setInput:r,send:a}){return L.jsx(pn,{sx:{p:1.25,borderTop:"1px solid",borderColor:"divider",display:"flex",gap:1,bgcolor:"background.paper",flexShrink:0},children:L.jsx(Cf,{inputRef:e,focused:!0,size:"small",fullWidth:!0,value:t,disabled:n||t.length>=xB,onChange:s=>r(s.target.value),onKeyDown:s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),a())},placeholder:"Scrie un mesaj",multiline:!0,maxRows:4,sx:{"& .MuiOutlinedInput-root":{borderRadius:3,pr:.75,backgroundColor:"rgba(0,0,0,.02)"}},InputProps:{endAdornment:L.jsx(Co,{size:"small",onClick:()=>a(),disabled:n||!t.trim(),sx:{ml:.5,borderRadius:999},children:L.jsx(XB,{})})}})})}function uU({open:e,setOpen:t,msgs:n,input:r,setInput:a,sending:s,send:u,anchorSx:f,conversationMode:d,directive:p,setDirective:m}){const y=yd(O=>O.items),b=I.useRef(null),v=I.useRef(null),E=us(),S=v5(E.breakpoints.down("md"));HB(),I.useEffect(()=>{v.current?.scrollIntoView({behavior:"smooth",block:"end"}),requestAnimationFrame(()=>b.current?.focus())},[n.length,s]),I.useEffect(()=>{e&&v.current?.scrollIntoView({behavior:"auto",block:"end"})},[e]),I.useEffect(()=>{if(!(e&&S))return;const O=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${O}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",document.body.style.width="",window.scrollTo(0,O)}},[e,S]);const w=I.useCallback((O,T,C,N)=>{const k=O===C.length-1,z=C[C.length-1],H=k&&T&&z?.seen,j=H&&z?.id===N.id;return{showSeenIndicator:H,isSeen:j}},[]),_=O=>O?!(O.value.kind==pi.OperationError||O.value.kind==pi.OperationSuccess):!1;return L.jsxs(pn,{sx:f,children:[!e&&L.jsx(dm,{variant:"contained",onClick:()=>t(!0),startIcon:L.jsx(UB,{}),sx:{borderRadius:999,px:2,py:1,textTransform:"none",boxShadow:"0 10px 30px rgba(0,0,0,.18)"},children:"Chat"}),e&&L.jsx(Xh,{elevation:S?0:10,sx:{width:S?"100vw":380,height:S?"calc(var(--vh, 1vh) * 100)":560,"@supports (height: 100dvh)":{height:S?"100dvh":560},maxWidth:"100vw",maxHeight:"100dvh",borderRadius:S?0:4,position:S?"fixed":"relative",inset:S?0:"auto",overflow:"hidden",border:S?"none":"1px solid",borderColor:"divider",boxShadow:S?"none":"0 18px 60px rgba(0,0,0,.28)"},children:L.jsxs(pn,{sx:{display:"flex",flexDirection:"column",height:"100%"},children:[L.jsx(FB,{isMobile:S,conversationMode:d,setOpen:t}),L.jsx(sU,{msgs:n,isMessageSeen:w,send:u,sending:s,items:y,endRef:v,directive:p,setDirective:m}),L.jsx(lU,{inputRef:b,input:r,sending:s||_(p),setInput:a,send:u})]})})]})}class Ia extends Error{constructor(t,n){const r=new.target.prototype;super(`${t}: Status code '${n}'`),this.statusCode=n,this.__proto__=r}}class oy extends Error{constructor(t="A timeout occurred."){const n=new.target.prototype;super(t),this.__proto__=n}}class gi extends Error{constructor(t="An abort occurred."){const n=new.target.prototype;super(t),this.__proto__=n}}class cU extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.transport=n,this.errorType="UnsupportedTransportError",this.__proto__=r}}class fU extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.transport=n,this.errorType="DisabledTransportError",this.__proto__=r}}class dU extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.transport=n,this.errorType="FailedToStartTransportError",this.__proto__=r}}class E_ extends Error{constructor(t){const n=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=n}}class pU extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.innerErrors=n,this.__proto__=r}}class w_{constructor(t,n,r){this.statusCode=t,this.statusText=n,this.content=r}}class Md{get(t,n){return this.send({...n,method:"GET",url:t})}post(t,n){return this.send({...n,method:"POST",url:t})}delete(t,n){return this.send({...n,method:"DELETE",url:t})}getCookieString(t){return""}}var ue;(function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"})(ue||(ue={}));class Bu{constructor(){}log(t,n){}}Bu.instance=new Bu;const hU="10.0.0";class On{static isRequired(t,n){if(t==null)throw new Error(`The '${n}' argument is required.`)}static isNotEmpty(t,n){if(!t||t.match(/^\s*$/))throw new Error(`The '${n}' argument should not be empty.`)}static isIn(t,n,r){if(!(t in n))throw new Error(`Unknown ${r} value: ${t}.`)}}class cn{static get isBrowser(){return!cn.isNode&&typeof window=="object"&&typeof window.document=="object"}static get isWebWorker(){return!cn.isNode&&typeof self=="object"&&"importScripts"in self}static get isReactNative(){return!cn.isNode&&typeof window=="object"&&typeof window.document>"u"}static get isNode(){return typeof process<"u"&&process.release&&process.release.name==="node"}}function zu(e,t){let n="";return Ma(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${mU(e)}'`)):typeof e=="string"&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function mU(e){const t=new Uint8Array(e);let n="";return t.forEach(r=>{const a=r<16?"0":"";n+=`0x${a}${r.toString(16)} `}),n.substring(0,n.length-1)}function Ma(e){return e&&typeof ArrayBuffer<"u"&&(e instanceof ArrayBuffer||e.constructor&&e.constructor.name==="ArrayBuffer")}async function __(e,t,n,r,a,s){const u={},[f,d]=js();u[f]=d,e.log(ue.Trace,`(${t} transport) sending data. ${zu(a,s.logMessageContent)}.`);const p=Ma(a)?"arraybuffer":"text",m=await n.post(r,{content:a,headers:{...u,...s.headers},responseType:p,timeout:s.timeout,withCredentials:s.withCredentials});e.log(ue.Trace,`(${t} transport) request complete. Response status: ${m.statusCode}.`)}function gU(e){return e===void 0?new Dd(ue.Information):e===null?Bu.instance:e.log!==void 0?e:new Dd(e)}class yU{constructor(t,n){this._subject=t,this._observer=n}dispose(){const t=this._subject.observers.indexOf(this._observer);t>-1&&this._subject.observers.splice(t,1),this._subject.observers.length===0&&this._subject.cancelCallback&&this._subject.cancelCallback().catch(n=>{})}}class Dd{constructor(t){this._minLevel=t,this.out=console}log(t,n){if(t>=this._minLevel){const r=`[${new Date().toISOString()}] ${ue[t]}: ${n}`;switch(t){case ue.Critical:case ue.Error:this.out.error(r);break;case ue.Warning:this.out.warn(r);break;case ue.Information:this.out.info(r);break;default:this.out.log(r);break}}}}function js(){let e="X-SignalR-User-Agent";return cn.isNode&&(e="User-Agent"),[e,vU(hU,bU(),xU(),SU())]}function vU(e,t,n,r){let a="Microsoft SignalR/";const s=e.split(".");return a+=`${s[0]}.${s[1]}`,a+=` (${e}; `,t&&t!==""?a+=`${t}; `:a+="Unknown OS; ",a+=`${n}`,r?a+=`; ${r}`:a+="; Unknown Runtime Version",a+=")",a}function bU(){if(cn.isNode)switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}else return""}function SU(){if(cn.isNode)return process.versions.node}function xU(){return cn.isNode?"NodeJS":"Browser"}function ay(e){return e.stack?e.stack:e.message?e.message:`${e}`}function EU(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("could not find global")}class wU extends Md{constructor(t){if(super(),this._logger=t,typeof fetch>"u"||cn.isNode){const n=typeof __webpack_require__=="function"?__non_webpack_require__:require;this._jar=new(n("tough-cookie")).CookieJar,typeof fetch>"u"?this._fetchType=n("node-fetch"):this._fetchType=fetch,this._fetchType=n("fetch-cookie")(this._fetchType,this._jar)}else this._fetchType=fetch.bind(EU());if(typeof AbortController>"u"){const n=typeof __webpack_require__=="function"?__non_webpack_require__:require;this._abortControllerType=n("abort-controller")}else this._abortControllerType=AbortController}async send(t){if(t.abortSignal&&t.abortSignal.aborted)throw new gi;if(!t.method)throw new Error("No method defined.");if(!t.url)throw new Error("No url defined.");const n=new this._abortControllerType;let r;t.abortSignal&&(t.abortSignal.onabort=()=>{n.abort(),r=new gi});let a=null;if(t.timeout){const d=t.timeout;a=setTimeout(()=>{n.abort(),this._logger.log(ue.Warning,"Timeout from HTTP request."),r=new oy},d)}t.content===""&&(t.content=void 0),t.content&&(t.headers=t.headers||{},Ma(t.content)?t.headers["Content-Type"]="application/octet-stream":t.headers["Content-Type"]="text/plain;charset=UTF-8");let s;try{s=await this._fetchType(t.url,{body:t.content,cache:"no-cache",credentials:t.withCredentials===!0?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...t.headers},method:t.method,mode:"cors",redirect:"follow",signal:n.signal})}catch(d){throw r||(this._logger.log(ue.Warning,`Error from HTTP request. ${d}.`),d)}finally{a&&clearTimeout(a),t.abortSignal&&(t.abortSignal.onabort=null)}if(!s.ok){const d=await T_(s,"text");throw new Ia(d||s.statusText,s.status)}const f=await T_(s,t.responseType);return new w_(s.status,s.statusText,f)}getCookieString(t){let n="";return cn.isNode&&this._jar&&this._jar.getCookies(t,(r,a)=>n=a.join("; ")),n}}function T_(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text();break}return n}class _U extends Md{constructor(t){super(),this._logger=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new gi):t.method?t.url?new Promise((n,r)=>{const a=new XMLHttpRequest;a.open(t.method,t.url,!0),a.withCredentials=t.withCredentials===void 0?!0:t.withCredentials,a.setRequestHeader("X-Requested-With","XMLHttpRequest"),t.content===""&&(t.content=void 0),t.content&&(Ma(t.content)?a.setRequestHeader("Content-Type","application/octet-stream"):a.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const s=t.headers;s&&Object.keys(s).forEach(u=>{a.setRequestHeader(u,s[u])}),t.responseType&&(a.responseType=t.responseType),t.abortSignal&&(t.abortSignal.onabort=()=>{a.abort(),r(new gi)}),t.timeout&&(a.timeout=t.timeout),a.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),a.status>=200&&a.status<300?n(new w_(a.status,a.statusText,a.response||a.responseText)):r(new Ia(a.response||a.responseText||a.statusText,a.status))},a.onerror=()=>{this._logger.log(ue.Warning,`Error from HTTP request. ${a.status}: ${a.statusText}.`),r(new Ia(a.statusText,a.status))},a.ontimeout=()=>{this._logger.log(ue.Warning,"Timeout from HTTP request."),r(new oy)},a.send(t.content)}):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class TU extends Md{constructor(t){if(super(),typeof fetch<"u"||cn.isNode)this._httpClient=new wU(t);else if(typeof XMLHttpRequest<"u")this._httpClient=new _U(t);else throw new Error("No usable HttpClient found.")}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new gi):t.method?t.url?this._httpClient.send(t):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(t){return this._httpClient.getCookieString(t)}}class Ir{static write(t){return`${t}${Ir.RecordSeparator}`}static parse(t){if(t[t.length-1]!==Ir.RecordSeparator)throw new Error("Message is incomplete.");const n=t.split(Ir.RecordSeparator);return n.pop(),n}}Ir.RecordSeparatorCode=30,Ir.RecordSeparator=String.fromCharCode(Ir.RecordSeparatorCode);class CU{writeHandshakeRequest(t){return Ir.write(JSON.stringify(t))}parseHandshakeResponse(t){let n,r;if(Ma(t)){const f=new Uint8Array(t),d=f.indexOf(Ir.RecordSeparatorCode);if(d===-1)throw new Error("Message is incomplete.");const p=d+1;n=String.fromCharCode.apply(null,Array.prototype.slice.call(f.slice(0,p))),r=f.byteLength>p?f.slice(p).buffer:null}else{const f=t,d=f.indexOf(Ir.RecordSeparator);if(d===-1)throw new Error("Message is incomplete.");const p=d+1;n=f.substring(0,p),r=f.length>p?f.substring(p):null}const a=Ir.parse(n),s=JSON.parse(a[0]);if(s.type)throw new Error("Expected a handshake response from the server.");return[r,s]}}var Qe;(function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close",e[e.Ack=8]="Ack",e[e.Sequence=9]="Sequence"})(Qe||(Qe={}));class AU{constructor(){this.observers=[]}next(t){for(const n of this.observers)n.next(t)}error(t){for(const n of this.observers)n.error&&n.error(t)}complete(){for(const t of this.observers)t.complete&&t.complete()}subscribe(t){return this.observers.push(t),new yU(this,t)}}class kU{constructor(t,n,r){this._bufferSize=1e5,this._messages=[],this._totalMessageCount=0,this._waitForSequenceMessage=!1,this._nextReceivingSequenceId=1,this._latestReceivedSequenceId=0,this._bufferedByteCount=0,this._reconnectInProgress=!1,this._protocol=t,this._connection=n,this._bufferSize=r}async _send(t){const n=this._protocol.writeMessage(t);let r=Promise.resolve();if(this._isInvocationMessage(t)){this._totalMessageCount++;let a=()=>{},s=()=>{};Ma(n)?this._bufferedByteCount+=n.byteLength:this._bufferedByteCount+=n.length,this._bufferedByteCount>=this._bufferSize&&(r=new Promise((u,f)=>{a=u,s=f})),this._messages.push(new OU(n,this._totalMessageCount,a,s))}try{this._reconnectInProgress||await this._connection.send(n)}catch{this._disconnected()}await r}_ack(t){let n=-1;for(let r=0;r<this._messages.length;r++){const a=this._messages[r];if(a._id<=t.sequenceId)n=r,Ma(a._message)?this._bufferedByteCount-=a._message.byteLength:this._bufferedByteCount-=a._message.length,a._resolver();else if(this._bufferedByteCount<this._bufferSize)a._resolver();else break}n!==-1&&(this._messages=this._messages.slice(n+1))}_shouldProcessMessage(t){if(this._waitForSequenceMessage)return t.type!==Qe.Sequence?!1:(this._waitForSequenceMessage=!1,!0);if(!this._isInvocationMessage(t))return!0;const n=this._nextReceivingSequenceId;return this._nextReceivingSequenceId++,n<=this._latestReceivedSequenceId?(n===this._latestReceivedSequenceId&&this._ackTimer(),!1):(this._latestReceivedSequenceId=n,this._ackTimer(),!0)}_resetSequence(t){if(t.sequenceId>this._nextReceivingSequenceId){this._connection.stop(new Error("Sequence ID greater than amount of messages we've received."));return}this._nextReceivingSequenceId=t.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}async _resend(){const t=this._messages.length!==0?this._messages[0]._id:this._totalMessageCount+1;await this._connection.send(this._protocol.writeMessage({type:Qe.Sequence,sequenceId:t}));const n=this._messages;for(const r of n)await this._connection.send(r._message);this._reconnectInProgress=!1}_dispose(t){t??(t=new Error("Unable to reconnect to server."));for(const n of this._messages)n._rejector(t)}_isInvocationMessage(t){switch(t.type){case Qe.Invocation:case Qe.StreamItem:case Qe.Completion:case Qe.StreamInvocation:case Qe.CancelInvocation:return!0;case Qe.Close:case Qe.Sequence:case Qe.Ping:case Qe.Ack:return!1}}_ackTimer(){this._ackTimerHandle===void 0&&(this._ackTimerHandle=setTimeout(async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:Qe.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0},1e3))}}class OU{constructor(t,n,r,a){this._message=t,this._id=n,this._resolver=r,this._rejector=a}}const RU=30*1e3,NU=15*1e3,IU=1e5;var Pt;(function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"})(Pt||(Pt={}));class sy{static create(t,n,r,a,s,u,f){return new sy(t,n,r,a,s,u,f)}constructor(t,n,r,a,s,u,f){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(ue.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},On.isRequired(t,"connection"),On.isRequired(n,"logger"),On.isRequired(r,"protocol"),this.serverTimeoutInMilliseconds=s??RU,this.keepAliveIntervalInMilliseconds=u??NU,this._statefulReconnectBufferSize=f??IU,this._logger=n,this._protocol=r,this.connection=t,this._reconnectPolicy=a,this._handshakeProtocol=new CU,this.connection.onreceive=d=>this._processIncomingData(d),this.connection.onclose=d=>this._connectionClosed(d),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=Pt.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Qe.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(t){if(this._connectionState!==Pt.Disconnected&&this._connectionState!==Pt.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!t)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=t}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==Pt.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=Pt.Connecting,this._logger.log(ue.Debug,"Starting HubConnection.");try{await this._startInternal(),cn.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=Pt.Connected,this._connectionStarted=!0,this._logger.log(ue.Debug,"HubConnection connected successfully.")}catch(t){return this._connectionState=Pt.Disconnected,this._logger.log(ue.Debug,`HubConnection failed to start successfully because of error '${t}'.`),Promise.reject(t)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const t=new Promise((n,r)=>{this._handshakeResolver=n,this._handshakeRejecter=r});await this.connection.start(this._protocol.transferFormat);try{let n=this._protocol.version;this.connection.features.reconnect||(n=1);const r={protocol:this._protocol.name,version:n};if(this._logger.log(ue.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(r)),this._logger.log(ue.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await t,this._stopDuringStartError)throw this._stopDuringStartError;this.connection.features.reconnect&&(this._messageBuffer=new kU(this._protocol,this.connection,this._statefulReconnectBufferSize),this.connection.features.disconnected=this._messageBuffer._disconnected.bind(this._messageBuffer),this.connection.features.resend=()=>{if(this._messageBuffer)return this._messageBuffer._resend()}),this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(n){throw this._logger.log(ue.Debug,`Hub handshake failed with error '${n}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(n),n}}async stop(){const t=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),await this._stopPromise;try{await t}catch{}}_stopInternal(t){if(this._connectionState===Pt.Disconnected)return this._logger.log(ue.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===Pt.Disconnecting)return this._logger.log(ue.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const n=this._connectionState;return this._connectionState=Pt.Disconnecting,this._logger.log(ue.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(ue.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(n===Pt.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=t||new gi("The connection was stopped before the hub handshake could complete."),this.connection.stop(t))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(t,...n){const[r,a]=this._replaceStreamingParams(n),s=this._createStreamInvocation(t,n,a);let u;const f=new AU;return f.cancelCallback=()=>{const d=this._createCancelInvocation(s.invocationId);return delete this._callbacks[s.invocationId],u.then(()=>this._sendWithProtocol(d))},this._callbacks[s.invocationId]=(d,p)=>{if(p){f.error(p);return}else d&&(d.type===Qe.Completion?d.error?f.error(new Error(d.error)):f.complete():f.next(d.item))},u=this._sendWithProtocol(s).catch(d=>{f.error(d),delete this._callbacks[s.invocationId]}),this._launchStreams(r,u),f}_sendMessage(t){return this._resetKeepAliveInterval(),this.connection.send(t)}_sendWithProtocol(t){return this._messageBuffer?this._messageBuffer._send(t):this._sendMessage(this._protocol.writeMessage(t))}send(t,...n){const[r,a]=this._replaceStreamingParams(n),s=this._sendWithProtocol(this._createInvocation(t,n,!0,a));return this._launchStreams(r,s),s}invoke(t,...n){const[r,a]=this._replaceStreamingParams(n),s=this._createInvocation(t,n,!1,a);return new Promise((f,d)=>{this._callbacks[s.invocationId]=(m,y)=>{if(y){d(y);return}else m&&(m.type===Qe.Completion?m.error?d(new Error(m.error)):f(m.result):d(new Error(`Unexpected message type: ${m.type}`)))};const p=this._sendWithProtocol(s).catch(m=>{d(m),delete this._callbacks[s.invocationId]});this._launchStreams(r,p)})}on(t,n){!t||!n||(t=t.toLowerCase(),this._methods[t]||(this._methods[t]=[]),this._methods[t].indexOf(n)===-1&&this._methods[t].push(n))}off(t,n){if(!t)return;t=t.toLowerCase();const r=this._methods[t];if(r)if(n){const a=r.indexOf(n);a!==-1&&(r.splice(a,1),r.length===0&&delete this._methods[t])}else delete this._methods[t]}onclose(t){t&&this._closedCallbacks.push(t)}onreconnecting(t){t&&this._reconnectingCallbacks.push(t)}onreconnected(t){t&&this._reconnectedCallbacks.push(t)}_processIncomingData(t){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(t=this._processHandshakeResponse(t),this._receivedHandshakeResponse=!0),t){const n=this._protocol.parseMessages(t,this._logger);for(const r of n)if(!(this._messageBuffer&&!this._messageBuffer._shouldProcessMessage(r)))switch(r.type){case Qe.Invocation:this._invokeClientMethod(r).catch(a=>{this._logger.log(ue.Error,`Invoke client method threw error: ${ay(a)}`)});break;case Qe.StreamItem:case Qe.Completion:{const a=this._callbacks[r.invocationId];if(a){r.type===Qe.Completion&&delete this._callbacks[r.invocationId];try{a(r)}catch(s){this._logger.log(ue.Error,`Stream callback threw error: ${ay(s)}`)}}break}case Qe.Ping:break;case Qe.Close:{this._logger.log(ue.Information,"Close message received from server.");const a=r.error?new Error("Server returned an error on close: "+r.error):void 0;r.allowReconnect===!0?this.connection.stop(a):this._stopPromise=this._stopInternal(a);break}case Qe.Ack:this._messageBuffer&&this._messageBuffer._ack(r);break;case Qe.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(r);break;default:this._logger.log(ue.Warning,`Invalid message type: ${r.type}.`);break}}this._resetTimeoutPeriod()}_processHandshakeResponse(t){let n,r;try{[r,n]=this._handshakeProtocol.parseHandshakeResponse(t)}catch(a){const s="Error parsing handshake response: "+a;this._logger.log(ue.Error,s);const u=new Error(s);throw this._handshakeRejecter(u),u}if(n.error){const a="Server returned handshake error: "+n.error;this._logger.log(ue.Error,a);const s=new Error(a);throw this._handshakeRejecter(s),s}else this._logger.log(ue.Debug,"Server handshake complete.");return this._handshakeResolver(),r}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=new Date().getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!this.connection.features||!this.connection.features.inherentKeepAlive){this._timeoutHandle=setTimeout(()=>this.serverTimeout(),this.serverTimeoutInMilliseconds);let t=this._nextKeepAlive-new Date().getTime();if(t<0){this._connectionState===Pt.Connected&&this._trySendPingMessage();return}this._pingServerHandle===void 0&&(t<0&&(t=0),this._pingServerHandle=setTimeout(async()=>{this._connectionState===Pt.Connected&&await this._trySendPingMessage()},t))}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(t){const n=t.target.toLowerCase(),r=this._methods[n];if(!r){this._logger.log(ue.Warning,`No client method with the name '${n}' found.`),t.invocationId&&(this._logger.log(ue.Warning,`No result given for '${n}' method and invocation ID '${t.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(t.invocationId,"Client didn't provide a result.",null)));return}const a=r.slice(),s=!!t.invocationId;let u,f,d;for(const p of a)try{const m=u;u=await p.apply(this,t.arguments),s&&u&&m&&(this._logger.log(ue.Error,`Multiple results provided for '${n}'. Sending error to server.`),d=this._createCompletionMessage(t.invocationId,"Client provided multiple results.",null)),f=void 0}catch(m){f=m,this._logger.log(ue.Error,`A callback for the method '${n}' threw error '${m}'.`)}d?await this._sendWithProtocol(d):s?(f?d=this._createCompletionMessage(t.invocationId,`${f}`,null):u!==void 0?d=this._createCompletionMessage(t.invocationId,null,u):(this._logger.log(ue.Warning,`No result given for '${n}' method and invocation ID '${t.invocationId}'.`),d=this._createCompletionMessage(t.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(d)):u&&this._logger.log(ue.Error,`Result given for '${n}' method but server is not expecting a result.`)}_connectionClosed(t){this._logger.log(ue.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||t||new gi("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(t||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===Pt.Disconnecting?this._completeClose(t):this._connectionState===Pt.Connected&&this._reconnectPolicy?this._reconnect(t):this._connectionState===Pt.Connected&&this._completeClose(t)}_completeClose(t){if(this._connectionStarted){this._connectionState=Pt.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(t??new Error("Connection closed.")),this._messageBuffer=void 0),cn.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach(n=>n.apply(this,[t]))}catch(n){this._logger.log(ue.Error,`An onclose callback called with error '${t}' threw error '${n}'.`)}}}async _reconnect(t){const n=Date.now();let r=0,a=t!==void 0?t:new Error("Attempting to reconnect due to a unknown error."),s=this._getNextRetryDelay(r,0,a);if(s===null){this._logger.log(ue.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),this._completeClose(t);return}if(this._connectionState=Pt.Reconnecting,t?this._logger.log(ue.Information,`Connection reconnecting because of error '${t}'.`):this._logger.log(ue.Information,"Connection reconnecting."),this._reconnectingCallbacks.length!==0){try{this._reconnectingCallbacks.forEach(u=>u.apply(this,[t]))}catch(u){this._logger.log(ue.Error,`An onreconnecting callback called with error '${t}' threw error '${u}'.`)}if(this._connectionState!==Pt.Reconnecting){this._logger.log(ue.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");return}}for(;s!==null;){if(this._logger.log(ue.Information,`Reconnect attempt number ${r+1} will start in ${s} ms.`),await new Promise(u=>{this._reconnectDelayHandle=setTimeout(u,s)}),this._reconnectDelayHandle=void 0,this._connectionState!==Pt.Reconnecting){this._logger.log(ue.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");return}try{if(await this._startInternal(),this._connectionState=Pt.Connected,this._logger.log(ue.Information,"HubConnection reconnected successfully."),this._reconnectedCallbacks.length!==0)try{this._reconnectedCallbacks.forEach(u=>u.apply(this,[this.connection.connectionId]))}catch(u){this._logger.log(ue.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${u}'.`)}return}catch(u){if(this._logger.log(ue.Information,`Reconnect attempt failed because of error '${u}'.`),this._connectionState!==Pt.Reconnecting){this._logger.log(ue.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),this._connectionState===Pt.Disconnecting&&this._completeClose();return}r++,a=u instanceof Error?u:new Error(u.toString()),s=this._getNextRetryDelay(r,Date.now()-n,a)}}this._logger.log(ue.Information,`Reconnect retries have been exhausted after ${Date.now()-n} ms and ${r} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(t,n,r){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:n,previousRetryCount:t,retryReason:r})}catch(a){return this._logger.log(ue.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${n}) threw error '${a}'.`),null}}_cancelCallbacksWithError(t){const n=this._callbacks;this._callbacks={},Object.keys(n).forEach(r=>{const a=n[r];try{a(null,t)}catch(s){this._logger.log(ue.Error,`Stream 'error' callback called with '${t}' threw error: ${ay(s)}`)}})}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(t,n,r,a){if(r)return a.length!==0?{target:t,arguments:n,streamIds:a,type:Qe.Invocation}:{target:t,arguments:n,type:Qe.Invocation};{const s=this._invocationId;return this._invocationId++,a.length!==0?{target:t,arguments:n,invocationId:s.toString(),streamIds:a,type:Qe.Invocation}:{target:t,arguments:n,invocationId:s.toString(),type:Qe.Invocation}}}_launchStreams(t,n){if(t.length!==0){n||(n=Promise.resolve());for(const r in t)t[r].subscribe({complete:()=>{n=n.then(()=>this._sendWithProtocol(this._createCompletionMessage(r)))},error:a=>{let s;a instanceof Error?s=a.message:a&&a.toString?s=a.toString():s="Unknown error",n=n.then(()=>this._sendWithProtocol(this._createCompletionMessage(r,s)))},next:a=>{n=n.then(()=>this._sendWithProtocol(this._createStreamItemMessage(r,a)))}})}}_replaceStreamingParams(t){const n=[],r=[];for(let a=0;a<t.length;a++){const s=t[a];if(this._isObservable(s)){const u=this._invocationId;this._invocationId++,n[u]=s,r.push(u.toString()),t.splice(a,1)}}return[n,r]}_isObservable(t){return t&&t.subscribe&&typeof t.subscribe=="function"}_createStreamInvocation(t,n,r){const a=this._invocationId;return this._invocationId++,r.length!==0?{target:t,arguments:n,invocationId:a.toString(),streamIds:r,type:Qe.StreamInvocation}:{target:t,arguments:n,invocationId:a.toString(),type:Qe.StreamInvocation}}_createCancelInvocation(t){return{invocationId:t,type:Qe.CancelInvocation}}_createStreamItemMessage(t,n){return{invocationId:t,item:n,type:Qe.StreamItem}}_createCompletionMessage(t,n,r){return n?{error:n,invocationId:t,type:Qe.Completion}:{invocationId:t,result:r,type:Qe.Completion}}_createCloseMessage(){return{type:Qe.Close}}async _trySendPingMessage(){try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}}const MU=[0,2e3,1e4,3e4,null];class C_{constructor(t){this._retryDelays=t!==void 0?[...t,null]:MU}nextRetryDelayInMilliseconds(t){return this._retryDelays[t.previousRetryCount]}}class Da{}Da.Authorization="Authorization",Da.Cookie="Cookie";class DU extends Md{constructor(t,n){super(),this._innerClient=t,this._accessTokenFactory=n}async send(t){let n=!0;this._accessTokenFactory&&(!this._accessToken||t.url&&t.url.indexOf("/negotiate?")>0)&&(n=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(t);const r=await this._innerClient.send(t);return n&&r.statusCode===401&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(t),await this._innerClient.send(t)):r}_setAuthorizationHeader(t){t.headers||(t.headers={}),this._accessToken?t.headers[Da.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&t.headers[Da.Authorization]&&delete t.headers[Da.Authorization]}getCookieString(t){return this._innerClient.getCookieString(t)}}var Dn;(function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"})(Dn||(Dn={}));var er;(function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"})(er||(er={}));let BU=class{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}};class A_{get pollAborted(){return this._pollAbort.aborted}constructor(t,n,r){this._httpClient=t,this._logger=n,this._pollAbort=new BU,this._options=r,this._running=!1,this.onreceive=null,this.onclose=null}async connect(t,n){if(On.isRequired(t,"url"),On.isRequired(n,"transferFormat"),On.isIn(n,er,"transferFormat"),this._url=t,this._logger.log(ue.Trace,"(LongPolling transport) Connecting."),n===er.Binary&&typeof XMLHttpRequest<"u"&&typeof new XMLHttpRequest().responseType!="string")throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[r,a]=js(),s={[r]:a,...this._options.headers},u={abortSignal:this._pollAbort.signal,headers:s,timeout:1e5,withCredentials:this._options.withCredentials};n===er.Binary&&(u.responseType="arraybuffer");const f=`${t}&_=${Date.now()}`;this._logger.log(ue.Trace,`(LongPolling transport) polling: ${f}.`);const d=await this._httpClient.get(f,u);d.statusCode!==200?(this._logger.log(ue.Error,`(LongPolling transport) Unexpected response code: ${d.statusCode}.`),this._closeError=new Ia(d.statusText||"",d.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,u)}async _poll(t,n){try{for(;this._running;)try{const r=`${t}&_=${Date.now()}`;this._logger.log(ue.Trace,`(LongPolling transport) polling: ${r}.`);const a=await this._httpClient.get(r,n);a.statusCode===204?(this._logger.log(ue.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):a.statusCode!==200?(this._logger.log(ue.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new Ia(a.statusText||"",a.statusCode),this._running=!1):a.content?(this._logger.log(ue.Trace,`(LongPolling transport) data received. ${zu(a.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(a.content)):this._logger.log(ue.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(r){this._running?r instanceof oy?this._logger.log(ue.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=r,this._running=!1):this._logger.log(ue.Trace,`(LongPolling transport) Poll errored after shutdown: ${r.message}`)}}finally{this._logger.log(ue.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(t){return this._running?__(this._logger,"LongPolling",this._httpClient,this._url,t,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(ue.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(ue.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const t={},[n,r]=js();t[n]=r;const a={headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let s;try{await this._httpClient.delete(this._url,a)}catch(u){s=u}s?s instanceof Ia&&(s.statusCode===404?this._logger.log(ue.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(ue.Trace,`(LongPolling transport) Error sending a DELETE request: ${s}`)):this._logger.log(ue.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(ue.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let t="(LongPolling transport) Firing onclose event.";this._closeError&&(t+=" Error: "+this._closeError),this._logger.log(ue.Trace,t),this.onclose(this._closeError)}}}class zU{constructor(t,n,r,a){this._httpClient=t,this._accessToken=n,this._logger=r,this._options=a,this.onreceive=null,this.onclose=null}async connect(t,n){return On.isRequired(t,"url"),On.isRequired(n,"transferFormat"),On.isIn(n,er,"transferFormat"),this._logger.log(ue.Trace,"(SSE transport) Connecting."),this._url=t,this._accessToken&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise((r,a)=>{let s=!1;if(n!==er.Text){a(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));return}let u;if(cn.isBrowser||cn.isWebWorker)u=new this._options.EventSource(t,{withCredentials:this._options.withCredentials});else{const f=this._httpClient.getCookieString(t),d={};d.Cookie=f;const[p,m]=js();d[p]=m,u=new this._options.EventSource(t,{withCredentials:this._options.withCredentials,headers:{...d,...this._options.headers}})}try{u.onmessage=f=>{if(this.onreceive)try{this._logger.log(ue.Trace,`(SSE transport) data received. ${zu(f.data,this._options.logMessageContent)}.`),this.onreceive(f.data)}catch(d){this._close(d);return}},u.onerror=f=>{s?this._close():a(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},u.onopen=()=>{this._logger.log(ue.Information,`SSE connected to ${this._url}`),this._eventSource=u,s=!0,r()}}catch(f){a(f);return}})}async send(t){return this._eventSource?__(this._logger,"SSE",this._httpClient,this._url,t,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(t){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(t))}}class LU{constructor(t,n,r,a,s,u){this._logger=r,this._accessTokenFactory=n,this._logMessageContent=a,this._webSocketConstructor=s,this._httpClient=t,this.onreceive=null,this.onclose=null,this._headers=u}async connect(t,n){On.isRequired(t,"url"),On.isRequired(n,"transferFormat"),On.isIn(n,er,"transferFormat"),this._logger.log(ue.Trace,"(WebSockets transport) Connecting.");let r;return this._accessTokenFactory&&(r=await this._accessTokenFactory()),new Promise((a,s)=>{t=t.replace(/^http/,"ws");let u;const f=this._httpClient.getCookieString(t);let d=!1;if(cn.isNode||cn.isReactNative){const p={},[m,y]=js();p[m]=y,r&&(p[Da.Authorization]=`Bearer ${r}`),f&&(p[Da.Cookie]=f),u=new this._webSocketConstructor(t,void 0,{headers:{...p,...this._headers}})}else r&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(r)}`);u||(u=new this._webSocketConstructor(t)),n===er.Binary&&(u.binaryType="arraybuffer"),u.onopen=p=>{this._logger.log(ue.Information,`WebSocket connected to ${t}.`),this._webSocket=u,d=!0,a()},u.onerror=p=>{let m=null;typeof ErrorEvent<"u"&&p instanceof ErrorEvent?m=p.error:m="There was an error with the transport",this._logger.log(ue.Information,`(WebSockets transport) ${m}.`)},u.onmessage=p=>{if(this._logger.log(ue.Trace,`(WebSockets transport) data received. ${zu(p.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(p.data)}catch(m){this._close(m);return}},u.onclose=p=>{if(d)this._close(p);else{let m=null;typeof ErrorEvent<"u"&&p instanceof ErrorEvent?m=p.error:m="WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",s(new Error(m))}}})}send(t){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(ue.Trace,`(WebSockets transport) sending data. ${zu(t,this._logMessageContent)}.`),this._webSocket.send(t),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(t){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(ue.Trace,"(WebSockets transport) socket closed."),this.onclose&&(this._isCloseEvent(t)&&(t.wasClean===!1||t.code!==1e3)?this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason||"no reason given"}).`)):t instanceof Error?this.onclose(t):this.onclose())}_isCloseEvent(t){return t&&typeof t.wasClean=="boolean"&&typeof t.code=="number"}}const k_=100;class PU{constructor(t,n={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,On.isRequired(t,"url"),this._logger=gU(n.logger),this.baseUrl=this._resolveUrl(t),n=n||{},n.logMessageContent=n.logMessageContent===void 0?!1:n.logMessageContent,typeof n.withCredentials=="boolean"||n.withCredentials===void 0)n.withCredentials=n.withCredentials===void 0?!0:n.withCredentials;else throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");n.timeout=n.timeout===void 0?100*1e3:n.timeout;let r=null,a=null;if(cn.isNode&&typeof require<"u"){const s=typeof __webpack_require__=="function"?__non_webpack_require__:require;r=s("ws"),a=s("eventsource")}!cn.isNode&&typeof WebSocket<"u"&&!n.WebSocket?n.WebSocket=WebSocket:cn.isNode&&!n.WebSocket&&r&&(n.WebSocket=r),!cn.isNode&&typeof EventSource<"u"&&!n.EventSource?n.EventSource=EventSource:cn.isNode&&!n.EventSource&&typeof a<"u"&&(n.EventSource=a),this._httpClient=new DU(n.httpClient||new TU(this._logger),n.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=n,this.onreceive=null,this.onclose=null}async start(t){if(t=t||er.Binary,On.isIn(t,er,"transferFormat"),this._logger.log(ue.Debug,`Starting connection with transfer format '${er[t]}'.`),this._connectionState!=="Disconnected")return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(t),await this._startInternalPromise,this._connectionState==="Disconnecting"){const n="Failed to start the HttpConnection before stop() was called.";return this._logger.log(ue.Error,n),await this._stopPromise,Promise.reject(new gi(n))}else if(this._connectionState!=="Connected"){const n="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(ue.Error,n),Promise.reject(new gi(n))}this._connectionStarted=!0}send(t){return this._connectionState!=="Connected"?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new ly(this.transport)),this._sendQueue.send(t))}async stop(t){if(this._connectionState==="Disconnected")return this._logger.log(ue.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`),Promise.resolve();if(this._connectionState==="Disconnecting")return this._logger.log(ue.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;this._connectionState="Disconnecting",this._stopPromise=new Promise(n=>{this._stopPromiseResolver=n}),await this._stopInternal(t),await this._stopPromise}async _stopInternal(t){this._stopError=t;try{await this._startInternalPromise}catch{}if(this.transport){try{await this.transport.stop()}catch(n){this._logger.log(ue.Error,`HttpConnection.transport.stop() threw error '${n}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(ue.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(t){let n=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation)if(this._options.transport===Dn.WebSockets)this.transport=this._constructTransport(Dn.WebSockets),await this._startTransport(n,t);else throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");else{let r=null,a=0;do{if(r=await this._getNegotiationResponse(n),this._connectionState==="Disconnecting"||this._connectionState==="Disconnected")throw new gi("The connection was stopped during negotiation.");if(r.error)throw new Error(r.error);if(r.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(r.url&&(n=r.url),r.accessToken){const s=r.accessToken;this._accessTokenFactory=()=>s,this._httpClient._accessToken=s,this._httpClient._accessTokenFactory=void 0}a++}while(r.url&&a<k_);if(a===k_&&r.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(n,this._options.transport,r,t)}this.transport instanceof A_&&(this.features.inherentKeepAlive=!0),this._connectionState==="Connecting"&&(this._logger.log(ue.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(r){return this._logger.log(ue.Error,"Failed to start the connection: "+r),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(r)}}async _getNegotiationResponse(t){const n={},[r,a]=js();n[r]=a;const s=this._resolveNegotiateUrl(t);this._logger.log(ue.Debug,`Sending negotiation request: ${s}.`);try{const u=await this._httpClient.post(s,{content:"",headers:{...n,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(u.statusCode!==200)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${u.statusCode}'`));const f=JSON.parse(u.content);return(!f.negotiateVersion||f.negotiateVersion<1)&&(f.connectionToken=f.connectionId),f.useStatefulReconnect&&this._options._useStatefulReconnect!==!0?Promise.reject(new E_("Client didn't negotiate Stateful Reconnect but the server did.")):f}catch(u){let f="Failed to complete negotiation with the server: "+u;return u instanceof Ia&&u.statusCode===404&&(f=f+" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(ue.Error,f),Promise.reject(new E_(f))}}_createConnectUrl(t,n){return n?t+(t.indexOf("?")===-1?"?":"&")+`id=${n}`:t}async _createTransport(t,n,r,a){let s=this._createConnectUrl(t,r.connectionToken);if(this._isITransport(n)){this._logger.log(ue.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=n,await this._startTransport(s,a),this.connectionId=r.connectionId;return}const u=[],f=r.availableTransports||[];let d=r;for(const p of f){const m=this._resolveTransportOrError(p,n,a,d?.useStatefulReconnect===!0);if(m instanceof Error)u.push(`${p.transport} failed:`),u.push(m);else if(this._isITransport(m)){if(this.transport=m,!d){try{d=await this._getNegotiationResponse(t)}catch(y){return Promise.reject(y)}s=this._createConnectUrl(t,d.connectionToken)}try{await this._startTransport(s,a),this.connectionId=d.connectionId;return}catch(y){if(this._logger.log(ue.Error,`Failed to start the transport '${p.transport}': ${y}`),d=void 0,u.push(new dU(`${p.transport} failed: ${y}`,Dn[p.transport])),this._connectionState!=="Connecting"){const b="Failed to select transport before stop() was called.";return this._logger.log(ue.Debug,b),Promise.reject(new gi(b))}}}}return u.length>0?Promise.reject(new pU(`Unable to connect to the server with any of the available transports. ${u.join(" ")}`,u)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(t){switch(t){case Dn.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new LU(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case Dn.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new zU(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case Dn.LongPolling:return new A_(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${t}.`)}}_startTransport(t,n){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async r=>{let a=!1;if(this.features.reconnect)try{this.features.disconnected(),await this.transport.connect(t,n),await this.features.resend()}catch{a=!0}else{this._stopConnection(r);return}a&&this._stopConnection(r)}:this.transport.onclose=r=>this._stopConnection(r),this.transport.connect(t,n)}_resolveTransportOrError(t,n,r,a){const s=Dn[t.transport];if(s==null)return this._logger.log(ue.Debug,`Skipping transport '${t.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`);if($U(n,s))if(t.transferFormats.map(f=>er[f]).indexOf(r)>=0){if(s===Dn.WebSockets&&!this._options.WebSocket||s===Dn.ServerSentEvents&&!this._options.EventSource)return this._logger.log(ue.Debug,`Skipping transport '${Dn[s]}' because it is not supported in your environment.'`),new cU(`'${Dn[s]}' is not supported in your environment.`,s);this._logger.log(ue.Debug,`Selecting transport '${Dn[s]}'.`);try{return this.features.reconnect=s===Dn.WebSockets?a:void 0,this._constructTransport(s)}catch(f){return f}}else return this._logger.log(ue.Debug,`Skipping transport '${Dn[s]}' because it does not support the requested transfer format '${er[r]}'.`),new Error(`'${Dn[s]}' does not support ${er[r]}.`);else return this._logger.log(ue.Debug,`Skipping transport '${Dn[s]}' because it was disabled by the client.`),new fU(`'${Dn[s]}' is disabled by the client.`,s)}_isITransport(t){return t&&typeof t=="object"&&"connect"in t}_stopConnection(t){if(this._logger.log(ue.Debug,`HttpConnection.stopConnection(${t}) called while in state ${this._connectionState}.`),this.transport=void 0,t=this._stopError||t,this._stopError=void 0,this._connectionState==="Disconnected"){this._logger.log(ue.Debug,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`);return}if(this._connectionState==="Connecting")throw this._logger.log(ue.Warning,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`);if(this._connectionState==="Disconnecting"&&this._stopPromiseResolver(),t?this._logger.log(ue.Error,`Connection disconnected with error '${t}'.`):this._logger.log(ue.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch(n=>{this._logger.log(ue.Error,`TransportSendQueue.stop() threw error '${n}'.`)}),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(t)}catch(n){this._logger.log(ue.Error,`HttpConnection.onclose(${t}) threw error '${n}'.`)}}}_resolveUrl(t){if(t.lastIndexOf("https://",0)===0||t.lastIndexOf("http://",0)===0)return t;if(!cn.isBrowser)throw new Error(`Cannot resolve '${t}'.`);const n=window.document.createElement("a");return n.href=t,this._logger.log(ue.Information,`Normalizing '${t}' to '${n.href}'.`),n.href}_resolveNegotiateUrl(t){const n=new URL(t);n.pathname.endsWith("/")?n.pathname+="negotiate":n.pathname+="/negotiate";const r=new URLSearchParams(n.searchParams);return r.has("negotiateVersion")||r.append("negotiateVersion",this._negotiateVersion.toString()),r.has("useStatefulReconnect")?r.get("useStatefulReconnect")==="true"&&(this._options._useStatefulReconnect=!0):this._options._useStatefulReconnect===!0&&r.append("useStatefulReconnect","true"),n.search=r.toString(),n.toString()}}function $U(e,t){return!e||(t&e)!==0}class ly{constructor(t){this._transport=t,this._buffer=[],this._executing=!0,this._sendBufferedData=new Bd,this._transportResult=new Bd,this._sendLoopPromise=this._sendLoop()}send(t){return this._bufferData(t),this._transportResult||(this._transportResult=new Bd),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(t){if(this._buffer.length&&typeof this._buffer[0]!=typeof t)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof t}`);this._buffer.push(t),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new Bd;const t=this._transportResult;this._transportResult=void 0;const n=typeof this._buffer[0]=="string"?this._buffer.join(""):ly._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(n),t.resolve()}catch(r){t.reject(r)}}}static _concatBuffers(t){const n=t.map(s=>s.byteLength).reduce((s,u)=>s+u),r=new Uint8Array(n);let a=0;for(const s of t)r.set(new Uint8Array(s),a),a+=s.byteLength;return r.buffer}}class Bd{constructor(){this.promise=new Promise((t,n)=>[this._resolver,this._rejecter]=[t,n])}resolve(){this._resolver()}reject(t){this._rejecter(t)}}const UU="json";class jU{constructor(){this.name=UU,this.version=2,this.transferFormat=er.Text}parseMessages(t,n){if(typeof t!="string")throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!t)return[];n===null&&(n=Bu.instance);const r=Ir.parse(t),a=[];for(const s of r){const u=JSON.parse(s);if(typeof u.type!="number")throw new Error("Invalid payload.");switch(u.type){case Qe.Invocation:this._isInvocationMessage(u);break;case Qe.StreamItem:this._isStreamItemMessage(u);break;case Qe.Completion:this._isCompletionMessage(u);break;case Qe.Ping:break;case Qe.Close:break;case Qe.Ack:this._isAckMessage(u);break;case Qe.Sequence:this._isSequenceMessage(u);break;default:n.log(ue.Information,"Unknown message type '"+u.type+"' ignored.");continue}a.push(u)}return a}writeMessage(t){return Ir.write(JSON.stringify(t))}_isInvocationMessage(t){this._assertNotEmptyString(t.target,"Invalid payload for Invocation message."),t.invocationId!==void 0&&this._assertNotEmptyString(t.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(t){if(this._assertNotEmptyString(t.invocationId,"Invalid payload for StreamItem message."),t.item===void 0)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(t){if(t.result&&t.error)throw new Error("Invalid payload for Completion message.");!t.result&&t.error&&this._assertNotEmptyString(t.error,"Invalid payload for Completion message."),this._assertNotEmptyString(t.invocationId,"Invalid payload for Completion message.")}_isAckMessage(t){if(typeof t.sequenceId!="number")throw new Error("Invalid SequenceId for Ack message.")}_isSequenceMessage(t){if(typeof t.sequenceId!="number")throw new Error("Invalid SequenceId for Sequence message.")}_assertNotEmptyString(t,n){if(typeof t!="string"||t==="")throw new Error(n)}}const HU={trace:ue.Trace,debug:ue.Debug,info:ue.Information,information:ue.Information,warn:ue.Warning,warning:ue.Warning,error:ue.Error,critical:ue.Critical,none:ue.None};function VU(e){const t=HU[e.toLowerCase()];if(typeof t<"u")return t;throw new Error(`Unknown log level: ${e}`)}class FU{configureLogging(t){if(On.isRequired(t,"logging"),qU(t))this.logger=t;else if(typeof t=="string"){const n=VU(t);this.logger=new Dd(n)}else this.logger=new Dd(t);return this}withUrl(t,n){return On.isRequired(t,"url"),On.isNotEmpty(t,"url"),this.url=t,typeof n=="object"?this.httpConnectionOptions={...this.httpConnectionOptions,...n}:this.httpConnectionOptions={...this.httpConnectionOptions,transport:n},this}withHubProtocol(t){return On.isRequired(t,"protocol"),this.protocol=t,this}withAutomaticReconnect(t){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return t?Array.isArray(t)?this.reconnectPolicy=new C_(t):this.reconnectPolicy=t:this.reconnectPolicy=new C_,this}withServerTimeout(t){return On.isRequired(t,"milliseconds"),this._serverTimeoutInMilliseconds=t,this}withKeepAliveInterval(t){return On.isRequired(t,"milliseconds"),this._keepAliveIntervalInMilliseconds=t,this}withStatefulReconnect(t){return this.httpConnectionOptions===void 0&&(this.httpConnectionOptions={}),this.httpConnectionOptions._useStatefulReconnect=!0,this._statefulReconnectBufferSize=t?.bufferSize,this}build(){const t=this.httpConnectionOptions||{};if(t.logger===void 0&&(t.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const n=new PU(this.url,t);return sy.create(n,this.logger||Bu.instance,this.protocol||new jU,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}function qU(e){return e.log!==void 0}function GU({url:e,accessToken:t,autoStart:n=!0}){const r=I.useRef(null),a=I.useRef(new Map),s=I.useRef(null),u=I.useRef(0),f=I.useRef(!1),[d,p]=I.useState("disconnected"),[m,y]=I.useState(null),b=I.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),v=I.useCallback(()=>{if(f.current||s.current)return;u.current+=1;const k=u.current,z=Math.min(3e4,1e3*Math.pow(2,k-1)),H=Math.floor(Math.random()*500),j=z+H;s.current=setTimeout(()=>{s.current=null,_()},j)},[b]),E=I.useCallback(k=>{a.current.forEach((z,H)=>{k.off(H),z.forEach(j=>{k.on(H,j)})})},[]),S=I.useCallback(async()=>fg(),[]),w=I.useCallback(()=>{const k=new FU().withUrl(e,{accessTokenFactory:S}).withAutomaticReconnect({nextRetryDelayInMilliseconds:z=>z.elapsedMilliseconds<6e4?Math.random()*1e4:null}).build();return k.onreconnecting(()=>{b(),p("reconnecting")}),k.onreconnected(()=>{b(),u.current=0,p("connected"),E(k)}),k.onclose(z=>{p("disconnected"),z&&y(z),f.current||v()}),k},[e,S,E,b,v]),_=I.useCallback(async()=>{f.current=!1,b(),r.current||(r.current=w());const k=r.current;if(k.state===Pt.Connected){p("connected");return}if(k.state===Pt.Connecting){p("connecting");return}if(k.state===Pt.Reconnecting){p("reconnecting");return}p("connecting");try{await k.start(),E(k),u.current=0,p("connected"),y(null)}catch(z){y(z),p("disconnected"),v()}},[E,w,b,v]),O=I.useCallback(async()=>{f.current=!0,b(),u.current=0;const k=r.current;if(r.current=null,!k){p("disconnected");return}try{await k.stop()}finally{p("disconnected")}},[b]),T=I.useCallback((k,z)=>{let H=a.current.get(k);H||(H=new Set,a.current.set(k,H)),H.add(z);const j=r.current;j&&j.on(k,z)},[]),C=I.useCallback((k,z)=>{const H=a.current.get(k);if(!H)return;H.delete(z),H.size===0&&a.current.delete(k);const j=r.current;j&&j.off(k,z)},[]),N=I.useCallback(async(k,...z)=>{const H=r.current;if(!H||H.state!==Pt.Connected)throw new Error("SignalR not connected");return H.invoke(k,...z)},[]);return I.useEffect(()=>(n&&_(),()=>{O()}),[n,_,O]),{status:d,connected:d==="connected",error:m,start:_,stop:O,on:T,off:C,invoke:N}}async function YU(e,t,n){vu(e.apiBaseUrl+gd+"/"+e.clientId+"/messages/",{method:"GET",headers:{"Content-Type":"application/json","X-Conversation-Id":t}}).then(r=>{if(!r.ok)throw new Error("Request failed");return r.json()}).then(r=>{n(r.map(a=>a))}).catch(r=>{console.error(r)})}async function XU(e,t){const n=await vu(e.apiBaseUrl+gd+"/"+e.clientId+"/conversation-status/",{method:"GET",headers:{"Content-Type":"application/json","X-Conversation-Id":t}});return n.ok,await n.json()}async function ZU(e){return(await vu(e.apiBaseUrl+"/api/health/"+e.clientId,{method:"GET",headers:{"Content-Type":"application/json"}})).ok}async function KU(e,t){const n=await vu(e.apiBaseUrl+gd+"/"+e.clientId+"/client-activity-status",{method:"GET",headers:{"Content-Type":"application/json",...t?{"X-Conversation-Id":t}:{}}});return n.ok?n.body?await n.json():{isActive:!1,hideForUrls:[]}:{isActive:!1,hideForUrls:[]}}function uy(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""}function WU({config:e}){const{connected:t,start:n,on:r,off:a}=GU({url:e.apiBaseUrl+`/ws?sessionId=${Su()}&clientId=${e.clientId}`,autoStart:!1}),[s,u]=I.useState(!1),[f,d]=I.useState(""),[p,m]=I.useState(Su()),[y,b]=I.useState(),[v,E]=I.useState([]),[S,w]=I.useState(!1),[_,O]=I.useState(!1),[T,C]=I.useState(null),N=I.useMemo(()=>({position:"fixed",right:16,bottom:16,zIndex:2147483647,fontFamily:"system-ui"}),[]);I.useEffect(()=>{const $=window.location.pathname;e.hideChatForUrls?.some(U=>$.startsWith(U))?O(!0):O(!1)}),I.useEffect(()=>{s&&v.length==0&&YU(e,Su()||e.conversationId||"",$=>{const U=$.map(D=>({id:D.id,role:D.role,text:D.text,sentAt:uy(D.sentAt),seen:D.seen}));E(D=>[...U])}),s&&p&&(async()=>{const U=await XU(e,p);b(U)})()},[s]);function k($){E(U=>{const D=U[U.length-1];if(!D||D.role!=="assistant"||D.id!==$.id)return[...U,{id:$.id,role:$.role,text:$.text,sentAt:uy(new Date().toISOString()),seen:!1}];const Y=U.slice();return Y[Y.length-1]={...D,text:D.text+$.text},Y})}const z=($,U,D,Y)=>{if($)return U.find(ae=>ae.id===$);const re=D.trim();if(!(!re||Y))return{id:new Jn().toString(),role:"User",text:re,seen:!1,sentAt:uy(new Date().toISOString()),status:"sending",errorText:void 0}};async function H($,U=null){A(),w(!0);const D=z($,v,f,S);!$&&D!=null&&U==null&&(d(""),E(re=>[...re.map(B=>({...B,status:B.status==="failed"?"ignored":B.status})),D]));let Y;try{await BB({url:e.apiBaseUrl+gd+"/"+e.clientId+"/send-message/",token:e.sessionToken,clientId:e.clientId,conversationId:p,messageId:D?.id,body:D?.text||null,directiveForAgent:U,onDelta:re=>{k(re)},onRunStarted:re=>{m(re),PB(re)},onAgentEvent:re=>C(re)}),Y="sent"}catch{Y="failed"}finally{U==null&&E(re=>re.map(ae=>ae.id===D.id?{...ae,status:Y,errorText:"Eroare la trimitere."}:ae)),w(!1)}}const j=I.useCallback(($,U)=>{k({id:U.messageId,role:"assistant",text:U.text})},[]),G=I.useCallback($=>{E(U=>U.map(D=>D.id===$?{...D,seen:!0}:D))},[]),F=I.useCallback($=>{b($),console.log($)},[]),A=I.useCallback(()=>{(T?.value.kind==pi.OperationSuccess||T?.value.kind==pi.OperationError)&&C(null)},[T]);I.useEffect(()=>{T?.name==bu.AgentDirective&&T?.value.kind==kB.ReplayMessagePendingActionAfterVerification&&(H(void 0,T),C(null))},[T]),I.useEffect(()=>{p==""||p==null||n()},[p]),I.useEffect(()=>(r("ReceivedOperatorMessage",j),r("ReceivedSeenAtByOperator",G),r("RecievedConversationModeChanged",F),()=>{a("ReceivedOperatorMessage",j),a("ReceivedSeenAtByOperator",G),a("RecievedConversationModeChanged",F)}),[r,t,a]);const X=I.useCallback($=>p?t?$?.mode=="Bot"?"AI":$?.mode=="Human"?"Human":"AI":"Disconnected":"New",[p,t]);return _?L.jsx(L.Fragment,{}):L.jsx(uU,{anchorSx:N,open:s,setOpen:u,msgs:v,input:f,setInput:d,send:H,sending:S,conversationMode:X(y),directive:T,setDirective:C})}class QU extends HTMLElement{connectedCallback(){const t=yu();if(!t)return;const n=this.attachShadow({mode:"open"}),r=document.createElement("style");r.textContent=`
175
+ ${d}\\${p}/`)}t.seenObjects[t.seenObjects.length-1].obj=e}if(Array.isArray(e))return W8(e,t);if(e===void 0)return null;if(e instanceof Date||v8(e)){const n=e.getTime(),r=n>-1&&n<2534023188e5;return t.legacy?t.relaxed&&r?{$date:e.getTime()}:{$date:b_(e)}:t.relaxed&&r?{$date:b_(e)}:{$date:{$numberLong:e.getTime().toString()}}}if(typeof e=="number"&&(!t.relaxed||!isFinite(e))){if(Number.isInteger(e)&&!Object.is(e,-0)){if(e>=Jg&&e<=Qg)return{$numberInt:e.toString()};if(e>=Ww&&e<=Kw)return{$numberLong:e.toString()}}return{$numberDouble:Object.is(e,-0)?"-0.0":e.toString()}}if(typeof e=="bigint")return t.relaxed?Number(BigInt.asIntN(64,e)):{$numberLong:BigInt.asIntN(64,e).toString()};if(e instanceof RegExp||y8(e)){let n=e.flags;if(n===void 0){const a=e.toString().match(/[gimuy]*$/);a&&(n=a[0])}return new eo(e.source,n).toExtendedJSON(t)}return e!=null&&typeof e=="object"?J8(e,t):e}const Q8={Binary:e=>new dt(e.value(),e.sub_type),Code:e=>new Nu(e.code,e.scope),DBRef:e=>new Ls(e.collection||e.namespace,e.oid,e.db,e.fields),Decimal128:e=>new Nr(e.bytes),Double:e=>new Ji(e.value),Int32:e=>new Us(e.value),Long:e=>K.fromBits(e.low!=null?e.low:e.low_,e.low!=null?e.high:e.high_,e.low!=null?e.unsigned:e.unsigned_),MaxKey:()=>new Od,MinKey:()=>new Rd,ObjectId:e=>new En(e),BSONRegExp:e=>new eo(e.pattern,e.options),BSONSymbol:e=>new Nd(e.value),Timestamp:e=>$o.fromBits(e.low,e.high)};function J8(e,t){if(e==null||typeof e!="object")throw new ve("not an object instance");const n=e._bsontype;if(typeof n>"u"){const r={};for(const a of Object.keys(e)){t.seenObjects.push({propertyName:a,obj:null});try{const s=to(e[a],t);a==="__proto__"?Object.defineProperty(r,a,{value:s,writable:!0,enumerable:!0,configurable:!0}):r[a]=s}finally{t.seenObjects.pop()}}return r}else{if(e!=null&&typeof e=="object"&&typeof e._bsontype=="string"&&e[Zw]!==Wg)throw new E8;if(Z8(e)){let r=e;if(typeof r.toExtendedJSON!="function"){const a=Q8[e._bsontype];if(!a)throw new ve("Unrecognized or invalid _bsontype: "+e._bsontype);r=a(r)}return n==="Code"&&r.scope?r=new Nu(r.code,to(r.scope,t)):n==="DBRef"&&r.oid&&(r=new Ls(to(r.collection,t),to(r.oid,t),to(r.db,t),to(r.fields,t))),r.toExtendedJSON(t)}else throw new ve("_bsontype must be a string, but was: "+typeof n)}}function S_(e,t){const n={useBigInt64:t?.useBigInt64??!1,relaxed:t?.relaxed??!0,legacy:t?.legacy??!1};return JSON.parse(e,(r,a)=>{if(r.indexOf("\0")!==-1)throw new ve(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(r)}`);return v_(a,n)})}function x_(e,t,n,r){n!=null&&typeof n=="object"&&(r=n,n=0),t!=null&&typeof t=="object"&&!Array.isArray(t)&&(r=t,t=void 0,n=0);const a=Object.assign({relaxed:!0,legacy:!1},r,{seenObjects:[{propertyName:"(root)",obj:null}]}),s=to(e,a);return JSON.stringify(s,t,n)}function eU(e,t){return t=t||{},JSON.parse(x_(e,t))}function tU(e,t){return t=t||{},S_(JSON.stringify(e),t)}const Du=Object.create(null);Du.parse=S_,Du.stringify=x_,Du.serialize=eU,Du.deserialize=tU,Object.freeze(Du);const un={double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:255,maxKey:127};function ry(e,t){try{return Ra.getNonnegativeInt32LE(e,t)}catch(n){throw new Lo("BSON size cannot be negative",t,{cause:n})}}function iy(e,t){let n=t;for(;e[n]!==0;n++);if(n===e.length-1)throw new Lo("Null terminator not found",t);return n}function nU(e,t=0){if(t??=0,e.length<5)throw new Lo(`Input must be at least 5 bytes, got ${e.length} bytes`,t);const n=ry(e,t);if(n>e.length-t)throw new Lo(`Parsed documentSize (${n} bytes) does not match input length (${e.length} bytes)`,t);if(e[t+n-1]!==0)throw new Lo("BSON documents must end in 0x00",t+n);const r=[];let a=t+4;for(;a<=n+t;){const s=e[a];if(a+=1,s===0){if(a-t!==n)throw new Lo("Invalid 0x00 type byte",a);break}const u=a,f=iy(e,a)-u;a+=f+1;let d;if(s===un.double||s===un.long||s===un.date||s===un.timestamp)d=8;else if(s===un.int)d=4;else if(s===un.objectId)d=12;else if(s===un.decimal)d=16;else if(s===un.bool)d=1;else if(s===un.null||s===un.undefined||s===un.maxKey||s===un.minKey)d=0;else if(s===un.regex)d=iy(e,iy(e,a)+1)+1-a;else if(s===un.object||s===un.array||s===un.javascriptWithScope)d=ry(e,a);else if(s===un.string||s===un.binData||s===un.dbPointer||s===un.javascript||s===un.symbol)d=ry(e,a)+4,s===un.binData&&(d+=1),s===un.dbPointer&&(d+=12);else throw new Lo(`Invalid 0x${s.toString(16).padStart(2,"0")} type byte`,a);if(d>n)throw new Lo("value reports length larger than document",a);r.push([s,u,f,a,d]),a+=d}return r}const Id=Object.create(null);Id.parseToElements=nU,Id.ByteUtils=Le,Id.NumberUtils=Ra,Object.freeze(Id);const rU=1024*1024*17;Le.allocate(rU);const iU=({directive:e,setDirective:t})=>{if(!e)return null;const[n,r]=I.useState(null),a=I.useCallback(s=>{p8(s).then(u=>{const f=u.events;if(f.length==0)return null;let d=f[0];const p=JSON.parse(d.value);if(d.value=p,d.value.kind==pi.OperationValidationFailed){r(d);return}t(d)}).catch(()=>t(null))},[e]);switch(e.value.kind){case pi.verificationForm:return e.value?.payload?.channels?.includes("email")?L.jsx(d8,{send:a,cancel:()=>t(null)}):L.jsx(u8,{send:a});case pi.OtpForm:const s=e?.value?.payload;return L.jsx(h8,{valueRecieved:s,failedValidationOperation:n,send:a,cancel:()=>t(null)});case pi.OperationError:return L.jsx(Tr,{color:"error",children:e.value.payload.message});case pi.OperationSuccess:const u={id:new Jn().toString(),role:"assistant",text:e.value.payload?.message,sentAt:void 0,seen:!1,status:void 0,errorText:void 0};return L.jsxs(pn,{sx:{display:"flex",justifyContent:"flex-start",gap:1,mb:1.2,overflowAnchor:"none"},children:[L.jsx(Yw,{msg:u,isMe:!1}),L.jsx(Gw,{msg:u,isMe:!1,showSeenIndicator:!1,isSeen:!1,send:()=>null})]});default:return null}},oU=()=>L.jsxs(pn,{sx:{display:"flex",alignItems:"flex-end",gap:1,mb:1.2},children:[L.jsx(bf,{sx:{width:30,height:30,bgcolor:"primary.main"},children:L.jsx(pg,{sx:{fontSize:18}})}),L.jsxs(pn,{sx:{px:1.4,py:1.1,borderRadius:3,border:"1px solid",borderColor:"divider",bgcolor:"background.paper",boxShadow:"0 10px 30px rgba(0,0,0,.10)",display:"flex",alignItems:"center",gap:.6},children:[L.jsx(pn,{sx:{width:6,height:6,borderRadius:999,bgcolor:"text.secondary",animation:"dot 1.1s infinite ease-in-out","@keyframes dot":{"0%, 80%, 100%":{transform:"scale(0.6)",opacity:.4},"40%":{transform:"scale(1)",opacity:1}}}}),L.jsx(pn,{sx:{width:6,height:6,borderRadius:999,bgcolor:"text.secondary",animation:"dot 1.1s infinite ease-in-out",animationDelay:"0.15s","@keyframes dot":{"0%, 80%, 100%":{transform:"scale(0.6)",opacity:.4},"40%":{transform:"scale(1)",opacity:1}}}}),L.jsx(pn,{sx:{width:6,height:6,borderRadius:999,bgcolor:"text.secondary",animation:"dot 1.1s infinite ease-in-out",animationDelay:"0.3s","@keyframes dot":{"0%, 80%, 100%":{transform:"scale(0.6)",opacity:.4},"40%":{transform:"scale(1)",opacity:1}}}})]})]}),aU={display:"flex",flexDirection:"column",flex:1,minHeight:0,overflow:"auto",px:1.5,pt:1.5,backgroundImage:"radial-gradient(circle at 20% 10%, rgba(25,118,210,.10), transparent 45%),radial-gradient(circle at 80% 20%, rgba(156,39,176,.10), transparent 50%),radial-gradient(circle at 40% 90%, rgba(0,200,83,.08), transparent 45%)","&::-webkit-scrollbar":{width:10},"&::-webkit-scrollbar-thumb":{backgroundColor:"rgba(0,0,0,.18)",borderRadius:999,border:"3px solid transparent",backgroundClip:"content-box"}};function sU({msgs:e,isMessageSeen:t,send:n,sending:r,items:a,endRef:s,directive:u,setDirective:f}){return L.jsxs(pn,{sx:aU,children:[L.jsx(l8,{msgs:e,isMessageSeen:t,reSend:n}),L.jsx("div",{style:{paddingBottom:2},children:r&&L.jsx(oU,{})}),a.map(d=>L.jsx(qB,{error:d.message,onClose:()=>yd.getState().remove(d.id)},d.id)),L.jsx(iU,{directive:u,setDirective:f}),L.jsx(x4,{ref:s,href:"https://x-bot.ro",target:"_blank",rel:"noreferrer",underline:"none",sx:{pb:1,marginTop:"auto",alignSelf:"center",fontSize:12,color:"text.secondary",opacity:.75,"&:hover":{opacity:1,color:"text.primary"},justifyContent:"center"},children:"Chat oferit de X-bot.ro"})]})}function lU({inputRef:e,input:t,sending:n,setInput:r,send:a}){return L.jsx(pn,{sx:{p:1.25,borderTop:"1px solid",borderColor:"divider",display:"flex",gap:1,bgcolor:"background.paper",flexShrink:0},children:L.jsx(Cf,{inputRef:e,focused:!0,size:"small",fullWidth:!0,value:t,disabled:n||t.length>=xB,onChange:s=>r(s.target.value),onKeyDown:s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),a())},placeholder:"Scrie un mesaj",multiline:!0,maxRows:4,sx:{"& .MuiOutlinedInput-root":{borderRadius:3,pr:.75,backgroundColor:"rgba(0,0,0,.02)"}},InputProps:{endAdornment:L.jsx(Co,{size:"small",onClick:()=>a(),disabled:n||!t.trim(),sx:{ml:.5,borderRadius:999},children:L.jsx(XB,{})})}})})}function uU({open:e,setOpen:t,msgs:n,input:r,setInput:a,sending:s,send:u,anchorSx:f,conversationMode:d,directive:p,setDirective:m}){const y=yd(O=>O.items),b=I.useRef(null),v=I.useRef(null),E=us(),S=v5(E.breakpoints.down("md"));HB(),I.useEffect(()=>{v.current?.scrollIntoView({behavior:"smooth",block:"end"}),requestAnimationFrame(()=>b.current?.focus())},[n.length,s]),I.useEffect(()=>{e&&v.current?.scrollIntoView({behavior:"auto",block:"end"})},[e]),I.useEffect(()=>{if(!(e&&S))return;const O=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${O}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",document.body.style.width="",window.scrollTo(0,O)}},[e,S]);const w=I.useCallback((O,T,C,N)=>{const k=O===C.length-1,z=C[C.length-1],H=k&&T&&z?.seen,j=H&&z?.id===N.id;return{showSeenIndicator:H,isSeen:j}},[]),_=O=>O?!(O.value.kind==pi.OperationError||O.value.kind==pi.OperationSuccess):!1;return L.jsxs(pn,{sx:f,children:[!e&&L.jsx(dm,{variant:"contained",onClick:()=>t(!0),startIcon:L.jsx(UB,{}),sx:{borderRadius:999,px:2,py:1,textTransform:"none",boxShadow:"0 10px 30px rgba(0,0,0,.18)"},children:"Chat"}),e&&L.jsx(Xh,{elevation:S?0:10,sx:{width:S?"100vw":380,height:S?"calc(var(--vh, 1vh) * 100)":560,"@supports (height: 100dvh)":{height:S?"100dvh":560},maxWidth:"100vw",maxHeight:"100dvh",borderRadius:S?0:4,position:S?"fixed":"relative",inset:S?0:"auto",overflow:"hidden",border:S?"none":"1px solid",borderColor:"divider",boxShadow:S?"none":"0 18px 60px rgba(0,0,0,.28)"},children:L.jsxs(pn,{sx:{display:"flex",flexDirection:"column",height:"100%"},children:[L.jsx(FB,{isMobile:S,conversationMode:d,setOpen:t}),L.jsx(sU,{msgs:n,isMessageSeen:w,send:u,sending:s,items:y,endRef:v,directive:p,setDirective:m}),L.jsx(lU,{inputRef:b,input:r,sending:s||_(p),setInput:a,send:u})]})})]})}class Ia extends Error{constructor(t,n){const r=new.target.prototype;super(`${t}: Status code '${n}'`),this.statusCode=n,this.__proto__=r}}class oy extends Error{constructor(t="A timeout occurred."){const n=new.target.prototype;super(t),this.__proto__=n}}class gi extends Error{constructor(t="An abort occurred."){const n=new.target.prototype;super(t),this.__proto__=n}}class cU extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.transport=n,this.errorType="UnsupportedTransportError",this.__proto__=r}}class fU extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.transport=n,this.errorType="DisabledTransportError",this.__proto__=r}}class dU extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.transport=n,this.errorType="FailedToStartTransportError",this.__proto__=r}}class E_ extends Error{constructor(t){const n=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=n}}class pU extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.innerErrors=n,this.__proto__=r}}class w_{constructor(t,n,r){this.statusCode=t,this.statusText=n,this.content=r}}class Md{get(t,n){return this.send({...n,method:"GET",url:t})}post(t,n){return this.send({...n,method:"POST",url:t})}delete(t,n){return this.send({...n,method:"DELETE",url:t})}getCookieString(t){return""}}var ue;(function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"})(ue||(ue={}));class Bu{constructor(){}log(t,n){}}Bu.instance=new Bu;const hU="10.0.0";class On{static isRequired(t,n){if(t==null)throw new Error(`The '${n}' argument is required.`)}static isNotEmpty(t,n){if(!t||t.match(/^\s*$/))throw new Error(`The '${n}' argument should not be empty.`)}static isIn(t,n,r){if(!(t in n))throw new Error(`Unknown ${r} value: ${t}.`)}}class cn{static get isBrowser(){return!cn.isNode&&typeof window=="object"&&typeof window.document=="object"}static get isWebWorker(){return!cn.isNode&&typeof self=="object"&&"importScripts"in self}static get isReactNative(){return!cn.isNode&&typeof window=="object"&&typeof window.document>"u"}static get isNode(){return typeof process<"u"&&process.release&&process.release.name==="node"}}function zu(e,t){let n="";return Ma(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${mU(e)}'`)):typeof e=="string"&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function mU(e){const t=new Uint8Array(e);let n="";return t.forEach(r=>{const a=r<16?"0":"";n+=`0x${a}${r.toString(16)} `}),n.substring(0,n.length-1)}function Ma(e){return e&&typeof ArrayBuffer<"u"&&(e instanceof ArrayBuffer||e.constructor&&e.constructor.name==="ArrayBuffer")}async function __(e,t,n,r,a,s){const u={},[f,d]=js();u[f]=d,e.log(ue.Trace,`(${t} transport) sending data. ${zu(a,s.logMessageContent)}.`);const p=Ma(a)?"arraybuffer":"text",m=await n.post(r,{content:a,headers:{...u,...s.headers},responseType:p,timeout:s.timeout,withCredentials:s.withCredentials});e.log(ue.Trace,`(${t} transport) request complete. Response status: ${m.statusCode}.`)}function gU(e){return e===void 0?new Dd(ue.Information):e===null?Bu.instance:e.log!==void 0?e:new Dd(e)}class yU{constructor(t,n){this._subject=t,this._observer=n}dispose(){const t=this._subject.observers.indexOf(this._observer);t>-1&&this._subject.observers.splice(t,1),this._subject.observers.length===0&&this._subject.cancelCallback&&this._subject.cancelCallback().catch(n=>{})}}class Dd{constructor(t){this._minLevel=t,this.out=console}log(t,n){if(t>=this._minLevel){const r=`[${new Date().toISOString()}] ${ue[t]}: ${n}`;switch(t){case ue.Critical:case ue.Error:this.out.error(r);break;case ue.Warning:this.out.warn(r);break;case ue.Information:this.out.info(r);break;default:this.out.log(r);break}}}}function js(){let e="X-SignalR-User-Agent";return cn.isNode&&(e="User-Agent"),[e,vU(hU,bU(),xU(),SU())]}function vU(e,t,n,r){let a="Microsoft SignalR/";const s=e.split(".");return a+=`${s[0]}.${s[1]}`,a+=` (${e}; `,t&&t!==""?a+=`${t}; `:a+="Unknown OS; ",a+=`${n}`,r?a+=`; ${r}`:a+="; Unknown Runtime Version",a+=")",a}function bU(){if(cn.isNode)switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}else return""}function SU(){if(cn.isNode)return process.versions.node}function xU(){return cn.isNode?"NodeJS":"Browser"}function ay(e){return e.stack?e.stack:e.message?e.message:`${e}`}function EU(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("could not find global")}class wU extends Md{constructor(t){if(super(),this._logger=t,typeof fetch>"u"||cn.isNode){const n=typeof __webpack_require__=="function"?__non_webpack_require__:require;this._jar=new(n("tough-cookie")).CookieJar,typeof fetch>"u"?this._fetchType=n("node-fetch"):this._fetchType=fetch,this._fetchType=n("fetch-cookie")(this._fetchType,this._jar)}else this._fetchType=fetch.bind(EU());if(typeof AbortController>"u"){const n=typeof __webpack_require__=="function"?__non_webpack_require__:require;this._abortControllerType=n("abort-controller")}else this._abortControllerType=AbortController}async send(t){if(t.abortSignal&&t.abortSignal.aborted)throw new gi;if(!t.method)throw new Error("No method defined.");if(!t.url)throw new Error("No url defined.");const n=new this._abortControllerType;let r;t.abortSignal&&(t.abortSignal.onabort=()=>{n.abort(),r=new gi});let a=null;if(t.timeout){const d=t.timeout;a=setTimeout(()=>{n.abort(),this._logger.log(ue.Warning,"Timeout from HTTP request."),r=new oy},d)}t.content===""&&(t.content=void 0),t.content&&(t.headers=t.headers||{},Ma(t.content)?t.headers["Content-Type"]="application/octet-stream":t.headers["Content-Type"]="text/plain;charset=UTF-8");let s;try{s=await this._fetchType(t.url,{body:t.content,cache:"no-cache",credentials:t.withCredentials===!0?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...t.headers},method:t.method,mode:"cors",redirect:"follow",signal:n.signal})}catch(d){throw r||(this._logger.log(ue.Warning,`Error from HTTP request. ${d}.`),d)}finally{a&&clearTimeout(a),t.abortSignal&&(t.abortSignal.onabort=null)}if(!s.ok){const d=await T_(s,"text");throw new Ia(d||s.statusText,s.status)}const f=await T_(s,t.responseType);return new w_(s.status,s.statusText,f)}getCookieString(t){let n="";return cn.isNode&&this._jar&&this._jar.getCookies(t,(r,a)=>n=a.join("; ")),n}}function T_(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:n=e.text();break}return n}class _U extends Md{constructor(t){super(),this._logger=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new gi):t.method?t.url?new Promise((n,r)=>{const a=new XMLHttpRequest;a.open(t.method,t.url,!0),a.withCredentials=t.withCredentials===void 0?!0:t.withCredentials,a.setRequestHeader("X-Requested-With","XMLHttpRequest"),t.content===""&&(t.content=void 0),t.content&&(Ma(t.content)?a.setRequestHeader("Content-Type","application/octet-stream"):a.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const s=t.headers;s&&Object.keys(s).forEach(u=>{a.setRequestHeader(u,s[u])}),t.responseType&&(a.responseType=t.responseType),t.abortSignal&&(t.abortSignal.onabort=()=>{a.abort(),r(new gi)}),t.timeout&&(a.timeout=t.timeout),a.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),a.status>=200&&a.status<300?n(new w_(a.status,a.statusText,a.response||a.responseText)):r(new Ia(a.response||a.responseText||a.statusText,a.status))},a.onerror=()=>{this._logger.log(ue.Warning,`Error from HTTP request. ${a.status}: ${a.statusText}.`),r(new Ia(a.statusText,a.status))},a.ontimeout=()=>{this._logger.log(ue.Warning,"Timeout from HTTP request."),r(new oy)},a.send(t.content)}):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class TU extends Md{constructor(t){if(super(),typeof fetch<"u"||cn.isNode)this._httpClient=new wU(t);else if(typeof XMLHttpRequest<"u")this._httpClient=new _U(t);else throw new Error("No usable HttpClient found.")}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new gi):t.method?t.url?this._httpClient.send(t):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(t){return this._httpClient.getCookieString(t)}}class Ir{static write(t){return`${t}${Ir.RecordSeparator}`}static parse(t){if(t[t.length-1]!==Ir.RecordSeparator)throw new Error("Message is incomplete.");const n=t.split(Ir.RecordSeparator);return n.pop(),n}}Ir.RecordSeparatorCode=30,Ir.RecordSeparator=String.fromCharCode(Ir.RecordSeparatorCode);class CU{writeHandshakeRequest(t){return Ir.write(JSON.stringify(t))}parseHandshakeResponse(t){let n,r;if(Ma(t)){const f=new Uint8Array(t),d=f.indexOf(Ir.RecordSeparatorCode);if(d===-1)throw new Error("Message is incomplete.");const p=d+1;n=String.fromCharCode.apply(null,Array.prototype.slice.call(f.slice(0,p))),r=f.byteLength>p?f.slice(p).buffer:null}else{const f=t,d=f.indexOf(Ir.RecordSeparator);if(d===-1)throw new Error("Message is incomplete.");const p=d+1;n=f.substring(0,p),r=f.length>p?f.substring(p):null}const a=Ir.parse(n),s=JSON.parse(a[0]);if(s.type)throw new Error("Expected a handshake response from the server.");return[r,s]}}var Qe;(function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close",e[e.Ack=8]="Ack",e[e.Sequence=9]="Sequence"})(Qe||(Qe={}));class AU{constructor(){this.observers=[]}next(t){for(const n of this.observers)n.next(t)}error(t){for(const n of this.observers)n.error&&n.error(t)}complete(){for(const t of this.observers)t.complete&&t.complete()}subscribe(t){return this.observers.push(t),new yU(this,t)}}class kU{constructor(t,n,r){this._bufferSize=1e5,this._messages=[],this._totalMessageCount=0,this._waitForSequenceMessage=!1,this._nextReceivingSequenceId=1,this._latestReceivedSequenceId=0,this._bufferedByteCount=0,this._reconnectInProgress=!1,this._protocol=t,this._connection=n,this._bufferSize=r}async _send(t){const n=this._protocol.writeMessage(t);let r=Promise.resolve();if(this._isInvocationMessage(t)){this._totalMessageCount++;let a=()=>{},s=()=>{};Ma(n)?this._bufferedByteCount+=n.byteLength:this._bufferedByteCount+=n.length,this._bufferedByteCount>=this._bufferSize&&(r=new Promise((u,f)=>{a=u,s=f})),this._messages.push(new OU(n,this._totalMessageCount,a,s))}try{this._reconnectInProgress||await this._connection.send(n)}catch{this._disconnected()}await r}_ack(t){let n=-1;for(let r=0;r<this._messages.length;r++){const a=this._messages[r];if(a._id<=t.sequenceId)n=r,Ma(a._message)?this._bufferedByteCount-=a._message.byteLength:this._bufferedByteCount-=a._message.length,a._resolver();else if(this._bufferedByteCount<this._bufferSize)a._resolver();else break}n!==-1&&(this._messages=this._messages.slice(n+1))}_shouldProcessMessage(t){if(this._waitForSequenceMessage)return t.type!==Qe.Sequence?!1:(this._waitForSequenceMessage=!1,!0);if(!this._isInvocationMessage(t))return!0;const n=this._nextReceivingSequenceId;return this._nextReceivingSequenceId++,n<=this._latestReceivedSequenceId?(n===this._latestReceivedSequenceId&&this._ackTimer(),!1):(this._latestReceivedSequenceId=n,this._ackTimer(),!0)}_resetSequence(t){if(t.sequenceId>this._nextReceivingSequenceId){this._connection.stop(new Error("Sequence ID greater than amount of messages we've received."));return}this._nextReceivingSequenceId=t.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}async _resend(){const t=this._messages.length!==0?this._messages[0]._id:this._totalMessageCount+1;await this._connection.send(this._protocol.writeMessage({type:Qe.Sequence,sequenceId:t}));const n=this._messages;for(const r of n)await this._connection.send(r._message);this._reconnectInProgress=!1}_dispose(t){t??(t=new Error("Unable to reconnect to server."));for(const n of this._messages)n._rejector(t)}_isInvocationMessage(t){switch(t.type){case Qe.Invocation:case Qe.StreamItem:case Qe.Completion:case Qe.StreamInvocation:case Qe.CancelInvocation:return!0;case Qe.Close:case Qe.Sequence:case Qe.Ping:case Qe.Ack:return!1}}_ackTimer(){this._ackTimerHandle===void 0&&(this._ackTimerHandle=setTimeout(async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:Qe.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0},1e3))}}class OU{constructor(t,n,r,a){this._message=t,this._id=n,this._resolver=r,this._rejector=a}}const RU=30*1e3,NU=15*1e3,IU=1e5;var Pt;(function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"})(Pt||(Pt={}));class sy{static create(t,n,r,a,s,u,f){return new sy(t,n,r,a,s,u,f)}constructor(t,n,r,a,s,u,f){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(ue.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},On.isRequired(t,"connection"),On.isRequired(n,"logger"),On.isRequired(r,"protocol"),this.serverTimeoutInMilliseconds=s??RU,this.keepAliveIntervalInMilliseconds=u??NU,this._statefulReconnectBufferSize=f??IU,this._logger=n,this._protocol=r,this.connection=t,this._reconnectPolicy=a,this._handshakeProtocol=new CU,this.connection.onreceive=d=>this._processIncomingData(d),this.connection.onclose=d=>this._connectionClosed(d),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=Pt.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Qe.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(t){if(this._connectionState!==Pt.Disconnected&&this._connectionState!==Pt.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!t)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=t}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==Pt.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=Pt.Connecting,this._logger.log(ue.Debug,"Starting HubConnection.");try{await this._startInternal(),cn.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=Pt.Connected,this._connectionStarted=!0,this._logger.log(ue.Debug,"HubConnection connected successfully.")}catch(t){return this._connectionState=Pt.Disconnected,this._logger.log(ue.Debug,`HubConnection failed to start successfully because of error '${t}'.`),Promise.reject(t)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const t=new Promise((n,r)=>{this._handshakeResolver=n,this._handshakeRejecter=r});await this.connection.start(this._protocol.transferFormat);try{let n=this._protocol.version;this.connection.features.reconnect||(n=1);const r={protocol:this._protocol.name,version:n};if(this._logger.log(ue.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(r)),this._logger.log(ue.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await t,this._stopDuringStartError)throw this._stopDuringStartError;this.connection.features.reconnect&&(this._messageBuffer=new kU(this._protocol,this.connection,this._statefulReconnectBufferSize),this.connection.features.disconnected=this._messageBuffer._disconnected.bind(this._messageBuffer),this.connection.features.resend=()=>{if(this._messageBuffer)return this._messageBuffer._resend()}),this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(n){throw this._logger.log(ue.Debug,`Hub handshake failed with error '${n}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(n),n}}async stop(){const t=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),await this._stopPromise;try{await t}catch{}}_stopInternal(t){if(this._connectionState===Pt.Disconnected)return this._logger.log(ue.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===Pt.Disconnecting)return this._logger.log(ue.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const n=this._connectionState;return this._connectionState=Pt.Disconnecting,this._logger.log(ue.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(ue.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(n===Pt.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=t||new gi("The connection was stopped before the hub handshake could complete."),this.connection.stop(t))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(t,...n){const[r,a]=this._replaceStreamingParams(n),s=this._createStreamInvocation(t,n,a);let u;const f=new AU;return f.cancelCallback=()=>{const d=this._createCancelInvocation(s.invocationId);return delete this._callbacks[s.invocationId],u.then(()=>this._sendWithProtocol(d))},this._callbacks[s.invocationId]=(d,p)=>{if(p){f.error(p);return}else d&&(d.type===Qe.Completion?d.error?f.error(new Error(d.error)):f.complete():f.next(d.item))},u=this._sendWithProtocol(s).catch(d=>{f.error(d),delete this._callbacks[s.invocationId]}),this._launchStreams(r,u),f}_sendMessage(t){return this._resetKeepAliveInterval(),this.connection.send(t)}_sendWithProtocol(t){return this._messageBuffer?this._messageBuffer._send(t):this._sendMessage(this._protocol.writeMessage(t))}send(t,...n){const[r,a]=this._replaceStreamingParams(n),s=this._sendWithProtocol(this._createInvocation(t,n,!0,a));return this._launchStreams(r,s),s}invoke(t,...n){const[r,a]=this._replaceStreamingParams(n),s=this._createInvocation(t,n,!1,a);return new Promise((f,d)=>{this._callbacks[s.invocationId]=(m,y)=>{if(y){d(y);return}else m&&(m.type===Qe.Completion?m.error?d(new Error(m.error)):f(m.result):d(new Error(`Unexpected message type: ${m.type}`)))};const p=this._sendWithProtocol(s).catch(m=>{d(m),delete this._callbacks[s.invocationId]});this._launchStreams(r,p)})}on(t,n){!t||!n||(t=t.toLowerCase(),this._methods[t]||(this._methods[t]=[]),this._methods[t].indexOf(n)===-1&&this._methods[t].push(n))}off(t,n){if(!t)return;t=t.toLowerCase();const r=this._methods[t];if(r)if(n){const a=r.indexOf(n);a!==-1&&(r.splice(a,1),r.length===0&&delete this._methods[t])}else delete this._methods[t]}onclose(t){t&&this._closedCallbacks.push(t)}onreconnecting(t){t&&this._reconnectingCallbacks.push(t)}onreconnected(t){t&&this._reconnectedCallbacks.push(t)}_processIncomingData(t){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(t=this._processHandshakeResponse(t),this._receivedHandshakeResponse=!0),t){const n=this._protocol.parseMessages(t,this._logger);for(const r of n)if(!(this._messageBuffer&&!this._messageBuffer._shouldProcessMessage(r)))switch(r.type){case Qe.Invocation:this._invokeClientMethod(r).catch(a=>{this._logger.log(ue.Error,`Invoke client method threw error: ${ay(a)}`)});break;case Qe.StreamItem:case Qe.Completion:{const a=this._callbacks[r.invocationId];if(a){r.type===Qe.Completion&&delete this._callbacks[r.invocationId];try{a(r)}catch(s){this._logger.log(ue.Error,`Stream callback threw error: ${ay(s)}`)}}break}case Qe.Ping:break;case Qe.Close:{this._logger.log(ue.Information,"Close message received from server.");const a=r.error?new Error("Server returned an error on close: "+r.error):void 0;r.allowReconnect===!0?this.connection.stop(a):this._stopPromise=this._stopInternal(a);break}case Qe.Ack:this._messageBuffer&&this._messageBuffer._ack(r);break;case Qe.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(r);break;default:this._logger.log(ue.Warning,`Invalid message type: ${r.type}.`);break}}this._resetTimeoutPeriod()}_processHandshakeResponse(t){let n,r;try{[r,n]=this._handshakeProtocol.parseHandshakeResponse(t)}catch(a){const s="Error parsing handshake response: "+a;this._logger.log(ue.Error,s);const u=new Error(s);throw this._handshakeRejecter(u),u}if(n.error){const a="Server returned handshake error: "+n.error;this._logger.log(ue.Error,a);const s=new Error(a);throw this._handshakeRejecter(s),s}else this._logger.log(ue.Debug,"Server handshake complete.");return this._handshakeResolver(),r}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=new Date().getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!this.connection.features||!this.connection.features.inherentKeepAlive){this._timeoutHandle=setTimeout(()=>this.serverTimeout(),this.serverTimeoutInMilliseconds);let t=this._nextKeepAlive-new Date().getTime();if(t<0){this._connectionState===Pt.Connected&&this._trySendPingMessage();return}this._pingServerHandle===void 0&&(t<0&&(t=0),this._pingServerHandle=setTimeout(async()=>{this._connectionState===Pt.Connected&&await this._trySendPingMessage()},t))}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(t){const n=t.target.toLowerCase(),r=this._methods[n];if(!r){this._logger.log(ue.Warning,`No client method with the name '${n}' found.`),t.invocationId&&(this._logger.log(ue.Warning,`No result given for '${n}' method and invocation ID '${t.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(t.invocationId,"Client didn't provide a result.",null)));return}const a=r.slice(),s=!!t.invocationId;let u,f,d;for(const p of a)try{const m=u;u=await p.apply(this,t.arguments),s&&u&&m&&(this._logger.log(ue.Error,`Multiple results provided for '${n}'. Sending error to server.`),d=this._createCompletionMessage(t.invocationId,"Client provided multiple results.",null)),f=void 0}catch(m){f=m,this._logger.log(ue.Error,`A callback for the method '${n}' threw error '${m}'.`)}d?await this._sendWithProtocol(d):s?(f?d=this._createCompletionMessage(t.invocationId,`${f}`,null):u!==void 0?d=this._createCompletionMessage(t.invocationId,null,u):(this._logger.log(ue.Warning,`No result given for '${n}' method and invocation ID '${t.invocationId}'.`),d=this._createCompletionMessage(t.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(d)):u&&this._logger.log(ue.Error,`Result given for '${n}' method but server is not expecting a result.`)}_connectionClosed(t){this._logger.log(ue.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||t||new gi("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(t||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===Pt.Disconnecting?this._completeClose(t):this._connectionState===Pt.Connected&&this._reconnectPolicy?this._reconnect(t):this._connectionState===Pt.Connected&&this._completeClose(t)}_completeClose(t){if(this._connectionStarted){this._connectionState=Pt.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(t??new Error("Connection closed.")),this._messageBuffer=void 0),cn.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach(n=>n.apply(this,[t]))}catch(n){this._logger.log(ue.Error,`An onclose callback called with error '${t}' threw error '${n}'.`)}}}async _reconnect(t){const n=Date.now();let r=0,a=t!==void 0?t:new Error("Attempting to reconnect due to a unknown error."),s=this._getNextRetryDelay(r,0,a);if(s===null){this._logger.log(ue.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),this._completeClose(t);return}if(this._connectionState=Pt.Reconnecting,t?this._logger.log(ue.Information,`Connection reconnecting because of error '${t}'.`):this._logger.log(ue.Information,"Connection reconnecting."),this._reconnectingCallbacks.length!==0){try{this._reconnectingCallbacks.forEach(u=>u.apply(this,[t]))}catch(u){this._logger.log(ue.Error,`An onreconnecting callback called with error '${t}' threw error '${u}'.`)}if(this._connectionState!==Pt.Reconnecting){this._logger.log(ue.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");return}}for(;s!==null;){if(this._logger.log(ue.Information,`Reconnect attempt number ${r+1} will start in ${s} ms.`),await new Promise(u=>{this._reconnectDelayHandle=setTimeout(u,s)}),this._reconnectDelayHandle=void 0,this._connectionState!==Pt.Reconnecting){this._logger.log(ue.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");return}try{if(await this._startInternal(),this._connectionState=Pt.Connected,this._logger.log(ue.Information,"HubConnection reconnected successfully."),this._reconnectedCallbacks.length!==0)try{this._reconnectedCallbacks.forEach(u=>u.apply(this,[this.connection.connectionId]))}catch(u){this._logger.log(ue.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${u}'.`)}return}catch(u){if(this._logger.log(ue.Information,`Reconnect attempt failed because of error '${u}'.`),this._connectionState!==Pt.Reconnecting){this._logger.log(ue.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),this._connectionState===Pt.Disconnecting&&this._completeClose();return}r++,a=u instanceof Error?u:new Error(u.toString()),s=this._getNextRetryDelay(r,Date.now()-n,a)}}this._logger.log(ue.Information,`Reconnect retries have been exhausted after ${Date.now()-n} ms and ${r} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(t,n,r){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:n,previousRetryCount:t,retryReason:r})}catch(a){return this._logger.log(ue.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${n}) threw error '${a}'.`),null}}_cancelCallbacksWithError(t){const n=this._callbacks;this._callbacks={},Object.keys(n).forEach(r=>{const a=n[r];try{a(null,t)}catch(s){this._logger.log(ue.Error,`Stream 'error' callback called with '${t}' threw error: ${ay(s)}`)}})}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(t,n,r,a){if(r)return a.length!==0?{target:t,arguments:n,streamIds:a,type:Qe.Invocation}:{target:t,arguments:n,type:Qe.Invocation};{const s=this._invocationId;return this._invocationId++,a.length!==0?{target:t,arguments:n,invocationId:s.toString(),streamIds:a,type:Qe.Invocation}:{target:t,arguments:n,invocationId:s.toString(),type:Qe.Invocation}}}_launchStreams(t,n){if(t.length!==0){n||(n=Promise.resolve());for(const r in t)t[r].subscribe({complete:()=>{n=n.then(()=>this._sendWithProtocol(this._createCompletionMessage(r)))},error:a=>{let s;a instanceof Error?s=a.message:a&&a.toString?s=a.toString():s="Unknown error",n=n.then(()=>this._sendWithProtocol(this._createCompletionMessage(r,s)))},next:a=>{n=n.then(()=>this._sendWithProtocol(this._createStreamItemMessage(r,a)))}})}}_replaceStreamingParams(t){const n=[],r=[];for(let a=0;a<t.length;a++){const s=t[a];if(this._isObservable(s)){const u=this._invocationId;this._invocationId++,n[u]=s,r.push(u.toString()),t.splice(a,1)}}return[n,r]}_isObservable(t){return t&&t.subscribe&&typeof t.subscribe=="function"}_createStreamInvocation(t,n,r){const a=this._invocationId;return this._invocationId++,r.length!==0?{target:t,arguments:n,invocationId:a.toString(),streamIds:r,type:Qe.StreamInvocation}:{target:t,arguments:n,invocationId:a.toString(),type:Qe.StreamInvocation}}_createCancelInvocation(t){return{invocationId:t,type:Qe.CancelInvocation}}_createStreamItemMessage(t,n){return{invocationId:t,item:n,type:Qe.StreamItem}}_createCompletionMessage(t,n,r){return n?{error:n,invocationId:t,type:Qe.Completion}:{invocationId:t,result:r,type:Qe.Completion}}_createCloseMessage(){return{type:Qe.Close}}async _trySendPingMessage(){try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}}const MU=[0,2e3,1e4,3e4,null];class C_{constructor(t){this._retryDelays=t!==void 0?[...t,null]:MU}nextRetryDelayInMilliseconds(t){return this._retryDelays[t.previousRetryCount]}}class Da{}Da.Authorization="Authorization",Da.Cookie="Cookie";class DU extends Md{constructor(t,n){super(),this._innerClient=t,this._accessTokenFactory=n}async send(t){let n=!0;this._accessTokenFactory&&(!this._accessToken||t.url&&t.url.indexOf("/negotiate?")>0)&&(n=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(t);const r=await this._innerClient.send(t);return n&&r.statusCode===401&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(t),await this._innerClient.send(t)):r}_setAuthorizationHeader(t){t.headers||(t.headers={}),this._accessToken?t.headers[Da.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&t.headers[Da.Authorization]&&delete t.headers[Da.Authorization]}getCookieString(t){return this._innerClient.getCookieString(t)}}var Dn;(function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"})(Dn||(Dn={}));var er;(function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"})(er||(er={}));let BU=class{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}};class A_{get pollAborted(){return this._pollAbort.aborted}constructor(t,n,r){this._httpClient=t,this._logger=n,this._pollAbort=new BU,this._options=r,this._running=!1,this.onreceive=null,this.onclose=null}async connect(t,n){if(On.isRequired(t,"url"),On.isRequired(n,"transferFormat"),On.isIn(n,er,"transferFormat"),this._url=t,this._logger.log(ue.Trace,"(LongPolling transport) Connecting."),n===er.Binary&&typeof XMLHttpRequest<"u"&&typeof new XMLHttpRequest().responseType!="string")throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[r,a]=js(),s={[r]:a,...this._options.headers},u={abortSignal:this._pollAbort.signal,headers:s,timeout:1e5,withCredentials:this._options.withCredentials};n===er.Binary&&(u.responseType="arraybuffer");const f=`${t}&_=${Date.now()}`;this._logger.log(ue.Trace,`(LongPolling transport) polling: ${f}.`);const d=await this._httpClient.get(f,u);d.statusCode!==200?(this._logger.log(ue.Error,`(LongPolling transport) Unexpected response code: ${d.statusCode}.`),this._closeError=new Ia(d.statusText||"",d.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,u)}async _poll(t,n){try{for(;this._running;)try{const r=`${t}&_=${Date.now()}`;this._logger.log(ue.Trace,`(LongPolling transport) polling: ${r}.`);const a=await this._httpClient.get(r,n);a.statusCode===204?(this._logger.log(ue.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):a.statusCode!==200?(this._logger.log(ue.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new Ia(a.statusText||"",a.statusCode),this._running=!1):a.content?(this._logger.log(ue.Trace,`(LongPolling transport) data received. ${zu(a.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(a.content)):this._logger.log(ue.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(r){this._running?r instanceof oy?this._logger.log(ue.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=r,this._running=!1):this._logger.log(ue.Trace,`(LongPolling transport) Poll errored after shutdown: ${r.message}`)}}finally{this._logger.log(ue.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(t){return this._running?__(this._logger,"LongPolling",this._httpClient,this._url,t,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(ue.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(ue.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const t={},[n,r]=js();t[n]=r;const a={headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let s;try{await this._httpClient.delete(this._url,a)}catch(u){s=u}s?s instanceof Ia&&(s.statusCode===404?this._logger.log(ue.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(ue.Trace,`(LongPolling transport) Error sending a DELETE request: ${s}`)):this._logger.log(ue.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(ue.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let t="(LongPolling transport) Firing onclose event.";this._closeError&&(t+=" Error: "+this._closeError),this._logger.log(ue.Trace,t),this.onclose(this._closeError)}}}class zU{constructor(t,n,r,a){this._httpClient=t,this._accessToken=n,this._logger=r,this._options=a,this.onreceive=null,this.onclose=null}async connect(t,n){return On.isRequired(t,"url"),On.isRequired(n,"transferFormat"),On.isIn(n,er,"transferFormat"),this._logger.log(ue.Trace,"(SSE transport) Connecting."),this._url=t,this._accessToken&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise((r,a)=>{let s=!1;if(n!==er.Text){a(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));return}let u;if(cn.isBrowser||cn.isWebWorker)u=new this._options.EventSource(t,{withCredentials:this._options.withCredentials});else{const f=this._httpClient.getCookieString(t),d={};d.Cookie=f;const[p,m]=js();d[p]=m,u=new this._options.EventSource(t,{withCredentials:this._options.withCredentials,headers:{...d,...this._options.headers}})}try{u.onmessage=f=>{if(this.onreceive)try{this._logger.log(ue.Trace,`(SSE transport) data received. ${zu(f.data,this._options.logMessageContent)}.`),this.onreceive(f.data)}catch(d){this._close(d);return}},u.onerror=f=>{s?this._close():a(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},u.onopen=()=>{this._logger.log(ue.Information,`SSE connected to ${this._url}`),this._eventSource=u,s=!0,r()}}catch(f){a(f);return}})}async send(t){return this._eventSource?__(this._logger,"SSE",this._httpClient,this._url,t,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(t){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(t))}}class LU{constructor(t,n,r,a,s,u){this._logger=r,this._accessTokenFactory=n,this._logMessageContent=a,this._webSocketConstructor=s,this._httpClient=t,this.onreceive=null,this.onclose=null,this._headers=u}async connect(t,n){On.isRequired(t,"url"),On.isRequired(n,"transferFormat"),On.isIn(n,er,"transferFormat"),this._logger.log(ue.Trace,"(WebSockets transport) Connecting.");let r;return this._accessTokenFactory&&(r=await this._accessTokenFactory()),new Promise((a,s)=>{t=t.replace(/^http/,"ws");let u;const f=this._httpClient.getCookieString(t);let d=!1;if(cn.isNode||cn.isReactNative){const p={},[m,y]=js();p[m]=y,r&&(p[Da.Authorization]=`Bearer ${r}`),f&&(p[Da.Cookie]=f),u=new this._webSocketConstructor(t,void 0,{headers:{...p,...this._headers}})}else r&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(r)}`);u||(u=new this._webSocketConstructor(t)),n===er.Binary&&(u.binaryType="arraybuffer"),u.onopen=p=>{this._logger.log(ue.Information,`WebSocket connected to ${t}.`),this._webSocket=u,d=!0,a()},u.onerror=p=>{let m=null;typeof ErrorEvent<"u"&&p instanceof ErrorEvent?m=p.error:m="There was an error with the transport",this._logger.log(ue.Information,`(WebSockets transport) ${m}.`)},u.onmessage=p=>{if(this._logger.log(ue.Trace,`(WebSockets transport) data received. ${zu(p.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(p.data)}catch(m){this._close(m);return}},u.onclose=p=>{if(d)this._close(p);else{let m=null;typeof ErrorEvent<"u"&&p instanceof ErrorEvent?m=p.error:m="WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",s(new Error(m))}}})}send(t){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(ue.Trace,`(WebSockets transport) sending data. ${zu(t,this._logMessageContent)}.`),this._webSocket.send(t),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(t){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(ue.Trace,"(WebSockets transport) socket closed."),this.onclose&&(this._isCloseEvent(t)&&(t.wasClean===!1||t.code!==1e3)?this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason||"no reason given"}).`)):t instanceof Error?this.onclose(t):this.onclose())}_isCloseEvent(t){return t&&typeof t.wasClean=="boolean"&&typeof t.code=="number"}}const k_=100;class PU{constructor(t,n={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,On.isRequired(t,"url"),this._logger=gU(n.logger),this.baseUrl=this._resolveUrl(t),n=n||{},n.logMessageContent=n.logMessageContent===void 0?!1:n.logMessageContent,typeof n.withCredentials=="boolean"||n.withCredentials===void 0)n.withCredentials=n.withCredentials===void 0?!0:n.withCredentials;else throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");n.timeout=n.timeout===void 0?100*1e3:n.timeout;let r=null,a=null;if(cn.isNode&&typeof require<"u"){const s=typeof __webpack_require__=="function"?__non_webpack_require__:require;r=s("ws"),a=s("eventsource")}!cn.isNode&&typeof WebSocket<"u"&&!n.WebSocket?n.WebSocket=WebSocket:cn.isNode&&!n.WebSocket&&r&&(n.WebSocket=r),!cn.isNode&&typeof EventSource<"u"&&!n.EventSource?n.EventSource=EventSource:cn.isNode&&!n.EventSource&&typeof a<"u"&&(n.EventSource=a),this._httpClient=new DU(n.httpClient||new TU(this._logger),n.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=n,this.onreceive=null,this.onclose=null}async start(t){if(t=t||er.Binary,On.isIn(t,er,"transferFormat"),this._logger.log(ue.Debug,`Starting connection with transfer format '${er[t]}'.`),this._connectionState!=="Disconnected")return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(t),await this._startInternalPromise,this._connectionState==="Disconnecting"){const n="Failed to start the HttpConnection before stop() was called.";return this._logger.log(ue.Error,n),await this._stopPromise,Promise.reject(new gi(n))}else if(this._connectionState!=="Connected"){const n="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(ue.Error,n),Promise.reject(new gi(n))}this._connectionStarted=!0}send(t){return this._connectionState!=="Connected"?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new ly(this.transport)),this._sendQueue.send(t))}async stop(t){if(this._connectionState==="Disconnected")return this._logger.log(ue.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`),Promise.resolve();if(this._connectionState==="Disconnecting")return this._logger.log(ue.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;this._connectionState="Disconnecting",this._stopPromise=new Promise(n=>{this._stopPromiseResolver=n}),await this._stopInternal(t),await this._stopPromise}async _stopInternal(t){this._stopError=t;try{await this._startInternalPromise}catch{}if(this.transport){try{await this.transport.stop()}catch(n){this._logger.log(ue.Error,`HttpConnection.transport.stop() threw error '${n}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(ue.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(t){let n=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation)if(this._options.transport===Dn.WebSockets)this.transport=this._constructTransport(Dn.WebSockets),await this._startTransport(n,t);else throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");else{let r=null,a=0;do{if(r=await this._getNegotiationResponse(n),this._connectionState==="Disconnecting"||this._connectionState==="Disconnected")throw new gi("The connection was stopped during negotiation.");if(r.error)throw new Error(r.error);if(r.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(r.url&&(n=r.url),r.accessToken){const s=r.accessToken;this._accessTokenFactory=()=>s,this._httpClient._accessToken=s,this._httpClient._accessTokenFactory=void 0}a++}while(r.url&&a<k_);if(a===k_&&r.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(n,this._options.transport,r,t)}this.transport instanceof A_&&(this.features.inherentKeepAlive=!0),this._connectionState==="Connecting"&&(this._logger.log(ue.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(r){return this._logger.log(ue.Error,"Failed to start the connection: "+r),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(r)}}async _getNegotiationResponse(t){const n={},[r,a]=js();n[r]=a;const s=this._resolveNegotiateUrl(t);this._logger.log(ue.Debug,`Sending negotiation request: ${s}.`);try{const u=await this._httpClient.post(s,{content:"",headers:{...n,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(u.statusCode!==200)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${u.statusCode}'`));const f=JSON.parse(u.content);return(!f.negotiateVersion||f.negotiateVersion<1)&&(f.connectionToken=f.connectionId),f.useStatefulReconnect&&this._options._useStatefulReconnect!==!0?Promise.reject(new E_("Client didn't negotiate Stateful Reconnect but the server did.")):f}catch(u){let f="Failed to complete negotiation with the server: "+u;return u instanceof Ia&&u.statusCode===404&&(f=f+" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(ue.Error,f),Promise.reject(new E_(f))}}_createConnectUrl(t,n){return n?t+(t.indexOf("?")===-1?"?":"&")+`id=${n}`:t}async _createTransport(t,n,r,a){let s=this._createConnectUrl(t,r.connectionToken);if(this._isITransport(n)){this._logger.log(ue.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=n,await this._startTransport(s,a),this.connectionId=r.connectionId;return}const u=[],f=r.availableTransports||[];let d=r;for(const p of f){const m=this._resolveTransportOrError(p,n,a,d?.useStatefulReconnect===!0);if(m instanceof Error)u.push(`${p.transport} failed:`),u.push(m);else if(this._isITransport(m)){if(this.transport=m,!d){try{d=await this._getNegotiationResponse(t)}catch(y){return Promise.reject(y)}s=this._createConnectUrl(t,d.connectionToken)}try{await this._startTransport(s,a),this.connectionId=d.connectionId;return}catch(y){if(this._logger.log(ue.Error,`Failed to start the transport '${p.transport}': ${y}`),d=void 0,u.push(new dU(`${p.transport} failed: ${y}`,Dn[p.transport])),this._connectionState!=="Connecting"){const b="Failed to select transport before stop() was called.";return this._logger.log(ue.Debug,b),Promise.reject(new gi(b))}}}}return u.length>0?Promise.reject(new pU(`Unable to connect to the server with any of the available transports. ${u.join(" ")}`,u)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(t){switch(t){case Dn.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new LU(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case Dn.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new zU(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case Dn.LongPolling:return new A_(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${t}.`)}}_startTransport(t,n){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async r=>{let a=!1;if(this.features.reconnect)try{this.features.disconnected(),await this.transport.connect(t,n),await this.features.resend()}catch{a=!0}else{this._stopConnection(r);return}a&&this._stopConnection(r)}:this.transport.onclose=r=>this._stopConnection(r),this.transport.connect(t,n)}_resolveTransportOrError(t,n,r,a){const s=Dn[t.transport];if(s==null)return this._logger.log(ue.Debug,`Skipping transport '${t.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`);if($U(n,s))if(t.transferFormats.map(f=>er[f]).indexOf(r)>=0){if(s===Dn.WebSockets&&!this._options.WebSocket||s===Dn.ServerSentEvents&&!this._options.EventSource)return this._logger.log(ue.Debug,`Skipping transport '${Dn[s]}' because it is not supported in your environment.'`),new cU(`'${Dn[s]}' is not supported in your environment.`,s);this._logger.log(ue.Debug,`Selecting transport '${Dn[s]}'.`);try{return this.features.reconnect=s===Dn.WebSockets?a:void 0,this._constructTransport(s)}catch(f){return f}}else return this._logger.log(ue.Debug,`Skipping transport '${Dn[s]}' because it does not support the requested transfer format '${er[r]}'.`),new Error(`'${Dn[s]}' does not support ${er[r]}.`);else return this._logger.log(ue.Debug,`Skipping transport '${Dn[s]}' because it was disabled by the client.`),new fU(`'${Dn[s]}' is disabled by the client.`,s)}_isITransport(t){return t&&typeof t=="object"&&"connect"in t}_stopConnection(t){if(this._logger.log(ue.Debug,`HttpConnection.stopConnection(${t}) called while in state ${this._connectionState}.`),this.transport=void 0,t=this._stopError||t,this._stopError=void 0,this._connectionState==="Disconnected"){this._logger.log(ue.Debug,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`);return}if(this._connectionState==="Connecting")throw this._logger.log(ue.Warning,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`);if(this._connectionState==="Disconnecting"&&this._stopPromiseResolver(),t?this._logger.log(ue.Error,`Connection disconnected with error '${t}'.`):this._logger.log(ue.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch(n=>{this._logger.log(ue.Error,`TransportSendQueue.stop() threw error '${n}'.`)}),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(t)}catch(n){this._logger.log(ue.Error,`HttpConnection.onclose(${t}) threw error '${n}'.`)}}}_resolveUrl(t){if(t.lastIndexOf("https://",0)===0||t.lastIndexOf("http://",0)===0)return t;if(!cn.isBrowser)throw new Error(`Cannot resolve '${t}'.`);const n=window.document.createElement("a");return n.href=t,this._logger.log(ue.Information,`Normalizing '${t}' to '${n.href}'.`),n.href}_resolveNegotiateUrl(t){const n=new URL(t);n.pathname.endsWith("/")?n.pathname+="negotiate":n.pathname+="/negotiate";const r=new URLSearchParams(n.searchParams);return r.has("negotiateVersion")||r.append("negotiateVersion",this._negotiateVersion.toString()),r.has("useStatefulReconnect")?r.get("useStatefulReconnect")==="true"&&(this._options._useStatefulReconnect=!0):this._options._useStatefulReconnect===!0&&r.append("useStatefulReconnect","true"),n.search=r.toString(),n.toString()}}function $U(e,t){return!e||(t&e)!==0}class ly{constructor(t){this._transport=t,this._buffer=[],this._executing=!0,this._sendBufferedData=new Bd,this._transportResult=new Bd,this._sendLoopPromise=this._sendLoop()}send(t){return this._bufferData(t),this._transportResult||(this._transportResult=new Bd),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(t){if(this._buffer.length&&typeof this._buffer[0]!=typeof t)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof t}`);this._buffer.push(t),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new Bd;const t=this._transportResult;this._transportResult=void 0;const n=typeof this._buffer[0]=="string"?this._buffer.join(""):ly._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(n),t.resolve()}catch(r){t.reject(r)}}}static _concatBuffers(t){const n=t.map(s=>s.byteLength).reduce((s,u)=>s+u),r=new Uint8Array(n);let a=0;for(const s of t)r.set(new Uint8Array(s),a),a+=s.byteLength;return r.buffer}}class Bd{constructor(){this.promise=new Promise((t,n)=>[this._resolver,this._rejecter]=[t,n])}resolve(){this._resolver()}reject(t){this._rejecter(t)}}const UU="json";class jU{constructor(){this.name=UU,this.version=2,this.transferFormat=er.Text}parseMessages(t,n){if(typeof t!="string")throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!t)return[];n===null&&(n=Bu.instance);const r=Ir.parse(t),a=[];for(const s of r){const u=JSON.parse(s);if(typeof u.type!="number")throw new Error("Invalid payload.");switch(u.type){case Qe.Invocation:this._isInvocationMessage(u);break;case Qe.StreamItem:this._isStreamItemMessage(u);break;case Qe.Completion:this._isCompletionMessage(u);break;case Qe.Ping:break;case Qe.Close:break;case Qe.Ack:this._isAckMessage(u);break;case Qe.Sequence:this._isSequenceMessage(u);break;default:n.log(ue.Information,"Unknown message type '"+u.type+"' ignored.");continue}a.push(u)}return a}writeMessage(t){return Ir.write(JSON.stringify(t))}_isInvocationMessage(t){this._assertNotEmptyString(t.target,"Invalid payload for Invocation message."),t.invocationId!==void 0&&this._assertNotEmptyString(t.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(t){if(this._assertNotEmptyString(t.invocationId,"Invalid payload for StreamItem message."),t.item===void 0)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(t){if(t.result&&t.error)throw new Error("Invalid payload for Completion message.");!t.result&&t.error&&this._assertNotEmptyString(t.error,"Invalid payload for Completion message."),this._assertNotEmptyString(t.invocationId,"Invalid payload for Completion message.")}_isAckMessage(t){if(typeof t.sequenceId!="number")throw new Error("Invalid SequenceId for Ack message.")}_isSequenceMessage(t){if(typeof t.sequenceId!="number")throw new Error("Invalid SequenceId for Sequence message.")}_assertNotEmptyString(t,n){if(typeof t!="string"||t==="")throw new Error(n)}}const HU={trace:ue.Trace,debug:ue.Debug,info:ue.Information,information:ue.Information,warn:ue.Warning,warning:ue.Warning,error:ue.Error,critical:ue.Critical,none:ue.None};function VU(e){const t=HU[e.toLowerCase()];if(typeof t<"u")return t;throw new Error(`Unknown log level: ${e}`)}class FU{configureLogging(t){if(On.isRequired(t,"logging"),qU(t))this.logger=t;else if(typeof t=="string"){const n=VU(t);this.logger=new Dd(n)}else this.logger=new Dd(t);return this}withUrl(t,n){return On.isRequired(t,"url"),On.isNotEmpty(t,"url"),this.url=t,typeof n=="object"?this.httpConnectionOptions={...this.httpConnectionOptions,...n}:this.httpConnectionOptions={...this.httpConnectionOptions,transport:n},this}withHubProtocol(t){return On.isRequired(t,"protocol"),this.protocol=t,this}withAutomaticReconnect(t){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return t?Array.isArray(t)?this.reconnectPolicy=new C_(t):this.reconnectPolicy=t:this.reconnectPolicy=new C_,this}withServerTimeout(t){return On.isRequired(t,"milliseconds"),this._serverTimeoutInMilliseconds=t,this}withKeepAliveInterval(t){return On.isRequired(t,"milliseconds"),this._keepAliveIntervalInMilliseconds=t,this}withStatefulReconnect(t){return this.httpConnectionOptions===void 0&&(this.httpConnectionOptions={}),this.httpConnectionOptions._useStatefulReconnect=!0,this._statefulReconnectBufferSize=t?.bufferSize,this}build(){const t=this.httpConnectionOptions||{};if(t.logger===void 0&&(t.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const n=new PU(this.url,t);return sy.create(n,this.logger||Bu.instance,this.protocol||new jU,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}function qU(e){return e.log!==void 0}function GU({url:e,accessToken:t,autoStart:n=!0}){const r=I.useRef(null),a=I.useRef(new Map),s=I.useRef(null),u=I.useRef(0),f=I.useRef(!1),[d,p]=I.useState("disconnected"),[m,y]=I.useState(null),b=I.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),v=I.useCallback(()=>{if(f.current||s.current)return;u.current+=1;const k=u.current,z=Math.min(3e4,1e3*Math.pow(2,k-1)),H=Math.floor(Math.random()*500),j=z+H;s.current=setTimeout(()=>{s.current=null,_()},j)},[b]),E=I.useCallback(k=>{a.current.forEach((z,H)=>{k.off(H),z.forEach(j=>{k.on(H,j)})})},[]),S=I.useCallback(async()=>fg(),[]),w=I.useCallback(()=>{const k=new FU().withUrl(e,{accessTokenFactory:S}).withAutomaticReconnect({nextRetryDelayInMilliseconds:z=>z.elapsedMilliseconds<6e4?Math.random()*1e4:null}).build();return k.onreconnecting(()=>{b(),p("reconnecting")}),k.onreconnected(()=>{b(),u.current=0,p("connected"),E(k)}),k.onclose(z=>{p("disconnected"),z&&y(z),f.current||v()}),k},[e,S,E,b,v]),_=I.useCallback(async()=>{f.current=!1,b(),r.current||(r.current=w());const k=r.current;if(k.state===Pt.Connected){p("connected");return}if(k.state===Pt.Connecting){p("connecting");return}if(k.state===Pt.Reconnecting){p("reconnecting");return}p("connecting");try{await k.start(),E(k),u.current=0,p("connected"),y(null)}catch(z){y(z),p("disconnected"),v()}},[E,w,b,v]),O=I.useCallback(async()=>{f.current=!0,b(),u.current=0;const k=r.current;if(r.current=null,!k){p("disconnected");return}try{await k.stop()}finally{p("disconnected")}},[b]),T=I.useCallback((k,z)=>{let H=a.current.get(k);H||(H=new Set,a.current.set(k,H)),H.add(z);const j=r.current;j&&j.on(k,z)},[]),C=I.useCallback((k,z)=>{const H=a.current.get(k);if(!H)return;H.delete(z),H.size===0&&a.current.delete(k);const j=r.current;j&&j.off(k,z)},[]),N=I.useCallback(async(k,...z)=>{const H=r.current;if(!H||H.state!==Pt.Connected)throw new Error("SignalR not connected");return H.invoke(k,...z)},[]);return I.useEffect(()=>(n&&_(),()=>{O()}),[n,_,O]),{status:d,connected:d==="connected",error:m,start:_,stop:O,on:T,off:C,invoke:N}}async function YU(e,t,n){vu(e.apiBaseUrl+gd+"/"+e.clientId+"/messages/",{method:"GET",headers:{"Content-Type":"application/json","X-Conversation-Id":t}}).then(r=>{if(!r.ok)throw new Error("Request failed");return r.json()}).then(r=>{n(r.map(a=>a))}).catch(r=>{console.error(r)})}async function XU(e,t){const n=await vu(e.apiBaseUrl+gd+"/"+e.clientId+"/conversation-status/",{method:"GET",headers:{"Content-Type":"application/json","X-Conversation-Id":t}});return n.ok,await n.json()}async function ZU(e){return(await vu(e.apiBaseUrl+"/api/health/"+e.clientId,{method:"GET",headers:{"Content-Type":"application/json"}})).ok}async function KU(e,t){const n=await vu(e.apiBaseUrl+gd+"/"+e.clientId+"/client-activity-status",{method:"GET",headers:{"Content-Type":"application/json",...t?{"X-Conversation-Id":t}:{}}});return n.ok?n.body?await n.json():{isActive:!1,hideForUrls:[]}:{isActive:!1,hideForUrls:[]}}function uy(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""}function WU({config:e}){const{connected:t,start:n,on:r,off:a}=GU({url:e.apiBaseUrl+`/ws?sessionId=${Su()}&clientId=${e.clientId}`,autoStart:!1}),[s,u]=I.useState(!1),[f,d]=I.useState(""),[p,m]=I.useState(Su()),[y,b]=I.useState(),[v,E]=I.useState([]),[S,w]=I.useState(!1),[_,O]=I.useState(!1),[T,C]=I.useState(null),N=I.useMemo(()=>({position:"fixed",right:16,bottom:16,zIndex:2147483647,fontFamily:"system-ui"}),[]);I.useEffect(()=>{const $=window.location.pathname;e.hideChatForUrls?.some(U=>$.startsWith(U))?O(!0):O(!1)}),I.useEffect(()=>{s&&v.length==0&&YU(e,Su()||e.conversationId||"",$=>{const U=$.map(D=>({id:D.id,role:D.role,text:D.text,sentAt:uy(D.sentAt),seen:D.seen}));E(D=>[...U])}),s&&p&&(async()=>{const U=await XU(e,p);b(U)})()},[s]);function k($){E(U=>{const D=U[U.length-1];if(!D||D.role!=="assistant"||D.id!==$.id)return[...U,{id:$.id,role:$.role,text:$.text,sentAt:uy(new Date().toISOString()),seen:!1}];const Y=U.slice();return Y[Y.length-1]={...D,text:D.text+$.text},Y})}const z=($,U,D,Y)=>{if($)return U.find(ae=>ae.id===$);const re=D.trim();if(!(!re||Y))return{id:new Jn().toString(),role:"User",text:re,seen:!1,sentAt:uy(new Date().toISOString()),status:"sending",errorText:void 0}};async function H($,U=null){A(),w(!0);const D=z($,v,f,S);!$&&D!=null&&U==null&&(d(""),E(re=>[...re.map(B=>({...B,status:B.status==="failed"?"ignored":B.status})),D]));let Y;try{await BB({url:e.apiBaseUrl+gd+"/"+e.clientId+"/send-message/",token:e.sessionToken,clientId:e.clientId,conversationId:p,messageId:D?.id,body:D?.text||null,directiveForAgent:U,onDelta:re=>{k(re)},onRunStarted:re=>{m(re),PB(re)},onAgentEvent:re=>C(re)}),Y="sent"}catch{Y="failed"}finally{U==null&&E(re=>re.map(ae=>ae.id===D.id?{...ae,status:Y,errorText:"Eroare la trimitere."}:ae)),w(!1)}}const j=I.useCallback(($,U)=>{k({id:U.messageId,role:"assistant",text:U.text})},[]),G=I.useCallback($=>{E(U=>U.map(D=>D.id===$?{...D,seen:!0}:D))},[]),F=I.useCallback($=>{b($),console.log($)},[]),A=I.useCallback(()=>{(T?.value.kind==pi.OperationSuccess||T?.value.kind==pi.OperationError)&&C(null)},[T]);I.useEffect(()=>{T?.name==bu.AgentDirective&&T?.value.kind==kB.ReplayMessagePendingActionAfterVerification&&(C(null),H(void 0,T))},[T]),I.useEffect(()=>{p==""||p==null||n()},[p]),I.useEffect(()=>(r("ReceivedOperatorMessage",j),r("ReceivedSeenAtByOperator",G),r("RecievedConversationModeChanged",F),()=>{a("ReceivedOperatorMessage",j),a("ReceivedSeenAtByOperator",G),a("RecievedConversationModeChanged",F)}),[r,t,a]);const X=I.useCallback($=>p?t?$?.mode=="Bot"?"AI":$?.mode=="Human"?"Human":"AI":"Disconnected":"New",[p,t]);return _?L.jsx(L.Fragment,{}):L.jsx(uU,{anchorSx:N,open:s,setOpen:u,msgs:v,input:f,setInput:d,send:H,sending:S,conversationMode:X(y),directive:T,setDirective:C})}class QU extends HTMLElement{connectedCallback(){const t=yu();if(!t)return;const n=this.attachShadow({mode:"open"}),r=document.createElement("style");r.textContent=`
176
176
  :host { all: initial; }
177
177
  `,n.appendChild(r),this.mountEl=document.createElement("div"),n.appendChild(this.mountEl),jB();const a=F0({key:"chatbot",container:n}),s=ef();this.root=BA.createRoot(this.mountEl),this.root.render(L.jsx(Sk,{value:a,children:L.jsxs(cN,{theme:s,children:[L.jsx(TM,{}),L.jsx(WU,{config:t})]})}))}disconnectedCallback(){this.root?.unmount(),this.root=void 0}}function JU(){const e=document.currentScript;if(e)return e;const n=Array.from(document.getElementsByTagName("script")).filter(r=>(r.src||"").startsWith("http://localhost:5173/src/main.ts")||(r.src||"").includes("https://cdn.jsdelivr.net/npm/ss-support-widget"));return n.length?n[n.length-1]:null}const O_=JU(),R_=O_?.getAttribute("data-client-id")||"",ej=O_?.getAttribute("data-api-base-url")||"https://localhost:7352",zd=`chat-bot-${R_}`;customElements.get(zd)||customElements.define(zd,QU),(async function(){var t=yu();if(t||(t={clientId:R_,apiBaseUrl:ej,conversationId:void 0,userId:void 0,hideChatForUrls:void 0,sessionToken:null},AB(t)),document.querySelector(zd))return;var n=await ZU(t);if(!n)return;var r=await KU(t,Su());if(!r.isActive)return;t.hideChatForUrls=r.hideForUrls;const a=document.createElement(zd);document.body.appendChild(a)})()})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ss-chatbot-widget",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "Chatbot widget for customer support",
5
5
  "main": "./dist/x-bot-widget.js",
6
6
  "files": ["dist"],