ss-chatbot-widget 0.0.4 → 0.0.5

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.
@@ -166,7 +166,7 @@ Error: ${O}`)}}return d()}case fe.MESSAGES_SNAPSHOT:{let E=await tn(r,a,s,(_,w,O
166
166
  `});++r<e.length;)r&&n.push({type:"text",value:`
167
167
  `}),n.push(e[r]);return t&&e.length>0&&n.push({type:"text",value:`
168
168
  `}),n}function wE(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function CE(e,t){const n=iL(e,t),r=n.one(e,void 0),a=Yz(n),s=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&s.children.push({type:"text",value:`
169
- `},a),s}function uL(e,t){return e&&"run"in e?async function(n,r){const a=CE(n,{file:r,...t});await e.run(a,r)}:function(n,r){return CE(n,{file:r,...e||t})}}function TE(e){if(e)throw e}var Zm,AE;function cL(){if(AE)return Zm;AE=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=function(h){return typeof Array.isArray=="function"?Array.isArray(h):t.call(h)==="[object Array]"},s=function(h){if(!h||t.call(h)!=="[object Object]")return!1;var g=e.call(h,"constructor"),y=h.constructor&&h.constructor.prototype&&e.call(h.constructor.prototype,"isPrototypeOf");if(h.constructor&&!g&&!y)return!1;var b;for(b in h);return typeof b>"u"||e.call(h,b)},u=function(h,g){n&&g.name==="__proto__"?n(h,g.name,{enumerable:!0,configurable:!0,value:g.newValue,writable:!0}):h[g.name]=g.newValue},f=function(h,g){if(g==="__proto__")if(e.call(h,g)){if(r)return r(h,g).value}else return;return h[g]};return Zm=function d(){var h,g,y,b,v,x,E=arguments[0],_=1,w=arguments.length,O=!1;for(typeof E=="boolean"&&(O=E,E=arguments[1]||{},_=2),(E==null||typeof E!="object"&&typeof E!="function")&&(E={});_<w;++_)if(h=arguments[_],h!=null)for(g in h)y=f(E,g),b=f(h,g),E!==b&&(O&&b&&(s(b)||(v=a(b)))?(v?(v=!1,x=y&&a(y)?y:[]):x=y&&s(y)?y:{},u(E,{name:g,newValue:d(O,x,b)})):typeof b<"u"&&u(E,{name:g,newValue:b}));return E},Zm}var fL=cL();const Km=Ku(fL);function Wm(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function dL(){const e=[],t={run:n,use:r};return t;function n(...a){let s=-1;const u=a.pop();if(typeof u!="function")throw new TypeError("Expected function as last argument, not "+u);f(null,...a);function f(d,...h){const g=e[++s];let y=-1;if(d){u(d);return}for(;++y<a.length;)(h[y]===null||h[y]===void 0)&&(h[y]=a[y]);a=h,g?hL(g,f)(...h):u(null,...h)}}function r(a){if(typeof a!="function")throw new TypeError("Expected `middelware` to be a function, not "+a);return e.push(a),t}}function hL(e,t){let n;return r;function r(...u){const f=e.length>u.length;let d;f&&u.push(a);try{d=e.apply(this,u)}catch(h){const g=h;if(f&&n)throw g;return a(g)}f||(d&&d.then&&typeof d.then=="function"?d.then(s,a):d instanceof Error?a(d):s(d))}function a(u,...f){n||(n=!0,t(u,...f))}function s(u){a(null,u)}}const Ti={basename:pL,dirname:mL,extname:gL,join:yL,sep:"/"};function pL(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Ql(e);let n=0,r=-1,a=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(s){n=a+1;break}}else r<0&&(s=!0,r=a+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let u=-1,f=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(s){n=a+1;break}}else u<0&&(s=!0,u=a+1),f>-1&&(e.codePointAt(a)===t.codePointAt(f--)?f<0&&(r=a):(f=-1,r=u));return n===r?r=u:r<0&&(r=e.length),e.slice(n,r)}function mL(e){if(Ql(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function gL(e){Ql(e);let t=e.length,n=-1,r=0,a=-1,s=0,u;for(;t--;){const f=e.codePointAt(t);if(f===47){if(u){r=t+1;break}continue}n<0&&(u=!0,n=t+1),f===46?a<0?a=t:s!==1&&(s=1):a>-1&&(s=-1)}return a<0||n<0||s===0||s===1&&a===n-1&&a===r+1?"":e.slice(a,n)}function yL(...e){let t=-1,n;for(;++t<e.length;)Ql(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":vL(n)}function vL(e){Ql(e);const t=e.codePointAt(0)===47;let n=bL(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function bL(e,t){let n="",r=0,a=-1,s=0,u=-1,f,d;for(;++u<=e.length;){if(u<e.length)f=e.codePointAt(u);else{if(f===47)break;f=47}if(f===47){if(!(a===u-1||s===1))if(a!==u-1&&s===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(d=n.lastIndexOf("/"),d!==n.length-1){d<0?(n="",r=0):(n=n.slice(0,d),r=n.length-1-n.lastIndexOf("/")),a=u,s=0;continue}}else if(n.length>0){n="",r=0,a=u,s=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(a+1,u):n=e.slice(a+1,u),r=u-a-1;a=u,s=0}else f===46&&s>-1?s++:s=-1}return n}function Ql(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const SL={cwd:xL};function xL(){return"/"}function Qm(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function EL(e){if(typeof e=="string")e=new URL(e);else if(!Qm(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return _L(e)}function _L(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const a=new TypeError("File URL path must not include encoded / characters");throw a.code="ERR_INVALID_FILE_URL_PATH",a}}return decodeURIComponent(t)}const Jm=["history","path","basename","stem","extname","dirname"];class kE{constructor(t){let n;t?Qm(t)?n={path:t}:typeof t=="string"||wL(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":SL.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Jm.length;){const s=Jm[r];s in n&&n[s]!==void 0&&n[s]!==null&&(this[s]=s==="history"?[...n[s]]:n[s])}let a;for(a in n)Jm.includes(a)||(this[a]=n[a])}get basename(){return typeof this.path=="string"?Ti.basename(this.path):void 0}set basename(t){tg(t,"basename"),eg(t,"basename"),this.path=Ti.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Ti.dirname(this.path):void 0}set dirname(t){RE(this.basename,"dirname"),this.path=Ti.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Ti.extname(this.path):void 0}set extname(t){if(eg(t,"extname"),RE(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Ti.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Qm(t)&&(t=EL(t)),tg(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?Ti.basename(this.path,this.extname):void 0}set stem(t){tg(t,"stem"),eg(t,"stem"),this.path=Ti.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const a=this.message(t,n,r);throw a.fatal=!0,a}info(t,n,r){const a=this.message(t,n,r);return a.fatal=void 0,a}message(t,n,r){const a=new Kn(t,n,r);return this.path&&(a.name=this.path+":"+a.name,a.file=this.path),a.fatal=!1,this.messages.push(a),a}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function eg(e,t){if(e&&e.includes(Ti.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Ti.sep+"`")}function tg(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function RE(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function wL(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const CL=(function(e){const r=this.constructor.prototype,a=r[e],s=function(){return a.apply(s,arguments)};return Object.setPrototypeOf(s,r),s}),TL={}.hasOwnProperty;class ng extends CL{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=dL()}copy(){const t=new ng;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(Km(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(og("data",this.frozen),this.namespace[t]=n,this):TL.call(this.namespace,t)&&this.namespace[t]||void 0:t?(og("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const a=n.call(t,...r);typeof a=="function"&&this.transformers.use(a)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=qf(t),r=this.parser||this.Parser;return rg("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),rg("process",this.parser||this.Parser),ig("process",this.compiler||this.Compiler),n?a(void 0,n):new Promise(a);function a(s,u){const f=qf(t),d=r.parse(f);r.run(d,f,function(g,y,b){if(g||!y||!b)return h(g);const v=y,x=r.stringify(v,b);RL(x)?b.value=x:b.result=x,h(g,b)});function h(g,y){g||!y?u(g):s?s(y):n(void 0,y)}}}processSync(t){let n=!1,r;return this.freeze(),rg("processSync",this.parser||this.Parser),ig("processSync",this.compiler||this.Compiler),this.process(t,a),NE("processSync","process",n),r;function a(s,u){n=!0,TE(s),r=u}}run(t,n,r){OE(t),this.freeze();const a=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?s(void 0,r):new Promise(s);function s(u,f){const d=qf(n);a.run(t,d,h);function h(g,y,b){const v=y||t;g?f(g):u?u(v):r(void 0,v,b)}}}runSync(t,n){let r=!1,a;return this.run(t,n,s),NE("runSync","run",r),a;function s(u,f){TE(u),a=f,r=!0}}stringify(t,n){this.freeze();const r=qf(n),a=this.compiler||this.Compiler;return ig("stringify",a),OE(t),a(t,r)}use(t,...n){const r=this.attachers,a=this.namespace;if(og("use",this.frozen),t!=null)if(typeof t=="function")d(t,n);else if(typeof t=="object")Array.isArray(t)?f(t):u(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function s(h){if(typeof h=="function")d(h,[]);else if(typeof h=="object")if(Array.isArray(h)){const[g,...y]=h;d(g,y)}else u(h);else throw new TypeError("Expected usable value, not `"+h+"`")}function u(h){if(!("plugins"in h)&&!("settings"in h))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");f(h.plugins),h.settings&&(a.settings=Km(!0,a.settings,h.settings))}function f(h){let g=-1;if(h!=null)if(Array.isArray(h))for(;++g<h.length;){const y=h[g];s(y)}else throw new TypeError("Expected a list of plugins, not `"+h+"`")}function d(h,g){let y=-1,b=-1;for(;++y<r.length;)if(r[y][0]===h){b=y;break}if(b===-1)r.push([h,...g]);else if(g.length>0){let[v,...x]=g;const E=r[b][1];Wm(E)&&Wm(v)&&(v=Km(!0,E,v)),r[b]=[h,v,...x]}}}}const AL=new ng().freeze();function rg(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function ig(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function og(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function OE(e){if(!Wm(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function NE(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function qf(e){return kL(e)?e:new kE(e)}function kL(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function RL(e){return typeof e=="string"||OL(e)}function OL(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const NL="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",IE=[],ME={allowDangerousHtml:!0},IL=/^(https?|ircs?|mailto|xmpp)$/i,ML=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function DL(e){const t=BL(e),n=zL(e);return LL(t.runSync(t.parse(n),n),e)}function BL(e){const t=e.rehypePlugins||IE,n=e.remarkPlugins||IE,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...ME}:ME;return AL().use(pz).use(n).use(uL,r).use(t)}function zL(e){const t=e.children||"",n=new kE;return typeof t=="string"&&(n.value=t),n}function LL(e,t){const n=t.allowedElements,r=t.allowElement,a=t.components,s=t.disallowedElements,u=t.skipHtml,f=t.unwrapDisallowed,d=t.urlTransform||$L;for(const g of ML)Object.hasOwn(t,g.from)&&(""+g.from+(g.to?"use `"+g.to+"` instead":"remove it")+NL+g.id,void 0);return _E(e,h),nD(e,{Fragment:L.Fragment,components:a,ignoreInvalidStyle:!0,jsx:L.jsx,jsxs:L.jsxs,passKeys:!0,passNode:!0});function h(g,y,b){if(g.type==="raw"&&b&&typeof y=="number")return u?b.children.splice(y,1):b.children[y]={type:"text",value:g.value},y;if(g.type==="element"){let v;for(v in Bm)if(Object.hasOwn(Bm,v)&&Object.hasOwn(g.properties,v)){const x=g.properties[v],E=Bm[v];(E===null||E.includes(g.tagName))&&(g.properties[v]=d(String(x||""),v,g))}}if(g.type==="element"){let v=n?!n.includes(g.tagName):s?s.includes(g.tagName):!1;if(!v&&r&&typeof y=="number"&&(v=!r(g,y,b)),v&&b&&typeof y=="number")return f&&g.children?b.children.splice(y,1,...g.children):b.children.splice(y,1),y}}}function $L(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||n!==-1&&t>n||r!==-1&&t>r||IL.test(e.slice(0,t))?e:""}function PL({msg:e,isMe:t,showSeenIndicator:n,isSeen:r,send:a}){return L.jsxs(En,{sx:{maxWidth:"78%"},children:[L.jsx(En,{sx:{wordBreak:"break-word",position:"relative",px:1.4,py:1.05,borderRadius:3,border:"1px solid",borderColor:"divider",bgcolor:t?"primary.main":"background.paper",color:t?"primary.contrastText":"text.primary",boxShadow:t?"0 10px 30px rgba(25,118,210,.22)":"0 10px 30px rgba(0,0,0,.10)",whiteSpace:"normal","&:before":{content:'""',position:"absolute",top:14,width:10,height:10,transform:"rotate(45deg)",bgcolor:t?"primary.main":"background.paper",borderLeft:t?"none":"0px solid",borderTop:t?"none":"0px solid",borderColor:"divider",right:t?-5:"auto",left:t?"auto":-5},"& p":{margin:0,lineHeight:1.35},"& p + p":{marginTop:"6px"},"& ol, & ul":{margin:"6px 0",paddingLeft:"20px"},"& li":{margin:"2px 0"},"& li > p":{margin:0},"& a":{color:"inherit",textDecoration:"underline"},"& code":{fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"0.9em",padding:"2px 6px",borderRadius:8,backgroundColor:t?"rgba(255,255,255,.14)":"rgba(0,0,0,.06)"},"& pre":{margin:0,marginTop:8,padding:12,overflow:"auto",borderRadius:12,backgroundColor:t?"rgba(255,255,255,.12)":"rgba(0,0,0,.05)"}},children:L.jsx(DL,{children:e.text},"message"+e.id)}),n?L.jsx(ti,{sx:{mt:.35,fontSize:12,textAlign:"right",color:r?"text.secondary":"text.disabled"},children:r?"Seen":"Sent"}):null,e.status==="failed"?L.jsxs(En,{sx:{mt:.1,display:"flex",gap:1,alignItems:"center"},children:[L.jsx(ti,{variant:"caption",color:"error",children:e.errorText}),L.jsx(Cl,{sx:{p:0},size:"small",color:"primary",onClick:()=>a({id:e.id,role:"user",content:e.text}),children:L.jsx(w6,{sx:{fontSize:18}})})]}):null]},"container"+e.id)}function UL({msg:e,isMe:t}){return L.jsxs(En,{children:[L.jsx(Pc,{sx:{width:30,height:30,mt:.25,bgcolor:"primary.main"},children:L.jsx(Em,{sx:{fontSize:18}})}),e.sentAt&&L.jsx(En,{sx:{display:"flex",justifyContent:t?"flex-end":"flex-start",mt:.5},children:L.jsx(ti,{variant:"caption",sx:{color:"text.secondary",fontSize:11},children:e.sentAt})})]},"asistent"+e.id)}function jL({msg:e,isMe:t}){return L.jsxs(En,{children:[L.jsx(Pc,{sx:{width:30,height:30,mt:.25,bgcolor:"grey.900"},children:L.jsx(_6,{sx:{fontSize:18}})}),e.sentAt&&L.jsx(En,{sx:{display:"flex",justifyContent:t?"flex-end":"flex-start",mt:.5},children:L.jsx(ti,{variant:"caption",sx:{color:"text.secondary",fontSize:11},children:e.sentAt})})]},"sentAt"+e.id)}const HL=Jn.memo(function({msgs:t,isMessageSeen:n,endRef:r,reSend:a}){return L.jsxs(L.Fragment,{children:[t.map((s,u)=>{const f=s.role==="User",{showSeenIndicator:d,isSeen:h}=n(u,f,t,s);return L.jsxs(En,{sx:{display:"flex",justifyContent:f?"flex-end":"flex-start",gap:1,mb:1.2,overflowAnchor:"none"},children:[!f&&L.jsx(UL,{msg:s,isMe:f}),L.jsx(PL,{msg:s,isMe:f,showSeenIndicator:d,isSeen:h,send:a}),f&&L.jsx(jL,{msg:s,isMe:f})]},s.id)}),L.jsx("div",{ref:r})]})});function VL(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}function FL(e){return/^[0-9]{6}$/.test(e)}const GL=async e=>{const t=da(),n=vo();if(n==null)throw new Error("Missing config");if(t==null)throw new Error("Conversation id is missing");const r=await fa(n.apiBaseUrl+ax+`/${n.clientId}/start`,{method:"POST",headers:{"Content-Type":"application/json","X-Conversation-Id":t},body:JSON.stringify(e)});if(!r.ok)throw new Error("Somethig happend on the request");return await r.json()},qL=async e=>{const t=da(),n=vo();if(n==null)throw new Error("Missing config");if(t==null)throw new Error("Conversation id is missing");const r=await fa(n.apiBaseUrl+ax+`/${n.clientId}/confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Conversation-Id":t},body:JSON.stringify(e)});if(!r.ok)throw new Error("Somethig happend on the request");return await r.json()},YL=({request:e,onValidationSuccess:t})=>{const[n,r]=N.useState(""),[a,s]=N.useState(""),[u,f]=N.useState(!0),d=g=>{if(!FL(n)){f(!1);return}qL({requestId:e?.requestId||"",code:n}).then(y=>{if(y.verified){t();return}s(y.failureReason)})},h=()=>a||null;return L.jsxs(Fc,{spacing:1,sx:{position:"relative",p:2,bgcolor:"background.paper",borderRadius:2,boxShadow:"0 4px 12px rgba(0,0,0,.1)",maxWidth:380,mb:2,display:"flex",flexDirection:"column",alignItems:"center"},children:[L.jsxs(ti,{variant:"body1",align:"center",gutterBottom:!0,sx:{wordBreak:"break-word"},children:["Introdu codul primit la ",e?.contact]}),L.jsx(Ip,{focused:!0,fullWidth:!0,size:"small",value:n,onChange:g=>{r(g.target.value),f(!0)},error:h()!=null,helperText:h()}),L.jsx(Uc,{variant:"outlined",color:"primary",onClick:d,children:"Trimite codul"})]})},XL=({setRequest:e,setDisplayOtpForm:t})=>{const[n,r]=N.useState(""),[a,s]=N.useState(!0),u=async f=>{if(!VL(n)){s(!1);return}GL({channel:"email",value:n}).then(d=>{e(d),t(!0)})};return L.jsxs(Fc,{spacing:1,sx:{position:"relative",p:2,bgcolor:"background.paper",borderRadius:2,boxShadow:"0 4px 12px rgba(0,0,0,.1)",maxWidth:380,mb:2,display:"flex",flexDirection:"column",alignItems:"center"},children:[L.jsx(ti,{variant:"h6",gutterBottom:!0,children:"Introdu adresa de email"}),L.jsx(Ip,{focused:!0,fullWidth:!0,size:"small",value:n,onChange:f=>{r(f.target.value),s(!0)},error:!a,helperText:a?void 0:"Adresa de email nu este validă"}),L.jsx(Uc,{variant:"outlined",color:"primary",onClick:u,children:"Trimite"}),L.jsx(ti,{variant:"body2",color:"text.secondary",children:"Vom trimite un cod de verificare la aceasta."})]})},ZL=({verificationRequest:e,send:t,setToolCallEvents:n})=>{const[r,a]=N.useState(!1),[s,u]=N.useState(),f=N.useCallback(()=>{const d=e.delta;t({role:"tool",toolCallId:e.toolCallId,content:JSON.stringify({approval_id:d.request.approval_id,approved:!0}),id:""})},[]);return L.jsx(L.Fragment,{children:r?L.jsx(YL,{request:s,onValidationSuccess:f}):L.jsx(XL,{setDisplayOtpForm:a,setRequest:u})})},KL="request_verification",WL=({toolCallEvents:e,setToolCallEvents:t,send:n})=>{const[r,a]=N.useState("email");if(!e)return null;const s=e.filter(u=>u.toolCallName==KL)[0];return s&&r==="email"?L.jsx(ZL,{verificationRequest:s,send:n,setToolCallEvents:t}):null},QL=()=>L.jsxs(En,{sx:{display:"flex",alignItems:"flex-end",gap:1,mb:1.2},children:[L.jsx(Pc,{sx:{width:30,height:30,bgcolor:"primary.main"},children:L.jsx(Em,{sx:{fontSize:18}})}),L.jsxs(En,{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(En,{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(En,{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(En,{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}}}})]})]}),JL={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 e$({msgs:e,isMessageSeen:t,send:n,sending:r,items:a,endRef:s,toolCallEvents:u,setToolCallEvents:f}){return L.jsxs(En,{sx:JL,children:[L.jsx(HL,{msgs:e,isMessageSeen:t,reSend:n}),L.jsx("div",{style:{paddingBottom:2},children:r&&L.jsx(QL,{})}),a.map(d=>L.jsx(E6,{error:d.message,onClose:()=>Bf.getState().remove(d.id)},d.id)),L.jsx(WL,{toolCallEvents:u,setToolCallEvents:f,send:n}),L.jsx(iI,{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 t$({inputRef:e,input:t,sending:n,setInput:r,send:a}){return L.jsx(En,{sx:{p:1.25,borderTop:"1px solid",borderColor:"divider",display:"flex",gap:1,bgcolor:"background.paper",flexShrink:0},children:L.jsx(Ip,{inputRef:e,focused:!0,size:"small",fullWidth:!0,value:t,disabled:n||t.length>=Q5,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(Cl,{size:"small",onClick:()=>a(),disabled:n||!t.trim(),sx:{ml:.5,borderRadius:999},children:L.jsx(C6,{})})}})})}const n$=async e=>{const t=da(),n=vo();if(n==null)throw new Error("Missing config");if(t==null)throw new Error("Conversation id is missing");await fa(n.apiBaseUrl+Hl+`/${n.clientId}/conversation-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Conversation-Id":t},body:JSON.stringify(e)})};function r$({open:e,setOpen:t,msgs:n,input:r,setInput:a,sending:s,send:u,anchorSx:f,conversationMode:d,setConversationStatus:h,toolCallEvents:g,setToolCallEvents:y}){const b=Bf(O=>O.items),v=N.useRef(null),x=N.useRef(null),E=_l(),_=ZI(E.breakpoints.down("md"));b6(),N.useEffect(()=>{x.current?.scrollIntoView({behavior:"smooth",block:"end"}),requestAnimationFrame(()=>v.current?.focus())},[n.length,s]),N.useEffect(()=>{e&&x.current?.scrollIntoView({behavior:"auto",block:"end"})},[e]),N.useEffect(()=>{if(!(e&&_))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,_]);const w=N.useCallback((O,T,A,M)=>{const R=O===A.length-1,$=A[A.length-1],H=R&&T&&$?.seen,V=H&&$?.id===M.id;return{showSeenIndicator:H,isSeen:V}},[]);return L.jsxs(En,{sx:f,children:[!e&&L.jsx(Uc,{variant:"contained",onClick:()=>t(!0),startIcon:L.jsx(y6,{}),sx:{borderRadius:999,px:2,py:1,textTransform:"none",boxShadow:"0 10px 30px rgba(0,0,0,.18)"},children:"Chat"}),e&&L.jsx(Rc,{elevation:_?0:10,sx:{width:_?"100vw":380,height:_?"calc(var(--vh, 1vh) * 100)":560,"@supports (height: 100dvh)":{height:_?"100dvh":560},maxWidth:"100vw",maxHeight:"100dvh",borderRadius:_?0:4,position:_?"fixed":"relative",inset:_?0:"auto",overflow:"hidden",border:_?"none":"1px solid",borderColor:"divider",boxShadow:_?"none":"0 18px 60px rgba(0,0,0,.28)"},children:L.jsxs(En,{sx:{display:"flex",flexDirection:"column",height:"100%"},children:[L.jsx(x6,{isMobile:_,conversationMode:d,setOpen:t}),L.jsx(e$,{msgs:n,isMessageSeen:w,send:u,sending:s,items:b,endRef:x,toolCallEvents:g,setToolCallEvents:y}),d==="Human"&&L.jsx(i$,{conversationMode:d,setConversationStatus:h}),L.jsx(t$,{inputRef:v,input:r,sending:s,setInput:a,send:u})]})})]})}const i$=({conversationMode:e,setConversationStatus:t})=>L.jsx(Rc,{elevation:0,sx:{mx:2,mt:1.5,mb:1,px:2,py:1.5,border:"1px solid",borderColor:"divider",borderRadius:3,bgcolor:"background.paper",boxShadow:"0 6px 18px rgba(15, 23, 42, 0.04)"},children:L.jsxs(Fc,{direction:{xs:"column",sm:"row"},spacing:1.5,alignItems:{xs:"center",sm:"flex-start"},justifyContent:"space-between",children:[L.jsxs(Fc,{direction:"row",spacing:1,alignItems:"center",flexWrap:"wrap",children:[L.jsx(vN,{size:"small",icon:e==="Human"?L.jsx(A6,{}):L.jsx(T6,{}),label:e==="Human"?"Operator activ":"Asistent activ",color:e==="Human"?"warning":"success",variant:"outlined",sx:{height:28,borderRadius:2,"& .MuiChip-label":{px:1.25,fontWeight:600}}}),L.jsx(ti,{variant:"body2",color:"text.secondary",children:e==="Human"?"Puteți reveni oricând la asistentul virtual.":"Asistentul răspunde automat mesajelor."})]}),e==="Human"&&L.jsx(Uc,{variant:"contained",size:"small",onClick:async()=>{await n$("Bot"),t({mode:"Bot",state:"AI_ACTIVE"})},sx:{px:2.5,py:1.1,borderRadius:2.5,textTransform:"none",fontWeight:700,boxShadow:"0 8px 24px rgba(25, 118, 210, 0.18)","&:hover":{boxShadow:"0 10px 28px rgba(25, 118, 210, 0.24)"}},children:"Revino la asistentul virtual"})]})});class pa extends Error{constructor(t,n){const r=new.target.prototype;super(`${t}: Status code '${n}'`),this.statusCode=n,this.__proto__=r}}class ag extends Error{constructor(t="A timeout occurred."){const n=new.target.prototype;super(t),this.__proto__=n}}class ni extends Error{constructor(t="An abort occurred."){const n=new.target.prototype;super(t),this.__proto__=n}}class o$ extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.transport=n,this.errorType="UnsupportedTransportError",this.__proto__=r}}class a$ extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.transport=n,this.errorType="DisabledTransportError",this.__proto__=r}}class s$ extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.transport=n,this.errorType="FailedToStartTransportError",this.__proto__=r}}class DE extends Error{constructor(t){const n=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=n}}class l$ extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.innerErrors=n,this.__proto__=r}}class BE{constructor(t,n,r){this.statusCode=t,this.statusText=n,this.content=r}}class Yf{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 ae;(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"})(ae||(ae={}));class Jl{constructor(){}log(t,n){}}Jl.instance=new Jl;const u$="10.0.0";class Cn{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 nn{static get isBrowser(){return!nn.isNode&&typeof window=="object"&&typeof window.document=="object"}static get isWebWorker(){return!nn.isNode&&typeof self=="object"&&"importScripts"in self}static get isReactNative(){return!nn.isNode&&typeof window=="object"&&typeof window.document>"u"}static get isNode(){return typeof process<"u"&&process.release&&process.release.name==="node"}}function eu(e,t){let n="";return ma(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${c$(e)}'`)):typeof e=="string"&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function c$(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 zE(e,t,n,r,a,s){const u={},[f,d]=hs();u[f]=d,e.log(ae.Trace,`(${t} transport) sending data. ${eu(a,s.logMessageContent)}.`);const h=ma(a)?"arraybuffer":"text",g=await n.post(r,{content:a,headers:{...u,...s.headers},responseType:h,timeout:s.timeout,withCredentials:s.withCredentials});e.log(ae.Trace,`(${t} transport) request complete. Response status: ${g.statusCode}.`)}function f$(e){return e===void 0?new Xf(ae.Information):e===null?Jl.instance:e.log!==void 0?e:new Xf(e)}class d${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 Xf{constructor(t){this._minLevel=t,this.out=console}log(t,n){if(t>=this._minLevel){const r=`[${new Date().toISOString()}] ${ae[t]}: ${n}`;switch(t){case ae.Critical:case ae.Error:this.out.error(r);break;case ae.Warning:this.out.warn(r);break;case ae.Information:this.out.info(r);break;default:this.out.log(r);break}}}}function hs(){let e="X-SignalR-User-Agent";return nn.isNode&&(e="User-Agent"),[e,h$(u$,p$(),g$(),m$())]}function h$(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 p$(){if(nn.isNode)switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}else return""}function m$(){if(nn.isNode)return process.versions.node}function g$(){return nn.isNode?"NodeJS":"Browser"}function sg(e){return e.stack?e.stack:e.message?e.message:`${e}`}function y$(){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 v$ extends Yf{constructor(t){if(super(),this._logger=t,typeof fetch>"u"||nn.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(y$());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 ni;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 ni});let a=null;if(t.timeout){const d=t.timeout;a=setTimeout(()=>{n.abort(),this._logger.log(ae.Warning,"Timeout from HTTP request."),r=new ag},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(ae.Warning,`Error from HTTP request. ${d}.`),d)}finally{a&&clearTimeout(a),t.abortSignal&&(t.abortSignal.onabort=null)}if(!s.ok){const d=await LE(s,"text");throw new pa(d||s.statusText,s.status)}const f=await LE(s,t.responseType);return new BE(s.status,s.statusText,f)}getCookieString(t){let n="";return nn.isNode&&this._jar&&this._jar.getCookies(t,(r,a)=>n=a.join("; ")),n}}function LE(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 b$ extends Yf{constructor(t){super(),this._logger=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new ni):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 ni)}),t.timeout&&(a.timeout=t.timeout),a.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),a.status>=200&&a.status<300?n(new BE(a.status,a.statusText,a.response||a.responseText)):r(new pa(a.response||a.responseText||a.statusText,a.status))},a.onerror=()=>{this._logger.log(ae.Warning,`Error from HTTP request. ${a.status}: ${a.statusText}.`),r(new pa(a.statusText,a.status))},a.ontimeout=()=>{this._logger.log(ae.Warning,"Timeout from HTTP request."),r(new ag)},a.send(t.content)}):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class S$ extends Yf{constructor(t){if(super(),typeof fetch<"u"||nn.isNode)this._httpClient=new v$(t);else if(typeof XMLHttpRequest<"u")this._httpClient=new b$(t);else throw new Error("No usable HttpClient found.")}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new ni):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 Er{static write(t){return`${t}${Er.RecordSeparator}`}static parse(t){if(t[t.length-1]!==Er.RecordSeparator)throw new Error("Message is incomplete.");const n=t.split(Er.RecordSeparator);return n.pop(),n}}Er.RecordSeparatorCode=30,Er.RecordSeparator=String.fromCharCode(Er.RecordSeparatorCode);class x${writeHandshakeRequest(t){return Er.write(JSON.stringify(t))}parseHandshakeResponse(t){let n,r;if(ma(t)){const f=new Uint8Array(t),d=f.indexOf(Er.RecordSeparatorCode);if(d===-1)throw new Error("Message is incomplete.");const h=d+1;n=String.fromCharCode.apply(null,Array.prototype.slice.call(f.slice(0,h))),r=f.byteLength>h?f.slice(h).buffer:null}else{const f=t,d=f.indexOf(Er.RecordSeparator);if(d===-1)throw new Error("Message is incomplete.");const h=d+1;n=f.substring(0,h),r=f.length>h?f.substring(h):null}const a=Er.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 E${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 d$(this,t)}}class _${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 w$(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 w${constructor(t,n,r,a){this._message=t,this._id=n,this._resolver=r,this._rejector=a}}const C$=30*1e3,T$=15*1e3,A$=1e5;var Nt;(function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"})(Nt||(Nt={}));class lg{static create(t,n,r,a,s,u,f){return new lg(t,n,r,a,s,u,f)}constructor(t,n,r,a,s,u,f){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(ae.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")},Cn.isRequired(t,"connection"),Cn.isRequired(n,"logger"),Cn.isRequired(r,"protocol"),this.serverTimeoutInMilliseconds=s??C$,this.keepAliveIntervalInMilliseconds=u??T$,this._statefulReconnectBufferSize=f??A$,this._logger=n,this._protocol=r,this.connection=t,this._reconnectPolicy=a,this._handshakeProtocol=new x$,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=Nt.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!==Nt.Disconnected&&this._connectionState!==Nt.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!==Nt.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=Nt.Connecting,this._logger.log(ae.Debug,"Starting HubConnection.");try{await this._startInternal(),nn.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=Nt.Connected,this._connectionStarted=!0,this._logger.log(ae.Debug,"HubConnection connected successfully.")}catch(t){return this._connectionState=Nt.Disconnected,this._logger.log(ae.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(ae.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(r)),this._logger.log(ae.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 _$(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(ae.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===Nt.Disconnected)return this._logger.log(ae.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===Nt.Disconnecting)return this._logger.log(ae.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=Nt.Disconnecting,this._logger.log(ae.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(ae.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(n===Nt.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=t||new ni("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 E$;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,h)=>{if(h){f.error(h);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]=(g,y)=>{if(y){d(y);return}else g&&(g.type===qe.Completion?g.error?d(new Error(g.error)):f(g.result):d(new Error(`Unexpected message type: ${g.type}`)))};const h=this._sendWithProtocol(s).catch(g=>{d(g),delete this._callbacks[s.invocationId]});this._launchStreams(r,h)})}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(ae.Error,`Invoke client method threw error: ${sg(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(ae.Error,`Stream callback threw error: ${sg(s)}`)}}break}case qe.Ping:break;case qe.Close:{this._logger.log(ae.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(ae.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(ae.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(ae.Error,a);const s=new Error(a);throw this._handshakeRejecter(s),s}else this._logger.log(ae.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===Nt.Connected&&this._trySendPingMessage();return}this._pingServerHandle===void 0&&(t<0&&(t=0),this._pingServerHandle=setTimeout(async()=>{this._connectionState===Nt.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(ae.Warning,`No client method with the name '${n}' found.`),t.invocationId&&(this._logger.log(ae.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 h of a)try{const g=u;u=await h.apply(this,t.arguments),s&&u&&g&&(this._logger.log(ae.Error,`Multiple results provided for '${n}'. Sending error to server.`),d=this._createCompletionMessage(t.invocationId,"Client provided multiple results.",null)),f=void 0}catch(g){f=g,this._logger.log(ae.Error,`A callback for the method '${n}' threw error '${g}'.`)}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(ae.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(ae.Error,`Result given for '${n}' method but server is not expecting a result.`)}_connectionClosed(t){this._logger.log(ae.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||t||new ni("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===Nt.Disconnecting?this._completeClose(t):this._connectionState===Nt.Connected&&this._reconnectPolicy?this._reconnect(t):this._connectionState===Nt.Connected&&this._completeClose(t)}_completeClose(t){if(this._connectionStarted){this._connectionState=Nt.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(t??new Error("Connection closed.")),this._messageBuffer=void 0),nn.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach(n=>n.apply(this,[t]))}catch(n){this._logger.log(ae.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(ae.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),this._completeClose(t);return}if(this._connectionState=Nt.Reconnecting,t?this._logger.log(ae.Information,`Connection reconnecting because of error '${t}'.`):this._logger.log(ae.Information,"Connection reconnecting."),this._reconnectingCallbacks.length!==0){try{this._reconnectingCallbacks.forEach(u=>u.apply(this,[t]))}catch(u){this._logger.log(ae.Error,`An onreconnecting callback called with error '${t}' threw error '${u}'.`)}if(this._connectionState!==Nt.Reconnecting){this._logger.log(ae.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");return}}for(;s!==null;){if(this._logger.log(ae.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!==Nt.Reconnecting){this._logger.log(ae.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");return}try{if(await this._startInternal(),this._connectionState=Nt.Connected,this._logger.log(ae.Information,"HubConnection reconnected successfully."),this._reconnectedCallbacks.length!==0)try{this._reconnectedCallbacks.forEach(u=>u.apply(this,[this.connection.connectionId]))}catch(u){this._logger.log(ae.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${u}'.`)}return}catch(u){if(this._logger.log(ae.Information,`Reconnect attempt failed because of error '${u}'.`),this._connectionState!==Nt.Reconnecting){this._logger.log(ae.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),this._connectionState===Nt.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(ae.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(ae.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(ae.Error,`Stream 'error' callback called with '${t}' threw error: ${sg(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 k$=[0,2e3,1e4,3e4,null];class $E{constructor(t){this._retryDelays=t!==void 0?[...t,null]:k$}nextRetryDelayInMilliseconds(t){return this._retryDelays[t.previousRetryCount]}}class ga{}ga.Authorization="Authorization",ga.Cookie="Cookie";class R$ extends Yf{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[ga.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&t.headers[ga.Authorization]&&delete t.headers[ga.Authorization]}getCookieString(t){return this._innerClient.getCookieString(t)}}var Nn;(function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"})(Nn||(Nn={}));var Wn;(function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"})(Wn||(Wn={}));let O$=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 PE{get pollAborted(){return this._pollAbort.aborted}constructor(t,n,r){this._httpClient=t,this._logger=n,this._pollAbort=new O$,this._options=r,this._running=!1,this.onreceive=null,this.onclose=null}async connect(t,n){if(Cn.isRequired(t,"url"),Cn.isRequired(n,"transferFormat"),Cn.isIn(n,Wn,"transferFormat"),this._url=t,this._logger.log(ae.Trace,"(LongPolling transport) Connecting."),n===Wn.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]=hs(),s={[r]:a,...this._options.headers},u={abortSignal:this._pollAbort.signal,headers:s,timeout:1e5,withCredentials:this._options.withCredentials};n===Wn.Binary&&(u.responseType="arraybuffer");const f=`${t}&_=${Date.now()}`;this._logger.log(ae.Trace,`(LongPolling transport) polling: ${f}.`);const d=await this._httpClient.get(f,u);d.statusCode!==200?(this._logger.log(ae.Error,`(LongPolling transport) Unexpected response code: ${d.statusCode}.`),this._closeError=new pa(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(ae.Trace,`(LongPolling transport) polling: ${r}.`);const a=await this._httpClient.get(r,n);a.statusCode===204?(this._logger.log(ae.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):a.statusCode!==200?(this._logger.log(ae.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new pa(a.statusText||"",a.statusCode),this._running=!1):a.content?(this._logger.log(ae.Trace,`(LongPolling transport) data received. ${eu(a.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(a.content)):this._logger.log(ae.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(r){this._running?r instanceof ag?this._logger.log(ae.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=r,this._running=!1):this._logger.log(ae.Trace,`(LongPolling transport) Poll errored after shutdown: ${r.message}`)}}finally{this._logger.log(ae.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(t){return this._running?zE(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(ae.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(ae.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const t={},[n,r]=hs();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 pa&&(s.statusCode===404?this._logger.log(ae.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(ae.Trace,`(LongPolling transport) Error sending a DELETE request: ${s}`)):this._logger.log(ae.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(ae.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(ae.Trace,t),this.onclose(this._closeError)}}}class N${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 Cn.isRequired(t,"url"),Cn.isRequired(n,"transferFormat"),Cn.isIn(n,Wn,"transferFormat"),this._logger.log(ae.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!==Wn.Text){a(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));return}let u;if(nn.isBrowser||nn.isWebWorker)u=new this._options.EventSource(t,{withCredentials:this._options.withCredentials});else{const f=this._httpClient.getCookieString(t),d={};d.Cookie=f;const[h,g]=hs();d[h]=g,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(ae.Trace,`(SSE transport) data received. ${eu(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(ae.Information,`SSE connected to ${this._url}`),this._eventSource=u,s=!0,r()}}catch(f){a(f);return}})}async send(t){return this._eventSource?zE(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 I${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){Cn.isRequired(t,"url"),Cn.isRequired(n,"transferFormat"),Cn.isIn(n,Wn,"transferFormat"),this._logger.log(ae.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(nn.isNode||nn.isReactNative){const h={},[g,y]=hs();h[g]=y,r&&(h[ga.Authorization]=`Bearer ${r}`),f&&(h[ga.Cookie]=f),u=new this._webSocketConstructor(t,void 0,{headers:{...h,...this._headers}})}else r&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(r)}`);u||(u=new this._webSocketConstructor(t)),n===Wn.Binary&&(u.binaryType="arraybuffer"),u.onopen=h=>{this._logger.log(ae.Information,`WebSocket connected to ${t}.`),this._webSocket=u,d=!0,a()},u.onerror=h=>{let g=null;typeof ErrorEvent<"u"&&h instanceof ErrorEvent?g=h.error:g="There was an error with the transport",this._logger.log(ae.Information,`(WebSockets transport) ${g}.`)},u.onmessage=h=>{if(this._logger.log(ae.Trace,`(WebSockets transport) data received. ${eu(h.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(h.data)}catch(g){this._close(g);return}},u.onclose=h=>{if(d)this._close(h);else{let g=null;typeof ErrorEvent<"u"&&h instanceof ErrorEvent?g=h.error:g="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(g))}}})}send(t){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(ae.Trace,`(WebSockets transport) sending data. ${eu(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(ae.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 UE=100;class M${constructor(t,n={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Cn.isRequired(t,"url"),this._logger=f$(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(nn.isNode&&typeof require<"u"){const s=typeof __webpack_require__=="function"?__non_webpack_require__:require;r=s("ws"),a=s("eventsource")}!nn.isNode&&typeof WebSocket<"u"&&!n.WebSocket?n.WebSocket=WebSocket:nn.isNode&&!n.WebSocket&&r&&(n.WebSocket=r),!nn.isNode&&typeof EventSource<"u"&&!n.EventSource?n.EventSource=EventSource:nn.isNode&&!n.EventSource&&typeof a<"u"&&(n.EventSource=a),this._httpClient=new R$(n.httpClient||new S$(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||Wn.Binary,Cn.isIn(t,Wn,"transferFormat"),this._logger.log(ae.Debug,`Starting connection with transfer format '${Wn[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(ae.Error,n),await this._stopPromise,Promise.reject(new ni(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(ae.Error,n),Promise.reject(new ni(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 ug(this.transport)),this._sendQueue.send(t))}async stop(t){if(this._connectionState==="Disconnected")return this._logger.log(ae.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(ae.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(ae.Error,`HttpConnection.transport.stop() threw error '${n}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(ae.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===Nn.WebSockets)this.transport=this._constructTransport(Nn.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 ni("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<UE);if(a===UE&&r.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(n,this._options.transport,r,t)}this.transport instanceof PE&&(this.features.inherentKeepAlive=!0),this._connectionState==="Connecting"&&(this._logger.log(ae.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(r){return this._logger.log(ae.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]=hs();n[r]=a;const s=this._resolveNegotiateUrl(t);this._logger.log(ae.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 DE("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 pa&&u.statusCode===404&&(f=f+" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(ae.Error,f),Promise.reject(new DE(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(ae.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 h of f){const g=this._resolveTransportOrError(h,n,a,d?.useStatefulReconnect===!0);if(g instanceof Error)u.push(`${h.transport} failed:`),u.push(g);else if(this._isITransport(g)){if(this.transport=g,!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(ae.Error,`Failed to start the transport '${h.transport}': ${y}`),d=void 0,u.push(new s$(`${h.transport} failed: ${y}`,Nn[h.transport])),this._connectionState!=="Connecting"){const b="Failed to select transport before stop() was called.";return this._logger.log(ae.Debug,b),Promise.reject(new ni(b))}}}}return u.length>0?Promise.reject(new l$(`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 Nn.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new I$(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case Nn.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new N$(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case Nn.LongPolling:return new PE(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=Nn[t.transport];if(s==null)return this._logger.log(ae.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(D$(n,s))if(t.transferFormats.map(f=>Wn[f]).indexOf(r)>=0){if(s===Nn.WebSockets&&!this._options.WebSocket||s===Nn.ServerSentEvents&&!this._options.EventSource)return this._logger.log(ae.Debug,`Skipping transport '${Nn[s]}' because it is not supported in your environment.'`),new o$(`'${Nn[s]}' is not supported in your environment.`,s);this._logger.log(ae.Debug,`Selecting transport '${Nn[s]}'.`);try{return this.features.reconnect=s===Nn.WebSockets?a:void 0,this._constructTransport(s)}catch(f){return f}}else return this._logger.log(ae.Debug,`Skipping transport '${Nn[s]}' because it does not support the requested transfer format '${Wn[r]}'.`),new Error(`'${Nn[s]}' does not support ${Wn[r]}.`);else return this._logger.log(ae.Debug,`Skipping transport '${Nn[s]}' because it was disabled by the client.`),new a$(`'${Nn[s]}' is disabled by the client.`,s)}_isITransport(t){return t&&typeof t=="object"&&"connect"in t}_stopConnection(t){if(this._logger.log(ae.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(ae.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(ae.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(ae.Error,`Connection disconnected with error '${t}'.`):this._logger.log(ae.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch(n=>{this._logger.log(ae.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(ae.Error,`HttpConnection.onclose(${t}) threw error '${n}'.`)}}}_resolveUrl(t){if(t.lastIndexOf("https://",0)===0||t.lastIndexOf("http://",0)===0)return t;if(!nn.isBrowser)throw new Error(`Cannot resolve '${t}'.`);const n=window.document.createElement("a");return n.href=t,this._logger.log(ae.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 D$(e,t){return!e||(t&e)!==0}class ug{constructor(t){this._transport=t,this._buffer=[],this._executing=!0,this._sendBufferedData=new Zf,this._transportResult=new Zf,this._sendLoopPromise=this._sendLoop()}send(t){return this._bufferData(t),this._transportResult||(this._transportResult=new Zf),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 Zf;const t=this._transportResult;this._transportResult=void 0;const n=typeof this._buffer[0]=="string"?this._buffer.join(""):ug._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 Zf{constructor(){this.promise=new Promise((t,n)=>[this._resolver,this._rejecter]=[t,n])}resolve(){this._resolver()}reject(t){this._rejecter(t)}}const B$="json";class z${constructor(){this.name=B$,this.version=2,this.transferFormat=Wn.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=Jl.instance);const r=Er.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(ae.Information,"Unknown message type '"+u.type+"' ignored.");continue}a.push(u)}return a}writeMessage(t){return Er.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 L$={trace:ae.Trace,debug:ae.Debug,info:ae.Information,information:ae.Information,warn:ae.Warning,warning:ae.Warning,error:ae.Error,critical:ae.Critical,none:ae.None};function $$(e){const t=L$[e.toLowerCase()];if(typeof t<"u")return t;throw new Error(`Unknown log level: ${e}`)}class P${configureLogging(t){if(Cn.isRequired(t,"logging"),U$(t))this.logger=t;else if(typeof t=="string"){const n=$$(t);this.logger=new Xf(n)}else this.logger=new Xf(t);return this}withUrl(t,n){return Cn.isRequired(t,"url"),Cn.isNotEmpty(t,"url"),this.url=t,typeof n=="object"?this.httpConnectionOptions={...this.httpConnectionOptions,...n}:this.httpConnectionOptions={...this.httpConnectionOptions,transport:n},this}withHubProtocol(t){return Cn.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 $E(t):this.reconnectPolicy=t:this.reconnectPolicy=new $E,this}withServerTimeout(t){return Cn.isRequired(t,"milliseconds"),this._serverTimeoutInMilliseconds=t,this}withKeepAliveInterval(t){return Cn.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 M$(this.url,t);return lg.create(n,this.logger||Jl.instance,this.protocol||new z$,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}function U$(e){return e.log!==void 0}function j$({url:e,accessToken:t,autoStart:n=!0}){const r=N.useRef(null),a=N.useRef(new Map),s=N.useRef(null),u=N.useRef(0),f=N.useRef(!1),[d,h]=N.useState("disconnected"),[g,y]=N.useState(null),b=N.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),v=N.useCallback(()=>{if(f.current||s.current)return;u.current+=1;const R=u.current,$=Math.min(3e4,1e3*Math.pow(2,R-1)),H=Math.floor(Math.random()*500),V=$+H;s.current=setTimeout(()=>{s.current=null,w()},V)},[b]),x=N.useCallback(R=>{a.current.forEach(($,H)=>{R.off(H),$.forEach(V=>{R.on(H,V)})})},[]),E=N.useCallback(async()=>Lf(),[]),_=N.useCallback(()=>{const R=new P$().withUrl(e,{accessTokenFactory:async()=>{const $=vo()?.sessionToken;return $||await E()}}).withAutomaticReconnect({nextRetryDelayInMilliseconds:$=>$.elapsedMilliseconds<6e4?Math.random()*1e4:null}).build();return R.onreconnecting(()=>{b(),h("reconnecting")}),R.onreconnected(()=>{b(),u.current=0,h("connected"),x(R)}),R.onclose($=>{h("disconnected"),$&&y($),f.current||v()}),R},[e,E,x,b,v]),w=N.useCallback(async()=>{f.current=!1,b(),r.current||(r.current=_());const R=r.current;if(R.state===Nt.Connected){h("connected");return}if(R.state===Nt.Connecting){h("connecting");return}if(R.state===Nt.Reconnecting){h("reconnecting");return}h("connecting");try{await R.start(),x(R),u.current=0,h("connected"),y(null)}catch($){y($),h("disconnected"),v()}},[x,_,b,v]),O=N.useCallback(async()=>{f.current=!0,b(),u.current=0;const R=r.current;if(r.current=null,!R){h("disconnected");return}try{await R.stop()}finally{h("disconnected")}},[b]),T=N.useCallback((R,$)=>{let H=a.current.get(R);H||(H=new Set,a.current.set(R,H)),H.add($);const V=r.current;V&&V.on(R,$)},[]),A=N.useCallback((R,$)=>{const H=a.current.get(R);if(!H)return;H.delete($),H.size===0&&a.current.delete(R);const V=r.current;V&&V.off(R,$)},[]),M=N.useCallback(async(R,...$)=>{const H=r.current;if(!H||H.state!==Nt.Connected)throw new Error("SignalR not connected");return H.invoke(R,...$)},[]);return N.useEffect(()=>(n&&w(),()=>{O()}),[n,w,O]),{status:d,connected:d==="connected",error:g,start:w,stop:O,on:T,off:A,invoke:M}}const H$=(()=>{const e=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return t=>e.call(t)})();function Kf(e){return H$(e)==="Uint8Array"}function V$(e){return typeof e=="object"&&e!=null&&Symbol.toStringTag in e&&(e[Symbol.toStringTag]==="ArrayBuffer"||e[Symbol.toStringTag]==="SharedArrayBuffer")}function F$(e){return e instanceof RegExp||Object.prototype.toString.call(e)==="[object RegExp]"}function jE(e){return typeof e=="object"&&e!=null&&Symbol.toStringTag in e&&e[Symbol.toStringTag]==="Map"}function G$(e){return e instanceof Date||Object.prototype.toString.call(e)==="[object Date]"}function _r(e,t){return JSON.stringify(e,(n,r)=>typeof r=="bigint"?{$numberLong:`${r}`}:jE(r)?Object.fromEntries(r):r)}function q$(e){if(e!=null&&typeof e=="object"&&"stylize"in e&&typeof e.stylize=="function")return e.stylize}const cg=7,HE=Symbol.for("@@mdb.bson.version"),fg=2147483647,dg=-2147483648,VE=Math.pow(2,63)-1,FE=-Math.pow(2,63),Y$=Math.pow(2,53),X$=-Math.pow(2,53),GE=4;class be extends Error{get bsonError(){return!0}get name(){return"BSONError"}constructor(t,n){super(t,n)}static isBSONError(t){return t!=null&&typeof t=="object"&&"bsonError"in t&&t.bsonError===!0&&"name"in t&&"message"in t&&"stack"in t}}class Z$ extends be{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${cg}.x.x`)}}class qE extends be{get name(){return"BSONRuntimeError"}constructor(t){super(t)}}class xo extends be{get name(){return"BSONOffsetError"}offset;constructor(t,n,r){super(`${t}. offset: ${n}`,r),this.offset=n}}let YE,XE;function ZE(e,t,n,r){if(r){YE??=new TextDecoder("utf8",{fatal:!0});try{return YE.decode(e.subarray(t,n))}catch(a){throw new be("Invalid UTF-8 string in BSON document",{cause:a})}}return XE??=new TextDecoder("utf8",{fatal:!1}),XE.decode(e.subarray(t,n))}function KE(e,t,n){if(e.length===0)return"";const r=n-t;if(r===0)return"";if(r>20)return null;if(r===1&&e[t]<128)return String.fromCharCode(e[t]);if(r===2&&e[t]<128&&e[t+1]<128)return String.fromCharCode(e[t])+String.fromCharCode(e[t+1]);if(r===3&&e[t]<128&&e[t+1]<128&&e[t+2]<128)return String.fromCharCode(e[t])+String.fromCharCode(e[t+1])+String.fromCharCode(e[t+2]);const a=[];for(let s=t;s<n;s++){const u=e[s];if(u>127)return null;a.push(u)}return String.fromCharCode(...a)}function K$(e,t,n){if(t.length===0)return 0;if(t.length>25||e.length-n<t.length)return null;for(let r=0,a=n;r<t.length;r++,a++){const s=t.charCodeAt(r);if(s>127)return null;e[a]=s}return t.length}function W$(e){return ri.fromNumberArray(Array.from({length:e},()=>Math.floor(Math.random()*256)))}function Q$(e){return crypto.getRandomValues(ri.allocate(e))}const J$=(()=>{const{crypto:e}=globalThis;return e!=null&&typeof e.getRandomValues=="function"?Q$:W$})(),ri={isUint8Array:Kf,toLocalBufferType(e){if(Buffer.isBuffer(e))return e;if(ArrayBuffer.isView(e))return Buffer.from(e.buffer,e.byteOffset,e.byteLength);const t=e?.[Symbol.toStringTag]??Object.prototype.toString.call(e);if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return Buffer.from(e);throw new be("Cannot create Buffer from the passed potentialBuffer.")},allocate(e){return Buffer.alloc(e)},allocateUnsafe(e){return Buffer.allocUnsafe(e)},compare(e,t){return ri.toLocalBufferType(e).compare(t)},concat(e){return Buffer.concat(e)},equals(e,t){return ri.toLocalBufferType(e).equals(t)},fromNumberArray(e){return Buffer.from(e)},fromBase64(e){return Buffer.from(e,"base64")},fromUTF8(e){return Buffer.from(e,"utf8")},toBase64(e){return ri.toLocalBufferType(e).toString("base64")},fromISO88591(e){return Buffer.from(e,"binary")},toISO88591(e){return ri.toLocalBufferType(e).toString("binary")},fromHex(e){return Buffer.from(e,"hex")},toHex(e){return ri.toLocalBufferType(e).toString("hex")},toUTF8(e,t,n,r){const a=n-t<=20?KE(e,t,n):null;if(a!=null)return a;const s=ri.toLocalBufferType(e).toString("utf8",t,n);if(r){for(let u=0;u<s.length;u++)if(s.charCodeAt(u)===65533){ZE(e,t,n,!0);break}}return s},utf8ByteLength(e){return Buffer.byteLength(e,"utf8")},encodeUTF8Into(e,t,n){const r=K$(e,t,n);return r??ri.toLocalBufferType(e).write(t,n,void 0,"utf8")},randomBytes:J$,swap32(e){return ri.toLocalBufferType(e).swap32()}};function eP(){const{navigator:e}=globalThis;return typeof e=="object"&&e.product==="ReactNative"}function tP(e){if(e<0)throw new RangeError(`The argument 'byteLength' is invalid. Received ${e}`);return ya.fromNumberArray(Array.from({length:e},()=>Math.floor(Math.random()*256)))}const nP=(()=>{const{crypto:e}=globalThis;if(e!=null&&typeof e.getRandomValues=="function")return t=>e.getRandomValues(ya.allocate(t));if(eP()){const{console:t}=globalThis;t?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return tP})(),WE=/(\d|[a-f])/i,ya={isUint8Array:Kf,toLocalBufferType(e){const t=e?.[Symbol.toStringTag]??Object.prototype.toString.call(e);if(t==="Uint8Array")return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return new Uint8Array(e);throw new be("Cannot make a Uint8Array from passed potentialBuffer.")},allocate(e){if(typeof e!="number")throw new TypeError(`The "size" argument must be of type number. Received ${String(e)}`);return new Uint8Array(e)},allocateUnsafe(e){return ya.allocate(e)},compare(e,t){if(e===t)return 0;const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return e.length<t.length?-1:e.length>t.length?1:0},concat(e){if(e.length===0)return ya.allocate(0);let t=0;for(const a of e)t+=a.length;const n=ya.allocate(t);let r=0;for(const a of e)n.set(a,r),r+=a.length;return n},equals(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},fromNumberArray(e){return Uint8Array.from(e)},fromBase64(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))},fromUTF8(e){return new TextEncoder().encode(e)},toBase64(e){return btoa(ya.toISO88591(e))},fromISO88591(e){return Uint8Array.from(e,t=>t.charCodeAt(0)&255)},toISO88591(e){return Array.from(Uint16Array.from(e),t=>String.fromCharCode(t)).join("")},fromHex(e){const t=e.length%2===0?e:e.slice(0,e.length-1),n=[];for(let r=0;r<t.length;r+=2){const a=t[r],s=t[r+1];if(!WE.test(a)||!WE.test(s))break;const u=Number.parseInt(`${a}${s}`,16);n.push(u)}return Uint8Array.from(n)},toHex(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")},toUTF8(e,t,n,r){const a=n-t<=20?KE(e,t,n):null;return a??ZE(e,t,n,r)},utf8ByteLength(e){return new TextEncoder().encode(e).byteLength},encodeUTF8Into(e,t,n){const r=new TextEncoder().encode(t);return e.set(r,n),r.byteLength},randomBytes:nP,swap32(e){if(e.length%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e.length;t+=4){const n=e[t],r=e[t+1],a=e[t+2],s=e[t+3];e[t]=s,e[t+1]=a,e[t+2]=r,e[t+3]=n}return e}},Be=typeof Buffer=="function"&&Buffer.prototype?._isBuffer!==!0?ri:ya,QE=Symbol.for("@@mdb.bson.type");class $r{get[QE](){return this._bsontype}get[HE](){return cg}[Symbol.for("nodejs.util.inspect.custom")](t,n,r){return this.inspect(t,n,r)}}const ps=new Float64Array(1),pt=new Uint8Array(ps.buffer,0,8);ps[0]=-1;const hg=pt[7]===0,va={isBigEndian:hg,getNonnegativeInt32LE(e,t){if(e[t+3]>127)throw new RangeError(`Size cannot be negative at offset: ${t}`);return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},getInt32LE(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},getUint32LE(e,t){return e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216},getUint32BE(e,t){return e[t+3]+e[t+2]*256+e[t+1]*65536+e[t]*16777216},getBigInt64LE(e,t){const n=BigInt(e[t+4]+e[t+5]*256+e[t+6]*65536+(e[t+7]<<24)),r=BigInt(e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216);return(n<<32n)+r},getFloat64LE:hg?(e,t)=>(pt[7]=e[t],pt[6]=e[t+1],pt[5]=e[t+2],pt[4]=e[t+3],pt[3]=e[t+4],pt[2]=e[t+5],pt[1]=e[t+6],pt[0]=e[t+7],ps[0]):(e,t)=>(pt[0]=e[t],pt[1]=e[t+1],pt[2]=e[t+2],pt[3]=e[t+3],pt[4]=e[t+4],pt[5]=e[t+5],pt[6]=e[t+6],pt[7]=e[t+7],ps[0]),setInt32BE(e,t,n){return e[t+3]=n,n>>>=8,e[t+2]=n,n>>>=8,e[t+1]=n,n>>>=8,e[t]=n,4},setInt32LE(e,t,n){return e[t]=n,n>>>=8,e[t+1]=n,n>>>=8,e[t+2]=n,n>>>=8,e[t+3]=n,4},setBigInt64LE(e,t,n){const r=0xffffffffn;let a=Number(n&r);e[t]=a,a>>=8,e[t+1]=a,a>>=8,e[t+2]=a,a>>=8,e[t+3]=a;let s=Number(n>>32n&r);return e[t+4]=s,s>>=8,e[t+5]=s,s>>=8,e[t+6]=s,s>>=8,e[t+7]=s,8},setFloat64LE:hg?(e,t,n)=>(ps[0]=n,e[t]=pt[7],e[t+1]=pt[6],e[t+2]=pt[5],e[t+3]=pt[4],e[t+4]=pt[3],e[t+5]=pt[2],e[t+6]=pt[1],e[t+7]=pt[0],8):(e,t,n)=>(ps[0]=n,e[t]=pt[0],e[t+1]=pt[1],e[t+2]=pt[2],e[t+3]=pt[3],e[t+4]=pt[4],e[t+5]=pt[5],e[t+6]=pt[6],e[t+7]=pt[7],8)};class ut extends $r{get _bsontype(){return"Binary"}static BSON_BINARY_SUBTYPE_DEFAULT=0;static BUFFER_SIZE=256;static SUBTYPE_DEFAULT=0;static SUBTYPE_FUNCTION=1;static SUBTYPE_BYTE_ARRAY=2;static SUBTYPE_UUID_OLD=3;static SUBTYPE_UUID=4;static SUBTYPE_MD5=5;static SUBTYPE_ENCRYPTED=6;static SUBTYPE_COLUMN=7;static SUBTYPE_SENSITIVE=8;static SUBTYPE_VECTOR=9;static SUBTYPE_USER_DEFINED=128;static VECTOR_TYPE=Object.freeze({Int8:3,Float32:39,PackedBit:16});buffer;sub_type;position;constructor(t,n){if(super(),t!=null&&typeof t=="string"&&!ArrayBuffer.isView(t)&&!V$(t)&&!Array.isArray(t))throw new be("Binary can only be constructed from Uint8Array or number[]");this.sub_type=n??ut.BSON_BINARY_SUBTYPE_DEFAULT,t==null?(this.buffer=Be.allocate(ut.BUFFER_SIZE),this.position=0):(this.buffer=Array.isArray(t)?Be.fromNumberArray(t):Be.toLocalBufferType(t),this.position=this.buffer.byteLength)}put(t){if(typeof t=="string"&&t.length!==1)throw new be("only accepts single character String");if(typeof t!="number"&&t.length!==1)throw new be("only accepts single character Uint8Array or Array");let n;if(typeof t=="string"?n=t.charCodeAt(0):typeof t=="number"?n=t:n=t[0],n<0||n>255)throw new be("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.byteLength>this.position)this.buffer[this.position++]=n;else{const r=Be.allocate(ut.BUFFER_SIZE+this.buffer.length);r.set(this.buffer,0),this.buffer=r,this.buffer[this.position++]=n}}write(t,n){if(n=typeof n=="number"?n:this.position,this.buffer.byteLength<n+t.length){const r=Be.allocate(this.buffer.byteLength+t.length);r.set(this.buffer,0),this.buffer=r}if(ArrayBuffer.isView(t))this.buffer.set(Be.toLocalBufferType(t),n),this.position=n+t.byteLength>this.position?n+t.length:this.position;else if(typeof t=="string")throw new be("input cannot be string")}read(t,n){n=n&&n>0?n:this.position;const r=t+n;return this.buffer.subarray(t,r>this.position?this.position:r)}value(){return this.buffer.length===this.position?this.buffer:this.buffer.subarray(0,this.position)}length(){return this.position}toJSON(){return Be.toBase64(this.buffer.subarray(0,this.position))}toString(t){return t==="hex"?Be.toHex(this.buffer.subarray(0,this.position)):t==="base64"?Be.toBase64(this.buffer.subarray(0,this.position)):t==="utf8"||t==="utf-8"?Be.toUTF8(this.buffer,0,this.position,!1):Be.toUTF8(this.buffer,0,this.position,!1)}toExtendedJSON(t){t=t||{},this.sub_type===ut.SUBTYPE_VECTOR&&Eo(this);const n=Be.toBase64(this.buffer),r=Number(this.sub_type).toString(16);return t.legacy?{$binary:n,$type:r.length===1?"0"+r:r}:{$binary:{base64:n,subType:r.length===1?"0"+r:r}}}toUUID(){if(this.sub_type===ut.SUBTYPE_UUID)return new ir(this.buffer.subarray(0,this.position));throw new be(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${ut.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString(t,n){return new ut(Be.fromHex(t),n)}static createFromBase64(t,n){return new ut(Be.fromBase64(t),n)}static fromExtendedJSON(t,n){n=n||{};let r,a;if("$binary"in t?n.legacy&&typeof t.$binary=="string"&&"$type"in t?(a=t.$type?parseInt(t.$type,16):0,r=Be.fromBase64(t.$binary)):typeof t.$binary!="string"&&(a=t.$binary.subType?parseInt(t.$binary.subType,16):0,r=Be.fromBase64(t.$binary.base64)):"$uuid"in t&&(a=4,r=ir.bytesFromString(t.$uuid)),!r)throw new be(`Unexpected Binary Extended JSON format ${JSON.stringify(t)}`);return a===GE?new ir(r):new ut(r,a)}inspect(t,n,r){r??=_r;const a=Be.toBase64(this.buffer.subarray(0,this.position)),s=r(a,n),u=r(this.sub_type,n);return`Binary.createFromBase64(${s}, ${u})`}toInt8Array(){if(this.sub_type!==ut.SUBTYPE_VECTOR)throw new be("Binary sub_type is not Vector");if(this.buffer[0]!==ut.VECTOR_TYPE.Int8)throw new be("Binary datatype field is not Int8");return Eo(this),new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toFloat32Array(){if(this.sub_type!==ut.SUBTYPE_VECTOR)throw new be("Binary sub_type is not Vector");if(this.buffer[0]!==ut.VECTOR_TYPE.Float32)throw new be("Binary datatype field is not Float32");Eo(this);const t=new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position));return va.isBigEndian&&Be.swap32(t),new Float32Array(t.buffer)}toPackedBits(){if(this.sub_type!==ut.SUBTYPE_VECTOR)throw new be("Binary sub_type is not Vector");if(this.buffer[0]!==ut.VECTOR_TYPE.PackedBit)throw new be("Binary datatype field is not packed bit");return Eo(this),new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toBits(){if(this.sub_type!==ut.SUBTYPE_VECTOR)throw new be("Binary sub_type is not Vector");if(this.buffer[0]!==ut.VECTOR_TYPE.PackedBit)throw new be("Binary datatype field is not packed bit");Eo(this);const n=(this.length()-2)*8-this.buffer[1],r=new Int8Array(n);for(let a=0;a<r.length;a++){const s=a/8|0,u=this.buffer[s+2],f=7-a%8,d=u>>f&1;r[a]=d}return r}static fromInt8Array(t){const n=Be.allocate(t.byteLength+2);n[0]=ut.VECTOR_TYPE.Int8,n[1]=0;const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n.set(r,2);const a=new this(n,this.SUBTYPE_VECTOR);return Eo(a),a}static fromFloat32Array(t){const n=Be.allocate(t.byteLength+2);n[0]=ut.VECTOR_TYPE.Float32,n[1]=0;const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n.set(r,2),va.isBigEndian&&Be.swap32(new Uint8Array(n.buffer,2));const a=new this(n,this.SUBTYPE_VECTOR);return Eo(a),a}static fromPackedBits(t,n=0){const r=Be.allocate(t.byteLength+2);r[0]=ut.VECTOR_TYPE.PackedBit,r[1]=n,r.set(t,2);const a=new this(r,this.SUBTYPE_VECTOR);return Eo(a),a}static fromBits(t){const n=t.length+7>>>3,r=new Uint8Array(n+2);r[0]=ut.VECTOR_TYPE.PackedBit;const a=t.length%8;r[1]=a===0?0:8-a;for(let s=0;s<t.length;s++){const u=s>>>3,f=t[s];if(f!==0&&f!==1)throw new be(`Invalid bit value at ${s}: must be 0 or 1, found ${t[s]}`);if(f===0)continue;const d=7-s%8;r[u+2]|=f<<d}return new this(r,ut.SUBTYPE_VECTOR)}}function Eo(e){if(e.sub_type!==ut.SUBTYPE_VECTOR)return;const t=e.position,n=e.buffer[0],r=e.buffer[1];if((n===ut.VECTOR_TYPE.Float32||n===ut.VECTOR_TYPE.Int8)&&r!==0)throw new be("Invalid Vector: padding must be zero for int8 and float32 vectors");if(n===ut.VECTOR_TYPE.Float32&&t!==0&&t-2!==0&&(t-2)%4!==0)throw new be("Invalid Vector: Float32 vector must contain a multiple of 4 bytes");if(n===ut.VECTOR_TYPE.PackedBit&&r!==0&&t===2)throw new be("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(n===ut.VECTOR_TYPE.PackedBit&&r>7)throw new be(`Invalid Vector: padding must be a value between 0 and 7. found: ${r}`)}const pg=16,rP=/^[0-9A-F]{32}$/i,iP=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;class ir extends ut{constructor(t){let n;if(t==null)n=ir.generate();else if(t instanceof ir)n=Be.toLocalBufferType(new Uint8Array(t.buffer));else if(ArrayBuffer.isView(t)&&t.byteLength===pg)n=Be.toLocalBufferType(t);else if(typeof t=="string")n=ir.bytesFromString(t);else throw new be("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");super(n,GE)}get id(){return this.buffer}set id(t){this.buffer=t}toHexString(t=!0){return t?[Be.toHex(this.buffer.subarray(0,4)),Be.toHex(this.buffer.subarray(4,6)),Be.toHex(this.buffer.subarray(6,8)),Be.toHex(this.buffer.subarray(8,10)),Be.toHex(this.buffer.subarray(10,16))].join("-"):Be.toHex(this.buffer)}toString(t){return t==="hex"?Be.toHex(this.id):t==="base64"?Be.toBase64(this.id):this.toHexString()}toJSON(){return this.toHexString()}equals(t){if(!t)return!1;if(t instanceof ir)return Be.equals(t.id,this.id);try{return Be.equals(new ir(t).id,this.id)}catch{return!1}}toBinary(){return new ut(this.id,ut.SUBTYPE_UUID)}static generate(){const t=Be.randomBytes(pg);return t[6]=t[6]&15|64,t[8]=t[8]&63|128,t}static isValid(t){return t?typeof t=="string"?ir.isValidUUIDString(t):Kf(t)?t.byteLength===pg:t._bsontype==="Binary"&&t.sub_type===this.SUBTYPE_UUID&&t.buffer.byteLength===16:!1}static createFromHexString(t){const n=ir.bytesFromString(t);return new ir(n)}static createFromBase64(t){return new ir(Be.fromBase64(t))}static bytesFromString(t){if(!ir.isValidUUIDString(t))throw new be("UUID string representation must be 32 hex digits or canonical hyphenated representation");return Be.fromHex(t.replace(/-/g,""))}static isValidUUIDString(t){return rP.test(t)||iP.test(t)}inspect(t,n,r){return r??=_r,`new UUID(${r(this.toHexString(),n)})`}}class tu extends $r{get _bsontype(){return"Code"}code;scope;constructor(t,n){super(),this.code=t.toString(),this.scope=n??null}toJSON(){return this.scope!=null?{code:this.code,scope:this.scope}:{code:this.code}}toExtendedJSON(){return this.scope?{$code:this.code,$scope:this.scope}:{$code:this.code}}static fromExtendedJSON(t){return new tu(t.$code,t.$scope)}inspect(t,n,r){r??=_r;let a=r(this.code,n);const s=a.includes(`
169
+ `},a),s}function uL(e,t){return e&&"run"in e?async function(n,r){const a=CE(n,{file:r,...t});await e.run(a,r)}:function(n,r){return CE(n,{file:r,...e||t})}}function TE(e){if(e)throw e}var Zm,AE;function cL(){if(AE)return Zm;AE=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=function(h){return typeof Array.isArray=="function"?Array.isArray(h):t.call(h)==="[object Array]"},s=function(h){if(!h||t.call(h)!=="[object Object]")return!1;var g=e.call(h,"constructor"),y=h.constructor&&h.constructor.prototype&&e.call(h.constructor.prototype,"isPrototypeOf");if(h.constructor&&!g&&!y)return!1;var b;for(b in h);return typeof b>"u"||e.call(h,b)},u=function(h,g){n&&g.name==="__proto__"?n(h,g.name,{enumerable:!0,configurable:!0,value:g.newValue,writable:!0}):h[g.name]=g.newValue},f=function(h,g){if(g==="__proto__")if(e.call(h,g)){if(r)return r(h,g).value}else return;return h[g]};return Zm=function d(){var h,g,y,b,v,x,E=arguments[0],_=1,w=arguments.length,O=!1;for(typeof E=="boolean"&&(O=E,E=arguments[1]||{},_=2),(E==null||typeof E!="object"&&typeof E!="function")&&(E={});_<w;++_)if(h=arguments[_],h!=null)for(g in h)y=f(E,g),b=f(h,g),E!==b&&(O&&b&&(s(b)||(v=a(b)))?(v?(v=!1,x=y&&a(y)?y:[]):x=y&&s(y)?y:{},u(E,{name:g,newValue:d(O,x,b)})):typeof b<"u"&&u(E,{name:g,newValue:b}));return E},Zm}var fL=cL();const Km=Ku(fL);function Wm(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function dL(){const e=[],t={run:n,use:r};return t;function n(...a){let s=-1;const u=a.pop();if(typeof u!="function")throw new TypeError("Expected function as last argument, not "+u);f(null,...a);function f(d,...h){const g=e[++s];let y=-1;if(d){u(d);return}for(;++y<a.length;)(h[y]===null||h[y]===void 0)&&(h[y]=a[y]);a=h,g?hL(g,f)(...h):u(null,...h)}}function r(a){if(typeof a!="function")throw new TypeError("Expected `middelware` to be a function, not "+a);return e.push(a),t}}function hL(e,t){let n;return r;function r(...u){const f=e.length>u.length;let d;f&&u.push(a);try{d=e.apply(this,u)}catch(h){const g=h;if(f&&n)throw g;return a(g)}f||(d&&d.then&&typeof d.then=="function"?d.then(s,a):d instanceof Error?a(d):s(d))}function a(u,...f){n||(n=!0,t(u,...f))}function s(u){a(null,u)}}const Ti={basename:pL,dirname:mL,extname:gL,join:yL,sep:"/"};function pL(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Ql(e);let n=0,r=-1,a=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(s){n=a+1;break}}else r<0&&(s=!0,r=a+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let u=-1,f=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(s){n=a+1;break}}else u<0&&(s=!0,u=a+1),f>-1&&(e.codePointAt(a)===t.codePointAt(f--)?f<0&&(r=a):(f=-1,r=u));return n===r?r=u:r<0&&(r=e.length),e.slice(n,r)}function mL(e){if(Ql(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function gL(e){Ql(e);let t=e.length,n=-1,r=0,a=-1,s=0,u;for(;t--;){const f=e.codePointAt(t);if(f===47){if(u){r=t+1;break}continue}n<0&&(u=!0,n=t+1),f===46?a<0?a=t:s!==1&&(s=1):a>-1&&(s=-1)}return a<0||n<0||s===0||s===1&&a===n-1&&a===r+1?"":e.slice(a,n)}function yL(...e){let t=-1,n;for(;++t<e.length;)Ql(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":vL(n)}function vL(e){Ql(e);const t=e.codePointAt(0)===47;let n=bL(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function bL(e,t){let n="",r=0,a=-1,s=0,u=-1,f,d;for(;++u<=e.length;){if(u<e.length)f=e.codePointAt(u);else{if(f===47)break;f=47}if(f===47){if(!(a===u-1||s===1))if(a!==u-1&&s===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(d=n.lastIndexOf("/"),d!==n.length-1){d<0?(n="",r=0):(n=n.slice(0,d),r=n.length-1-n.lastIndexOf("/")),a=u,s=0;continue}}else if(n.length>0){n="",r=0,a=u,s=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(a+1,u):n=e.slice(a+1,u),r=u-a-1;a=u,s=0}else f===46&&s>-1?s++:s=-1}return n}function Ql(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const SL={cwd:xL};function xL(){return"/"}function Qm(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function EL(e){if(typeof e=="string")e=new URL(e);else if(!Qm(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return _L(e)}function _L(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const a=new TypeError("File URL path must not include encoded / characters");throw a.code="ERR_INVALID_FILE_URL_PATH",a}}return decodeURIComponent(t)}const Jm=["history","path","basename","stem","extname","dirname"];class kE{constructor(t){let n;t?Qm(t)?n={path:t}:typeof t=="string"||wL(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":SL.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Jm.length;){const s=Jm[r];s in n&&n[s]!==void 0&&n[s]!==null&&(this[s]=s==="history"?[...n[s]]:n[s])}let a;for(a in n)Jm.includes(a)||(this[a]=n[a])}get basename(){return typeof this.path=="string"?Ti.basename(this.path):void 0}set basename(t){tg(t,"basename"),eg(t,"basename"),this.path=Ti.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Ti.dirname(this.path):void 0}set dirname(t){RE(this.basename,"dirname"),this.path=Ti.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Ti.extname(this.path):void 0}set extname(t){if(eg(t,"extname"),RE(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Ti.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Qm(t)&&(t=EL(t)),tg(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?Ti.basename(this.path,this.extname):void 0}set stem(t){tg(t,"stem"),eg(t,"stem"),this.path=Ti.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const a=this.message(t,n,r);throw a.fatal=!0,a}info(t,n,r){const a=this.message(t,n,r);return a.fatal=void 0,a}message(t,n,r){const a=new Kn(t,n,r);return this.path&&(a.name=this.path+":"+a.name,a.file=this.path),a.fatal=!1,this.messages.push(a),a}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function eg(e,t){if(e&&e.includes(Ti.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Ti.sep+"`")}function tg(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function RE(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function wL(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const CL=(function(e){const r=this.constructor.prototype,a=r[e],s=function(){return a.apply(s,arguments)};return Object.setPrototypeOf(s,r),s}),TL={}.hasOwnProperty;class ng extends CL{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=dL()}copy(){const t=new ng;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(Km(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(og("data",this.frozen),this.namespace[t]=n,this):TL.call(this.namespace,t)&&this.namespace[t]||void 0:t?(og("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const a=n.call(t,...r);typeof a=="function"&&this.transformers.use(a)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=qf(t),r=this.parser||this.Parser;return rg("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),rg("process",this.parser||this.Parser),ig("process",this.compiler||this.Compiler),n?a(void 0,n):new Promise(a);function a(s,u){const f=qf(t),d=r.parse(f);r.run(d,f,function(g,y,b){if(g||!y||!b)return h(g);const v=y,x=r.stringify(v,b);RL(x)?b.value=x:b.result=x,h(g,b)});function h(g,y){g||!y?u(g):s?s(y):n(void 0,y)}}}processSync(t){let n=!1,r;return this.freeze(),rg("processSync",this.parser||this.Parser),ig("processSync",this.compiler||this.Compiler),this.process(t,a),NE("processSync","process",n),r;function a(s,u){n=!0,TE(s),r=u}}run(t,n,r){OE(t),this.freeze();const a=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?s(void 0,r):new Promise(s);function s(u,f){const d=qf(n);a.run(t,d,h);function h(g,y,b){const v=y||t;g?f(g):u?u(v):r(void 0,v,b)}}}runSync(t,n){let r=!1,a;return this.run(t,n,s),NE("runSync","run",r),a;function s(u,f){TE(u),a=f,r=!0}}stringify(t,n){this.freeze();const r=qf(n),a=this.compiler||this.Compiler;return ig("stringify",a),OE(t),a(t,r)}use(t,...n){const r=this.attachers,a=this.namespace;if(og("use",this.frozen),t!=null)if(typeof t=="function")d(t,n);else if(typeof t=="object")Array.isArray(t)?f(t):u(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function s(h){if(typeof h=="function")d(h,[]);else if(typeof h=="object")if(Array.isArray(h)){const[g,...y]=h;d(g,y)}else u(h);else throw new TypeError("Expected usable value, not `"+h+"`")}function u(h){if(!("plugins"in h)&&!("settings"in h))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");f(h.plugins),h.settings&&(a.settings=Km(!0,a.settings,h.settings))}function f(h){let g=-1;if(h!=null)if(Array.isArray(h))for(;++g<h.length;){const y=h[g];s(y)}else throw new TypeError("Expected a list of plugins, not `"+h+"`")}function d(h,g){let y=-1,b=-1;for(;++y<r.length;)if(r[y][0]===h){b=y;break}if(b===-1)r.push([h,...g]);else if(g.length>0){let[v,...x]=g;const E=r[b][1];Wm(E)&&Wm(v)&&(v=Km(!0,E,v)),r[b]=[h,v,...x]}}}}const AL=new ng().freeze();function rg(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function ig(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function og(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function OE(e){if(!Wm(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function NE(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function qf(e){return kL(e)?e:new kE(e)}function kL(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function RL(e){return typeof e=="string"||OL(e)}function OL(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const NL="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",IE=[],ME={allowDangerousHtml:!0},IL=/^(https?|ircs?|mailto|xmpp)$/i,ML=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function DL(e){const t=BL(e),n=zL(e);return LL(t.runSync(t.parse(n),n),e)}function BL(e){const t=e.rehypePlugins||IE,n=e.remarkPlugins||IE,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...ME}:ME;return AL().use(pz).use(n).use(uL,r).use(t)}function zL(e){const t=e.children||"",n=new kE;return typeof t=="string"&&(n.value=t),n}function LL(e,t){const n=t.allowedElements,r=t.allowElement,a=t.components,s=t.disallowedElements,u=t.skipHtml,f=t.unwrapDisallowed,d=t.urlTransform||$L;for(const g of ML)Object.hasOwn(t,g.from)&&(""+g.from+(g.to?"use `"+g.to+"` instead":"remove it")+NL+g.id,void 0);return _E(e,h),nD(e,{Fragment:L.Fragment,components:a,ignoreInvalidStyle:!0,jsx:L.jsx,jsxs:L.jsxs,passKeys:!0,passNode:!0});function h(g,y,b){if(g.type==="raw"&&b&&typeof y=="number")return u?b.children.splice(y,1):b.children[y]={type:"text",value:g.value},y;if(g.type==="element"){let v;for(v in Bm)if(Object.hasOwn(Bm,v)&&Object.hasOwn(g.properties,v)){const x=g.properties[v],E=Bm[v];(E===null||E.includes(g.tagName))&&(g.properties[v]=d(String(x||""),v,g))}}if(g.type==="element"){let v=n?!n.includes(g.tagName):s?s.includes(g.tagName):!1;if(!v&&r&&typeof y=="number"&&(v=!r(g,y,b)),v&&b&&typeof y=="number")return f&&g.children?b.children.splice(y,1,...g.children):b.children.splice(y,1),y}}}function $L(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||n!==-1&&t>n||r!==-1&&t>r||IL.test(e.slice(0,t))?e:""}function PL({msg:e,isMe:t,showSeenIndicator:n,isSeen:r,send:a}){return L.jsxs(En,{sx:{maxWidth:"78%"},children:[L.jsx(En,{sx:s=>({wordBreak:"break-word",position:"relative",px:1.4,py:1.05,borderRadius:3,border:"1px solid",borderColor:"divider",bgcolor:t?"primary.main":"background.paper",color:t?"primary.contrastText":"text.primary",boxShadow:t?"0 10px 30px rgba(25,118,210,.22)":"0 10px 30px rgba(0,0,0,.10)",whiteSpace:"normal",overflow:"visible","&::before":{content:'""',position:"absolute",top:14,width:10,height:10,transform:"rotate(45deg)",backgroundColor:t?s.palette.primary.main:s.palette.background.paper,right:t?-5:"auto",left:t?"auto":-5,zIndex:1},"& p":{margin:0,lineHeight:1.35},"& p + p":{marginTop:"6px"},"& ol, & ul":{margin:"6px 0",paddingLeft:"20px"},"& li":{margin:"2px 0"},"& li > p":{margin:0},"& a":{color:"inherit",textDecoration:"underline"},"& code":{fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"0.9em",padding:"2px 6px",borderRadius:8,backgroundColor:t?"rgba(255,255,255,.14)":"rgba(0,0,0,.06)"},"& pre":{margin:0,marginTop:8,padding:12,overflow:"auto",borderRadius:12,backgroundColor:t?"rgba(255,255,255,.12)":"rgba(0,0,0,.05)"}}),children:L.jsx(DL,{children:e.text})}),n?L.jsx(ti,{sx:{mt:.35,fontSize:12,textAlign:"right",color:r?"text.secondary":"text.disabled"},children:r?"Seen":"Sent"}):null,e.status==="failed"?L.jsxs(En,{sx:{mt:.1,display:"flex",gap:1,alignItems:"center"},children:[L.jsx(ti,{variant:"caption",color:"error",children:e.errorText}),L.jsx(Cl,{sx:{p:0},size:"small",color:"primary",onClick:()=>a({id:e.id,role:"user",content:e.text}),children:L.jsx(w6,{sx:{fontSize:18}})})]}):null]},"container"+e.id)}function UL({msg:e,isMe:t}){return L.jsxs(En,{children:[L.jsx(Pc,{sx:{width:30,height:30,mt:.25,bgcolor:"primary.main"},children:L.jsx(Em,{sx:{fontSize:18}})}),e.sentAt&&L.jsx(En,{sx:{display:"flex",justifyContent:t?"flex-end":"flex-start",mt:.5},children:L.jsx(ti,{variant:"caption",sx:{color:"text.secondary",fontSize:11},children:e.sentAt})})]},"asistent"+e.id)}function jL({msg:e,isMe:t}){return L.jsxs(En,{children:[L.jsx(Pc,{sx:{width:30,height:30,mt:.25,bgcolor:"grey.900"},children:L.jsx(_6,{sx:{fontSize:18}})}),e.sentAt&&L.jsx(En,{sx:{display:"flex",justifyContent:t?"flex-end":"flex-start",mt:.5},children:L.jsx(ti,{variant:"caption",sx:{color:"text.secondary",fontSize:11},children:e.sentAt})})]},"sentAt"+e.id)}const HL=Jn.memo(function({msgs:t,isMessageSeen:n,endRef:r,reSend:a}){return L.jsxs(L.Fragment,{children:[t.map((s,u)=>{const f=s.role==="User",{showSeenIndicator:d,isSeen:h}=n(u,f,t,s);return L.jsxs(En,{sx:{display:"flex",justifyContent:f?"flex-end":"flex-start",gap:1,mb:1.2,overflowAnchor:"none"},children:[!f&&L.jsx(UL,{msg:s,isMe:f}),L.jsx(PL,{msg:s,isMe:f,showSeenIndicator:d,isSeen:h,send:a}),f&&L.jsx(jL,{msg:s,isMe:f})]},s.id)}),L.jsx("div",{ref:r})]})});function VL(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}function FL(e){return/^[0-9]{6}$/.test(e)}const GL=async e=>{const t=da(),n=vo();if(n==null)throw new Error("Missing config");if(t==null)throw new Error("Conversation id is missing");const r=await fa(n.apiBaseUrl+ax+`/${n.clientId}/start`,{method:"POST",headers:{"Content-Type":"application/json","X-Conversation-Id":t},body:JSON.stringify(e)});if(!r.ok)throw new Error("Somethig happend on the request");return await r.json()},qL=async e=>{const t=da(),n=vo();if(n==null)throw new Error("Missing config");if(t==null)throw new Error("Conversation id is missing");const r=await fa(n.apiBaseUrl+ax+`/${n.clientId}/confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Conversation-Id":t},body:JSON.stringify(e)});if(!r.ok)throw new Error("Somethig happend on the request");return await r.json()},YL=({request:e,onValidationSuccess:t})=>{const[n,r]=N.useState(""),[a,s]=N.useState(""),[u,f]=N.useState(!0),d=g=>{if(!FL(n)){f(!1);return}qL({requestId:e?.requestId||"",code:n}).then(y=>{if(y.verified){t();return}s(y.failureReason)})},h=()=>a||null;return L.jsxs(Fc,{spacing:1,sx:{position:"relative",p:2,bgcolor:"background.paper",borderRadius:2,boxShadow:"0 4px 12px rgba(0,0,0,.1)",maxWidth:380,mb:2,display:"flex",flexDirection:"column",alignItems:"center"},children:[L.jsxs(ti,{variant:"body1",align:"center",gutterBottom:!0,sx:{wordBreak:"break-word"},children:["Introdu codul primit la ",e?.contact]}),L.jsx(Ip,{focused:!0,fullWidth:!0,size:"small",value:n,onChange:g=>{r(g.target.value),f(!0)},error:h()!=null,helperText:h()}),L.jsx(Uc,{variant:"outlined",color:"primary",onClick:d,children:"Trimite codul"})]})},XL=({setRequest:e,setDisplayOtpForm:t})=>{const[n,r]=N.useState(""),[a,s]=N.useState(!0),u=async f=>{if(!VL(n)){s(!1);return}GL({channel:"email",value:n}).then(d=>{e(d),t(!0)})};return L.jsxs(Fc,{spacing:1,sx:{position:"relative",p:2,bgcolor:"background.paper",borderRadius:2,boxShadow:"0 4px 12px rgba(0,0,0,.1)",maxWidth:380,mb:2,display:"flex",flexDirection:"column",alignItems:"center"},children:[L.jsx(ti,{variant:"h6",gutterBottom:!0,children:"Introdu adresa de email"}),L.jsx(Ip,{focused:!0,fullWidth:!0,size:"small",value:n,onChange:f=>{r(f.target.value),s(!0)},error:!a,helperText:a?void 0:"Adresa de email nu este validă"}),L.jsx(Uc,{variant:"outlined",color:"primary",onClick:u,children:"Trimite"}),L.jsx(ti,{variant:"body2",color:"text.secondary",children:"Vom trimite un cod de verificare la aceasta."})]})},ZL=({verificationRequest:e,send:t,setToolCallEvents:n})=>{const[r,a]=N.useState(!1),[s,u]=N.useState(),f=N.useCallback(()=>{const d=e.delta;t({role:"tool",toolCallId:e.toolCallId,content:JSON.stringify({approval_id:d.request.approval_id,approved:!0}),id:""})},[]);return L.jsx(L.Fragment,{children:r?L.jsx(YL,{request:s,onValidationSuccess:f}):L.jsx(XL,{setDisplayOtpForm:a,setRequest:u})})},KL="request_verification",WL=({toolCallEvents:e,setToolCallEvents:t,send:n})=>{const[r,a]=N.useState("email");if(!e)return null;const s=e.filter(u=>u.toolCallName==KL)[0];return s&&r==="email"?L.jsx(ZL,{verificationRequest:s,send:n,setToolCallEvents:t}):null},QL=()=>L.jsxs(En,{sx:{display:"flex",alignItems:"flex-end",gap:1,mb:1.2},children:[L.jsx(Pc,{sx:{width:30,height:30,bgcolor:"primary.main"},children:L.jsx(Em,{sx:{fontSize:18}})}),L.jsxs(En,{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(En,{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(En,{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(En,{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}}}})]})]}),JL={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 e$({msgs:e,isMessageSeen:t,send:n,sending:r,items:a,endRef:s,toolCallEvents:u,setToolCallEvents:f}){return L.jsxs(En,{sx:JL,children:[L.jsx(HL,{msgs:e,isMessageSeen:t,reSend:n}),L.jsx("div",{style:{paddingBottom:2},children:r&&L.jsx(QL,{})}),a.map(d=>L.jsx(E6,{error:d.message,onClose:()=>Bf.getState().remove(d.id)},d.id)),L.jsx(WL,{toolCallEvents:u,setToolCallEvents:f,send:n}),L.jsx(iI,{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 t$({inputRef:e,input:t,sending:n,setInput:r,send:a}){return L.jsx(En,{sx:{p:1.25,borderTop:"1px solid",borderColor:"divider",display:"flex",gap:1,bgcolor:"background.paper",flexShrink:0},children:L.jsx(Ip,{inputRef:e,focused:!0,size:"small",fullWidth:!0,value:t,disabled:n||t.length>=Q5,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(Cl,{size:"small",onClick:()=>a(),disabled:n||!t.trim(),sx:{ml:.5,borderRadius:999},children:L.jsx(C6,{})})}})})}const n$=async e=>{const t=da(),n=vo();if(n==null)throw new Error("Missing config");if(t==null)throw new Error("Conversation id is missing");await fa(n.apiBaseUrl+Hl+`/${n.clientId}/conversation-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Conversation-Id":t},body:JSON.stringify(e)})};function r$({open:e,setOpen:t,msgs:n,input:r,setInput:a,sending:s,send:u,anchorSx:f,conversationMode:d,setConversationStatus:h,toolCallEvents:g,setToolCallEvents:y}){const b=Bf(O=>O.items),v=N.useRef(null),x=N.useRef(null),E=_l(),_=ZI(E.breakpoints.down("md"));b6(),N.useEffect(()=>{x.current?.scrollIntoView({behavior:"smooth",block:"end"}),requestAnimationFrame(()=>v.current?.focus())},[n.length,s]),N.useEffect(()=>{e&&x.current?.scrollIntoView({behavior:"auto",block:"end"})},[e]),N.useEffect(()=>{if(!(e&&_))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,_]);const w=N.useCallback((O,T,A,M)=>{const R=O===A.length-1,$=A[A.length-1],H=R&&T&&$?.seen,V=H&&$?.id===M.id;return{showSeenIndicator:H,isSeen:V}},[]);return L.jsxs(En,{sx:f,children:[!e&&L.jsx(Uc,{variant:"contained",onClick:()=>t(!0),startIcon:L.jsx(y6,{}),sx:{borderRadius:999,px:2,py:1,textTransform:"none",boxShadow:"0 10px 30px rgba(0,0,0,.18)"},children:"Chat"}),e&&L.jsx(Rc,{elevation:_?0:10,sx:{width:_?"100vw":380,height:_?"calc(var(--vh, 1vh) * 100)":560,"@supports (height: 100dvh)":{height:_?"100dvh":560},maxWidth:"100vw",maxHeight:"100dvh",borderRadius:_?0:4,position:_?"fixed":"relative",inset:_?0:"auto",overflow:"hidden",border:_?"none":"1px solid",borderColor:"divider",boxShadow:_?"none":"0 18px 60px rgba(0,0,0,.28)"},children:L.jsxs(En,{sx:{display:"flex",flexDirection:"column",height:"100%"},children:[L.jsx(x6,{isMobile:_,conversationMode:d,setOpen:t}),L.jsx(e$,{msgs:n,isMessageSeen:w,send:u,sending:s,items:b,endRef:x,toolCallEvents:g,setToolCallEvents:y}),d==="Human"&&L.jsx(i$,{conversationMode:d,setConversationStatus:h}),L.jsx(t$,{inputRef:v,input:r,sending:s,setInput:a,send:u})]})})]})}const i$=({conversationMode:e,setConversationStatus:t})=>L.jsx(Rc,{elevation:0,sx:{mx:2,mt:1.5,mb:1,px:2,py:1.5,border:"1px solid",borderColor:"divider",borderRadius:3,bgcolor:"background.paper",boxShadow:"0 6px 18px rgba(15, 23, 42, 0.04)"},children:L.jsxs(Fc,{direction:{xs:"column",sm:"row"},spacing:1.5,alignItems:{xs:"center",sm:"flex-start"},justifyContent:"space-between",children:[L.jsxs(Fc,{direction:"row",spacing:1,alignItems:"center",flexWrap:"wrap",children:[L.jsx(vN,{size:"small",icon:e==="Human"?L.jsx(A6,{}):L.jsx(T6,{}),label:e==="Human"?"Operator activ":"Asistent activ",color:e==="Human"?"warning":"success",variant:"outlined",sx:{height:28,borderRadius:2,"& .MuiChip-label":{px:1.25,fontWeight:600}}}),L.jsx(ti,{variant:"body2",color:"text.secondary",children:e==="Human"?"Puteți reveni oricând la asistentul virtual.":"Asistentul răspunde automat mesajelor."})]}),e==="Human"&&L.jsx(Uc,{variant:"contained",size:"small",onClick:async()=>{await n$("Bot"),t({mode:"Bot",state:"AI_ACTIVE"})},sx:{px:2.5,py:1.1,borderRadius:2.5,textTransform:"none",fontWeight:700,boxShadow:"0 8px 24px rgba(25, 118, 210, 0.18)","&:hover":{boxShadow:"0 10px 28px rgba(25, 118, 210, 0.24)"}},children:"Revino la asistentul virtual"})]})});class pa extends Error{constructor(t,n){const r=new.target.prototype;super(`${t}: Status code '${n}'`),this.statusCode=n,this.__proto__=r}}class ag extends Error{constructor(t="A timeout occurred."){const n=new.target.prototype;super(t),this.__proto__=n}}class ni extends Error{constructor(t="An abort occurred."){const n=new.target.prototype;super(t),this.__proto__=n}}class o$ extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.transport=n,this.errorType="UnsupportedTransportError",this.__proto__=r}}class a$ extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.transport=n,this.errorType="DisabledTransportError",this.__proto__=r}}class s$ extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.transport=n,this.errorType="FailedToStartTransportError",this.__proto__=r}}class DE extends Error{constructor(t){const n=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=n}}class l$ extends Error{constructor(t,n){const r=new.target.prototype;super(t),this.innerErrors=n,this.__proto__=r}}class BE{constructor(t,n,r){this.statusCode=t,this.statusText=n,this.content=r}}class Yf{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 ae;(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"})(ae||(ae={}));class Jl{constructor(){}log(t,n){}}Jl.instance=new Jl;const u$="10.0.0";class Cn{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 nn{static get isBrowser(){return!nn.isNode&&typeof window=="object"&&typeof window.document=="object"}static get isWebWorker(){return!nn.isNode&&typeof self=="object"&&"importScripts"in self}static get isReactNative(){return!nn.isNode&&typeof window=="object"&&typeof window.document>"u"}static get isNode(){return typeof process<"u"&&process.release&&process.release.name==="node"}}function eu(e,t){let n="";return ma(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${c$(e)}'`)):typeof e=="string"&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function c$(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 zE(e,t,n,r,a,s){const u={},[f,d]=hs();u[f]=d,e.log(ae.Trace,`(${t} transport) sending data. ${eu(a,s.logMessageContent)}.`);const h=ma(a)?"arraybuffer":"text",g=await n.post(r,{content:a,headers:{...u,...s.headers},responseType:h,timeout:s.timeout,withCredentials:s.withCredentials});e.log(ae.Trace,`(${t} transport) request complete. Response status: ${g.statusCode}.`)}function f$(e){return e===void 0?new Xf(ae.Information):e===null?Jl.instance:e.log!==void 0?e:new Xf(e)}class d${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 Xf{constructor(t){this._minLevel=t,this.out=console}log(t,n){if(t>=this._minLevel){const r=`[${new Date().toISOString()}] ${ae[t]}: ${n}`;switch(t){case ae.Critical:case ae.Error:this.out.error(r);break;case ae.Warning:this.out.warn(r);break;case ae.Information:this.out.info(r);break;default:this.out.log(r);break}}}}function hs(){let e="X-SignalR-User-Agent";return nn.isNode&&(e="User-Agent"),[e,h$(u$,p$(),g$(),m$())]}function h$(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 p$(){if(nn.isNode)switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}else return""}function m$(){if(nn.isNode)return process.versions.node}function g$(){return nn.isNode?"NodeJS":"Browser"}function sg(e){return e.stack?e.stack:e.message?e.message:`${e}`}function y$(){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 v$ extends Yf{constructor(t){if(super(),this._logger=t,typeof fetch>"u"||nn.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(y$());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 ni;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 ni});let a=null;if(t.timeout){const d=t.timeout;a=setTimeout(()=>{n.abort(),this._logger.log(ae.Warning,"Timeout from HTTP request."),r=new ag},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(ae.Warning,`Error from HTTP request. ${d}.`),d)}finally{a&&clearTimeout(a),t.abortSignal&&(t.abortSignal.onabort=null)}if(!s.ok){const d=await LE(s,"text");throw new pa(d||s.statusText,s.status)}const f=await LE(s,t.responseType);return new BE(s.status,s.statusText,f)}getCookieString(t){let n="";return nn.isNode&&this._jar&&this._jar.getCookies(t,(r,a)=>n=a.join("; ")),n}}function LE(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 b$ extends Yf{constructor(t){super(),this._logger=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new ni):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 ni)}),t.timeout&&(a.timeout=t.timeout),a.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),a.status>=200&&a.status<300?n(new BE(a.status,a.statusText,a.response||a.responseText)):r(new pa(a.response||a.responseText||a.statusText,a.status))},a.onerror=()=>{this._logger.log(ae.Warning,`Error from HTTP request. ${a.status}: ${a.statusText}.`),r(new pa(a.statusText,a.status))},a.ontimeout=()=>{this._logger.log(ae.Warning,"Timeout from HTTP request."),r(new ag)},a.send(t.content)}):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class S$ extends Yf{constructor(t){if(super(),typeof fetch<"u"||nn.isNode)this._httpClient=new v$(t);else if(typeof XMLHttpRequest<"u")this._httpClient=new b$(t);else throw new Error("No usable HttpClient found.")}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new ni):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 Er{static write(t){return`${t}${Er.RecordSeparator}`}static parse(t){if(t[t.length-1]!==Er.RecordSeparator)throw new Error("Message is incomplete.");const n=t.split(Er.RecordSeparator);return n.pop(),n}}Er.RecordSeparatorCode=30,Er.RecordSeparator=String.fromCharCode(Er.RecordSeparatorCode);class x${writeHandshakeRequest(t){return Er.write(JSON.stringify(t))}parseHandshakeResponse(t){let n,r;if(ma(t)){const f=new Uint8Array(t),d=f.indexOf(Er.RecordSeparatorCode);if(d===-1)throw new Error("Message is incomplete.");const h=d+1;n=String.fromCharCode.apply(null,Array.prototype.slice.call(f.slice(0,h))),r=f.byteLength>h?f.slice(h).buffer:null}else{const f=t,d=f.indexOf(Er.RecordSeparator);if(d===-1)throw new Error("Message is incomplete.");const h=d+1;n=f.substring(0,h),r=f.length>h?f.substring(h):null}const a=Er.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 E${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 d$(this,t)}}class _${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 w$(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 w${constructor(t,n,r,a){this._message=t,this._id=n,this._resolver=r,this._rejector=a}}const C$=30*1e3,T$=15*1e3,A$=1e5;var Nt;(function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"})(Nt||(Nt={}));class lg{static create(t,n,r,a,s,u,f){return new lg(t,n,r,a,s,u,f)}constructor(t,n,r,a,s,u,f){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(ae.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")},Cn.isRequired(t,"connection"),Cn.isRequired(n,"logger"),Cn.isRequired(r,"protocol"),this.serverTimeoutInMilliseconds=s??C$,this.keepAliveIntervalInMilliseconds=u??T$,this._statefulReconnectBufferSize=f??A$,this._logger=n,this._protocol=r,this.connection=t,this._reconnectPolicy=a,this._handshakeProtocol=new x$,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=Nt.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!==Nt.Disconnected&&this._connectionState!==Nt.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!==Nt.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=Nt.Connecting,this._logger.log(ae.Debug,"Starting HubConnection.");try{await this._startInternal(),nn.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=Nt.Connected,this._connectionStarted=!0,this._logger.log(ae.Debug,"HubConnection connected successfully.")}catch(t){return this._connectionState=Nt.Disconnected,this._logger.log(ae.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(ae.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(r)),this._logger.log(ae.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 _$(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(ae.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===Nt.Disconnected)return this._logger.log(ae.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===Nt.Disconnecting)return this._logger.log(ae.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=Nt.Disconnecting,this._logger.log(ae.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(ae.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(n===Nt.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=t||new ni("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 E$;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,h)=>{if(h){f.error(h);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]=(g,y)=>{if(y){d(y);return}else g&&(g.type===qe.Completion?g.error?d(new Error(g.error)):f(g.result):d(new Error(`Unexpected message type: ${g.type}`)))};const h=this._sendWithProtocol(s).catch(g=>{d(g),delete this._callbacks[s.invocationId]});this._launchStreams(r,h)})}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(ae.Error,`Invoke client method threw error: ${sg(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(ae.Error,`Stream callback threw error: ${sg(s)}`)}}break}case qe.Ping:break;case qe.Close:{this._logger.log(ae.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(ae.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(ae.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(ae.Error,a);const s=new Error(a);throw this._handshakeRejecter(s),s}else this._logger.log(ae.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===Nt.Connected&&this._trySendPingMessage();return}this._pingServerHandle===void 0&&(t<0&&(t=0),this._pingServerHandle=setTimeout(async()=>{this._connectionState===Nt.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(ae.Warning,`No client method with the name '${n}' found.`),t.invocationId&&(this._logger.log(ae.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 h of a)try{const g=u;u=await h.apply(this,t.arguments),s&&u&&g&&(this._logger.log(ae.Error,`Multiple results provided for '${n}'. Sending error to server.`),d=this._createCompletionMessage(t.invocationId,"Client provided multiple results.",null)),f=void 0}catch(g){f=g,this._logger.log(ae.Error,`A callback for the method '${n}' threw error '${g}'.`)}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(ae.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(ae.Error,`Result given for '${n}' method but server is not expecting a result.`)}_connectionClosed(t){this._logger.log(ae.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||t||new ni("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===Nt.Disconnecting?this._completeClose(t):this._connectionState===Nt.Connected&&this._reconnectPolicy?this._reconnect(t):this._connectionState===Nt.Connected&&this._completeClose(t)}_completeClose(t){if(this._connectionStarted){this._connectionState=Nt.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(t??new Error("Connection closed.")),this._messageBuffer=void 0),nn.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach(n=>n.apply(this,[t]))}catch(n){this._logger.log(ae.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(ae.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),this._completeClose(t);return}if(this._connectionState=Nt.Reconnecting,t?this._logger.log(ae.Information,`Connection reconnecting because of error '${t}'.`):this._logger.log(ae.Information,"Connection reconnecting."),this._reconnectingCallbacks.length!==0){try{this._reconnectingCallbacks.forEach(u=>u.apply(this,[t]))}catch(u){this._logger.log(ae.Error,`An onreconnecting callback called with error '${t}' threw error '${u}'.`)}if(this._connectionState!==Nt.Reconnecting){this._logger.log(ae.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");return}}for(;s!==null;){if(this._logger.log(ae.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!==Nt.Reconnecting){this._logger.log(ae.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");return}try{if(await this._startInternal(),this._connectionState=Nt.Connected,this._logger.log(ae.Information,"HubConnection reconnected successfully."),this._reconnectedCallbacks.length!==0)try{this._reconnectedCallbacks.forEach(u=>u.apply(this,[this.connection.connectionId]))}catch(u){this._logger.log(ae.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${u}'.`)}return}catch(u){if(this._logger.log(ae.Information,`Reconnect attempt failed because of error '${u}'.`),this._connectionState!==Nt.Reconnecting){this._logger.log(ae.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),this._connectionState===Nt.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(ae.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(ae.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(ae.Error,`Stream 'error' callback called with '${t}' threw error: ${sg(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 k$=[0,2e3,1e4,3e4,null];class $E{constructor(t){this._retryDelays=t!==void 0?[...t,null]:k$}nextRetryDelayInMilliseconds(t){return this._retryDelays[t.previousRetryCount]}}class ga{}ga.Authorization="Authorization",ga.Cookie="Cookie";class R$ extends Yf{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[ga.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&t.headers[ga.Authorization]&&delete t.headers[ga.Authorization]}getCookieString(t){return this._innerClient.getCookieString(t)}}var Nn;(function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"})(Nn||(Nn={}));var Wn;(function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"})(Wn||(Wn={}));let O$=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 PE{get pollAborted(){return this._pollAbort.aborted}constructor(t,n,r){this._httpClient=t,this._logger=n,this._pollAbort=new O$,this._options=r,this._running=!1,this.onreceive=null,this.onclose=null}async connect(t,n){if(Cn.isRequired(t,"url"),Cn.isRequired(n,"transferFormat"),Cn.isIn(n,Wn,"transferFormat"),this._url=t,this._logger.log(ae.Trace,"(LongPolling transport) Connecting."),n===Wn.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]=hs(),s={[r]:a,...this._options.headers},u={abortSignal:this._pollAbort.signal,headers:s,timeout:1e5,withCredentials:this._options.withCredentials};n===Wn.Binary&&(u.responseType="arraybuffer");const f=`${t}&_=${Date.now()}`;this._logger.log(ae.Trace,`(LongPolling transport) polling: ${f}.`);const d=await this._httpClient.get(f,u);d.statusCode!==200?(this._logger.log(ae.Error,`(LongPolling transport) Unexpected response code: ${d.statusCode}.`),this._closeError=new pa(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(ae.Trace,`(LongPolling transport) polling: ${r}.`);const a=await this._httpClient.get(r,n);a.statusCode===204?(this._logger.log(ae.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):a.statusCode!==200?(this._logger.log(ae.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new pa(a.statusText||"",a.statusCode),this._running=!1):a.content?(this._logger.log(ae.Trace,`(LongPolling transport) data received. ${eu(a.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(a.content)):this._logger.log(ae.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(r){this._running?r instanceof ag?this._logger.log(ae.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=r,this._running=!1):this._logger.log(ae.Trace,`(LongPolling transport) Poll errored after shutdown: ${r.message}`)}}finally{this._logger.log(ae.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(t){return this._running?zE(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(ae.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(ae.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const t={},[n,r]=hs();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 pa&&(s.statusCode===404?this._logger.log(ae.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(ae.Trace,`(LongPolling transport) Error sending a DELETE request: ${s}`)):this._logger.log(ae.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(ae.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(ae.Trace,t),this.onclose(this._closeError)}}}class N${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 Cn.isRequired(t,"url"),Cn.isRequired(n,"transferFormat"),Cn.isIn(n,Wn,"transferFormat"),this._logger.log(ae.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!==Wn.Text){a(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));return}let u;if(nn.isBrowser||nn.isWebWorker)u=new this._options.EventSource(t,{withCredentials:this._options.withCredentials});else{const f=this._httpClient.getCookieString(t),d={};d.Cookie=f;const[h,g]=hs();d[h]=g,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(ae.Trace,`(SSE transport) data received. ${eu(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(ae.Information,`SSE connected to ${this._url}`),this._eventSource=u,s=!0,r()}}catch(f){a(f);return}})}async send(t){return this._eventSource?zE(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 I${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){Cn.isRequired(t,"url"),Cn.isRequired(n,"transferFormat"),Cn.isIn(n,Wn,"transferFormat"),this._logger.log(ae.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(nn.isNode||nn.isReactNative){const h={},[g,y]=hs();h[g]=y,r&&(h[ga.Authorization]=`Bearer ${r}`),f&&(h[ga.Cookie]=f),u=new this._webSocketConstructor(t,void 0,{headers:{...h,...this._headers}})}else r&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(r)}`);u||(u=new this._webSocketConstructor(t)),n===Wn.Binary&&(u.binaryType="arraybuffer"),u.onopen=h=>{this._logger.log(ae.Information,`WebSocket connected to ${t}.`),this._webSocket=u,d=!0,a()},u.onerror=h=>{let g=null;typeof ErrorEvent<"u"&&h instanceof ErrorEvent?g=h.error:g="There was an error with the transport",this._logger.log(ae.Information,`(WebSockets transport) ${g}.`)},u.onmessage=h=>{if(this._logger.log(ae.Trace,`(WebSockets transport) data received. ${eu(h.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(h.data)}catch(g){this._close(g);return}},u.onclose=h=>{if(d)this._close(h);else{let g=null;typeof ErrorEvent<"u"&&h instanceof ErrorEvent?g=h.error:g="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(g))}}})}send(t){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(ae.Trace,`(WebSockets transport) sending data. ${eu(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(ae.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 UE=100;class M${constructor(t,n={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Cn.isRequired(t,"url"),this._logger=f$(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(nn.isNode&&typeof require<"u"){const s=typeof __webpack_require__=="function"?__non_webpack_require__:require;r=s("ws"),a=s("eventsource")}!nn.isNode&&typeof WebSocket<"u"&&!n.WebSocket?n.WebSocket=WebSocket:nn.isNode&&!n.WebSocket&&r&&(n.WebSocket=r),!nn.isNode&&typeof EventSource<"u"&&!n.EventSource?n.EventSource=EventSource:nn.isNode&&!n.EventSource&&typeof a<"u"&&(n.EventSource=a),this._httpClient=new R$(n.httpClient||new S$(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||Wn.Binary,Cn.isIn(t,Wn,"transferFormat"),this._logger.log(ae.Debug,`Starting connection with transfer format '${Wn[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(ae.Error,n),await this._stopPromise,Promise.reject(new ni(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(ae.Error,n),Promise.reject(new ni(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 ug(this.transport)),this._sendQueue.send(t))}async stop(t){if(this._connectionState==="Disconnected")return this._logger.log(ae.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(ae.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(ae.Error,`HttpConnection.transport.stop() threw error '${n}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(ae.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===Nn.WebSockets)this.transport=this._constructTransport(Nn.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 ni("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<UE);if(a===UE&&r.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(n,this._options.transport,r,t)}this.transport instanceof PE&&(this.features.inherentKeepAlive=!0),this._connectionState==="Connecting"&&(this._logger.log(ae.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(r){return this._logger.log(ae.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]=hs();n[r]=a;const s=this._resolveNegotiateUrl(t);this._logger.log(ae.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 DE("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 pa&&u.statusCode===404&&(f=f+" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(ae.Error,f),Promise.reject(new DE(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(ae.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 h of f){const g=this._resolveTransportOrError(h,n,a,d?.useStatefulReconnect===!0);if(g instanceof Error)u.push(`${h.transport} failed:`),u.push(g);else if(this._isITransport(g)){if(this.transport=g,!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(ae.Error,`Failed to start the transport '${h.transport}': ${y}`),d=void 0,u.push(new s$(`${h.transport} failed: ${y}`,Nn[h.transport])),this._connectionState!=="Connecting"){const b="Failed to select transport before stop() was called.";return this._logger.log(ae.Debug,b),Promise.reject(new ni(b))}}}}return u.length>0?Promise.reject(new l$(`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 Nn.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new I$(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case Nn.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new N$(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case Nn.LongPolling:return new PE(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=Nn[t.transport];if(s==null)return this._logger.log(ae.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(D$(n,s))if(t.transferFormats.map(f=>Wn[f]).indexOf(r)>=0){if(s===Nn.WebSockets&&!this._options.WebSocket||s===Nn.ServerSentEvents&&!this._options.EventSource)return this._logger.log(ae.Debug,`Skipping transport '${Nn[s]}' because it is not supported in your environment.'`),new o$(`'${Nn[s]}' is not supported in your environment.`,s);this._logger.log(ae.Debug,`Selecting transport '${Nn[s]}'.`);try{return this.features.reconnect=s===Nn.WebSockets?a:void 0,this._constructTransport(s)}catch(f){return f}}else return this._logger.log(ae.Debug,`Skipping transport '${Nn[s]}' because it does not support the requested transfer format '${Wn[r]}'.`),new Error(`'${Nn[s]}' does not support ${Wn[r]}.`);else return this._logger.log(ae.Debug,`Skipping transport '${Nn[s]}' because it was disabled by the client.`),new a$(`'${Nn[s]}' is disabled by the client.`,s)}_isITransport(t){return t&&typeof t=="object"&&"connect"in t}_stopConnection(t){if(this._logger.log(ae.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(ae.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(ae.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(ae.Error,`Connection disconnected with error '${t}'.`):this._logger.log(ae.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch(n=>{this._logger.log(ae.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(ae.Error,`HttpConnection.onclose(${t}) threw error '${n}'.`)}}}_resolveUrl(t){if(t.lastIndexOf("https://",0)===0||t.lastIndexOf("http://",0)===0)return t;if(!nn.isBrowser)throw new Error(`Cannot resolve '${t}'.`);const n=window.document.createElement("a");return n.href=t,this._logger.log(ae.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 D$(e,t){return!e||(t&e)!==0}class ug{constructor(t){this._transport=t,this._buffer=[],this._executing=!0,this._sendBufferedData=new Zf,this._transportResult=new Zf,this._sendLoopPromise=this._sendLoop()}send(t){return this._bufferData(t),this._transportResult||(this._transportResult=new Zf),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 Zf;const t=this._transportResult;this._transportResult=void 0;const n=typeof this._buffer[0]=="string"?this._buffer.join(""):ug._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 Zf{constructor(){this.promise=new Promise((t,n)=>[this._resolver,this._rejecter]=[t,n])}resolve(){this._resolver()}reject(t){this._rejecter(t)}}const B$="json";class z${constructor(){this.name=B$,this.version=2,this.transferFormat=Wn.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=Jl.instance);const r=Er.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(ae.Information,"Unknown message type '"+u.type+"' ignored.");continue}a.push(u)}return a}writeMessage(t){return Er.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 L$={trace:ae.Trace,debug:ae.Debug,info:ae.Information,information:ae.Information,warn:ae.Warning,warning:ae.Warning,error:ae.Error,critical:ae.Critical,none:ae.None};function $$(e){const t=L$[e.toLowerCase()];if(typeof t<"u")return t;throw new Error(`Unknown log level: ${e}`)}class P${configureLogging(t){if(Cn.isRequired(t,"logging"),U$(t))this.logger=t;else if(typeof t=="string"){const n=$$(t);this.logger=new Xf(n)}else this.logger=new Xf(t);return this}withUrl(t,n){return Cn.isRequired(t,"url"),Cn.isNotEmpty(t,"url"),this.url=t,typeof n=="object"?this.httpConnectionOptions={...this.httpConnectionOptions,...n}:this.httpConnectionOptions={...this.httpConnectionOptions,transport:n},this}withHubProtocol(t){return Cn.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 $E(t):this.reconnectPolicy=t:this.reconnectPolicy=new $E,this}withServerTimeout(t){return Cn.isRequired(t,"milliseconds"),this._serverTimeoutInMilliseconds=t,this}withKeepAliveInterval(t){return Cn.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 M$(this.url,t);return lg.create(n,this.logger||Jl.instance,this.protocol||new z$,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}function U$(e){return e.log!==void 0}function j$({url:e,accessToken:t,autoStart:n=!0}){const r=N.useRef(null),a=N.useRef(new Map),s=N.useRef(null),u=N.useRef(0),f=N.useRef(!1),[d,h]=N.useState("disconnected"),[g,y]=N.useState(null),b=N.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),v=N.useCallback(()=>{if(f.current||s.current)return;u.current+=1;const R=u.current,$=Math.min(3e4,1e3*Math.pow(2,R-1)),H=Math.floor(Math.random()*500),V=$+H;s.current=setTimeout(()=>{s.current=null,w()},V)},[b]),x=N.useCallback(R=>{a.current.forEach(($,H)=>{R.off(H),$.forEach(V=>{R.on(H,V)})})},[]),E=N.useCallback(async()=>Lf(),[]),_=N.useCallback(()=>{const R=new P$().withUrl(e,{accessTokenFactory:async()=>{const $=vo()?.sessionToken;return $||await E()}}).withAutomaticReconnect({nextRetryDelayInMilliseconds:$=>$.elapsedMilliseconds<6e4?Math.random()*1e4:null}).build();return R.onreconnecting(()=>{b(),h("reconnecting")}),R.onreconnected(()=>{b(),u.current=0,h("connected"),x(R)}),R.onclose($=>{h("disconnected"),$&&y($),f.current||v()}),R},[e,E,x,b,v]),w=N.useCallback(async()=>{f.current=!1,b(),r.current||(r.current=_());const R=r.current;if(R.state===Nt.Connected){h("connected");return}if(R.state===Nt.Connecting){h("connecting");return}if(R.state===Nt.Reconnecting){h("reconnecting");return}h("connecting");try{await R.start(),x(R),u.current=0,h("connected"),y(null)}catch($){y($),h("disconnected"),v()}},[x,_,b,v]),O=N.useCallback(async()=>{f.current=!0,b(),u.current=0;const R=r.current;if(r.current=null,!R){h("disconnected");return}try{await R.stop()}finally{h("disconnected")}},[b]),T=N.useCallback((R,$)=>{let H=a.current.get(R);H||(H=new Set,a.current.set(R,H)),H.add($);const V=r.current;V&&V.on(R,$)},[]),A=N.useCallback((R,$)=>{const H=a.current.get(R);if(!H)return;H.delete($),H.size===0&&a.current.delete(R);const V=r.current;V&&V.off(R,$)},[]),M=N.useCallback(async(R,...$)=>{const H=r.current;if(!H||H.state!==Nt.Connected)throw new Error("SignalR not connected");return H.invoke(R,...$)},[]);return N.useEffect(()=>(n&&w(),()=>{O()}),[n,w,O]),{status:d,connected:d==="connected",error:g,start:w,stop:O,on:T,off:A,invoke:M}}const H$=(()=>{const e=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return t=>e.call(t)})();function Kf(e){return H$(e)==="Uint8Array"}function V$(e){return typeof e=="object"&&e!=null&&Symbol.toStringTag in e&&(e[Symbol.toStringTag]==="ArrayBuffer"||e[Symbol.toStringTag]==="SharedArrayBuffer")}function F$(e){return e instanceof RegExp||Object.prototype.toString.call(e)==="[object RegExp]"}function jE(e){return typeof e=="object"&&e!=null&&Symbol.toStringTag in e&&e[Symbol.toStringTag]==="Map"}function G$(e){return e instanceof Date||Object.prototype.toString.call(e)==="[object Date]"}function _r(e,t){return JSON.stringify(e,(n,r)=>typeof r=="bigint"?{$numberLong:`${r}`}:jE(r)?Object.fromEntries(r):r)}function q$(e){if(e!=null&&typeof e=="object"&&"stylize"in e&&typeof e.stylize=="function")return e.stylize}const cg=7,HE=Symbol.for("@@mdb.bson.version"),fg=2147483647,dg=-2147483648,VE=Math.pow(2,63)-1,FE=-Math.pow(2,63),Y$=Math.pow(2,53),X$=-Math.pow(2,53),GE=4;class be extends Error{get bsonError(){return!0}get name(){return"BSONError"}constructor(t,n){super(t,n)}static isBSONError(t){return t!=null&&typeof t=="object"&&"bsonError"in t&&t.bsonError===!0&&"name"in t&&"message"in t&&"stack"in t}}class Z$ extends be{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${cg}.x.x`)}}class qE extends be{get name(){return"BSONRuntimeError"}constructor(t){super(t)}}class xo extends be{get name(){return"BSONOffsetError"}offset;constructor(t,n,r){super(`${t}. offset: ${n}`,r),this.offset=n}}let YE,XE;function ZE(e,t,n,r){if(r){YE??=new TextDecoder("utf8",{fatal:!0});try{return YE.decode(e.subarray(t,n))}catch(a){throw new be("Invalid UTF-8 string in BSON document",{cause:a})}}return XE??=new TextDecoder("utf8",{fatal:!1}),XE.decode(e.subarray(t,n))}function KE(e,t,n){if(e.length===0)return"";const r=n-t;if(r===0)return"";if(r>20)return null;if(r===1&&e[t]<128)return String.fromCharCode(e[t]);if(r===2&&e[t]<128&&e[t+1]<128)return String.fromCharCode(e[t])+String.fromCharCode(e[t+1]);if(r===3&&e[t]<128&&e[t+1]<128&&e[t+2]<128)return String.fromCharCode(e[t])+String.fromCharCode(e[t+1])+String.fromCharCode(e[t+2]);const a=[];for(let s=t;s<n;s++){const u=e[s];if(u>127)return null;a.push(u)}return String.fromCharCode(...a)}function K$(e,t,n){if(t.length===0)return 0;if(t.length>25||e.length-n<t.length)return null;for(let r=0,a=n;r<t.length;r++,a++){const s=t.charCodeAt(r);if(s>127)return null;e[a]=s}return t.length}function W$(e){return ri.fromNumberArray(Array.from({length:e},()=>Math.floor(Math.random()*256)))}function Q$(e){return crypto.getRandomValues(ri.allocate(e))}const J$=(()=>{const{crypto:e}=globalThis;return e!=null&&typeof e.getRandomValues=="function"?Q$:W$})(),ri={isUint8Array:Kf,toLocalBufferType(e){if(Buffer.isBuffer(e))return e;if(ArrayBuffer.isView(e))return Buffer.from(e.buffer,e.byteOffset,e.byteLength);const t=e?.[Symbol.toStringTag]??Object.prototype.toString.call(e);if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return Buffer.from(e);throw new be("Cannot create Buffer from the passed potentialBuffer.")},allocate(e){return Buffer.alloc(e)},allocateUnsafe(e){return Buffer.allocUnsafe(e)},compare(e,t){return ri.toLocalBufferType(e).compare(t)},concat(e){return Buffer.concat(e)},equals(e,t){return ri.toLocalBufferType(e).equals(t)},fromNumberArray(e){return Buffer.from(e)},fromBase64(e){return Buffer.from(e,"base64")},fromUTF8(e){return Buffer.from(e,"utf8")},toBase64(e){return ri.toLocalBufferType(e).toString("base64")},fromISO88591(e){return Buffer.from(e,"binary")},toISO88591(e){return ri.toLocalBufferType(e).toString("binary")},fromHex(e){return Buffer.from(e,"hex")},toHex(e){return ri.toLocalBufferType(e).toString("hex")},toUTF8(e,t,n,r){const a=n-t<=20?KE(e,t,n):null;if(a!=null)return a;const s=ri.toLocalBufferType(e).toString("utf8",t,n);if(r){for(let u=0;u<s.length;u++)if(s.charCodeAt(u)===65533){ZE(e,t,n,!0);break}}return s},utf8ByteLength(e){return Buffer.byteLength(e,"utf8")},encodeUTF8Into(e,t,n){const r=K$(e,t,n);return r??ri.toLocalBufferType(e).write(t,n,void 0,"utf8")},randomBytes:J$,swap32(e){return ri.toLocalBufferType(e).swap32()}};function eP(){const{navigator:e}=globalThis;return typeof e=="object"&&e.product==="ReactNative"}function tP(e){if(e<0)throw new RangeError(`The argument 'byteLength' is invalid. Received ${e}`);return ya.fromNumberArray(Array.from({length:e},()=>Math.floor(Math.random()*256)))}const nP=(()=>{const{crypto:e}=globalThis;if(e!=null&&typeof e.getRandomValues=="function")return t=>e.getRandomValues(ya.allocate(t));if(eP()){const{console:t}=globalThis;t?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return tP})(),WE=/(\d|[a-f])/i,ya={isUint8Array:Kf,toLocalBufferType(e){const t=e?.[Symbol.toStringTag]??Object.prototype.toString.call(e);if(t==="Uint8Array")return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return new Uint8Array(e);throw new be("Cannot make a Uint8Array from passed potentialBuffer.")},allocate(e){if(typeof e!="number")throw new TypeError(`The "size" argument must be of type number. Received ${String(e)}`);return new Uint8Array(e)},allocateUnsafe(e){return ya.allocate(e)},compare(e,t){if(e===t)return 0;const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return e.length<t.length?-1:e.length>t.length?1:0},concat(e){if(e.length===0)return ya.allocate(0);let t=0;for(const a of e)t+=a.length;const n=ya.allocate(t);let r=0;for(const a of e)n.set(a,r),r+=a.length;return n},equals(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},fromNumberArray(e){return Uint8Array.from(e)},fromBase64(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))},fromUTF8(e){return new TextEncoder().encode(e)},toBase64(e){return btoa(ya.toISO88591(e))},fromISO88591(e){return Uint8Array.from(e,t=>t.charCodeAt(0)&255)},toISO88591(e){return Array.from(Uint16Array.from(e),t=>String.fromCharCode(t)).join("")},fromHex(e){const t=e.length%2===0?e:e.slice(0,e.length-1),n=[];for(let r=0;r<t.length;r+=2){const a=t[r],s=t[r+1];if(!WE.test(a)||!WE.test(s))break;const u=Number.parseInt(`${a}${s}`,16);n.push(u)}return Uint8Array.from(n)},toHex(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")},toUTF8(e,t,n,r){const a=n-t<=20?KE(e,t,n):null;return a??ZE(e,t,n,r)},utf8ByteLength(e){return new TextEncoder().encode(e).byteLength},encodeUTF8Into(e,t,n){const r=new TextEncoder().encode(t);return e.set(r,n),r.byteLength},randomBytes:nP,swap32(e){if(e.length%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e.length;t+=4){const n=e[t],r=e[t+1],a=e[t+2],s=e[t+3];e[t]=s,e[t+1]=a,e[t+2]=r,e[t+3]=n}return e}},Be=typeof Buffer=="function"&&Buffer.prototype?._isBuffer!==!0?ri:ya,QE=Symbol.for("@@mdb.bson.type");class $r{get[QE](){return this._bsontype}get[HE](){return cg}[Symbol.for("nodejs.util.inspect.custom")](t,n,r){return this.inspect(t,n,r)}}const ps=new Float64Array(1),pt=new Uint8Array(ps.buffer,0,8);ps[0]=-1;const hg=pt[7]===0,va={isBigEndian:hg,getNonnegativeInt32LE(e,t){if(e[t+3]>127)throw new RangeError(`Size cannot be negative at offset: ${t}`);return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},getInt32LE(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},getUint32LE(e,t){return e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216},getUint32BE(e,t){return e[t+3]+e[t+2]*256+e[t+1]*65536+e[t]*16777216},getBigInt64LE(e,t){const n=BigInt(e[t+4]+e[t+5]*256+e[t+6]*65536+(e[t+7]<<24)),r=BigInt(e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216);return(n<<32n)+r},getFloat64LE:hg?(e,t)=>(pt[7]=e[t],pt[6]=e[t+1],pt[5]=e[t+2],pt[4]=e[t+3],pt[3]=e[t+4],pt[2]=e[t+5],pt[1]=e[t+6],pt[0]=e[t+7],ps[0]):(e,t)=>(pt[0]=e[t],pt[1]=e[t+1],pt[2]=e[t+2],pt[3]=e[t+3],pt[4]=e[t+4],pt[5]=e[t+5],pt[6]=e[t+6],pt[7]=e[t+7],ps[0]),setInt32BE(e,t,n){return e[t+3]=n,n>>>=8,e[t+2]=n,n>>>=8,e[t+1]=n,n>>>=8,e[t]=n,4},setInt32LE(e,t,n){return e[t]=n,n>>>=8,e[t+1]=n,n>>>=8,e[t+2]=n,n>>>=8,e[t+3]=n,4},setBigInt64LE(e,t,n){const r=0xffffffffn;let a=Number(n&r);e[t]=a,a>>=8,e[t+1]=a,a>>=8,e[t+2]=a,a>>=8,e[t+3]=a;let s=Number(n>>32n&r);return e[t+4]=s,s>>=8,e[t+5]=s,s>>=8,e[t+6]=s,s>>=8,e[t+7]=s,8},setFloat64LE:hg?(e,t,n)=>(ps[0]=n,e[t]=pt[7],e[t+1]=pt[6],e[t+2]=pt[5],e[t+3]=pt[4],e[t+4]=pt[3],e[t+5]=pt[2],e[t+6]=pt[1],e[t+7]=pt[0],8):(e,t,n)=>(ps[0]=n,e[t]=pt[0],e[t+1]=pt[1],e[t+2]=pt[2],e[t+3]=pt[3],e[t+4]=pt[4],e[t+5]=pt[5],e[t+6]=pt[6],e[t+7]=pt[7],8)};class ut extends $r{get _bsontype(){return"Binary"}static BSON_BINARY_SUBTYPE_DEFAULT=0;static BUFFER_SIZE=256;static SUBTYPE_DEFAULT=0;static SUBTYPE_FUNCTION=1;static SUBTYPE_BYTE_ARRAY=2;static SUBTYPE_UUID_OLD=3;static SUBTYPE_UUID=4;static SUBTYPE_MD5=5;static SUBTYPE_ENCRYPTED=6;static SUBTYPE_COLUMN=7;static SUBTYPE_SENSITIVE=8;static SUBTYPE_VECTOR=9;static SUBTYPE_USER_DEFINED=128;static VECTOR_TYPE=Object.freeze({Int8:3,Float32:39,PackedBit:16});buffer;sub_type;position;constructor(t,n){if(super(),t!=null&&typeof t=="string"&&!ArrayBuffer.isView(t)&&!V$(t)&&!Array.isArray(t))throw new be("Binary can only be constructed from Uint8Array or number[]");this.sub_type=n??ut.BSON_BINARY_SUBTYPE_DEFAULT,t==null?(this.buffer=Be.allocate(ut.BUFFER_SIZE),this.position=0):(this.buffer=Array.isArray(t)?Be.fromNumberArray(t):Be.toLocalBufferType(t),this.position=this.buffer.byteLength)}put(t){if(typeof t=="string"&&t.length!==1)throw new be("only accepts single character String");if(typeof t!="number"&&t.length!==1)throw new be("only accepts single character Uint8Array or Array");let n;if(typeof t=="string"?n=t.charCodeAt(0):typeof t=="number"?n=t:n=t[0],n<0||n>255)throw new be("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.byteLength>this.position)this.buffer[this.position++]=n;else{const r=Be.allocate(ut.BUFFER_SIZE+this.buffer.length);r.set(this.buffer,0),this.buffer=r,this.buffer[this.position++]=n}}write(t,n){if(n=typeof n=="number"?n:this.position,this.buffer.byteLength<n+t.length){const r=Be.allocate(this.buffer.byteLength+t.length);r.set(this.buffer,0),this.buffer=r}if(ArrayBuffer.isView(t))this.buffer.set(Be.toLocalBufferType(t),n),this.position=n+t.byteLength>this.position?n+t.length:this.position;else if(typeof t=="string")throw new be("input cannot be string")}read(t,n){n=n&&n>0?n:this.position;const r=t+n;return this.buffer.subarray(t,r>this.position?this.position:r)}value(){return this.buffer.length===this.position?this.buffer:this.buffer.subarray(0,this.position)}length(){return this.position}toJSON(){return Be.toBase64(this.buffer.subarray(0,this.position))}toString(t){return t==="hex"?Be.toHex(this.buffer.subarray(0,this.position)):t==="base64"?Be.toBase64(this.buffer.subarray(0,this.position)):t==="utf8"||t==="utf-8"?Be.toUTF8(this.buffer,0,this.position,!1):Be.toUTF8(this.buffer,0,this.position,!1)}toExtendedJSON(t){t=t||{},this.sub_type===ut.SUBTYPE_VECTOR&&Eo(this);const n=Be.toBase64(this.buffer),r=Number(this.sub_type).toString(16);return t.legacy?{$binary:n,$type:r.length===1?"0"+r:r}:{$binary:{base64:n,subType:r.length===1?"0"+r:r}}}toUUID(){if(this.sub_type===ut.SUBTYPE_UUID)return new ir(this.buffer.subarray(0,this.position));throw new be(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${ut.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString(t,n){return new ut(Be.fromHex(t),n)}static createFromBase64(t,n){return new ut(Be.fromBase64(t),n)}static fromExtendedJSON(t,n){n=n||{};let r,a;if("$binary"in t?n.legacy&&typeof t.$binary=="string"&&"$type"in t?(a=t.$type?parseInt(t.$type,16):0,r=Be.fromBase64(t.$binary)):typeof t.$binary!="string"&&(a=t.$binary.subType?parseInt(t.$binary.subType,16):0,r=Be.fromBase64(t.$binary.base64)):"$uuid"in t&&(a=4,r=ir.bytesFromString(t.$uuid)),!r)throw new be(`Unexpected Binary Extended JSON format ${JSON.stringify(t)}`);return a===GE?new ir(r):new ut(r,a)}inspect(t,n,r){r??=_r;const a=Be.toBase64(this.buffer.subarray(0,this.position)),s=r(a,n),u=r(this.sub_type,n);return`Binary.createFromBase64(${s}, ${u})`}toInt8Array(){if(this.sub_type!==ut.SUBTYPE_VECTOR)throw new be("Binary sub_type is not Vector");if(this.buffer[0]!==ut.VECTOR_TYPE.Int8)throw new be("Binary datatype field is not Int8");return Eo(this),new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toFloat32Array(){if(this.sub_type!==ut.SUBTYPE_VECTOR)throw new be("Binary sub_type is not Vector");if(this.buffer[0]!==ut.VECTOR_TYPE.Float32)throw new be("Binary datatype field is not Float32");Eo(this);const t=new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position));return va.isBigEndian&&Be.swap32(t),new Float32Array(t.buffer)}toPackedBits(){if(this.sub_type!==ut.SUBTYPE_VECTOR)throw new be("Binary sub_type is not Vector");if(this.buffer[0]!==ut.VECTOR_TYPE.PackedBit)throw new be("Binary datatype field is not packed bit");return Eo(this),new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toBits(){if(this.sub_type!==ut.SUBTYPE_VECTOR)throw new be("Binary sub_type is not Vector");if(this.buffer[0]!==ut.VECTOR_TYPE.PackedBit)throw new be("Binary datatype field is not packed bit");Eo(this);const n=(this.length()-2)*8-this.buffer[1],r=new Int8Array(n);for(let a=0;a<r.length;a++){const s=a/8|0,u=this.buffer[s+2],f=7-a%8,d=u>>f&1;r[a]=d}return r}static fromInt8Array(t){const n=Be.allocate(t.byteLength+2);n[0]=ut.VECTOR_TYPE.Int8,n[1]=0;const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n.set(r,2);const a=new this(n,this.SUBTYPE_VECTOR);return Eo(a),a}static fromFloat32Array(t){const n=Be.allocate(t.byteLength+2);n[0]=ut.VECTOR_TYPE.Float32,n[1]=0;const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n.set(r,2),va.isBigEndian&&Be.swap32(new Uint8Array(n.buffer,2));const a=new this(n,this.SUBTYPE_VECTOR);return Eo(a),a}static fromPackedBits(t,n=0){const r=Be.allocate(t.byteLength+2);r[0]=ut.VECTOR_TYPE.PackedBit,r[1]=n,r.set(t,2);const a=new this(r,this.SUBTYPE_VECTOR);return Eo(a),a}static fromBits(t){const n=t.length+7>>>3,r=new Uint8Array(n+2);r[0]=ut.VECTOR_TYPE.PackedBit;const a=t.length%8;r[1]=a===0?0:8-a;for(let s=0;s<t.length;s++){const u=s>>>3,f=t[s];if(f!==0&&f!==1)throw new be(`Invalid bit value at ${s}: must be 0 or 1, found ${t[s]}`);if(f===0)continue;const d=7-s%8;r[u+2]|=f<<d}return new this(r,ut.SUBTYPE_VECTOR)}}function Eo(e){if(e.sub_type!==ut.SUBTYPE_VECTOR)return;const t=e.position,n=e.buffer[0],r=e.buffer[1];if((n===ut.VECTOR_TYPE.Float32||n===ut.VECTOR_TYPE.Int8)&&r!==0)throw new be("Invalid Vector: padding must be zero for int8 and float32 vectors");if(n===ut.VECTOR_TYPE.Float32&&t!==0&&t-2!==0&&(t-2)%4!==0)throw new be("Invalid Vector: Float32 vector must contain a multiple of 4 bytes");if(n===ut.VECTOR_TYPE.PackedBit&&r!==0&&t===2)throw new be("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(n===ut.VECTOR_TYPE.PackedBit&&r>7)throw new be(`Invalid Vector: padding must be a value between 0 and 7. found: ${r}`)}const pg=16,rP=/^[0-9A-F]{32}$/i,iP=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;class ir extends ut{constructor(t){let n;if(t==null)n=ir.generate();else if(t instanceof ir)n=Be.toLocalBufferType(new Uint8Array(t.buffer));else if(ArrayBuffer.isView(t)&&t.byteLength===pg)n=Be.toLocalBufferType(t);else if(typeof t=="string")n=ir.bytesFromString(t);else throw new be("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");super(n,GE)}get id(){return this.buffer}set id(t){this.buffer=t}toHexString(t=!0){return t?[Be.toHex(this.buffer.subarray(0,4)),Be.toHex(this.buffer.subarray(4,6)),Be.toHex(this.buffer.subarray(6,8)),Be.toHex(this.buffer.subarray(8,10)),Be.toHex(this.buffer.subarray(10,16))].join("-"):Be.toHex(this.buffer)}toString(t){return t==="hex"?Be.toHex(this.id):t==="base64"?Be.toBase64(this.id):this.toHexString()}toJSON(){return this.toHexString()}equals(t){if(!t)return!1;if(t instanceof ir)return Be.equals(t.id,this.id);try{return Be.equals(new ir(t).id,this.id)}catch{return!1}}toBinary(){return new ut(this.id,ut.SUBTYPE_UUID)}static generate(){const t=Be.randomBytes(pg);return t[6]=t[6]&15|64,t[8]=t[8]&63|128,t}static isValid(t){return t?typeof t=="string"?ir.isValidUUIDString(t):Kf(t)?t.byteLength===pg:t._bsontype==="Binary"&&t.sub_type===this.SUBTYPE_UUID&&t.buffer.byteLength===16:!1}static createFromHexString(t){const n=ir.bytesFromString(t);return new ir(n)}static createFromBase64(t){return new ir(Be.fromBase64(t))}static bytesFromString(t){if(!ir.isValidUUIDString(t))throw new be("UUID string representation must be 32 hex digits or canonical hyphenated representation");return Be.fromHex(t.replace(/-/g,""))}static isValidUUIDString(t){return rP.test(t)||iP.test(t)}inspect(t,n,r){return r??=_r,`new UUID(${r(this.toHexString(),n)})`}}class tu extends $r{get _bsontype(){return"Code"}code;scope;constructor(t,n){super(),this.code=t.toString(),this.scope=n??null}toJSON(){return this.scope!=null?{code:this.code,scope:this.scope}:{code:this.code}}toExtendedJSON(){return this.scope?{$code:this.code,$scope:this.scope}:{$code:this.code}}static fromExtendedJSON(t){return new tu(t.$code,t.$scope)}inspect(t,n,r){r??=_r;let a=r(this.code,n);const s=a.includes(`
170
170
  `);this.scope!=null&&(a+=`,${s?`
171
171
  `:" "}${r(this.scope,n)}`);const u=s&&this.scope===null;return`new Code(${s?`
172
172
  `:""}${a}${u?`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ss-chatbot-widget",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "description": "Chatbot widget for customer support",
5
5
  "main": "./dist/x-bot-widget.js",
6
6
  "files": ["dist"],