@khvavuong/ezchat 1.1.16 → 1.1.17

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.
@@ -9,5 +9,5 @@
9
9
 
10
10
  `);return[ee(H({},i),{text:C,type:"normal",isNormalType:!0,contents:[{content:C}]})]}}if(((de=e.body)==null?void 0:de.type)==="MULTIPLE"&&s==="user"){const B=e.body.children.find(x=>x.type==="NORMAL"&&typeof x.content=="string");if(B&&B.content){const x=B.content.split("|").map(C=>C.trim()).join(`
11
11
 
12
- `);return[ee(H({},i),{text:x,type:"normal",isNormalType:!0,contents:[{content:x}]})]}}return s==="bot"&&e.body&&typeof e.body.content=="string"&&!e.body.type?[ee(H({},i),{text:e.body.content,type:"normal",isNormalType:!0,contents:[{content:e.body.content,metadata:e.body.metadata}]})]:[ee(H({},i),{type:"normal",isNormalType:!0,contents:i.text?[{content:i.text}]:[]})]}).flat().filter(e=>e.type==="choice"?!!e.question&&Array.isArray(e.options)&&e.options.length>0:e.type==="normal"?!!e.text&&e.text.trim()!=="":e.type==="form"?Array.isArray(e.fields)&&e.fields.length>0:e.type==="survey"?Array.isArray(e.options)&&e.options.length>0:!!e.text&&e.text.trim()!=="")}function Wi(t,e,n){var o;const s=[...t].reverse().find(r=>r.sender==="bot");let i;if(s&&s.contents&&Array.isArray(s.contents)&&(i=(o=s.contents.find(r=>r.metadata))==null?void 0:o.metadata),i){const r=parseInt(i.section),c=parseInt(i.totalSections)||6;e(r),n(c)}else e(1),n(6)}function Un(t){return v(this,null,function*(){var n,s,i;if(!t)return!1;const e=yield t.listConversationAsync(100);for(const o of e)if(o.id&&o.id.endsWith("~SURVEY")){const r=yield t.listMessagesAsync(o.id);let c=1,a=6;for(let d=r.length-1;d>=0;d--){const u=r[d];if(((n=u.sender)==null?void 0:n.id)!=="me"&&((s=u.body)!=null&&s.children)){const f=(i=u.body.children.find(j=>j.metadata))==null?void 0:i.metadata;if(f){c=parseInt(f.section),a=parseInt(f.totalSections)||6;break}}}if(c<a)return!0}return!1})}function jn(t,e,n,s,i,o,r,c,a){return v(this,null,function*(){if(!t.remoteRepo)return;const u=(yield t.remoteRepo.listConversationAsync(100)).find(f=>f.id&&f.id.endsWith("~SURVEY"));if(u)e.setCurrentConversation({id:u.id,name:u.name,type:"BOT"}),n(u.id),s(u.name),i(!0),o(new Set),r(!1),yield e.listMessagesAsync(u.id),c&&c();else{const f=`${Pt()}~SURVEY`,$=yield e.createConversationAsync({id:f,name:"Tư vấn đầu tư",type:"BOT",members:[{userId:"BOT~surveybot",role:"MEMBER"}],updatedAt:new Date});e.setCurrentConversation({id:$.id,name:$.name,type:"BOT"}),n($.id),s($.name),i(!0),o(new Set),r(!1),yield e.listMessagesAsync($.id),c&&c(),a&&a()}})}function qi(t,e){if(!e||t.length===0)return!0;const n=[...t].reverse().find(s=>s.sender==="bot");return!!(n&&n.type==="normal")}function Zi(t,e,n,s,i,o,r,c,a,d,u){return v(this,null,function*(){if(yield Un(t.remoteRepo)){alert("Bạn chưa hoàn thành khảo sát hiện tại!");return}const f=e.trim();if(!f){n("Vui lòng nhập tên cuộc hội thoại");return}if(f.length>100){n("Tên cuộc hội thoại không được quá 100 ký tự");return}n(void 0),s(!1);try{const j=Pt(),U=yield i.createConversationAsync({id:j,name:f,type:"BOT",members:[{userId:"BOT~rasaconnector",role:"MEMBER"}],updatedAt:new Date});i.setCurrentConversation({id:U.id,name:U.name,type:"BOT"}),o(U.id),r(U.name),c(!0),a(new Set),d(!1),yield i.listMessagesAsync(U.id),u&&u()}catch(j){console.error("Tạo hội thoại mới thất bại:",j)}})}function Yi(t,e,n,s){return v(this,null,function*(){var d,u,f,j;const{props:i,currentConversationId:o,formattedMessages:r,popup:c,setSubmittedMessages:a}=s;if(!(!i.remoteRepo||!o))try{const $=[...r].reverse().find(M=>M.type==="choice"&&M.sender==="bot");if(!$)return;const U=Array.isArray($.contents)&&$.contents.length>0?$.contents[$.contents.length-1].metadata||{}:{};a(M=>new Set([...M,n]));let W={};e==="ordered"?W={type:"RANKING",content:"",ranking:{items:((d=$.rawItems)==null?void 0:d.map(k=>ee(H({},k),{rank:t.indexOf(k.label)+1})))||t.map((k,z)=>({label:k,value:k,rank:z+1})),submitted:!0},metadata:U}:e==="selected"?W={type:"CHOICE",content:"",choice:{items:((u=$.rawItems)==null?void 0:u.map(k=>ee(H({},k),{selected:t.includes(k.label)})))||((f=$.options)==null?void 0:f.map(k=>({label:k,value:k,selected:t.includes(k)})))||[],multiple:$.multiSelect||!1,submitted:!0},metadata:U}:e==="input"&&(W={type:"FORM",content:"",form:{fields:((j=$.fields)==null?void 0:j.map((M,k)=>ee(H({},M),{value:t[k]||""})))||[],submitted:!0},metadata:U});const Z={body:W,conversationId:o,sender:{id:"me"}};yield c.sendMessageAsync(Z)}catch($){console.error("Error sending survey response:",$)}})}function Xi(t,e,n,s){return v(this,null,function*(){var u,f,j,$;const{props:i,currentConversationId:o,formattedMessages:r,popup:c,setEditingMsgIdBot:a,setEditingMsgIdUser:d}=s;if(!(!i.remoteRepo||!o))try{if(!r.find(A=>A.id===n&&A.sender==="user"))return;const W=r.findIndex(A=>A.id===n);let Z;for(let A=W-1;A>=0;A--){const O=r[A];if(O.sender==="bot"&&(O.type==="choice"||O.type==="survey"||O.type==="form")){Z=O;break}}if(!Z)return;const M=Array.isArray(Z.contents)&&Z.contents.length>0?Z.contents[Z.contents.length-1].metadata||{}:{};let k={};e==="input"?k={type:"NORMAL",content:t[0],metadata:M}:e==="ordered"?k={type:"RANKING",content:"",ranking:{items:((u=Z.rawItems)==null?void 0:u.map(O=>ee(H({},O),{rank:t.indexOf(O.label)+1})))||t.map((O,w)=>({label:O,value:O,rank:w+1})),submitted:!0},metadata:M}:e==="selected"?k={type:"CHOICE",content:"",choice:{items:((f=Z.rawItems)==null?void 0:f.map(O=>ee(H({},O),{selected:t.includes(O.label)})))||((j=Z.options)==null?void 0:j.map(O=>({label:O,value:O,selected:t.includes(O)})))||[],multiple:Z.multiSelect||!1,submitted:!0},metadata:M}:e==="input"&&(k={type:"FORM",content:"",form:{fields:(($=Z.fields)==null?void 0:$.map((A,O)=>ee(H({},A),{value:t[O]||""})))||[],submitted:!0},metadata:M});const z={id:n,body:k,conversationId:o,sender:{id:"me"}};yield c.updateMessageAsync(z),a(null),d(null)}catch(U){console.error("Error updating survey response:",U)}})}var Gi=F("<div>"),Ki=F("<button class=chat-popup-button><img>"),Qi=F("<div style=font-size:14px;margin-top:4px>"),Ji=F("<div class=modal-backdrop><div class=modal-content style=background-color:white;border-radius:8px><div style=margin-bottom:12px><label style=margin-bottom:18px;font-weight:500;text-align:left>Tên cuộc trò chuyện mới:</label><input autofocus class=chat-popup-input></div><div style=text-align:right><button class=modal-button-delete style=margin-right:8px;background-color:#f0f0f0>Hủy bỏ</button><button class=modal-button-delete style=background-color:#1AAF74>Tạo"),eo=F("<div class=modal-backdrop><div style=background-color:white;border-radius:8px><div style=font-size:16px;font-weight:500;margin-bottom:12px;text-align:left>Xóa đoạn chat?</div><div style=font-size:14px;margin-bottom:16px;text-align:left>Hành động này sẽ xóa <b></b>?</div><div style=text-align:right><button class=modal-button-delete style=margin-right:8px>Hủy bỏ</button><button class=modal-button-delete style=background-color:#e74c3c>Xóa"),to=F("<div class=modal-backdrop><div class=modal-content style=background-color:white;border-radius:8px><div style=font-size:16px;font-weight:500;margin-bottom:12px>Bạn chưa làm khảo sát. Vui lòng thực hiện khảo sát trước khi bắt đầu tư vấn!</div><div style=text-align:right><button class=modal-button-delete style=background-color:#1AAF74>Đã hiểu"),no=F("<div><div style=flex-direction:row><div style=flex-direction:column;min-height:0>"),so=F("<div class=chat-popup-header><img><div class=chat-popup-title><img style=margin-right:4px><span style=user-select:none>Ez</span><span style=margin-left:4px;user-select:none>Advise</span></div><div style=align-items:center;margin-top:4px><button><img>"),zn=F("<button><img>"),io=F("<div><div>"),oo=F("<div style=text-align:center;font-size:32px;font-weight:600;margin-bottom:32px;user-select:none>Hôm nay thị trường khiến bạn quan tâm điều gì?"),ro=F("<div class=chat-popup-action-buttons>");function ao(t){var st;const e=Vi(),[n,s]=L(""),[i,o]=L(!1),[r,c]=L(!1),[a,d]=L(!1),[u,f]=L(!1),[j,$]=L(0),[U]=L({}),[W,Z]=L(new Set),[M,k]=L(null),[z,A]=L(!1),[O,w]=L(!0),[Ae,oe]=L(""),[de,B]=L(1),[x,C]=L(6),[p,m]=L(null),[I,R]=L(null),[b,D]=L(!1),[Y,he]=L(""),[fe,ce]=L(void 0);let ne=null;const[G,E]=L(null),[K,ye]=L(!1),J=((st=t.options)==null?void 0:st.onlyMobile)||!1,be=()=>v(null,null,function*(){yield jn(t,e,k,oe,w,Z,A,ne,()=>ye(!0)),yield Zi(t,Y(),ce,D,e,k,oe,w,Z,A,ne)});Qe(()=>v(null,null,function*(){if(t.remoteRepo)try{const h=yield t.remoteRepo.listConversationAsync(10);console.log("listConversationAsync result:",h),(!h||h.length===0)&&console.warn("listConversationAsync returned empty or null")}catch(h){console.error("Error calling listConversationAsync:",h)}})),Qe(()=>{const h=e.getCurrentMessages();h&&h.length>0&&Wi(Nn(h),B,C)});const Oe=()=>{const h=M();return!!h&&h.endsWith("~SURVEY")},nt=()=>v(null,null,function*(){he(""),ce(void 0),D(!0)});return Mt(()=>{const h=()=>{const y=window.innerWidth<768;f(y),a()&&y&&(d(!1),f(!0))};return window.addEventListener("resize",h),h(),()=>{window.removeEventListener("resize",h)}}),Qe(()=>{var h,_;(h=t.options)!=null&&h.onFullScreen&&t.options.onFullScreen(a()),(_=t.options)!=null&&_.onMobile&&t.options.onMobile(u())}),(()=>{var h=Gi();return P(h,(()=>{var _=te(()=>!i());return()=>_()&&(()=>{var y=Ki(),S=y.firstChild;return y.$$click=()=>{var T;J&&f(!0),o(!0),(T=t.options)!=null&&T.onOpen&&t.options.onOpen()},l(y,"background","none"),l(y,"border","none"),l(y,"cursor","pointer"),l(y,"padding","0"),se(S,"src",hn),y})()})(),null),P(h,(()=>{var _=te(()=>!!i());return()=>_()&&(()=>{const y=Je(()=>Nn(e.getCurrentMessages())),S=()=>qi(y(),M()),T=(re,Ie,X)=>Yi(re,Ie,X,{props:t,currentConversationId:M(),formattedMessages:y(),popup:e,setSubmittedMessages:Z}),ge=(re,Ie,X)=>Xi(re,Ie,X,{props:t,currentConversationId:M(),formattedMessages:y(),popup:e,setEditingMsgIdBot:m,setEditingMsgIdUser:R}),xe=()=>v(null,null,function*(){var re,Ie;if(!(!n().trim()||!t.remoteRepo)){if(yield Un(t.remoteRepo)){alert("Bạn chưa hoàn thành khảo sát hiện tại!");return}if(!M()){yield jn(t,e,k,oe,w,Z,A,ne,()=>ye(!0));try{const X=Pt(),Q="BOT~rasaconnector",N=`Cuộc hội thoại mới ${X.slice(-4)}`,V=yield e.createConversationAsync({id:X,name:N,type:"BOT",members:[{userId:Q,role:"MEMBER"}],updatedAt:new Date});e.setCurrentConversation({id:V.id,name:V.name,type:"BOT"}),k(V.id),oe(V.name),w(!0),Z(new Set),A(!1),yield e.listMessagesAsync(V.id),ne&&ne()}catch(X){console.error("Tạo hội thoại mới thất bại:",X);return}}try{let X={};const Q=y().filter(V=>V.sender==="bot"&&Array.isArray(V.contents)&&V.contents.length>0&&V.contents[V.contents.length-1].metadata);if(Q.length>0){const V=Q[Q.length-1];X=((Ie=(re=V.contents)==null?void 0:re[V.contents.length-1])==null?void 0:Ie.metadata)||{}}const N={body:{type:"NORMAL",content:n(),metadata:X},conversationId:M(),sender:{id:"me"}};yield e.sendMessageAsync(N),s("")}catch(X){console.error("Error sending message:",X)}}}),Le=()=>v(null,null,function*(){var re,Ie;if(!(!e||y().length===0||!M()||!O()))try{const X=y()[0].id,Q=30,N=y().findIndex(ze=>ze.id===X);if(N>=0&&N-Q>=0)return;const V=document.querySelector(".chat-messages-container"),ae=V==null?void 0:V.querySelector(`[data-message-id="${X}"]`),le=(re=ae==null?void 0:ae.offsetTop)!=null?re:0,Xe=(Ie=V==null?void 0:V.scrollTop)!=null?Ie:0;yield e.listMessagesAsync("BEFORE",X,Q),requestAnimationFrame(()=>{var _e;const ze=V==null?void 0:V.querySelector(`[data-message-id="${X}"]`),Ve=(_e=ze==null?void 0:ze.offsetTop)!=null?_e:0;V&&(V.scrollTop=Ve-(le-Xe))})}catch(X){console.error("Error loading more messages:",X)}});return Qe(()=>{y(),i()&&requestAnimationFrame(()=>{const re=document.querySelector(".chat-messages-container");re&&(re.scrollTop=re.scrollHeight)})}),(()=>{var re=no(),Ie=re.firstChild,X=Ie.firstChild;return P(re,ie(Ye,{get when(){return b()},get children(){var Q=Ji(),N=Q.firstChild,V=N.firstChild,ae=V.firstChild,le=ae.nextSibling,Xe=V.nextSibling,ze=Xe.firstChild,Ve=ze.nextSibling;return Q.$$click=()=>D(!1),N.$$click=_e=>_e.stopPropagation(),l(N,"padding","20px"),l(N,"width","400px"),l(ae,"display","block"),l(ae,"color","#1A1D1F"),le.$$keydown=_e=>{_e.key==="Enter"&&be()},le.$$input=_e=>he(_e.currentTarget.value),P(V,ie(Ye,{get when(){return fe()},get children(){var _e=Qi();return l(_e,"color","red"),P(_e,fe),_e}}),null),ze.$$click=()=>D(!1),Ve.$$click=be,l(Ve,"color","#fff"),ue(()=>le.value=Y()),Q}}),Ie),P(re,(()=>{var Q=te(()=>!a());return()=>Q()&&(()=>{var N=so(),V=N.firstChild,ae=V.nextSibling,le=ae.firstChild,Xe=le.nextSibling,ze=Xe.nextSibling,Ve=ae.nextSibling,_e=Ve.firstChild,We=_e.firstChild;return V.$$click=()=>c(!0),se(V,"src",Ss),l(V,"width","28px"),l(V,"height","28px"),l(V,"cursor","pointer"),se(le,"src",hn),l(le,"width","32px"),l(le,"height","32px"),l(Xe,"color","#1A1D1F"),l(ze,"color","#1AAF74"),l(Ve,"display","flex"),l(Ve,"gap","12px"),P(Ve,(()=>{var lt=te(()=>!u());return()=>lt()&&[(()=>{var He=zn(),dt=He.firstChild;return He.$$click=()=>{var Lt;a()?(d(!1),f(!0)):u()?f(!1):f(!0),(Lt=t.options)!=null&&Lt.onMinimize&&t.options.onMinimize()},l(He,"background","none"),l(He,"border","none"),l(He,"cursor","pointer"),l(He,"padding","0"),se(dt,"src",Is),l(dt,"width","20px"),l(dt,"height","20px"),He})(),(()=>{var He=zn(),dt=He.firstChild;return He.$$click=()=>{var Lt;f(!1),d(!0),(Lt=t.options)!=null&&Lt.onMaximize&&t.options.onMaximize()},l(He,"background","none"),l(He,"border","none"),l(He,"cursor","pointer"),l(He,"padding","0"),se(dt,"src",As),l(dt,"width","20px"),l(dt,"height","20px"),He})()]})(),_e),_e.$$click=()=>{var lt;o(!1),f(!1),d(!1),(lt=t.options)!=null&&lt.onClose&&t.options.onClose()},l(_e,"background","none"),l(_e,"border","none"),l(_e,"cursor","pointer"),l(_e,"padding","0"),se(We,"src",kn),l(We,"width","20px"),l(We,"height","20px"),N})()})(),Ie),l(Ie,"display","flex"),l(Ie,"height","100%"),P(Ie,(()=>{var Q=te(()=>!!a());return()=>Q()?ie(Pn,{onClose:()=>{var N;o(!1),f(!1),d(!1),(N=t.options)!=null&&N.onClose&&t.options.onClose()},onShrink:()=>{var N;d(!1),(N=t.options)!=null&&N.onShrink&&t.options.onShrink()},open:!0,fullScreen:!0,get isMobile(){return u()},onMobile:()=>{d(!1),f(!0)},onNewConversation:nt,get options(){return t.options},get remoteRepo(){var N;return(N=t.remoteRepo)!=null?N:void 0},onDeleteConversation:E,onReloadConversations:N=>ne=N,onLoadMessages:(N,V)=>v(null,null,function*(){if(e.setCurrentConversation({id:N,name:"",type:"BOT"}),k(N),oe(V||""),w(!0),t.remoteRepo)try{yield e.listMessagesAsync(N),Z(new Set),A(!1),requestAnimationFrame(()=>{requestAnimationFrame(()=>{const ae=document.querySelector(".chat-messages-container");ae&&(ae.scrollTop=ae.scrollHeight),A(!1)})})}catch(ae){console.error("Error loading messages:",ae),A(!1)}})}):ie(Pn,{onClose:()=>c(!1),get open(){return r()},fullScreen:!1,get isMobile(){return u()},onNewConversation:nt,get options(){return t.options},get remoteRepo(){var N;return(N=t.remoteRepo)!=null?N:void 0},onDeleteConversation:E,onReloadConversations:N=>ne=N,onLoadMessages:(N,V)=>v(null,null,function*(){if(e.setCurrentConversation({id:N,name:"",type:"BOT"}),k(N),oe(V||""),w(!0),t.remoteRepo)try{yield e.listMessagesAsync(N);const ae=e.getCurrentMessages();console.log("message data: ",ae),Z(new Set),A(!1),requestAnimationFrame(()=>{requestAnimationFrame(()=>{const le=document.querySelector(".chat-messages-container");le&&(le.scrollTop=le.scrollHeight),A(!1)})})}catch(ae){console.error("Error loading messages:",ae),A(!1)}})})})(),X),l(X,"flex","1"),l(X,"display","flex"),l(X,"position","relative"),l(X,"height","100%"),P(X,(()=>{var Q=te(()=>!!a());return()=>Q()&&ie(Hi,{get currentStep(){return de()},get totalSteps(){return x()},get title(){return Ae()},get isSurveyConversation(){return Oe()}})})(),null),P(X,ie(wi,{get messages(){return y()},get isFullScreen(){return a()},get inputHeight(){return te(()=>!!a())()?j():void 0},get isMobile(){return u()},onSubmit:T,onUpdateSurvey:ge,get surveyOptions(){return U()},get submittedMessages(){return W()},onLoadMoreMessages:Le,get conversationId(){return M()},get isLoadingMessages(){return z()},get editingMsgIdBot(){return p()},setEditingMsgIdBot:m,get editingMsgIdUser(){return I()},setEditingMsgIdUser:R}),null),P(X,(()=>{var Q=te(()=>!!a());return()=>Q()?(()=>{var N=io(),V=N.firstChild;return P(N,(()=>{var ae=te(()=>y().length===0);return()=>ae()&&(()=>{var le=oo();return l(le,"width","100%"),l(le,"color","#1A1D1F"),le})()})(),V),l(V,"width","100%"),P(V,ie(Rn,{get input(){return n()},setInput:s,sendMessage:xe,onHeightChange:$,get disabled(){return!S()}})),P(N,(()=>{var ae=te(()=>y().length===0);return()=>ae()&&(()=>{var le=ro();return P(le,ie(qt,{text:"Khảo sát đầu tư"}),null),P(le,ie(qt,{text:"Mục tiêu tài chính"}),null),P(le,ie(qt,{text:"Khả năng chấp nhận rủi ro"}),null),P(le,ie(qt,{text:"Khả năng chấp nhận rủi ro"}),null),le})()})(),null),ue(()=>it(N,`chat-input-floating-box${y().length>0?" chat-input-floating-box--with-messages":""}`)),N})():ie(Rn,{get input(){return n()},setInput:s,sendMessage:xe,onHeightChange:$,get disabled(){return!S()}})})(),null),P(re,ie(Ye,{get when(){return!!G()},get children(){var Q=eo(),N=Q.firstChild,V=N.firstChild,ae=V.nextSibling,le=ae.firstChild,Xe=le.nextSibling,ze=ae.nextSibling,Ve=ze.firstChild,_e=Ve.nextSibling;return Q.$$click=()=>E(null),N.$$click=We=>We.stopPropagation(),l(N,"padding","20px"),l(N,"width","350px"),l(V,"color","#1A1D1F"),l(ae,"color","#1A1D1F"),P(Xe,()=>{var We;return(We=G())==null?void 0:We.name}),Ve.$$click=We=>{We.stopPropagation(),E(null)},_e.$$click=We=>v(null,null,function*(){var lt;We.stopPropagation();try{yield(lt=t.remoteRepo)==null?void 0:lt.deleteConversationAsync(G().id),E(null),ne&&ne()}catch(He){alert("Xóa hội thoại thất bại!")}}),l(_e,"color","#fff"),Q}}),null),P(re,ie(Ye,{get when(){return K()},get children(){var Q=to(),N=Q.firstChild,V=N.firstChild,ae=V.nextSibling,le=ae.firstChild;return Q.$$click=()=>ye(!1),N.$$click=Xe=>Xe.stopPropagation(),l(N,"padding","20px"),l(N,"width","350px"),le.$$click=()=>ye(!1),l(le,"color","#fff"),Q}}),null),ue(Q=>{var N=`chat-popup-window${i()?" chat-popup-window--open":""}${a()?" chat-popup-window--fullscreen":""}${u()?" chat-popup-window--mobile":""}`,V=a()||u()?{"--chat-input-height":`${j()}px`}:void 0;return N!==Q.e&&it(re,Q.e=N),Q.t=dn(re,V,Q.t),Q},{e:void 0,t:void 0}),re})()})()})(),null),h})()}pt(["click","input","keydown"]);function co(t){return ie(ao,{get remoteRepo(){return t.remoteRepo},get options(){return t.options}})}class rt extends Error{constructor(e,n){const s=new.target.prototype;super(`${e}: Status code '${n}'`),this.statusCode=n,this.__proto__=s}}class fn extends Error{constructor(e="A timeout occurred."){const n=new.target.prototype;super(e),this.__proto__=n}}class qe extends Error{constructor(e="An abort occurred."){const n=new.target.prototype;super(e),this.__proto__=n}}class lo extends Error{constructor(e,n){const s=new.target.prototype;super(e),this.transport=n,this.errorType="UnsupportedTransportError",this.__proto__=s}}class uo extends Error{constructor(e,n){const s=new.target.prototype;super(e),this.transport=n,this.errorType="DisabledTransportError",this.__proto__=s}}class ho extends Error{constructor(e,n){const s=new.target.prototype;super(e),this.transport=n,this.errorType="FailedToStartTransportError",this.__proto__=s}}class Vn extends Error{constructor(e){const n=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=n}}class fo extends Error{constructor(e,n){const s=new.target.prototype;super(e),this.innerErrors=n,this.__proto__=s}}class Wn{constructor(e,n,s){this.statusCode=e,this.statusText=n,this.content=s}}class Gt{get(e,n){return this.send(ee(H({},n),{method:"GET",url:e}))}post(e,n){return this.send(ee(H({},n),{method:"POST",url:e}))}delete(e,n){return this.send(ee(H({},n),{method:"DELETE",url:e}))}getCookieString(e){return""}}var g;(function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Information=2]="Information",t[t.Warning=3]="Warning",t[t.Error=4]="Error",t[t.Critical=5]="Critical",t[t.None=6]="None"})(g||(g={}));class $t{constructor(){}log(e,n){}}$t.instance=new $t;const go="8.0.17";class Ee{static isRequired(e,n){if(e==null)throw new Error(`The '${n}' argument is required.`)}static isNotEmpty(e,n){if(!e||e.match(/^\s*$/))throw new Error(`The '${n}' argument should not be empty.`)}static isIn(e,n,s){if(!(e in n))throw new Error(`Unknown ${s} value: ${e}.`)}}class ve{static get isBrowser(){return!ve.isNode&&typeof window=="object"&&typeof window.document=="object"}static get isWebWorker(){return!ve.isNode&&typeof self=="object"&&"importScripts"in self}static get isReactNative(){return!ve.isNode&&typeof window=="object"&&typeof window.document=="undefined"}static get isNode(){return typeof process!="undefined"&&process.release&&process.release.name==="node"}}function Dt(t,e){let n="";return at(t)?(n=`Binary data of length ${t.byteLength}`,e&&(n+=`. Content: '${po(t)}'`)):typeof t=="string"&&(n=`String data of length ${t.length}`,e&&(n+=`. Content: '${t}'`)),n}function po(t){const e=new Uint8Array(t);let n="";return e.forEach(s=>{const i=s<16?"0":"";n+=`0x${i}${s.toString(16)} `}),n.substr(0,n.length-1)}function at(t){return t&&typeof ArrayBuffer!="undefined"&&(t instanceof ArrayBuffer||t.constructor&&t.constructor.name==="ArrayBuffer")}function qn(t,e,n,s,i,o){return v(this,null,function*(){const r={},[c,a]=bt();r[c]=a,t.log(g.Trace,`(${e} transport) sending data. ${Dt(i,o.logMessageContent)}.`);const d=at(i)?"arraybuffer":"text",u=yield n.post(s,{content:i,headers:H(H({},r),o.headers),responseType:d,timeout:o.timeout,withCredentials:o.withCredentials});t.log(g.Trace,`(${e} transport) request complete. Response status: ${u.statusCode}.`)})}function Co(t){return t===void 0?new Kt(g.Information):t===null?$t.instance:t.log!==void 0?t:new Kt(t)}class mo{constructor(e,n){this._subject=e,this._observer=n}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),this._subject.observers.length===0&&this._subject.cancelCallback&&this._subject.cancelCallback().catch(n=>{})}}class Kt{constructor(e){this._minLevel=e,this.out=console}log(e,n){if(e>=this._minLevel){const s=`[${new Date().toISOString()}] ${g[e]}: ${n}`;switch(e){case g.Critical:case g.Error:this.out.error(s);break;case g.Warning:this.out.warn(s);break;case g.Information:this.out.info(s);break;default:this.out.log(s);break}}}}function bt(){let t="X-SignalR-User-Agent";return ve.isNode&&(t="User-Agent"),[t,wo(go,vo(),bo(),yo())]}function wo(t,e,n,s){let i="Microsoft SignalR/";const o=t.split(".");return i+=`${o[0]}.${o[1]}`,i+=` (${t}; `,e&&e!==""?i+=`${e}; `:i+="Unknown OS; ",i+=`${n}`,s?i+=`; ${s}`:i+="; Unknown Runtime Version",i+=")",i}function vo(){if(ve.isNode)switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}else return""}function yo(){if(ve.isNode)return process.versions.node}function bo(){return ve.isNode?"NodeJS":"Browser"}function gn(t){return t.stack?t.stack:t.message?t.message:`${t}`}function _o(){if(typeof globalThis!="undefined")return globalThis;if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;throw new Error("could not find global")}class So extends Gt{constructor(e){if(super(),this._logger=e,typeof fetch=="undefined"||ve.isNode){const n=typeof __webpack_require__=="function"?__non_webpack_require__:require;this._jar=new(n("tough-cookie")).CookieJar,typeof fetch=="undefined"?this._fetchType=n("node-fetch"):this._fetchType=fetch,this._fetchType=n("fetch-cookie")(this._fetchType,this._jar)}else this._fetchType=fetch.bind(_o());if(typeof AbortController=="undefined"){const n=typeof __webpack_require__=="function"?__non_webpack_require__:require;this._abortControllerType=n("abort-controller")}else this._abortControllerType=AbortController}send(e){return v(this,null,function*(){if(e.abortSignal&&e.abortSignal.aborted)throw new qe;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const n=new this._abortControllerType;let s;e.abortSignal&&(e.abortSignal.onabort=()=>{n.abort(),s=new qe});let i=null;if(e.timeout){const a=e.timeout;i=setTimeout(()=>{n.abort(),this._logger.log(g.Warning,"Timeout from HTTP request."),s=new fn},a)}e.content===""&&(e.content=void 0),e.content&&(e.headers=e.headers||{},at(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");let o;try{o=yield this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:e.withCredentials===!0?"include":"same-origin",headers:H({"X-Requested-With":"XMLHttpRequest"},e.headers),method:e.method,mode:"cors",redirect:"follow",signal:n.signal})}catch(a){throw s||(this._logger.log(g.Warning,`Error from HTTP request. ${a}.`),a)}finally{i&&clearTimeout(i),e.abortSignal&&(e.abortSignal.onabort=null)}if(!o.ok){const a=yield Zn(o,"text");throw new rt(a||o.statusText,o.status)}const c=yield Zn(o,e.responseType);return new Wn(o.status,o.statusText,c)})}getCookieString(e){let n="";return ve.isNode&&this._jar&&this._jar.getCookies(e,(s,i)=>n=i.join("; ")),n}}function Zn(t,e){let n;switch(e){case"arraybuffer":n=t.arrayBuffer();break;case"text":n=t.text();break;case"blob":case"document":case"json":throw new Error(`${e} is not supported.`);default:n=t.text();break}return n}class Ao extends Gt{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new qe):e.method?e.url?new Promise((n,s)=>{const i=new XMLHttpRequest;i.open(e.method,e.url,!0),i.withCredentials=e.withCredentials===void 0?!0:e.withCredentials,i.setRequestHeader("X-Requested-With","XMLHttpRequest"),e.content===""&&(e.content=void 0),e.content&&(at(e.content)?i.setRequestHeader("Content-Type","application/octet-stream"):i.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const o=e.headers;o&&Object.keys(o).forEach(r=>{i.setRequestHeader(r,o[r])}),e.responseType&&(i.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{i.abort(),s(new qe)}),e.timeout&&(i.timeout=e.timeout),i.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),i.status>=200&&i.status<300?n(new Wn(i.status,i.statusText,i.response||i.responseText)):s(new rt(i.response||i.responseText||i.statusText,i.status))},i.onerror=()=>{this._logger.log(g.Warning,`Error from HTTP request. ${i.status}: ${i.statusText}.`),s(new rt(i.statusText,i.status))},i.ontimeout=()=>{this._logger.log(g.Warning,"Timeout from HTTP request."),s(new fn)},i.send(e.content)}):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class xo extends Gt{constructor(e){if(super(),typeof fetch!="undefined"||ve.isNode)this._httpClient=new So(e);else if(typeof XMLHttpRequest!="undefined")this._httpClient=new Ao(e);else throw new Error("No usable HttpClient found.")}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new qe):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}class Ne{static write(e){return`${e}${Ne.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ne.RecordSeparator)throw new Error("Message is incomplete.");const n=e.split(Ne.RecordSeparator);return n.pop(),n}}Ne.RecordSeparatorCode=30,Ne.RecordSeparator=String.fromCharCode(Ne.RecordSeparatorCode);class Io{writeHandshakeRequest(e){return Ne.write(JSON.stringify(e))}parseHandshakeResponse(e){let n,s;if(at(e)){const c=new Uint8Array(e),a=c.indexOf(Ne.RecordSeparatorCode);if(a===-1)throw new Error("Message is incomplete.");const d=a+1;n=String.fromCharCode.apply(null,Array.prototype.slice.call(c.slice(0,d))),s=c.byteLength>d?c.slice(d).buffer:null}else{const c=e,a=c.indexOf(Ne.RecordSeparator);if(a===-1)throw new Error("Message is incomplete.");const d=a+1;n=c.substring(0,d),s=c.length>d?c.substring(d):null}const i=Ne.parse(n),o=JSON.parse(i[0]);if(o.type)throw new Error("Expected a handshake response from the server.");return[s,o]}}var q;(function(t){t[t.Invocation=1]="Invocation",t[t.StreamItem=2]="StreamItem",t[t.Completion=3]="Completion",t[t.StreamInvocation=4]="StreamInvocation",t[t.CancelInvocation=5]="CancelInvocation",t[t.Ping=6]="Ping",t[t.Close=7]="Close",t[t.Ack=8]="Ack",t[t.Sequence=9]="Sequence"})(q||(q={}));class Mo{constructor(){this.observers=[]}next(e){for(const n of this.observers)n.next(e)}error(e){for(const n of this.observers)n.error&&n.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new mo(this,e)}}class ko{constructor(e,n,s){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=e,this._connection=n,this._bufferSize=s}_send(e){return v(this,null,function*(){const n=this._protocol.writeMessage(e);let s=Promise.resolve();if(this._isInvocationMessage(e)){this._totalMessageCount++;let i=()=>{},o=()=>{};at(n)?this._bufferedByteCount+=n.byteLength:this._bufferedByteCount+=n.length,this._bufferedByteCount>=this._bufferSize&&(s=new Promise((r,c)=>{i=r,o=c})),this._messages.push(new Eo(n,this._totalMessageCount,i,o))}try{this._reconnectInProgress||(yield this._connection.send(n))}catch(i){this._disconnected()}yield s})}_ack(e){let n=-1;for(let s=0;s<this._messages.length;s++){const i=this._messages[s];if(i._id<=e.sequenceId)n=s,at(i._message)?this._bufferedByteCount-=i._message.byteLength:this._bufferedByteCount-=i._message.length,i._resolver();else if(this._bufferedByteCount<this._bufferSize)i._resolver();else break}n!==-1&&(this._messages=this._messages.slice(n+1))}_shouldProcessMessage(e){if(this._waitForSequenceMessage)return e.type!==q.Sequence?!1:(this._waitForSequenceMessage=!1,!0);if(!this._isInvocationMessage(e))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(e){if(e.sequenceId>this._nextReceivingSequenceId){this._connection.stop(new Error("Sequence ID greater than amount of messages we've received."));return}this._nextReceivingSequenceId=e.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}_resend(){return v(this,null,function*(){const e=this._messages.length!==0?this._messages[0]._id:this._totalMessageCount+1;yield this._connection.send(this._protocol.writeMessage({type:q.Sequence,sequenceId:e}));const n=this._messages;for(const s of n)yield this._connection.send(s._message);this._reconnectInProgress=!1})}_dispose(e){e!=null||(e=new Error("Unable to reconnect to server."));for(const n of this._messages)n._rejector(e)}_isInvocationMessage(e){switch(e.type){case q.Invocation:case q.StreamItem:case q.Completion:case q.StreamInvocation:case q.CancelInvocation:return!0;case q.Close:case q.Sequence:case q.Ping:case q.Ack:return!1}}_ackTimer(){this._ackTimerHandle===void 0&&(this._ackTimerHandle=setTimeout(()=>v(this,null,function*(){try{this._reconnectInProgress||(yield this._connection.send(this._protocol.writeMessage({type:q.Ack,sequenceId:this._latestReceivedSequenceId})))}catch(e){}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0}),1e3))}}class Eo{constructor(e,n,s,i){this._message=e,this._id=n,this._resolver=s,this._rejector=i}}const To=30*1e3,Ro=15*1e3,Po=1e5;var Ce;(function(t){t.Disconnected="Disconnected",t.Connecting="Connecting",t.Connected="Connected",t.Disconnecting="Disconnecting",t.Reconnecting="Reconnecting"})(Ce||(Ce={}));class pn{static create(e,n,s,i,o,r,c){return new pn(e,n,s,i,o,r,c)}constructor(e,n,s,i,o,r,c){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(g.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")},Ee.isRequired(e,"connection"),Ee.isRequired(n,"logger"),Ee.isRequired(s,"protocol"),this.serverTimeoutInMilliseconds=o!=null?o:To,this.keepAliveIntervalInMilliseconds=r!=null?r:Ro,this._statefulReconnectBufferSize=c!=null?c:Po,this._logger=n,this._protocol=s,this.connection=e,this._reconnectPolicy=i,this._handshakeProtocol=new Io,this.connection.onreceive=a=>this._processIncomingData(a),this.connection.onclose=a=>this._connectionClosed(a),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=Ce.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:q.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==Ce.Disconnected&&this._connectionState!==Ce.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}_startWithStateTransitions(){return v(this,null,function*(){if(this._connectionState!==Ce.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=Ce.Connecting,this._logger.log(g.Debug,"Starting HubConnection.");try{yield this._startInternal(),ve.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=Ce.Connected,this._connectionStarted=!0,this._logger.log(g.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=Ce.Disconnected,this._logger.log(g.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}})}_startInternal(){return v(this,null,function*(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise((n,s)=>{this._handshakeResolver=n,this._handshakeRejecter=s});yield this.connection.start(this._protocol.transferFormat);try{let n=this._protocol.version;this.connection.features.reconnect||(n=1);const s={protocol:this._protocol.name,version:n};if(this._logger.log(g.Debug,"Sending handshake request."),yield this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(s)),this._logger.log(g.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),yield e,this._stopDuringStartError)throw this._stopDuringStartError;(this.connection.features.reconnect||!1)&&(this._messageBuffer=new ko(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||(yield this._sendMessage(this._cachedPingMessage))}catch(n){throw this._logger.log(g.Debug,`Hub handshake failed with error '${n}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),yield this.connection.stop(n),n}})}stop(){return v(this,null,function*(){const e=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),yield this._stopPromise;try{yield e}catch(n){}})}_stopInternal(e){if(this._connectionState===Ce.Disconnected)return this._logger.log(g.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===Ce.Disconnecting)return this._logger.log(g.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const n=this._connectionState;return this._connectionState=Ce.Disconnecting,this._logger.log(g.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(g.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(n===Ce.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new qe("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}_sendCloseMessage(){return v(this,null,function*(){try{yield this._sendWithProtocol(this._createCloseMessage())}catch(e){}})}stream(e,...n){const[s,i]=this._replaceStreamingParams(n),o=this._createStreamInvocation(e,n,i);let r;const c=new Mo;return c.cancelCallback=()=>{const a=this._createCancelInvocation(o.invocationId);return delete this._callbacks[o.invocationId],r.then(()=>this._sendWithProtocol(a))},this._callbacks[o.invocationId]=(a,d)=>{if(d){c.error(d);return}else a&&(a.type===q.Completion?a.error?c.error(new Error(a.error)):c.complete():c.next(a.item))},r=this._sendWithProtocol(o).catch(a=>{c.error(a),delete this._callbacks[o.invocationId]}),this._launchStreams(s,r),c}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._messageBuffer?this._messageBuffer._send(e):this._sendMessage(this._protocol.writeMessage(e))}send(e,...n){const[s,i]=this._replaceStreamingParams(n),o=this._sendWithProtocol(this._createInvocation(e,n,!0,i));return this._launchStreams(s,o),o}invoke(e,...n){const[s,i]=this._replaceStreamingParams(n),o=this._createInvocation(e,n,!1,i);return new Promise((c,a)=>{this._callbacks[o.invocationId]=(u,f)=>{if(f){a(f);return}else u&&(u.type===q.Completion?u.error?a(new Error(u.error)):c(u.result):a(new Error(`Unexpected message type: ${u.type}`)))};const d=this._sendWithProtocol(o).catch(u=>{a(u),delete this._callbacks[o.invocationId]});this._launchStreams(s,d)})}on(e,n){!e||!n||(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),this._methods[e].indexOf(n)===-1&&this._methods[e].push(n))}off(e,n){if(!e)return;e=e.toLowerCase();const s=this._methods[e];if(s)if(n){const i=s.indexOf(n);i!==-1&&(s.splice(i,1),s.length===0&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const n=this._protocol.parseMessages(e,this._logger);for(const s of n)if(!(this._messageBuffer&&!this._messageBuffer._shouldProcessMessage(s)))switch(s.type){case q.Invocation:this._invokeClientMethod(s).catch(i=>{this._logger.log(g.Error,`Invoke client method threw error: ${gn(i)}`)});break;case q.StreamItem:case q.Completion:{const i=this._callbacks[s.invocationId];if(i){s.type===q.Completion&&delete this._callbacks[s.invocationId];try{i(s)}catch(o){this._logger.log(g.Error,`Stream callback threw error: ${gn(o)}`)}}break}case q.Ping:break;case q.Close:{this._logger.log(g.Information,"Close message received from server.");const i=s.error?new Error("Server returned an error on close: "+s.error):void 0;s.allowReconnect===!0?this.connection.stop(i):this._stopPromise=this._stopInternal(i);break}case q.Ack:this._messageBuffer&&this._messageBuffer._ack(s);break;case q.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(s);break;default:this._logger.log(g.Warning,`Invalid message type: ${s.type}.`);break}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let n,s;try{[s,n]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(i){const o="Error parsing handshake response: "+i;this._logger.log(g.Error,o);const r=new Error(o);throw this._handshakeRejecter(r),r}if(n.error){const i="Server returned handshake error: "+n.error;this._logger.log(g.Error,i);const o=new Error(i);throw this._handshakeRejecter(o),o}else this._logger.log(g.Debug,"Server handshake complete.");return this._handshakeResolver(),s}_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),this._pingServerHandle===void 0)){let e=this._nextKeepAlive-new Date().getTime();e<0&&(e=0),this._pingServerHandle=setTimeout(()=>v(this,null,function*(){if(this._connectionState===Ce.Connected)try{yield this._sendMessage(this._cachedPingMessage)}catch(n){this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}_invokeClientMethod(e){return v(this,null,function*(){const n=e.target.toLowerCase(),s=this._methods[n];if(!s){this._logger.log(g.Warning,`No client method with the name '${n}' found.`),e.invocationId&&(this._logger.log(g.Warning,`No result given for '${n}' method and invocation ID '${e.invocationId}'.`),yield this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)));return}const i=s.slice(),o=!!e.invocationId;let r,c,a;for(const d of i)try{const u=r;r=yield d.apply(this,e.arguments),o&&r&&u&&(this._logger.log(g.Error,`Multiple results provided for '${n}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),c=void 0}catch(u){c=u,this._logger.log(g.Error,`A callback for the method '${n}' threw error '${u}'.`)}a?yield this._sendWithProtocol(a):o?(c?a=this._createCompletionMessage(e.invocationId,`${c}`,null):r!==void 0?a=this._createCompletionMessage(e.invocationId,null,r):(this._logger.log(g.Warning,`No result given for '${n}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),yield this._sendWithProtocol(a)):r&&this._logger.log(g.Error,`Result given for '${n}' method but server is not expecting a result.`)})}_connectionClosed(e){this._logger.log(g.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new qe("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===Ce.Disconnecting?this._completeClose(e):this._connectionState===Ce.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===Ce.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=Ce.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(e!=null?e:new Error("Connection closed.")),this._messageBuffer=void 0),ve.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach(n=>n.apply(this,[e]))}catch(n){this._logger.log(g.Error,`An onclose callback called with error '${e}' threw error '${n}'.`)}}}_reconnect(e){return v(this,null,function*(){const n=Date.now();let s=0,i=e!==void 0?e:new Error("Attempting to reconnect due to a unknown error."),o=this._getNextRetryDelay(s++,0,i);if(o===null){this._logger.log(g.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),this._completeClose(e);return}if(this._connectionState=Ce.Reconnecting,e?this._logger.log(g.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(g.Information,"Connection reconnecting."),this._reconnectingCallbacks.length!==0){try{this._reconnectingCallbacks.forEach(r=>r.apply(this,[e]))}catch(r){this._logger.log(g.Error,`An onreconnecting callback called with error '${e}' threw error '${r}'.`)}if(this._connectionState!==Ce.Reconnecting){this._logger.log(g.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");return}}for(;o!==null;){if(this._logger.log(g.Information,`Reconnect attempt number ${s} will start in ${o} ms.`),yield new Promise(r=>{this._reconnectDelayHandle=setTimeout(r,o)}),this._reconnectDelayHandle=void 0,this._connectionState!==Ce.Reconnecting){this._logger.log(g.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");return}try{if(yield this._startInternal(),this._connectionState=Ce.Connected,this._logger.log(g.Information,"HubConnection reconnected successfully."),this._reconnectedCallbacks.length!==0)try{this._reconnectedCallbacks.forEach(r=>r.apply(this,[this.connection.connectionId]))}catch(r){this._logger.log(g.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${r}'.`)}return}catch(r){if(this._logger.log(g.Information,`Reconnect attempt failed because of error '${r}'.`),this._connectionState!==Ce.Reconnecting){this._logger.log(g.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),this._connectionState===Ce.Disconnecting&&this._completeClose();return}i=r instanceof Error?r:new Error(r.toString()),o=this._getNextRetryDelay(s++,Date.now()-n,i)}}this._logger.log(g.Information,`Reconnect retries have been exhausted after ${Date.now()-n} ms and ${s} failed attempts. Connection disconnecting.`),this._completeClose()})}_getNextRetryDelay(e,n,s){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:n,previousRetryCount:e,retryReason:s})}catch(i){return this._logger.log(g.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${n}) threw error '${i}'.`),null}}_cancelCallbacksWithError(e){const n=this._callbacks;this._callbacks={},Object.keys(n).forEach(s=>{const i=n[s];try{i(null,e)}catch(o){this._logger.log(g.Error,`Stream 'error' callback called with '${e}' threw error: ${gn(o)}`)}})}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,n,s,i){if(s)return i.length!==0?{arguments:n,streamIds:i,target:e,type:q.Invocation}:{arguments:n,target:e,type:q.Invocation};{const o=this._invocationId;return this._invocationId++,i.length!==0?{arguments:n,invocationId:o.toString(),streamIds:i,target:e,type:q.Invocation}:{arguments:n,invocationId:o.toString(),target:e,type:q.Invocation}}}_launchStreams(e,n){if(e.length!==0){n||(n=Promise.resolve());for(const s in e)e[s].subscribe({complete:()=>{n=n.then(()=>this._sendWithProtocol(this._createCompletionMessage(s)))},error:i=>{let o;i instanceof Error?o=i.message:i&&i.toString?o=i.toString():o="Unknown error",n=n.then(()=>this._sendWithProtocol(this._createCompletionMessage(s,o)))},next:i=>{n=n.then(()=>this._sendWithProtocol(this._createStreamItemMessage(s,i)))}})}}_replaceStreamingParams(e){const n=[],s=[];for(let i=0;i<e.length;i++){const o=e[i];if(this._isObservable(o)){const r=this._invocationId;this._invocationId++,n[r]=o,s.push(r.toString()),e.splice(i,1)}}return[n,s]}_isObservable(e){return e&&e.subscribe&&typeof e.subscribe=="function"}_createStreamInvocation(e,n,s){const i=this._invocationId;return this._invocationId++,s.length!==0?{arguments:n,invocationId:i.toString(),streamIds:s,target:e,type:q.StreamInvocation}:{arguments:n,invocationId:i.toString(),target:e,type:q.StreamInvocation}}_createCancelInvocation(e){return{invocationId:e,type:q.CancelInvocation}}_createStreamItemMessage(e,n){return{invocationId:e,item:n,type:q.StreamItem}}_createCompletionMessage(e,n,s){return n?{error:n,invocationId:e,type:q.Completion}:{invocationId:e,result:s,type:q.Completion}}_createCloseMessage(){return{type:q.Close}}}const $o=[0,2e3,1e4,3e4,null];class Yn{constructor(e){this._retryDelays=e!==void 0?[...e,null]:$o}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ct{}ct.Authorization="Authorization",ct.Cookie="Cookie";class Do extends Gt{constructor(e,n){super(),this._innerClient=e,this._accessTokenFactory=n}send(e){return v(this,null,function*(){let n=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(n=!1,this._accessToken=yield this._accessTokenFactory()),this._setAuthorizationHeader(e);const s=yield this._innerClient.send(e);return n&&s.statusCode===401&&this._accessTokenFactory?(this._accessToken=yield this._accessTokenFactory(),this._setAuthorizationHeader(e),yield this._innerClient.send(e)):s})}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[ct.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[ct.Authorization]&&delete e.headers[ct.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}var Re;(function(t){t[t.None=0]="None",t[t.WebSockets=1]="WebSockets",t[t.ServerSentEvents=2]="ServerSentEvents",t[t.LongPolling=4]="LongPolling"})(Re||(Re={}));var De;(function(t){t[t.Text=1]="Text",t[t.Binary=2]="Binary"})(De||(De={}));let Bo=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 Xn{get pollAborted(){return this._pollAbort.aborted}constructor(e,n,s){this._httpClient=e,this._logger=n,this._pollAbort=new Bo,this._options=s,this._running=!1,this.onreceive=null,this.onclose=null}connect(e,n){return v(this,null,function*(){if(Ee.isRequired(e,"url"),Ee.isRequired(n,"transferFormat"),Ee.isIn(n,De,"transferFormat"),this._url=e,this._logger.log(g.Trace,"(LongPolling transport) Connecting."),n===De.Binary&&typeof XMLHttpRequest!="undefined"&&typeof new XMLHttpRequest().responseType!="string")throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[s,i]=bt(),o=H({[s]:i},this._options.headers),r={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._options.withCredentials};n===De.Binary&&(r.responseType="arraybuffer");const c=`${e}&_=${Date.now()}`;this._logger.log(g.Trace,`(LongPolling transport) polling: ${c}.`);const a=yield this._httpClient.get(c,r);a.statusCode!==200?(this._logger.log(g.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new rt(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,r)})}_poll(e,n){return v(this,null,function*(){try{for(;this._running;)try{const s=`${e}&_=${Date.now()}`;this._logger.log(g.Trace,`(LongPolling transport) polling: ${s}.`);const i=yield this._httpClient.get(s,n);i.statusCode===204?(this._logger.log(g.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):i.statusCode!==200?(this._logger.log(g.Error,`(LongPolling transport) Unexpected response code: ${i.statusCode}.`),this._closeError=new rt(i.statusText||"",i.statusCode),this._running=!1):i.content?(this._logger.log(g.Trace,`(LongPolling transport) data received. ${Dt(i.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(i.content)):this._logger.log(g.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(s){this._running?s instanceof fn?this._logger.log(g.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=s,this._running=!1):this._logger.log(g.Trace,`(LongPolling transport) Poll errored after shutdown: ${s.message}`)}}finally{this._logger.log(g.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}})}send(e){return v(this,null,function*(){return this._running?qn(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))})}stop(){return v(this,null,function*(){this._logger.log(g.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{yield this._receiving,this._logger.log(g.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[n,s]=bt();e[n]=s;const i={headers:H(H({},e),this._options.headers),timeout:this._options.timeout,withCredentials:this._options.withCredentials};let o;try{yield this._httpClient.delete(this._url,i)}catch(r){o=r}o?o instanceof rt&&(o.statusCode===404?this._logger.log(g.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(g.Trace,`(LongPolling transport) Error sending a DELETE request: ${o}`)):this._logger.log(g.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(g.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}})}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(g.Trace,e),this.onclose(this._closeError)}}}class Ho{constructor(e,n,s,i){this._httpClient=e,this._accessToken=n,this._logger=s,this._options=i,this.onreceive=null,this.onclose=null}connect(e,n){return v(this,null,function*(){return Ee.isRequired(e,"url"),Ee.isRequired(n,"transferFormat"),Ee.isIn(n,De,"transferFormat"),this._logger.log(g.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise((s,i)=>{let o=!1;if(n!==De.Text){i(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));return}let r;if(ve.isBrowser||ve.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const c=this._httpClient.getCookieString(e),a={};a.Cookie=c;const[d,u]=bt();a[d]=u,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:H(H({},a),this._options.headers)})}try{r.onmessage=c=>{if(this.onreceive)try{this._logger.log(g.Trace,`(SSE transport) data received. ${Dt(c.data,this._options.logMessageContent)}.`),this.onreceive(c.data)}catch(a){this._close(a);return}},r.onerror=c=>{o?this._close():i(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."))},r.onopen=()=>{this._logger.log(g.Information,`SSE connected to ${this._url}`),this._eventSource=r,o=!0,s()}}catch(c){i(c);return}})})}send(e){return v(this,null,function*(){return this._eventSource?qn(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))})}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class Lo{constructor(e,n,s,i,o,r){this._logger=s,this._accessTokenFactory=n,this._logMessageContent=i,this._webSocketConstructor=o,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=r}connect(e,n){return v(this,null,function*(){Ee.isRequired(e,"url"),Ee.isRequired(n,"transferFormat"),Ee.isIn(n,De,"transferFormat"),this._logger.log(g.Trace,"(WebSockets transport) Connecting.");let s;return this._accessTokenFactory&&(s=yield this._accessTokenFactory()),new Promise((i,o)=>{e=e.replace(/^http/,"ws");let r;const c=this._httpClient.getCookieString(e);let a=!1;if(ve.isNode||ve.isReactNative){const d={},[u,f]=bt();d[u]=f,s&&(d[ct.Authorization]=`Bearer ${s}`),c&&(d[ct.Cookie]=c),r=new this._webSocketConstructor(e,void 0,{headers:H(H({},d),this._headers)})}else s&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(s)}`);r||(r=new this._webSocketConstructor(e)),n===De.Binary&&(r.binaryType="arraybuffer"),r.onopen=d=>{this._logger.log(g.Information,`WebSocket connected to ${e}.`),this._webSocket=r,a=!0,i()},r.onerror=d=>{let u=null;typeof ErrorEvent!="undefined"&&d instanceof ErrorEvent?u=d.error:u="There was an error with the transport",this._logger.log(g.Information,`(WebSockets transport) ${u}.`)},r.onmessage=d=>{if(this._logger.log(g.Trace,`(WebSockets transport) data received. ${Dt(d.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(d.data)}catch(u){this._close(u);return}},r.onclose=d=>{if(a)this._close(d);else{let u=null;typeof ErrorEvent!="undefined"&&d instanceof ErrorEvent?u=d.error:u="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.",o(new Error(u))}}})})}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(g.Trace,`(WebSockets transport) sending data. ${Dt(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(g.Trace,"(WebSockets transport) socket closed."),this.onclose&&(this._isCloseEvent(e)&&(e.wasClean===!1||e.code!==1e3)?this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)):e instanceof Error?this.onclose(e):this.onclose())}_isCloseEvent(e){return e&&typeof e.wasClean=="boolean"&&typeof e.code=="number"}}const Gn=100;class Fo{constructor(e,n={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ee.isRequired(e,"url"),this._logger=Co(n.logger),this.baseUrl=this._resolveUrl(e),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 s=null,i=null;if(ve.isNode&&typeof require!="undefined"){const o=typeof __webpack_require__=="function"?__non_webpack_require__:require;s=o("ws"),i=o("eventsource")}!ve.isNode&&typeof WebSocket!="undefined"&&!n.WebSocket?n.WebSocket=WebSocket:ve.isNode&&!n.WebSocket&&s&&(n.WebSocket=s),!ve.isNode&&typeof EventSource!="undefined"&&!n.EventSource?n.EventSource=EventSource:ve.isNode&&!n.EventSource&&typeof i!="undefined"&&(n.EventSource=i),this._httpClient=new Do(n.httpClient||new xo(this._logger),n.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=n,this.onreceive=null,this.onclose=null}start(e){return v(this,null,function*(){if(e=e||De.Binary,Ee.isIn(e,De,"transferFormat"),this._logger.log(g.Debug,`Starting connection with transfer format '${De[e]}'.`),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(e),yield this._startInternalPromise,this._connectionState==="Disconnecting"){const n="Failed to start the HttpConnection before stop() was called.";return this._logger.log(g.Error,n),yield this._stopPromise,Promise.reject(new qe(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(g.Error,n),Promise.reject(new qe(n))}this._connectionStarted=!0})}send(e){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 Cn(this.transport)),this._sendQueue.send(e))}stop(e){return v(this,null,function*(){if(this._connectionState==="Disconnected")return this._logger.log(g.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve();if(this._connectionState==="Disconnecting")return this._logger.log(g.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;this._connectionState="Disconnecting",this._stopPromise=new Promise(n=>{this._stopPromiseResolver=n}),yield this._stopInternal(e),yield this._stopPromise})}_stopInternal(e){return v(this,null,function*(){this._stopError=e;try{yield this._startInternalPromise}catch(n){}if(this.transport){try{yield this.transport.stop()}catch(n){this._logger.log(g.Error,`HttpConnection.transport.stop() threw error '${n}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(g.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")})}_startInternal(e){return v(this,null,function*(){let n=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation)if(this._options.transport===Re.WebSockets)this.transport=this._constructTransport(Re.WebSockets),yield this._startTransport(n,e);else throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");else{let s=null,i=0;do{if(s=yield this._getNegotiationResponse(n),this._connectionState==="Disconnecting"||this._connectionState==="Disconnected")throw new qe("The connection was stopped during negotiation.");if(s.error)throw new Error(s.error);if(s.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(s.url&&(n=s.url),s.accessToken){const o=s.accessToken;this._accessTokenFactory=()=>o,this._httpClient._accessToken=o,this._httpClient._accessTokenFactory=void 0}i++}while(s.url&&i<Gn);if(i===Gn&&s.url)throw new Error("Negotiate redirection limit exceeded.");yield this._createTransport(n,this._options.transport,s,e)}this.transport instanceof Xn&&(this.features.inherentKeepAlive=!0),this._connectionState==="Connecting"&&(this._logger.log(g.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(s){return this._logger.log(g.Error,"Failed to start the connection: "+s),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(s)}})}_getNegotiationResponse(e){return v(this,null,function*(){const n={},[s,i]=bt();n[s]=i;const o=this._resolveNegotiateUrl(e);this._logger.log(g.Debug,`Sending negotiation request: ${o}.`);try{const r=yield this._httpClient.post(o,{content:"",headers:H(H({},n),this._options.headers),timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(r.statusCode!==200)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${r.statusCode}'`));const c=JSON.parse(r.content);return(!c.negotiateVersion||c.negotiateVersion<1)&&(c.connectionToken=c.connectionId),c.useStatefulReconnect&&this._options._useStatefulReconnect!==!0?Promise.reject(new Vn("Client didn't negotiate Stateful Reconnect but the server did.")):c}catch(r){let c="Failed to complete negotiation with the server: "+r;return r instanceof rt&&r.statusCode===404&&(c=c+" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(g.Error,c),Promise.reject(new Vn(c))}})}_createConnectUrl(e,n){return n?e+(e.indexOf("?")===-1?"?":"&")+`id=${n}`:e}_createTransport(e,n,s,i){return v(this,null,function*(){let o=this._createConnectUrl(e,s.connectionToken);if(this._isITransport(n)){this._logger.log(g.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=n,yield this._startTransport(o,i),this.connectionId=s.connectionId;return}const r=[],c=s.availableTransports||[];let a=s;for(const d of c){const u=this._resolveTransportOrError(d,n,i,(a==null?void 0:a.useStatefulReconnect)===!0);if(u instanceof Error)r.push(`${d.transport} failed:`),r.push(u);else if(this._isITransport(u)){if(this.transport=u,!a){try{a=yield this._getNegotiationResponse(e)}catch(f){return Promise.reject(f)}o=this._createConnectUrl(e,a.connectionToken)}try{yield this._startTransport(o,i),this.connectionId=a.connectionId;return}catch(f){if(this._logger.log(g.Error,`Failed to start the transport '${d.transport}': ${f}`),a=void 0,r.push(new ho(`${d.transport} failed: ${f}`,Re[d.transport])),this._connectionState!=="Connecting"){const j="Failed to select transport before stop() was called.";return this._logger.log(g.Debug,j),Promise.reject(new qe(j))}}}}return r.length>0?Promise.reject(new fo(`Unable to connect to the server with any of the available transports. ${r.join(" ")}`,r)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))})}_constructTransport(e){switch(e){case Re.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Lo(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case Re.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Ho(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case Re.LongPolling:return new Xn(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,n){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=s=>v(this,null,function*(){let i=!1;if(this.features.reconnect)try{this.features.disconnected(),yield this.transport.connect(e,n),yield this.features.resend()}catch(o){i=!0}else{this._stopConnection(s);return}i&&this._stopConnection(s)}):this.transport.onclose=s=>this._stopConnection(s),this.transport.connect(e,n)}_resolveTransportOrError(e,n,s,i){const o=Re[e.transport];if(o==null)return this._logger.log(g.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(Oo(n,o))if(e.transferFormats.map(c=>De[c]).indexOf(s)>=0){if(o===Re.WebSockets&&!this._options.WebSocket||o===Re.ServerSentEvents&&!this._options.EventSource)return this._logger.log(g.Debug,`Skipping transport '${Re[o]}' because it is not supported in your environment.'`),new lo(`'${Re[o]}' is not supported in your environment.`,o);this._logger.log(g.Debug,`Selecting transport '${Re[o]}'.`);try{return this.features.reconnect=o===Re.WebSockets?i:void 0,this._constructTransport(o)}catch(c){return c}}else return this._logger.log(g.Debug,`Skipping transport '${Re[o]}' because it does not support the requested transfer format '${De[s]}'.`),new Error(`'${Re[o]}' does not support ${De[s]}.`);else return this._logger.log(g.Debug,`Skipping transport '${Re[o]}' because it was disabled by the client.`),new uo(`'${Re[o]}' is disabled by the client.`,o)}_isITransport(e){return e&&typeof e=="object"&&"connect"in e}_stopConnection(e){if(this._logger.log(g.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,this._connectionState==="Disconnected"){this._logger.log(g.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`);return}if(this._connectionState==="Connecting")throw this._logger.log(g.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if(this._connectionState==="Disconnecting"&&this._stopPromiseResolver(),e?this._logger.log(g.Error,`Connection disconnected with error '${e}'.`):this._logger.log(g.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch(n=>{this._logger.log(g.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(e)}catch(n){this._logger.log(g.Error,`HttpConnection.onclose(${e}) threw error '${n}'.`)}}}_resolveUrl(e){if(e.lastIndexOf("https://",0)===0||e.lastIndexOf("http://",0)===0)return e;if(!ve.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const n=window.document.createElement("a");return n.href=e,this._logger.log(g.Information,`Normalizing '${e}' to '${n.href}'.`),n.href}_resolveNegotiateUrl(e){const n=new URL(e);n.pathname.endsWith("/")?n.pathname+="negotiate":n.pathname+="/negotiate";const s=new URLSearchParams(n.searchParams);return s.has("negotiateVersion")||s.append("negotiateVersion",this._negotiateVersion.toString()),s.has("useStatefulReconnect")?s.get("useStatefulReconnect")==="true"&&(this._options._useStatefulReconnect=!0):this._options._useStatefulReconnect===!0&&s.append("useStatefulReconnect","true"),n.search=s.toString(),n.toString()}}function Oo(t,e){return!t||(e&t)!==0}class Cn{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Qt,this._transportResult=new Qt,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Qt),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}_sendLoop(){return v(this,null,function*(){for(;;){if(yield this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new Qt;const e=this._transportResult;this._transportResult=void 0;const n=typeof this._buffer[0]=="string"?this._buffer.join(""):Cn._concatBuffers(this._buffer);this._buffer.length=0;try{yield this._transport.send(n),e.resolve()}catch(s){e.reject(s)}}})}static _concatBuffers(e){const n=e.map(o=>o.byteLength).reduce((o,r)=>o+r),s=new Uint8Array(n);let i=0;for(const o of e)s.set(new Uint8Array(o),i),i+=o.byteLength;return s.buffer}}class Qt{constructor(){this.promise=new Promise((e,n)=>[this._resolver,this._rejecter]=[e,n])}resolve(){this._resolver()}reject(e){this._rejecter(e)}}const No="json";class Uo{constructor(){this.name=No,this.version=2,this.transferFormat=De.Text}parseMessages(e,n){if(typeof e!="string")throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!e)return[];n===null&&(n=$t.instance);const s=Ne.parse(e),i=[];for(const o of s){const r=JSON.parse(o);if(typeof r.type!="number")throw new Error("Invalid payload.");switch(r.type){case q.Invocation:this._isInvocationMessage(r);break;case q.StreamItem:this._isStreamItemMessage(r);break;case q.Completion:this._isCompletionMessage(r);break;case q.Ping:break;case q.Close:break;case q.Ack:this._isAckMessage(r);break;case q.Sequence:this._isSequenceMessage(r);break;default:n.log(g.Information,"Unknown message type '"+r.type+"' ignored.");continue}i.push(r)}return i}writeMessage(e){return Ne.write(JSON.stringify(e))}_isInvocationMessage(e){this._assertNotEmptyString(e.target,"Invalid payload for Invocation message."),e.invocationId!==void 0&&this._assertNotEmptyString(e.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(e){if(this._assertNotEmptyString(e.invocationId,"Invalid payload for StreamItem message."),e.item===void 0)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(e){if(e.result&&e.error)throw new Error("Invalid payload for Completion message.");!e.result&&e.error&&this._assertNotEmptyString(e.error,"Invalid payload for Completion message."),this._assertNotEmptyString(e.invocationId,"Invalid payload for Completion message.")}_isAckMessage(e){if(typeof e.sequenceId!="number")throw new Error("Invalid SequenceId for Ack message.")}_isSequenceMessage(e){if(typeof e.sequenceId!="number")throw new Error("Invalid SequenceId for Sequence message.")}_assertNotEmptyString(e,n){if(typeof e!="string"||e==="")throw new Error(n)}}const jo={trace:g.Trace,debug:g.Debug,info:g.Information,information:g.Information,warn:g.Warning,warning:g.Warning,error:g.Error,critical:g.Critical,none:g.None};function zo(t){const e=jo[t.toLowerCase()];if(typeof e!="undefined")return e;throw new Error(`Unknown log level: ${t}`)}class Vo{configureLogging(e){if(Ee.isRequired(e,"logging"),Wo(e))this.logger=e;else if(typeof e=="string"){const n=zo(e);this.logger=new Kt(n)}else this.logger=new Kt(e);return this}withUrl(e,n){return Ee.isRequired(e,"url"),Ee.isNotEmpty(e,"url"),this.url=e,typeof n=="object"?this.httpConnectionOptions=H(H({},this.httpConnectionOptions),n):this.httpConnectionOptions=ee(H({},this.httpConnectionOptions),{transport:n}),this}withHubProtocol(e){return Ee.isRequired(e,"protocol"),this.protocol=e,this}withAutomaticReconnect(e){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return e?Array.isArray(e)?this.reconnectPolicy=new Yn(e):this.reconnectPolicy=e:this.reconnectPolicy=new Yn,this}withServerTimeout(e){return Ee.isRequired(e,"milliseconds"),this._serverTimeoutInMilliseconds=e,this}withKeepAliveInterval(e){return Ee.isRequired(e,"milliseconds"),this._keepAliveIntervalInMilliseconds=e,this}withStatefulReconnect(e){return this.httpConnectionOptions===void 0&&(this.httpConnectionOptions={}),this.httpConnectionOptions._useStatefulReconnect=!0,this._statefulReconnectBufferSize=e==null?void 0:e.bufferSize,this}build(){const e=this.httpConnectionOptions||{};if(e.logger===void 0&&(e.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const n=new Fo(this.url,e);return pn.create(n,this.logger||$t.instance,this.protocol||new Uo,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}function Wo(t){return t.log!==void 0}function Be(t,e={}){var c;const{popupRequestInfo:n}=window;t=It(t);const s=(c=n==null?void 0:n.credentialType)==null?void 0:c.toUpperCase(),i=n==null?void 0:n.accessToken,r=H(H({},{method:"GET",headers:{}}),e);switch(r.body&&typeof r.body=="object"&&(r.body instanceof FormData?r.headers=ee(H({},r.headers),{"Content-Type":"multipart/form-data"}):(r.headers=ee(H({},r.headers),{"Content-Type":"application/json"}),r.body=JSON.stringify(r.body))),s){case"COOKIE":r.credentials="include";break;case"QUERY":break;default:i&&(r.headers=ee(H({},r.headers),{Authorization:`Bearer ${i}`}));break}return fetch(t,r).then(a=>{if(!a.ok){console.error(`HTTP error! status: ${a.status}`);return}return a.json()}).then(a=>{if(a&&a.code){if(a.code!=="0"){console.error(`API error! code: ${a.code}, message: ${a.message}`);return}return a.data}return a}).catch(a=>{console.error("Error fetching data:",a)})}function Bt(t,e){if(!e)return t;let n="";for(let s in e){const i=e[s];i!=null&&(n.length>0&&(n+="&"),n+=`${encodeURIComponent(s)}=${encodeURIComponent(i)}`)}return t.indexOf("?")===-1?t+="?"+n:t+="&"+n,t}function Kn(t){return v(this,null,function*(){if(!t||t.length===0)return[];const s=yield Be("user/batch/get",{method:"POST",body:{ids:t}});return!s||!Array.isArray(s)?[]:s.map(i=>({id:i.id,username:i.username,fullName:i.fullName,avatarUrl:i.avatarUrl}))})}const Ht=window,qo=Ht.indexedDB||Ht.mozIndexedDB||Ht.webkitIndexedDB||Ht.msIndexedDB||Ht.shimIndexedDB,Zo="chatPopupDb",Yo=1,Jt="users";function Xo(t){if(!t.objectStoreNames.contains(Jt)){const e=t.createObjectStore(Jt,{keyPath:"id",autoIncrement:!1});["username","fullName","avatarUrl"].forEach(n=>e.createIndex(n,n,{unique:!1}))}}let en;function Go(){return new Promise((t,e)=>{if(en)t(en);else{const n=qo.open(Zo,Yo);n.onerror=s=>e(s.target.error),n.onsuccess=s=>{en=s.target.result,t(en)},n.onupgradeneeded=s=>{const i=s.target.result;Xo(i)}}})}function Qn(t,e){return v(this,null,function*(){const n=yield Go();return n?n.transaction(Jt,t,e).objectStore(Jt):void 0})}function Ko(t){return new Promise((e,n)=>v(null,null,function*(){if(t==="SYSTEM"){e({id:"SYSTEM",username:"system",fullName:"Hệ thống"});return}const s=yield Qn("readonly");if(!s){n(new Error("User object store not found"));return}const i=s.get(t);i.onsuccess=o=>v(null,null,function*(){const r=o.target.result;e(r)}),i.onerror=o=>n(o.target.error)}))}function Qo(t){return v(this,null,function*(){const e=yield Qn("readwrite");if(!e)throw new Error("User object store not found");return new Promise((n,s)=>{const i=e.put(t);i.onsuccess=o=>n(o.target.result),i.onerror=o=>s(o.target.error)})})}function Jo(t){return v(this,null,function*(){const e=t.map(s=>Ko(s));return(yield Promise.all(e)).filter(s=>s!==void 0)})}function _t(t){return v(this,null,function*(){const e=Array.from(new Set(t.filter(r=>typeof r=="string"&&r.length>0))),n=yield Jo(e),s=e.filter(r=>!n.some(c=>c.id===r)),i=yield Kn(s);yield Promise.all(i.map(r=>Qo(r)));const o=[...n,...i];return new Map(o.map(r=>[r.id,r]))})}function tn(t){return{id:t.id||t.conversationId,name:t.name,lastMessage:t.lastMessage,updatedAt:t.updatedAt||t.dateTime,type:t.type,membersCount:t.membersCount,status:t.status,isPinned:t.isPinned,isRead:t.isRead,traceId:t.traceId}}function tt(t,e){if(!t)return;let n;e||t.quotedMessage&&(n=tt(t.quotedMessage,!0));const s=t.body;return s&&Array.isArray(s.files)&&(s.files=s.files.map(i=>{const o=i.thumbId?It(`file/${i.thumbId}`):void 0,r=It(`file/${i.id||i.fileId}`);return{id:i.id||i.fileId,thumbId:i.thumbId,url:r,name:i.name,contentType:i.contentType,thumbUrl:o}})),{id:t.id||t.messageId,conversationId:t.conversationId,senderId:t.senderId||t.editedBy,sender:t.sender,body:s,sentAt:t.sentAt,deleted:t.deleted,edited:t.edited,mentions:t.mentions,deletedFor:t.deletedFor,quotedMessage:n,traceId:t.traceId}}function nn(t){return v(this,null,function*(){const e=t.lastMessage?[t.lastMessage.senderId]:[],n=yield _t(e);if(t.lastMessage){const s=n.get(t.lastMessage.senderId);s&&(t.lastMessage.sender=s,t.lastMessage.sentAt=t.lastMessage.sentAt?new Date(t.lastMessage.sentAt):new Date)}return{id:t.id,name:t.name,lastMessage:t.lastMessage,updatedAt:new Date(t.updatedAt),type:t.type,membersCount:t.membersCount,status:t.status,isPinned:t.isPinned,isRead:t.isRead,traceId:t.traceId}})}function St(t,e=new Set){return t.senderId&&e.add(t.senderId),t.quotedMessage&&St(t.quotedMessage,e),e}function At(t,e){const n=t.sender||e.get(t.senderId),s=t.quotedMessage?At(t.quotedMessage,e):void 0;return t.sender=n,s&&(t.quotedMessage=s),t}function xt(t){if(!t)return;const e=t.quotedMessage?xt(t.quotedMessage):void 0,n={id:t.id,conversationId:t.conversationId,sender:t.sender,body:t.body,sentAt:t.sentAt?new Date(t.sentAt):new Date,deleted:t.deleted,edited:t.edited,mentions:t.mentions,deletedFor:t.deletedFor,traceId:t.traceId};return e&&(n.quotedMessage=e),n}function Jn(t,e){var c;if(!t)return console.error("URL base is not defined."),"";e=e?e.startsWith("/")?e.slice(1):e:"";let n=t.endsWith("/")?`${t}${e}`:`${t}/${e}`;n.endsWith("/")&&(n=n.slice(0,-1));const{popupRequestInfo:s}=window,i=(c=s==null?void 0:s.credentialType)==null?void 0:c.toUpperCase(),o=s==null?void 0:s.credentialName,r=s==null?void 0:s.accessToken;switch(i){case"COOKIE":const a=new URL(n);a.searchParams.append("credentialType",i),a.searchParams.append("credentialName",o||""),n=a.toString();break;case"QUERY":if(r){const d=new URL(n);d.searchParams.append("access_token",r),n=d.toString()}break}return n}function It(t){const{popupRequestInfo:e}=window,n=e==null?void 0:e.apiUrlBase;return Jn(n,t)}function er(t){const{popupRequestInfo:e}=window,n=t||(e==null?void 0:e.hubUrlBase);return Jn(n)}function tr(t){var i;let e=er(t);const{popupRequestInfo:n}=window,s=(i=n==null?void 0:n.credentialType)==null?void 0:i.toUpperCase();if(s!="COOKIE"&&s!="QUERY"){const o=n==null?void 0:n.accessToken;if(o){const r=new URL(e);r.searchParams.append("access_token",o),e=r.toString()}}return new Vo().withUrl(e).configureLogging(g.Information).withAutomaticReconnect().build()}const mn=window;mn.messagesCache={};function nr(t,e,n,s){return v(this,null,function*(){const i=Bt(`message/conversation/${t}/user`,{direction:e,messageId:n,top:s}),o=yield Be(i);return!o||!Array.isArray(o)?[]:o.filter(r=>!!r).map(r=>tt(r))})}function sr(t){return v(this,null,function*(){const e="message";let n;t.quotedMessage&&(n=t.quotedMessage.id,n&&(mn.messagesCache[n]=t.quotedMessage));const s={conversationId:t.conversationId,body:t.body,quotedId:n,traceId:t.traceId},i=yield Be(e,{method:"POST",body:s});return i.quotedMessage=t.quotedMessage,tt(i)})}function ir(t){return v(this,null,function*(){if(!t||!t.id)return;const e=`message/${t.id}`;let n;t.quotedMessage&&(n=t.quotedMessage.id,n&&(mn.messagesCache[n]=t.quotedMessage));const s={body:t.body,quotedId:n,mentions:t.mentions},i=yield Be(e,{method:"POST",body:s});return i.quotedMessage=t.quotedMessage,tt(i)})}function or(t,e){return v(this,null,function*(){if(!t)return!1;e||(e="Recall");const n=`message/${t}/delete`;return!!(yield Be(n,{method:"POST",body:{type:e}}))})}function es(t){return v(this,null,function*(){if(!t)return;const e=`message/${t}`,n=yield Be(e);if(n)return tt(n)})}function rr(t){return v(this,null,function*(){if(!t||t.length===0)return[];const s=yield Be("message/batch/get",{method:"POST",body:{ids:t}});return!s||!Array.isArray(s)?[]:s.map(i=>tt(i))})}function ar(t,e,n,s){return v(this,null,function*(){var c;const i=Bt("aggregate/search",{conversationId:t,keyword:e,from:n,top:s,type:"MESSAGE"}),r=(c=(yield Be(i)).filter(a=>a.type==="MESSAGE").at(0))==null?void 0:c.items;return r?r.map(a=>tt(a)):[]})}const sn=window;function cr(t,e){return v(this,null,function*(){if(!e||!t)return;if(!t.quotedMessage&&t.quotedId){const c=sn.messagesCache[t.quotedId];c?(t.quotedMessage=c,delete sn.messagesCache[t.quotedId]):t.quotedMessage=yield es(t.quotedId)}const n=tt(t);if(!n)return;const s=St(n),i=yield _t(Array.from(s)),o=At(n,i),r=xt(o);e(r)})}function lr(t,e){return v(this,null,function*(){if(!e||!t)return;const n=tn(t);if(!n)return;const s=yield nn(n);e(s)})}function dr(t,e){if(!e||!t)return;const{conversationId:n,name:s}=t;!n||!s||e(n,s)}function ur(t,e){if(!e||!t)return;const{conversationId:n}=t;n&&e(n)}function hr(t,e){return v(this,null,function*(){if(!e||!t)return;if(!t.quotedMessage&&t.quotedId){const c=sn.messagesCache[t.quotedId];c?(t.quotedMessage=c,delete sn.messagesCache[t.quotedId]):t.quotedMessage=yield es(t.quotedId)}const n=tt(t);if(!n)return;const s=St(n),i=yield _t(Array.from(s)),o=At(n,i),r=xt(o);e(r)})}function fr(t,e){if(!e||!t)return;const{messageId:n,conversationId:s,type:i,deletedBy:o}=t;!n||!s||e({messageId:n,conversationId:s,deleteType:i||"Recall",deletedBy:o||""})}let Fe;function gr(t){return Fe&&Fe.stop(),Fe=tr(t),Fe?(Fe.on("UserStatusChanged",n=>console.log("UserStatusChanged",n)),{onConnected(n){Fe.on("Connected",n)},onMessageSent(n){Fe.on("MessageSent",s=>v(null,null,function*(){yield cr(s,n)}))},onMessageEdited(n){Fe.on("MessageEdited",s=>v(null,null,function*(){yield hr(s,n)}))},onMessageDeleted(n){Fe.on("MessageDeleted",s=>{fr(s,n)})},onConversationCreated(n){Fe.on("ConversationCreated",s=>v(null,null,function*(){yield lr(s,n)}))},onConversationBasicInfoChanged(n){Fe.on("ConversationBasicInfoChanged",s=>{dr(s,n)})},onConversationDeleted(n){Fe.on("ConversationDeleted",s=>{ur(s,n)})},start:()=>Fe.start(),stop:()=>Fe.stop()}):void 0}function pr(){return new Promise(t=>{t([{name:"Khiếu nại và hỗ trợ",description:"Tạo khiếu nại của khách hàng và được trợ giúp bởi hỗ trợ viên",conversationType:"HELP",icon:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABGCAYAAABbnhMrAAAAAXNSR0IArs4c6QAAG/hJREFUeF7tXHk8lNv/n2HGPggRcVEporihuvJttVaylW6khlJdKfuaJbJlK2QZVBSVdlFp0WZJkmgh5ep+lSWSyBIGv9fnMcd3cmds6d7++D2v1zTT85xzPue8z2f/nAce9//XdyGA/67eP7jzwMAACw6HY8XhcH14PL7/B5Ob0PD/OoCvXr0iNTY2ylVXV8s0NDRIf/z4Uby5uVmgvb19Sk9PDyesioWFhcrFxdXNx8fXws/P/1FYWPidpKTkWxERkYrffvutHI/H901o9ZPQ6V8BsLq6WuTevXuaJSUl/6mqqlJpaWmZ8enTJ1JXVxdwGw6PxwNo2Ad+DwwM4Pr7+3F9fX3YB+7x8PDgSCTSZ3Fx8VIFBYUiNTW13NmzZ9+SkZHpngRcxjzEPwpgTk7O0uvXr+vn5eWta2homAWgEAiEHlFR0XczZsx4Pn369LfAXSIiIvX8/Pyfubm5O9jY2Pp6enpYgSM/ffok8PHjx2m1tbWS1dXVc2tra+Wam5unwjisrKw4KSmpEi0trQs6OjqZ8+fPfz5mFL6j4T8CYHp6ul5mZqbp06dPdVpaWviFhITalZSUcuXk5O4vWrSoWEhIqGT+/Pkt413Hs2fPZlRWViqVlZWpFRYWrqipqVnQ1dWFExYWfquhoXFFV1c3ffny5Q/HO+542v9QAAsKChbGx8fvKSsrM/rw4QPXrFmz3q1cuTJ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4S0tTUNB1q0vTHdSFBAWBCqZVAIPRtMt10xIa854C43MQjiMkC8qcBEBaUceHCurPnLlgWlzxZ1tXZyY/iXnQiVUpKqszYeH3Kot8WHVFRURk8xPMvXz8VgIAFJCbu3Lyj9t93b+Xq6z9M7+ntIXBzcjfJzpF9M3f+3KJZs2Y1/suYfUP+pwPwZwJnLHP5P2JCPxnrY2whAAAAAElFTkSuQmCC"},{name:"Tư vấn đầu tư",description:"Tạo một cuộc hội thoại để bắt đầu nhận được các tư vấn đầu tư",botId:"BOT~rasaconnector",isDefault:!0,icon:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABZCAYAAACpHqNlAAAAAXNSR0IArs4c6QAAG71JREFUeF7tXAlYU0fXnpuQBAgCURFRqQvwsbhABUGgoihFoAhal7pUxaVaQVvr8nXRPvWrUpdafxcEra0VFVwQRRG1LqAoS63WBRcgAQSV1QbByBIg+f8zNxNuYoDEBfX7e5+HhyR3ljPvnG3OnBkK/fO8EALUi9SOjY3tW1paOlRGydhyOUtOIZlMJqfkzDZZlFzlu1ztvab+KblqnbZolFOUyjgoSo6/y+T07yy17/AbRckouZzV1M3cvMLCwiK/c+fOOY6Ojk/b6kv9vc4ALl669ItLly4uKyoq6lRWVobbY46X+VltXLrS1i7l5U0y1KlTJ9StW7eKvn37Jvv7+x9ydnY+1q9fP6k2BOgEoLGpSUF1VVUv0jCLzQaeo7/qxjTa0NY+ZeTAjZSSCYyMOyCHvn3zJk6cFL7o889/a4sIrQC0sbHpIxQJ7xjy+byamhoMFkePgxoaGhDSqoW2yHh977kcLmpqasJ/zKdLV3Pk5up2/Nvly0NdXV3vt0Rhm8PndzC6+/Tp038huZwFjXC4dIeyRrpDis1SEeHXB8Vz9ixTUdGIw+Hg8TQ2NeIGXQa5in5YtSrE19c3TaO+bqnbkJAQv13RuxIQQjwQVRailLNE9Jyenh5qbKQ7elsfLpeLJQnGxGaz8X+ilgDMhsYGZN61a9Xe3Xv83n///Uz1cWrkwKVffx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yiGcB4eyQe9ZWFjk+fr6Hvfz8zsUFBR0SZcBtXfZdgeQOcALGRfs7+fdtxKLxRa1tbVUx44dq6ytrfMsLCxy7OzsnrQ3GM/T32sF8HkIftPq/C/BcWIskM+NvgAAAABJRU5ErkJggg=="}])})}function Cr(t,e){return v(this,null,function*(){var a,d;const n=Bt("conversation/user/pinned",{top:t,type:e,ignoredFields:"members"}),s=Bt("conversation/user",{top:t,type:e,ignoredFields:"members"}),i=yield Promise.all([Be(n),Be(s)]);let o=(a=i[0])==null?void 0:a.items,r=(d=i[1])==null?void 0:d.items;return o||(o=[]),r||(r=[]),[...o,...r].map(u=>tn(u))})}function mr(t){return v(this,null,function*(){const e=`conversation/${t}?ignoredFields=members`,n=yield Be(e);if(n)return tn(n)})}function wr(t){return v(this,null,function*(){const e=t.type?t.type:"BOT";let n="conversation";const s={name:t.name,traceId:t.traceId};switch(e){case"BOT":n+="/bot",s.botId=t.members?t.members.filter(f=>{var j;return(j=f.userId)==null?void 0:j.startsWith("BOT~")}).map(f=>f.userId)[0]:null;break;case"SURVEY":n+="/survey",s.botId=t.members?t.members.filter(f=>{var j;return(j=f.userId)==null?void 0:j.startsWith("BOT~")}).map(f=>f.userId)[0]:null;break;case"GROUP":n+="/group",s.memberIds=t.members?t.members.filter(f=>f.id!=="me").map(f=>f.userId):[];break;case"HELP":n+="/help";break}const i=yield Be(n,{method:"POST",body:s}),{conversationId:o,name:r,type:c,membersCount:a,updatedAt:d,traceId:u}=i;return{id:o,name:r,type:c,membersCount:a,updatedAt:d,traceId:u}})}function vr(t,e){return v(this,null,function*(){let n="conversation";return e?n+=`/${t}/pin`:n+=`/${t}/unpin`,yield Be(n,{method:"POST",body:{}}),!0})}function yr(t,e){return v(this,null,function*(){const n=`conversation/${t}`;return yield Be(n,{method:"PATCH",body:{name:e}}),!0})}function br(t){return v(this,null,function*(){const e=`conversation/${t}/delete`;return yield Be(e,{method:"POST",body:{}}),!0})}function _r(t,e,n){return v(this,null,function*(){var c;const s=Bt("aggregate/search",{keyword:t,from:e,top:n,type:"CONVERSATION"}),o=(c=(yield Be(s)).filter(a=>a.type==="CONVERSATION").at(0))==null?void 0:c.items;if(!o)return[];const r=[...new Set(o.map(a=>a.lastMessageId))];if(r.length>0){const a=yield rr(r),d={};a.forEach(u=>{u&&(d[u.id]=u)}),o.forEach(u=>{u.lastMessageId&&(u.lastMessage=d[u.lastMessageId])})}return o.map(a=>tn(a))})}function Sr(t,e){return v(this,null,function*(){const n=yield Cr(t,e);return yield Promise.all(n.map(nn))})}function Ar(t){return v(this,null,function*(){const e=yield mr(t);return e?yield nn(e):void 0})}function xr(t,e,n){return v(this,null,function*(){const s=yield _r(t,e,n);return yield Promise.all(s.map(nn))})}function Ir(t){return v(this,null,function*(){const e=yield wr(t);return{id:e.id,name:e.name,type:e.type,membersCount:e.membersCount,updatedAt:new Date(e.updatedAt)}})}function Mr(t,e){return vr(t,e)}function kr(t,e){return yr(t,e)}function Er(t){return br(t)}function Tr(t,e){var a;if(!t)return;const{popupRequestInfo:n}=window,s=It("file"),i=new XMLHttpRequest,o=(a=n==null?void 0:n.credentialType)==null?void 0:a.toUpperCase(),r=n==null?void 0:n.accessToken;switch(o){case"COOKIE":i.withCredentials=!0;break;case"QUERY":break;default:i.setRequestHeader("Authorization",`Bearer ${r}`);break}const c=new FormData;c.append("file",t),e&&(i.upload.onprogress=function(d){if(d.lengthComputable){const u=d.loaded/d.total*80;e({loaded:d.loaded,total:d.total,percent:u,status:"uploading"})}}),i.onload=function(){if(i.status===200){const d=JSON.parse(i.responseText);if(e){const u=d.thumbId?It(`file/${d.thumbId}`):void 0,f=It(`file/${d.fileId}`);e({loaded:d.size,total:d.size,percent:100,status:"done",httpCode:i.status,fileItem:{id:d.fileId,name:d.fileName,contentType:d.contentType,thumbId:d.thumbId,thumbUrl:u,url:f}})}}else e&&e({loaded:0,total:0,percent:0,status:"error",error:i.statusText,httpCode:i.status})},i.open("POST",s,!0),i.send(c),console.log(`------- Uploading file: ${t.name} to ${s}`)}function Rr(t,e){Tr(t,e)}function Pr(t,e,n,s){return v(this,null,function*(){const i=(yield nr(t,e,n,s)).filter(a=>!!a);if(!i||!Array.isArray(i))return[];const o=new Set;i.forEach(a=>St(a,o));const r=yield _t(Array.from(o));return i.map(a=>At(a,r)).map(a=>xt(a))})}function $r(t){return v(this,null,function*(){const e=yield sr(t);if(!e)return;const n=St(e),s=yield _t(Array.from(n)),i=At(e,s);return xt(i)})}function Dr(t){return v(this,null,function*(){return!!(yield ir(t))})}function Br(t,e){return or(t,e)}function Hr(t,e,n,s){return v(this,null,function*(){const i=yield ar(t,e,n,s);if(!i||!Array.isArray(i))return[];const o=new Set;i.forEach(a=>St(a,o));const r=yield _t(Array.from(o));return i.map(a=>At(a,r)).map(a=>xt(a))})}function Lr(t){return Kn(t)}class Fr{constructor(e){me(this,"hubConnection");me(this,"onHubConnected",e=>{this.hubConnection.onConnected(n=>{window.currentUserId=n.userId,e(n)})});me(this,"onMessageSent",e=>{this.hubConnection.onMessageSent(n=>{n.conversationId=this.normalizeConvId(n.conversationId),this.normalizeSender(n.sender),e(n)})});me(this,"onMessageEdited",e=>{this.hubConnection.onMessageEdited(n=>{n.conversationId=this.normalizeConvId(n.conversationId),this.normalizeSender(n.sender),e(n)})});me(this,"onMessageDeleted",e=>{this.hubConnection.onMessageDeleted(e)});me(this,"onConversationCreated",e=>{this.hubConnection.onConversationCreated(n=>{this.normalizeConversation(n),e(n)})});me(this,"onConversationBasicInfoChanged",e=>{this.hubConnection.onConversationBasicInfoChanged((n,s)=>{n=this.normalizeConvId(n),e(n,s)})});me(this,"onConversationDeleted",e=>{this.hubConnection.onConversationDeleted(n=>{n=this.normalizeConvId(n),e(n)})});me(this,"getConversationAsync",e=>v(this,null,function*(){const n=this.denormalizeConvId(e),s=yield Ar(n);if(s)return this.normalizeConversation(s),s}));me(this,"listConversationAsync",(e,n)=>v(this,null,function*(){const s=yield Sr(e,n);return s.forEach(i=>this.normalizeConversation(i)),s}));me(this,"searchConversationsAsync",(e,n,s)=>v(this,null,function*(){const i=yield xr(e,n,s);return i.forEach(o=>this.normalizeConversation(o)),i}));me(this,"pinConversationAsync",(e,n)=>{const s=this.denormalizeConvId(e);return Mr(s,n)});me(this,"createConversationAsync",e=>Ir(e));me(this,"updateConversationNameAsync",(e,n)=>{const s=this.denormalizeConvId(e);return kr(s,n)});me(this,"deleteConversationAsync",e=>{const n=this.denormalizeConvId(e);return Er(n)});me(this,"sendMessageAsync",e=>v(this,null,function*(){const n=H({},e);n.conversationId=this.denormalizeConvId(n.conversationId);const s=yield $r(n);return this.normalizeSender(s.sender),s}));me(this,"listMessagesAsync",(e,n,s,i)=>v(this,null,function*(){const o=this.denormalizeConvId(e),r=yield Pr(o,n,s,i);return this.normalizeMessages(r),r}));me(this,"searchMessagesAsync",(e,n,s,i)=>v(this,null,function*(){const o=this.denormalizeConvId(e),r=yield Hr(o,n,s,i);return this.normalizeMessages(r),r}));me(this,"updateMessageAsync",e=>Dr(e));me(this,"batchGetUsersAsync",e=>Lr(e));me(this,"deleteMessageAsync",(e,n)=>Br(e,n));me(this,"uploadFile",(e,n)=>{Rr(e,n)});me(this,"listChatTypesAsync",()=>v(null,null,function*(){return yield pr()}));const n=gr(e);if(!n)throw new Error("Connect to hub error");this.hubConnection=n,this.hubConnection.start()}get currentUserId(){return window.currentUserId}normalizeConvId(e){return e.startsWith(`${this.currentUserId}~`)?e.replace(new RegExp(`^${this.currentUserId}`),"me"):e}denormalizeConvId(e){return e.replace(/^me/,this.currentUserId)}normalizeSender(e){e&&e.id===this.currentUserId&&(e.id="me")}normalizeConversation(e){e.id=this.normalizeConvId(e.id),e.lastMessage&&this.normalizeSender(e.lastMessage.sender)}normalizeMessages(e){e.forEach(n=>this.normalizeSender(n.sender))}}var Or=F("<div>Loading...");const[wn,Nr]=L(null),[Ur,jr]=L(null),Pe={},ts={apiUrlBase:"http://10.26.4.49:5000/api",hubUrlBase:"http://10.26.4.49:5099/hub/notification",credentialType:"cookie",credentialName:"aspfpt_sessiontoken"};window.popupRequestInfo=ts;const ns=ts.hubUrlBase,ss=()=>{var s;const t=window.popupRequestInfo;if(!ns)throw new Error("VITE_PUBLIC_HUB_URL is not defined");const e=(s=t==null?void 0:t.credentialType)==null?void 0:s.toLowerCase();if(e!=="cookie"&&!(t!=null&&t.accessToken))throw new Error("Missing JWT token: accessToken chưa được gán vào popupRequestInfo");if(e!=="cookie"&&!window.currentUserId)throw new Error("Missing currentUserId: chưa chọn user");const n=new Fr(ns);Nr(n),n.onHubConnected(i=>{console.log("SignalR: Hub connected",i)}),n.onMessageSent(i=>{var o;console.log("SignalR: Message sent event received",i),(o=Pe.appendMessage)==null||o.call(Pe,i)}),n.onMessageEdited(i=>{var o;console.log("SignalR: Message edited event received",i),(o=Pe.updateMessage)==null||o.call(Pe,i)}),n.onMessageDeleted(i=>{var o;console.log("SignalR: Message deleted event received",i),(o=Pe.deleteMessage)==null||o.call(Pe,i)}),n.onConversationCreated(i=>{var o;console.log("SignalR: Conversation created event received",i),(o=Pe.appendConversation)==null||o.call(Pe,i)}),n.onConversationBasicInfoChanged((i,o)=>{var r;console.log("SignalR: Conversation name changed",i,o),(r=Pe.updateConversationName)==null||r.call(Pe,i,o)}),n.onConversationDeleted(i=>{var o;console.log("SignalR: Conversation deleted",i),(o=Pe.deleteConversation)==null||o.call(Pe,i)})};function is(t,e){const n=typeof t=="string"?document.querySelector(t):t;if(!n)throw new Error(`Element "${t}" not found.`);e!=null&&e.credentialType&&(window.popupRequestInfo.credentialType=e.credentialType),e!=null&&e.accessToken&&(window.popupRequestInfo.accessToken=e.accessToken),e!=null&&e.currentUserId&&(window.currentUserId=e.currentUserId),jr(e),ss(),bs(()=>ie(Ye,{get when(){return wn()},get fallback(){return Or()},get children(){return ie(zi,{get remoteRepository(){return wn()},exportMethods:Pe,get children(){return ie(co,{get remoteRepo(){return wn()},get options(){return Ur()}})}})}}),n)}typeof window!="undefined"&&(window.EzChat={createPopup:is}),window.addEventListener("startChat",()=>{ss()}),Me.createPopup=is,Object.defineProperty(Me,Symbol.toStringTag,{value:"Module"})}));
12
+ `);return[ee(H({},i),{text:x,type:"normal",isNormalType:!0,contents:[{content:x}]})]}}return s==="bot"&&e.body&&typeof e.body.content=="string"&&!e.body.type?[ee(H({},i),{text:e.body.content,type:"normal",isNormalType:!0,contents:[{content:e.body.content,metadata:e.body.metadata}]})]:[ee(H({},i),{type:"normal",isNormalType:!0,contents:i.text?[{content:i.text}]:[]})]}).flat().filter(e=>e.type==="choice"?!!e.question&&Array.isArray(e.options)&&e.options.length>0:e.type==="normal"?!!e.text&&e.text.trim()!=="":e.type==="form"?Array.isArray(e.fields)&&e.fields.length>0:e.type==="survey"?Array.isArray(e.options)&&e.options.length>0:!!e.text&&e.text.trim()!=="")}function Wi(t,e,n){var o;const s=[...t].reverse().find(r=>r.sender==="bot");let i;if(s&&s.contents&&Array.isArray(s.contents)&&(i=(o=s.contents.find(r=>r.metadata))==null?void 0:o.metadata),i){const r=parseInt(i.section),c=parseInt(i.totalSections)||6;e(r),n(c)}else e(1),n(6)}function Un(t){return v(this,null,function*(){var n,s,i;if(!t)return!1;const e=yield t.listConversationAsync(100);for(const o of e)if(o.id&&o.id.endsWith("~SURVEY")){const r=yield t.listMessagesAsync(o.id);let c=1,a=6;for(let d=r.length-1;d>=0;d--){const u=r[d];if(((n=u.sender)==null?void 0:n.id)!=="me"&&((s=u.body)!=null&&s.children)){const f=(i=u.body.children.find(j=>j.metadata))==null?void 0:i.metadata;if(f){c=parseInt(f.section),a=parseInt(f.totalSections)||6;break}}}if(c<a)return!0}return!1})}function jn(t,e,n,s,i,o,r,c,a){return v(this,null,function*(){if(!t.remoteRepo)return;const u=(yield t.remoteRepo.listConversationAsync(100)).find(f=>f.id&&f.id.endsWith("~SURVEY"));if(u)e.setCurrentConversation({id:u.id,name:u.name,type:"BOT"}),n(u.id),s(u.name),i(!0),o(new Set),r(!1),yield e.listMessagesAsync(u.id),c&&c();else{const f=`${Pt()}~SURVEY`,$=yield e.createConversationAsync({id:f,name:"Tư vấn đầu tư",type:"BOT",members:[{userId:"BOT~surveybot",role:"MEMBER"}],updatedAt:new Date});e.setCurrentConversation({id:$.id,name:$.name,type:"BOT"}),n($.id),s($.name),i(!0),o(new Set),r(!1),yield e.listMessagesAsync($.id),c&&c(),a&&a()}})}function qi(t,e){if(!e||t.length===0)return!0;const n=[...t].reverse().find(s=>s.sender==="bot");return!!(n&&n.type==="normal")}function Zi(t,e,n,s,i,o,r,c,a,d,u){return v(this,null,function*(){if(yield Un(t.remoteRepo)){alert("Bạn chưa hoàn thành khảo sát hiện tại!");return}const f=e.trim();if(!f){n("Vui lòng nhập tên cuộc hội thoại");return}if(f.length>100){n("Tên cuộc hội thoại không được quá 100 ký tự");return}n(void 0),s(!1);try{const j=Pt(),U=yield i.createConversationAsync({id:j,name:f,type:"BOT",members:[{userId:"BOT~rasaconnector",role:"MEMBER"}],updatedAt:new Date});i.setCurrentConversation({id:U.id,name:U.name,type:"BOT"}),o(U.id),r(U.name),c(!0),a(new Set),d(!1),yield i.listMessagesAsync(U.id),u&&u()}catch(j){console.error("Tạo hội thoại mới thất bại:",j)}})}function Yi(t,e,n,s){return v(this,null,function*(){var d,u,f,j;const{props:i,currentConversationId:o,formattedMessages:r,popup:c,setSubmittedMessages:a}=s;if(!(!i.remoteRepo||!o))try{const $=[...r].reverse().find(M=>M.type==="choice"&&M.sender==="bot");if(!$)return;const U=Array.isArray($.contents)&&$.contents.length>0?$.contents[$.contents.length-1].metadata||{}:{};a(M=>new Set([...M,n]));let W={};e==="ordered"?W={type:"RANKING",content:"",ranking:{items:((d=$.rawItems)==null?void 0:d.map(k=>ee(H({},k),{rank:t.indexOf(k.label)+1})))||t.map((k,z)=>({label:k,value:k,rank:z+1})),submitted:!0},metadata:U}:e==="selected"?W={type:"CHOICE",content:"",choice:{items:((u=$.rawItems)==null?void 0:u.map(k=>ee(H({},k),{selected:t.includes(k.label)})))||((f=$.options)==null?void 0:f.map(k=>({label:k,value:k,selected:t.includes(k)})))||[],multiple:$.multiSelect||!1,submitted:!0},metadata:U}:e==="input"&&(W={type:"FORM",content:"",form:{fields:((j=$.fields)==null?void 0:j.map((M,k)=>ee(H({},M),{value:t[k]||""})))||[],submitted:!0},metadata:U});const Z={body:W,conversationId:o,sender:{id:"me"}};yield c.sendMessageAsync(Z)}catch($){console.error("Error sending survey response:",$)}})}function Xi(t,e,n,s){return v(this,null,function*(){var u,f,j,$;const{props:i,currentConversationId:o,formattedMessages:r,popup:c,setEditingMsgIdBot:a,setEditingMsgIdUser:d}=s;if(!(!i.remoteRepo||!o))try{if(!r.find(A=>A.id===n&&A.sender==="user"))return;const W=r.findIndex(A=>A.id===n);let Z;for(let A=W-1;A>=0;A--){const O=r[A];if(O.sender==="bot"&&(O.type==="choice"||O.type==="survey"||O.type==="form")){Z=O;break}}if(!Z)return;const M=Array.isArray(Z.contents)&&Z.contents.length>0?Z.contents[Z.contents.length-1].metadata||{}:{};let k={};e==="input"?k={type:"NORMAL",content:t[0],metadata:M}:e==="ordered"?k={type:"RANKING",content:"",ranking:{items:((u=Z.rawItems)==null?void 0:u.map(O=>ee(H({},O),{rank:t.indexOf(O.label)+1})))||t.map((O,w)=>({label:O,value:O,rank:w+1})),submitted:!0},metadata:M}:e==="selected"?k={type:"CHOICE",content:"",choice:{items:((f=Z.rawItems)==null?void 0:f.map(O=>ee(H({},O),{selected:t.includes(O.label)})))||((j=Z.options)==null?void 0:j.map(O=>({label:O,value:O,selected:t.includes(O)})))||[],multiple:Z.multiSelect||!1,submitted:!0},metadata:M}:e==="input"&&(k={type:"FORM",content:"",form:{fields:(($=Z.fields)==null?void 0:$.map((A,O)=>ee(H({},A),{value:t[O]||""})))||[],submitted:!0},metadata:M});const z={id:n,body:k,conversationId:o,sender:{id:"me"}};yield c.updateMessageAsync(z),a(null),d(null)}catch(U){console.error("Error updating survey response:",U)}})}var Gi=F("<div>"),Ki=F("<button class=chat-popup-button><img>"),Qi=F("<div style=font-size:14px;margin-top:4px>"),Ji=F("<div class=modal-backdrop><div class=modal-content style=background-color:white;border-radius:8px><div style=margin-bottom:12px><label style=margin-bottom:18px;font-weight:500;text-align:left>Tên cuộc trò chuyện mới:</label><input autofocus class=chat-popup-input></div><div style=text-align:right><button class=modal-button-delete style=margin-right:8px;background-color:#f0f0f0>Hủy bỏ</button><button class=modal-button-delete style=background-color:#1AAF74>Tạo"),eo=F("<div class=modal-backdrop><div style=background-color:white;border-radius:8px><div style=font-size:16px;font-weight:500;margin-bottom:12px;text-align:left>Xóa đoạn chat?</div><div style=font-size:14px;margin-bottom:16px;text-align:left>Hành động này sẽ xóa <b></b>?</div><div style=text-align:right><button class=modal-button-delete style=margin-right:8px>Hủy bỏ</button><button class=modal-button-delete style=background-color:#e74c3c>Xóa"),to=F("<div class=modal-backdrop><div class=modal-content style=background-color:white;border-radius:8px><div style=font-size:16px;font-weight:500;margin-bottom:12px>Bạn chưa làm khảo sát. Vui lòng thực hiện khảo sát trước khi bắt đầu tư vấn!</div><div style=text-align:right><button class=modal-button-delete style=background-color:#1AAF74>Đã hiểu"),no=F("<div><div style=flex-direction:row><div style=flex-direction:column;min-height:0>"),so=F("<div class=chat-popup-header><img><div class=chat-popup-title><img style=margin-right:4px><span style=user-select:none>Ez</span><span style=margin-left:4px;user-select:none>Advise</span></div><div style=align-items:center;margin-top:4px><button><img>"),zn=F("<button><img>"),io=F("<div><div>"),oo=F("<div style=text-align:center;font-size:32px;font-weight:600;margin-bottom:32px;user-select:none>Hôm nay thị trường khiến bạn quan tâm điều gì?"),ro=F("<div class=chat-popup-action-buttons>");function ao(t){var st;const e=Vi(),[n,s]=L(""),[i,o]=L(!1),[r,c]=L(!1),[a,d]=L(!1),[u,f]=L(!1),[j,$]=L(0),[U]=L({}),[W,Z]=L(new Set),[M,k]=L(null),[z,A]=L(!1),[O,w]=L(!0),[Ae,oe]=L(""),[de,B]=L(1),[x,C]=L(6),[p,m]=L(null),[I,R]=L(null),[b,D]=L(!1),[Y,he]=L(""),[fe,ce]=L(void 0);let ne=null;const[G,E]=L(null),[K,ye]=L(!1),J=((st=t.options)==null?void 0:st.onlyMobile)||!1,be=()=>v(null,null,function*(){yield jn(t,e,k,oe,w,Z,A,ne,()=>ye(!0)),yield Zi(t,Y(),ce,D,e,k,oe,w,Z,A,ne)});Qe(()=>v(null,null,function*(){if(t.remoteRepo)try{const h=yield t.remoteRepo.listConversationAsync(10);console.log("listConversationAsync result:",h),(!h||h.length===0)&&console.warn("listConversationAsync returned empty or null")}catch(h){console.error("Error calling listConversationAsync:",h)}})),Qe(()=>{const h=e.getCurrentMessages();h&&h.length>0&&Wi(Nn(h),B,C)});const Oe=()=>{const h=M();return!!h&&h.endsWith("~SURVEY")},nt=()=>v(null,null,function*(){he(""),ce(void 0),D(!0)});return Mt(()=>{const h=()=>{const y=window.innerWidth<768;f(y),a()&&y&&(d(!1),f(!0))};return window.addEventListener("resize",h),h(),()=>{window.removeEventListener("resize",h)}}),Qe(()=>{var h,_;(h=t.options)!=null&&h.onFullScreen&&t.options.onFullScreen(a()),(_=t.options)!=null&&_.onMobile&&t.options.onMobile(u())}),(()=>{var h=Gi();return P(h,(()=>{var _=te(()=>!i());return()=>_()&&(()=>{var y=Ki(),S=y.firstChild;return y.$$click=()=>{var T;J&&f(!0),o(!0),(T=t.options)!=null&&T.onOpen&&t.options.onOpen()},l(y,"background","none"),l(y,"border","none"),l(y,"cursor","pointer"),l(y,"padding","0"),se(S,"src",hn),y})()})(),null),P(h,(()=>{var _=te(()=>!!i());return()=>_()&&(()=>{const y=Je(()=>Nn(e.getCurrentMessages())),S=()=>qi(y(),M()),T=(re,Ie,X)=>Yi(re,Ie,X,{props:t,currentConversationId:M(),formattedMessages:y(),popup:e,setSubmittedMessages:Z}),ge=(re,Ie,X)=>Xi(re,Ie,X,{props:t,currentConversationId:M(),formattedMessages:y(),popup:e,setEditingMsgIdBot:m,setEditingMsgIdUser:R}),xe=()=>v(null,null,function*(){var re,Ie;if(!(!n().trim()||!t.remoteRepo)){if(yield Un(t.remoteRepo)){alert("Bạn chưa hoàn thành khảo sát hiện tại!");return}if(!M()){yield jn(t,e,k,oe,w,Z,A,ne,()=>ye(!0));try{const X=Pt(),Q="BOT~rasaconnector",N=`Cuộc hội thoại mới ${X.slice(-4)}`,V=yield e.createConversationAsync({id:X,name:N,type:"BOT",members:[{userId:Q,role:"MEMBER"}],updatedAt:new Date});e.setCurrentConversation({id:V.id,name:V.name,type:"BOT"}),k(V.id),oe(V.name),w(!0),Z(new Set),A(!1),yield e.listMessagesAsync(V.id),ne&&ne()}catch(X){console.error("Tạo hội thoại mới thất bại:",X);return}}try{let X={};const Q=y().filter(V=>V.sender==="bot"&&Array.isArray(V.contents)&&V.contents.length>0&&V.contents[V.contents.length-1].metadata);if(Q.length>0){const V=Q[Q.length-1];X=((Ie=(re=V.contents)==null?void 0:re[V.contents.length-1])==null?void 0:Ie.metadata)||{}}const N={body:{type:"NORMAL",content:n(),metadata:X},conversationId:M(),sender:{id:"me"}};yield e.sendMessageAsync(N),s("")}catch(X){console.error("Error sending message:",X)}}}),Le=()=>v(null,null,function*(){var re,Ie;if(!(!e||y().length===0||!M()||!O()))try{const X=y()[0].id,Q=30,N=y().findIndex(ze=>ze.id===X);if(N>=0&&N-Q>=0)return;const V=document.querySelector(".chat-messages-container"),ae=V==null?void 0:V.querySelector(`[data-message-id="${X}"]`),le=(re=ae==null?void 0:ae.offsetTop)!=null?re:0,Xe=(Ie=V==null?void 0:V.scrollTop)!=null?Ie:0;yield e.listMessagesAsync("BEFORE",X,Q),requestAnimationFrame(()=>{var _e;const ze=V==null?void 0:V.querySelector(`[data-message-id="${X}"]`),Ve=(_e=ze==null?void 0:ze.offsetTop)!=null?_e:0;V&&(V.scrollTop=Ve-(le-Xe))})}catch(X){console.error("Error loading more messages:",X)}});return Qe(()=>{y(),i()&&requestAnimationFrame(()=>{const re=document.querySelector(".chat-messages-container");re&&(re.scrollTop=re.scrollHeight)})}),(()=>{var re=no(),Ie=re.firstChild,X=Ie.firstChild;return P(re,ie(Ye,{get when(){return b()},get children(){var Q=Ji(),N=Q.firstChild,V=N.firstChild,ae=V.firstChild,le=ae.nextSibling,Xe=V.nextSibling,ze=Xe.firstChild,Ve=ze.nextSibling;return Q.$$click=()=>D(!1),N.$$click=_e=>_e.stopPropagation(),l(N,"padding","20px"),l(N,"width","400px"),l(ae,"display","block"),l(ae,"color","#1A1D1F"),le.$$keydown=_e=>{_e.key==="Enter"&&be()},le.$$input=_e=>he(_e.currentTarget.value),P(V,ie(Ye,{get when(){return fe()},get children(){var _e=Qi();return l(_e,"color","red"),P(_e,fe),_e}}),null),ze.$$click=()=>D(!1),Ve.$$click=be,l(Ve,"color","#fff"),ue(()=>le.value=Y()),Q}}),Ie),P(re,(()=>{var Q=te(()=>!a());return()=>Q()&&(()=>{var N=so(),V=N.firstChild,ae=V.nextSibling,le=ae.firstChild,Xe=le.nextSibling,ze=Xe.nextSibling,Ve=ae.nextSibling,_e=Ve.firstChild,We=_e.firstChild;return V.$$click=()=>c(!0),se(V,"src",Ss),l(V,"width","28px"),l(V,"height","28px"),l(V,"cursor","pointer"),se(le,"src",hn),l(le,"width","32px"),l(le,"height","32px"),l(Xe,"color","#1A1D1F"),l(ze,"color","#1AAF74"),l(Ve,"display","flex"),l(Ve,"gap","12px"),P(Ve,(()=>{var lt=te(()=>!u());return()=>lt()&&[(()=>{var He=zn(),dt=He.firstChild;return He.$$click=()=>{var Lt;a()?(d(!1),f(!0)):u()?f(!1):f(!0),(Lt=t.options)!=null&&Lt.onMinimize&&t.options.onMinimize()},l(He,"background","none"),l(He,"border","none"),l(He,"cursor","pointer"),l(He,"padding","0"),se(dt,"src",Is),l(dt,"width","20px"),l(dt,"height","20px"),He})(),(()=>{var He=zn(),dt=He.firstChild;return He.$$click=()=>{var Lt;f(!1),d(!0),(Lt=t.options)!=null&&Lt.onMaximize&&t.options.onMaximize()},l(He,"background","none"),l(He,"border","none"),l(He,"cursor","pointer"),l(He,"padding","0"),se(dt,"src",As),l(dt,"width","20px"),l(dt,"height","20px"),He})()]})(),_e),_e.$$click=()=>{var lt;o(!1),f(!1),d(!1),(lt=t.options)!=null&&lt.onClose&&t.options.onClose()},l(_e,"background","none"),l(_e,"border","none"),l(_e,"cursor","pointer"),l(_e,"padding","0"),se(We,"src",kn),l(We,"width","20px"),l(We,"height","20px"),N})()})(),Ie),l(Ie,"display","flex"),l(Ie,"height","100%"),P(Ie,(()=>{var Q=te(()=>!!a());return()=>Q()?ie(Pn,{onClose:()=>{var N;o(!1),f(!1),d(!1),(N=t.options)!=null&&N.onClose&&t.options.onClose()},onShrink:()=>{var N;d(!1),(N=t.options)!=null&&N.onShrink&&t.options.onShrink()},open:!0,fullScreen:!0,get isMobile(){return u()},onMobile:()=>{d(!1),f(!0)},onNewConversation:nt,get options(){return t.options},get remoteRepo(){var N;return(N=t.remoteRepo)!=null?N:void 0},onDeleteConversation:E,onReloadConversations:N=>ne=N,onLoadMessages:(N,V)=>v(null,null,function*(){if(e.setCurrentConversation({id:N,name:"",type:"BOT"}),k(N),oe(V||""),w(!0),t.remoteRepo)try{yield e.listMessagesAsync(N),Z(new Set),A(!1),requestAnimationFrame(()=>{requestAnimationFrame(()=>{const ae=document.querySelector(".chat-messages-container");ae&&(ae.scrollTop=ae.scrollHeight),A(!1)})})}catch(ae){console.error("Error loading messages:",ae),A(!1)}})}):ie(Pn,{onClose:()=>c(!1),get open(){return r()},fullScreen:!1,get isMobile(){return u()},onNewConversation:nt,get options(){return t.options},get remoteRepo(){var N;return(N=t.remoteRepo)!=null?N:void 0},onDeleteConversation:E,onReloadConversations:N=>ne=N,onLoadMessages:(N,V)=>v(null,null,function*(){if(e.setCurrentConversation({id:N,name:"",type:"BOT"}),k(N),oe(V||""),w(!0),t.remoteRepo)try{yield e.listMessagesAsync(N);const ae=e.getCurrentMessages();console.log("message data: ",ae),Z(new Set),A(!1),requestAnimationFrame(()=>{requestAnimationFrame(()=>{const le=document.querySelector(".chat-messages-container");le&&(le.scrollTop=le.scrollHeight),A(!1)})})}catch(ae){console.error("Error loading messages:",ae),A(!1)}})})})(),X),l(X,"flex","1"),l(X,"display","flex"),l(X,"position","relative"),l(X,"height","100%"),P(X,(()=>{var Q=te(()=>!!a());return()=>Q()&&ie(Hi,{get currentStep(){return de()},get totalSteps(){return x()},get title(){return Ae()},get isSurveyConversation(){return Oe()}})})(),null),P(X,ie(wi,{get messages(){return y()},get isFullScreen(){return a()},get inputHeight(){return te(()=>!!a())()?j():void 0},get isMobile(){return u()},onSubmit:T,onUpdateSurvey:ge,get surveyOptions(){return U()},get submittedMessages(){return W()},onLoadMoreMessages:Le,get conversationId(){return M()},get isLoadingMessages(){return z()},get editingMsgIdBot(){return p()},setEditingMsgIdBot:m,get editingMsgIdUser(){return I()},setEditingMsgIdUser:R}),null),P(X,(()=>{var Q=te(()=>!!a());return()=>Q()?(()=>{var N=io(),V=N.firstChild;return P(N,(()=>{var ae=te(()=>y().length===0);return()=>ae()&&(()=>{var le=oo();return l(le,"width","100%"),l(le,"color","#1A1D1F"),le})()})(),V),l(V,"width","100%"),P(V,ie(Rn,{get input(){return n()},setInput:s,sendMessage:xe,onHeightChange:$,get disabled(){return!S()}})),P(N,(()=>{var ae=te(()=>y().length===0);return()=>ae()&&(()=>{var le=ro();return P(le,ie(qt,{text:"Khảo sát đầu tư"}),null),P(le,ie(qt,{text:"Mục tiêu tài chính"}),null),P(le,ie(qt,{text:"Khả năng chấp nhận rủi ro"}),null),P(le,ie(qt,{text:"Khả năng chấp nhận rủi ro"}),null),le})()})(),null),ue(()=>it(N,`chat-input-floating-box${y().length>0?" chat-input-floating-box--with-messages":""}`)),N})():ie(Rn,{get input(){return n()},setInput:s,sendMessage:xe,onHeightChange:$,get disabled(){return!S()}})})(),null),P(re,ie(Ye,{get when(){return!!G()},get children(){var Q=eo(),N=Q.firstChild,V=N.firstChild,ae=V.nextSibling,le=ae.firstChild,Xe=le.nextSibling,ze=ae.nextSibling,Ve=ze.firstChild,_e=Ve.nextSibling;return Q.$$click=()=>E(null),N.$$click=We=>We.stopPropagation(),l(N,"padding","20px"),l(N,"width","350px"),l(V,"color","#1A1D1F"),l(ae,"color","#1A1D1F"),P(Xe,()=>{var We;return(We=G())==null?void 0:We.name}),Ve.$$click=We=>{We.stopPropagation(),E(null)},_e.$$click=We=>v(null,null,function*(){var lt;We.stopPropagation();try{yield(lt=t.remoteRepo)==null?void 0:lt.deleteConversationAsync(G().id),E(null),ne&&ne()}catch(He){alert("Xóa hội thoại thất bại!")}}),l(_e,"color","#fff"),Q}}),null),P(re,ie(Ye,{get when(){return K()},get children(){var Q=to(),N=Q.firstChild,V=N.firstChild,ae=V.nextSibling,le=ae.firstChild;return Q.$$click=()=>ye(!1),N.$$click=Xe=>Xe.stopPropagation(),l(N,"padding","20px"),l(N,"width","350px"),le.$$click=()=>ye(!1),l(le,"color","#fff"),Q}}),null),ue(Q=>{var N=`chat-popup-window${i()?" chat-popup-window--open":""}${a()?" chat-popup-window--fullscreen":""}${u()?" chat-popup-window--mobile":""}`,V=a()||u()?{"--chat-input-height":`${j()}px`}:void 0;return N!==Q.e&&it(re,Q.e=N),Q.t=dn(re,V,Q.t),Q},{e:void 0,t:void 0}),re})()})()})(),null),h})()}pt(["click","input","keydown"]);function co(t){return ie(ao,{get remoteRepo(){return t.remoteRepo},get options(){return t.options}})}class rt extends Error{constructor(e,n){const s=new.target.prototype;super(`${e}: Status code '${n}'`),this.statusCode=n,this.__proto__=s}}class fn extends Error{constructor(e="A timeout occurred."){const n=new.target.prototype;super(e),this.__proto__=n}}class qe extends Error{constructor(e="An abort occurred."){const n=new.target.prototype;super(e),this.__proto__=n}}class lo extends Error{constructor(e,n){const s=new.target.prototype;super(e),this.transport=n,this.errorType="UnsupportedTransportError",this.__proto__=s}}class uo extends Error{constructor(e,n){const s=new.target.prototype;super(e),this.transport=n,this.errorType="DisabledTransportError",this.__proto__=s}}class ho extends Error{constructor(e,n){const s=new.target.prototype;super(e),this.transport=n,this.errorType="FailedToStartTransportError",this.__proto__=s}}class Vn extends Error{constructor(e){const n=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=n}}class fo extends Error{constructor(e,n){const s=new.target.prototype;super(e),this.innerErrors=n,this.__proto__=s}}class Wn{constructor(e,n,s){this.statusCode=e,this.statusText=n,this.content=s}}class Gt{get(e,n){return this.send(ee(H({},n),{method:"GET",url:e}))}post(e,n){return this.send(ee(H({},n),{method:"POST",url:e}))}delete(e,n){return this.send(ee(H({},n),{method:"DELETE",url:e}))}getCookieString(e){return""}}var g;(function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Information=2]="Information",t[t.Warning=3]="Warning",t[t.Error=4]="Error",t[t.Critical=5]="Critical",t[t.None=6]="None"})(g||(g={}));class $t{constructor(){}log(e,n){}}$t.instance=new $t;const go="8.0.17";class Ee{static isRequired(e,n){if(e==null)throw new Error(`The '${n}' argument is required.`)}static isNotEmpty(e,n){if(!e||e.match(/^\s*$/))throw new Error(`The '${n}' argument should not be empty.`)}static isIn(e,n,s){if(!(e in n))throw new Error(`Unknown ${s} value: ${e}.`)}}class ve{static get isBrowser(){return!ve.isNode&&typeof window=="object"&&typeof window.document=="object"}static get isWebWorker(){return!ve.isNode&&typeof self=="object"&&"importScripts"in self}static get isReactNative(){return!ve.isNode&&typeof window=="object"&&typeof window.document=="undefined"}static get isNode(){return typeof process!="undefined"&&process.release&&process.release.name==="node"}}function Dt(t,e){let n="";return at(t)?(n=`Binary data of length ${t.byteLength}`,e&&(n+=`. Content: '${po(t)}'`)):typeof t=="string"&&(n=`String data of length ${t.length}`,e&&(n+=`. Content: '${t}'`)),n}function po(t){const e=new Uint8Array(t);let n="";return e.forEach(s=>{const i=s<16?"0":"";n+=`0x${i}${s.toString(16)} `}),n.substr(0,n.length-1)}function at(t){return t&&typeof ArrayBuffer!="undefined"&&(t instanceof ArrayBuffer||t.constructor&&t.constructor.name==="ArrayBuffer")}function qn(t,e,n,s,i,o){return v(this,null,function*(){const r={},[c,a]=bt();r[c]=a,t.log(g.Trace,`(${e} transport) sending data. ${Dt(i,o.logMessageContent)}.`);const d=at(i)?"arraybuffer":"text",u=yield n.post(s,{content:i,headers:H(H({},r),o.headers),responseType:d,timeout:o.timeout,withCredentials:o.withCredentials});t.log(g.Trace,`(${e} transport) request complete. Response status: ${u.statusCode}.`)})}function Co(t){return t===void 0?new Kt(g.Information):t===null?$t.instance:t.log!==void 0?t:new Kt(t)}class mo{constructor(e,n){this._subject=e,this._observer=n}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),this._subject.observers.length===0&&this._subject.cancelCallback&&this._subject.cancelCallback().catch(n=>{})}}class Kt{constructor(e){this._minLevel=e,this.out=console}log(e,n){if(e>=this._minLevel){const s=`[${new Date().toISOString()}] ${g[e]}: ${n}`;switch(e){case g.Critical:case g.Error:this.out.error(s);break;case g.Warning:this.out.warn(s);break;case g.Information:this.out.info(s);break;default:this.out.log(s);break}}}}function bt(){let t="X-SignalR-User-Agent";return ve.isNode&&(t="User-Agent"),[t,wo(go,vo(),bo(),yo())]}function wo(t,e,n,s){let i="Microsoft SignalR/";const o=t.split(".");return i+=`${o[0]}.${o[1]}`,i+=` (${t}; `,e&&e!==""?i+=`${e}; `:i+="Unknown OS; ",i+=`${n}`,s?i+=`; ${s}`:i+="; Unknown Runtime Version",i+=")",i}function vo(){if(ve.isNode)switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}else return""}function yo(){if(ve.isNode)return process.versions.node}function bo(){return ve.isNode?"NodeJS":"Browser"}function gn(t){return t.stack?t.stack:t.message?t.message:`${t}`}function _o(){if(typeof globalThis!="undefined")return globalThis;if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;throw new Error("could not find global")}class So extends Gt{constructor(e){if(super(),this._logger=e,typeof fetch=="undefined"||ve.isNode){const n=typeof __webpack_require__=="function"?__non_webpack_require__:require;this._jar=new(n("tough-cookie")).CookieJar,typeof fetch=="undefined"?this._fetchType=n("node-fetch"):this._fetchType=fetch,this._fetchType=n("fetch-cookie")(this._fetchType,this._jar)}else this._fetchType=fetch.bind(_o());if(typeof AbortController=="undefined"){const n=typeof __webpack_require__=="function"?__non_webpack_require__:require;this._abortControllerType=n("abort-controller")}else this._abortControllerType=AbortController}send(e){return v(this,null,function*(){if(e.abortSignal&&e.abortSignal.aborted)throw new qe;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const n=new this._abortControllerType;let s;e.abortSignal&&(e.abortSignal.onabort=()=>{n.abort(),s=new qe});let i=null;if(e.timeout){const a=e.timeout;i=setTimeout(()=>{n.abort(),this._logger.log(g.Warning,"Timeout from HTTP request."),s=new fn},a)}e.content===""&&(e.content=void 0),e.content&&(e.headers=e.headers||{},at(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");let o;try{o=yield this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:e.withCredentials===!0?"include":"same-origin",headers:H({"X-Requested-With":"XMLHttpRequest"},e.headers),method:e.method,mode:"cors",redirect:"follow",signal:n.signal})}catch(a){throw s||(this._logger.log(g.Warning,`Error from HTTP request. ${a}.`),a)}finally{i&&clearTimeout(i),e.abortSignal&&(e.abortSignal.onabort=null)}if(!o.ok){const a=yield Zn(o,"text");throw new rt(a||o.statusText,o.status)}const c=yield Zn(o,e.responseType);return new Wn(o.status,o.statusText,c)})}getCookieString(e){let n="";return ve.isNode&&this._jar&&this._jar.getCookies(e,(s,i)=>n=i.join("; ")),n}}function Zn(t,e){let n;switch(e){case"arraybuffer":n=t.arrayBuffer();break;case"text":n=t.text();break;case"blob":case"document":case"json":throw new Error(`${e} is not supported.`);default:n=t.text();break}return n}class Ao extends Gt{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new qe):e.method?e.url?new Promise((n,s)=>{const i=new XMLHttpRequest;i.open(e.method,e.url,!0),i.withCredentials=e.withCredentials===void 0?!0:e.withCredentials,i.setRequestHeader("X-Requested-With","XMLHttpRequest"),e.content===""&&(e.content=void 0),e.content&&(at(e.content)?i.setRequestHeader("Content-Type","application/octet-stream"):i.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const o=e.headers;o&&Object.keys(o).forEach(r=>{i.setRequestHeader(r,o[r])}),e.responseType&&(i.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{i.abort(),s(new qe)}),e.timeout&&(i.timeout=e.timeout),i.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),i.status>=200&&i.status<300?n(new Wn(i.status,i.statusText,i.response||i.responseText)):s(new rt(i.response||i.responseText||i.statusText,i.status))},i.onerror=()=>{this._logger.log(g.Warning,`Error from HTTP request. ${i.status}: ${i.statusText}.`),s(new rt(i.statusText,i.status))},i.ontimeout=()=>{this._logger.log(g.Warning,"Timeout from HTTP request."),s(new fn)},i.send(e.content)}):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class xo extends Gt{constructor(e){if(super(),typeof fetch!="undefined"||ve.isNode)this._httpClient=new So(e);else if(typeof XMLHttpRequest!="undefined")this._httpClient=new Ao(e);else throw new Error("No usable HttpClient found.")}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new qe):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}class Ne{static write(e){return`${e}${Ne.RecordSeparator}`}static parse(e){if(e[e.length-1]!==Ne.RecordSeparator)throw new Error("Message is incomplete.");const n=e.split(Ne.RecordSeparator);return n.pop(),n}}Ne.RecordSeparatorCode=30,Ne.RecordSeparator=String.fromCharCode(Ne.RecordSeparatorCode);class Io{writeHandshakeRequest(e){return Ne.write(JSON.stringify(e))}parseHandshakeResponse(e){let n,s;if(at(e)){const c=new Uint8Array(e),a=c.indexOf(Ne.RecordSeparatorCode);if(a===-1)throw new Error("Message is incomplete.");const d=a+1;n=String.fromCharCode.apply(null,Array.prototype.slice.call(c.slice(0,d))),s=c.byteLength>d?c.slice(d).buffer:null}else{const c=e,a=c.indexOf(Ne.RecordSeparator);if(a===-1)throw new Error("Message is incomplete.");const d=a+1;n=c.substring(0,d),s=c.length>d?c.substring(d):null}const i=Ne.parse(n),o=JSON.parse(i[0]);if(o.type)throw new Error("Expected a handshake response from the server.");return[s,o]}}var q;(function(t){t[t.Invocation=1]="Invocation",t[t.StreamItem=2]="StreamItem",t[t.Completion=3]="Completion",t[t.StreamInvocation=4]="StreamInvocation",t[t.CancelInvocation=5]="CancelInvocation",t[t.Ping=6]="Ping",t[t.Close=7]="Close",t[t.Ack=8]="Ack",t[t.Sequence=9]="Sequence"})(q||(q={}));class Mo{constructor(){this.observers=[]}next(e){for(const n of this.observers)n.next(e)}error(e){for(const n of this.observers)n.error&&n.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new mo(this,e)}}class ko{constructor(e,n,s){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=e,this._connection=n,this._bufferSize=s}_send(e){return v(this,null,function*(){const n=this._protocol.writeMessage(e);let s=Promise.resolve();if(this._isInvocationMessage(e)){this._totalMessageCount++;let i=()=>{},o=()=>{};at(n)?this._bufferedByteCount+=n.byteLength:this._bufferedByteCount+=n.length,this._bufferedByteCount>=this._bufferSize&&(s=new Promise((r,c)=>{i=r,o=c})),this._messages.push(new Eo(n,this._totalMessageCount,i,o))}try{this._reconnectInProgress||(yield this._connection.send(n))}catch(i){this._disconnected()}yield s})}_ack(e){let n=-1;for(let s=0;s<this._messages.length;s++){const i=this._messages[s];if(i._id<=e.sequenceId)n=s,at(i._message)?this._bufferedByteCount-=i._message.byteLength:this._bufferedByteCount-=i._message.length,i._resolver();else if(this._bufferedByteCount<this._bufferSize)i._resolver();else break}n!==-1&&(this._messages=this._messages.slice(n+1))}_shouldProcessMessage(e){if(this._waitForSequenceMessage)return e.type!==q.Sequence?!1:(this._waitForSequenceMessage=!1,!0);if(!this._isInvocationMessage(e))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(e){if(e.sequenceId>this._nextReceivingSequenceId){this._connection.stop(new Error("Sequence ID greater than amount of messages we've received."));return}this._nextReceivingSequenceId=e.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}_resend(){return v(this,null,function*(){const e=this._messages.length!==0?this._messages[0]._id:this._totalMessageCount+1;yield this._connection.send(this._protocol.writeMessage({type:q.Sequence,sequenceId:e}));const n=this._messages;for(const s of n)yield this._connection.send(s._message);this._reconnectInProgress=!1})}_dispose(e){e!=null||(e=new Error("Unable to reconnect to server."));for(const n of this._messages)n._rejector(e)}_isInvocationMessage(e){switch(e.type){case q.Invocation:case q.StreamItem:case q.Completion:case q.StreamInvocation:case q.CancelInvocation:return!0;case q.Close:case q.Sequence:case q.Ping:case q.Ack:return!1}}_ackTimer(){this._ackTimerHandle===void 0&&(this._ackTimerHandle=setTimeout(()=>v(this,null,function*(){try{this._reconnectInProgress||(yield this._connection.send(this._protocol.writeMessage({type:q.Ack,sequenceId:this._latestReceivedSequenceId})))}catch(e){}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0}),1e3))}}class Eo{constructor(e,n,s,i){this._message=e,this._id=n,this._resolver=s,this._rejector=i}}const To=30*1e3,Ro=15*1e3,Po=1e5;var Ce;(function(t){t.Disconnected="Disconnected",t.Connecting="Connecting",t.Connected="Connected",t.Disconnecting="Disconnecting",t.Reconnecting="Reconnecting"})(Ce||(Ce={}));class pn{static create(e,n,s,i,o,r,c){return new pn(e,n,s,i,o,r,c)}constructor(e,n,s,i,o,r,c){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(g.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")},Ee.isRequired(e,"connection"),Ee.isRequired(n,"logger"),Ee.isRequired(s,"protocol"),this.serverTimeoutInMilliseconds=o!=null?o:To,this.keepAliveIntervalInMilliseconds=r!=null?r:Ro,this._statefulReconnectBufferSize=c!=null?c:Po,this._logger=n,this._protocol=s,this.connection=e,this._reconnectPolicy=i,this._handshakeProtocol=new Io,this.connection.onreceive=a=>this._processIncomingData(a),this.connection.onclose=a=>this._connectionClosed(a),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=Ce.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:q.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==Ce.Disconnected&&this._connectionState!==Ce.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}_startWithStateTransitions(){return v(this,null,function*(){if(this._connectionState!==Ce.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=Ce.Connecting,this._logger.log(g.Debug,"Starting HubConnection.");try{yield this._startInternal(),ve.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=Ce.Connected,this._connectionStarted=!0,this._logger.log(g.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=Ce.Disconnected,this._logger.log(g.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}})}_startInternal(){return v(this,null,function*(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise((n,s)=>{this._handshakeResolver=n,this._handshakeRejecter=s});yield this.connection.start(this._protocol.transferFormat);try{let n=this._protocol.version;this.connection.features.reconnect||(n=1);const s={protocol:this._protocol.name,version:n};if(this._logger.log(g.Debug,"Sending handshake request."),yield this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(s)),this._logger.log(g.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),yield e,this._stopDuringStartError)throw this._stopDuringStartError;(this.connection.features.reconnect||!1)&&(this._messageBuffer=new ko(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||(yield this._sendMessage(this._cachedPingMessage))}catch(n){throw this._logger.log(g.Debug,`Hub handshake failed with error '${n}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),yield this.connection.stop(n),n}})}stop(){return v(this,null,function*(){const e=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),yield this._stopPromise;try{yield e}catch(n){}})}_stopInternal(e){if(this._connectionState===Ce.Disconnected)return this._logger.log(g.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===Ce.Disconnecting)return this._logger.log(g.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const n=this._connectionState;return this._connectionState=Ce.Disconnecting,this._logger.log(g.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(g.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(n===Ce.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new qe("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}_sendCloseMessage(){return v(this,null,function*(){try{yield this._sendWithProtocol(this._createCloseMessage())}catch(e){}})}stream(e,...n){const[s,i]=this._replaceStreamingParams(n),o=this._createStreamInvocation(e,n,i);let r;const c=new Mo;return c.cancelCallback=()=>{const a=this._createCancelInvocation(o.invocationId);return delete this._callbacks[o.invocationId],r.then(()=>this._sendWithProtocol(a))},this._callbacks[o.invocationId]=(a,d)=>{if(d){c.error(d);return}else a&&(a.type===q.Completion?a.error?c.error(new Error(a.error)):c.complete():c.next(a.item))},r=this._sendWithProtocol(o).catch(a=>{c.error(a),delete this._callbacks[o.invocationId]}),this._launchStreams(s,r),c}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._messageBuffer?this._messageBuffer._send(e):this._sendMessage(this._protocol.writeMessage(e))}send(e,...n){const[s,i]=this._replaceStreamingParams(n),o=this._sendWithProtocol(this._createInvocation(e,n,!0,i));return this._launchStreams(s,o),o}invoke(e,...n){const[s,i]=this._replaceStreamingParams(n),o=this._createInvocation(e,n,!1,i);return new Promise((c,a)=>{this._callbacks[o.invocationId]=(u,f)=>{if(f){a(f);return}else u&&(u.type===q.Completion?u.error?a(new Error(u.error)):c(u.result):a(new Error(`Unexpected message type: ${u.type}`)))};const d=this._sendWithProtocol(o).catch(u=>{a(u),delete this._callbacks[o.invocationId]});this._launchStreams(s,d)})}on(e,n){!e||!n||(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),this._methods[e].indexOf(n)===-1&&this._methods[e].push(n))}off(e,n){if(!e)return;e=e.toLowerCase();const s=this._methods[e];if(s)if(n){const i=s.indexOf(n);i!==-1&&(s.splice(i,1),s.length===0&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const n=this._protocol.parseMessages(e,this._logger);for(const s of n)if(!(this._messageBuffer&&!this._messageBuffer._shouldProcessMessage(s)))switch(s.type){case q.Invocation:this._invokeClientMethod(s).catch(i=>{this._logger.log(g.Error,`Invoke client method threw error: ${gn(i)}`)});break;case q.StreamItem:case q.Completion:{const i=this._callbacks[s.invocationId];if(i){s.type===q.Completion&&delete this._callbacks[s.invocationId];try{i(s)}catch(o){this._logger.log(g.Error,`Stream callback threw error: ${gn(o)}`)}}break}case q.Ping:break;case q.Close:{this._logger.log(g.Information,"Close message received from server.");const i=s.error?new Error("Server returned an error on close: "+s.error):void 0;s.allowReconnect===!0?this.connection.stop(i):this._stopPromise=this._stopInternal(i);break}case q.Ack:this._messageBuffer&&this._messageBuffer._ack(s);break;case q.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(s);break;default:this._logger.log(g.Warning,`Invalid message type: ${s.type}.`);break}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let n,s;try{[s,n]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(i){const o="Error parsing handshake response: "+i;this._logger.log(g.Error,o);const r=new Error(o);throw this._handshakeRejecter(r),r}if(n.error){const i="Server returned handshake error: "+n.error;this._logger.log(g.Error,i);const o=new Error(i);throw this._handshakeRejecter(o),o}else this._logger.log(g.Debug,"Server handshake complete.");return this._handshakeResolver(),s}_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),this._pingServerHandle===void 0)){let e=this._nextKeepAlive-new Date().getTime();e<0&&(e=0),this._pingServerHandle=setTimeout(()=>v(this,null,function*(){if(this._connectionState===Ce.Connected)try{yield this._sendMessage(this._cachedPingMessage)}catch(n){this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}_invokeClientMethod(e){return v(this,null,function*(){const n=e.target.toLowerCase(),s=this._methods[n];if(!s){this._logger.log(g.Warning,`No client method with the name '${n}' found.`),e.invocationId&&(this._logger.log(g.Warning,`No result given for '${n}' method and invocation ID '${e.invocationId}'.`),yield this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)));return}const i=s.slice(),o=!!e.invocationId;let r,c,a;for(const d of i)try{const u=r;r=yield d.apply(this,e.arguments),o&&r&&u&&(this._logger.log(g.Error,`Multiple results provided for '${n}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),c=void 0}catch(u){c=u,this._logger.log(g.Error,`A callback for the method '${n}' threw error '${u}'.`)}a?yield this._sendWithProtocol(a):o?(c?a=this._createCompletionMessage(e.invocationId,`${c}`,null):r!==void 0?a=this._createCompletionMessage(e.invocationId,null,r):(this._logger.log(g.Warning,`No result given for '${n}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),yield this._sendWithProtocol(a)):r&&this._logger.log(g.Error,`Result given for '${n}' method but server is not expecting a result.`)})}_connectionClosed(e){this._logger.log(g.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new qe("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===Ce.Disconnecting?this._completeClose(e):this._connectionState===Ce.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===Ce.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=Ce.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(e!=null?e:new Error("Connection closed.")),this._messageBuffer=void 0),ve.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach(n=>n.apply(this,[e]))}catch(n){this._logger.log(g.Error,`An onclose callback called with error '${e}' threw error '${n}'.`)}}}_reconnect(e){return v(this,null,function*(){const n=Date.now();let s=0,i=e!==void 0?e:new Error("Attempting to reconnect due to a unknown error."),o=this._getNextRetryDelay(s++,0,i);if(o===null){this._logger.log(g.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),this._completeClose(e);return}if(this._connectionState=Ce.Reconnecting,e?this._logger.log(g.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(g.Information,"Connection reconnecting."),this._reconnectingCallbacks.length!==0){try{this._reconnectingCallbacks.forEach(r=>r.apply(this,[e]))}catch(r){this._logger.log(g.Error,`An onreconnecting callback called with error '${e}' threw error '${r}'.`)}if(this._connectionState!==Ce.Reconnecting){this._logger.log(g.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");return}}for(;o!==null;){if(this._logger.log(g.Information,`Reconnect attempt number ${s} will start in ${o} ms.`),yield new Promise(r=>{this._reconnectDelayHandle=setTimeout(r,o)}),this._reconnectDelayHandle=void 0,this._connectionState!==Ce.Reconnecting){this._logger.log(g.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");return}try{if(yield this._startInternal(),this._connectionState=Ce.Connected,this._logger.log(g.Information,"HubConnection reconnected successfully."),this._reconnectedCallbacks.length!==0)try{this._reconnectedCallbacks.forEach(r=>r.apply(this,[this.connection.connectionId]))}catch(r){this._logger.log(g.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${r}'.`)}return}catch(r){if(this._logger.log(g.Information,`Reconnect attempt failed because of error '${r}'.`),this._connectionState!==Ce.Reconnecting){this._logger.log(g.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),this._connectionState===Ce.Disconnecting&&this._completeClose();return}i=r instanceof Error?r:new Error(r.toString()),o=this._getNextRetryDelay(s++,Date.now()-n,i)}}this._logger.log(g.Information,`Reconnect retries have been exhausted after ${Date.now()-n} ms and ${s} failed attempts. Connection disconnecting.`),this._completeClose()})}_getNextRetryDelay(e,n,s){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:n,previousRetryCount:e,retryReason:s})}catch(i){return this._logger.log(g.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${n}) threw error '${i}'.`),null}}_cancelCallbacksWithError(e){const n=this._callbacks;this._callbacks={},Object.keys(n).forEach(s=>{const i=n[s];try{i(null,e)}catch(o){this._logger.log(g.Error,`Stream 'error' callback called with '${e}' threw error: ${gn(o)}`)}})}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,n,s,i){if(s)return i.length!==0?{arguments:n,streamIds:i,target:e,type:q.Invocation}:{arguments:n,target:e,type:q.Invocation};{const o=this._invocationId;return this._invocationId++,i.length!==0?{arguments:n,invocationId:o.toString(),streamIds:i,target:e,type:q.Invocation}:{arguments:n,invocationId:o.toString(),target:e,type:q.Invocation}}}_launchStreams(e,n){if(e.length!==0){n||(n=Promise.resolve());for(const s in e)e[s].subscribe({complete:()=>{n=n.then(()=>this._sendWithProtocol(this._createCompletionMessage(s)))},error:i=>{let o;i instanceof Error?o=i.message:i&&i.toString?o=i.toString():o="Unknown error",n=n.then(()=>this._sendWithProtocol(this._createCompletionMessage(s,o)))},next:i=>{n=n.then(()=>this._sendWithProtocol(this._createStreamItemMessage(s,i)))}})}}_replaceStreamingParams(e){const n=[],s=[];for(let i=0;i<e.length;i++){const o=e[i];if(this._isObservable(o)){const r=this._invocationId;this._invocationId++,n[r]=o,s.push(r.toString()),e.splice(i,1)}}return[n,s]}_isObservable(e){return e&&e.subscribe&&typeof e.subscribe=="function"}_createStreamInvocation(e,n,s){const i=this._invocationId;return this._invocationId++,s.length!==0?{arguments:n,invocationId:i.toString(),streamIds:s,target:e,type:q.StreamInvocation}:{arguments:n,invocationId:i.toString(),target:e,type:q.StreamInvocation}}_createCancelInvocation(e){return{invocationId:e,type:q.CancelInvocation}}_createStreamItemMessage(e,n){return{invocationId:e,item:n,type:q.StreamItem}}_createCompletionMessage(e,n,s){return n?{error:n,invocationId:e,type:q.Completion}:{invocationId:e,result:s,type:q.Completion}}_createCloseMessage(){return{type:q.Close}}}const $o=[0,2e3,1e4,3e4,null];class Yn{constructor(e){this._retryDelays=e!==void 0?[...e,null]:$o}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class ct{}ct.Authorization="Authorization",ct.Cookie="Cookie";class Do extends Gt{constructor(e,n){super(),this._innerClient=e,this._accessTokenFactory=n}send(e){return v(this,null,function*(){let n=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(n=!1,this._accessToken=yield this._accessTokenFactory()),this._setAuthorizationHeader(e);const s=yield this._innerClient.send(e);return n&&s.statusCode===401&&this._accessTokenFactory?(this._accessToken=yield this._accessTokenFactory(),this._setAuthorizationHeader(e),yield this._innerClient.send(e)):s})}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[ct.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[ct.Authorization]&&delete e.headers[ct.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}var Re;(function(t){t[t.None=0]="None",t[t.WebSockets=1]="WebSockets",t[t.ServerSentEvents=2]="ServerSentEvents",t[t.LongPolling=4]="LongPolling"})(Re||(Re={}));var De;(function(t){t[t.Text=1]="Text",t[t.Binary=2]="Binary"})(De||(De={}));let Bo=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 Xn{get pollAborted(){return this._pollAbort.aborted}constructor(e,n,s){this._httpClient=e,this._logger=n,this._pollAbort=new Bo,this._options=s,this._running=!1,this.onreceive=null,this.onclose=null}connect(e,n){return v(this,null,function*(){if(Ee.isRequired(e,"url"),Ee.isRequired(n,"transferFormat"),Ee.isIn(n,De,"transferFormat"),this._url=e,this._logger.log(g.Trace,"(LongPolling transport) Connecting."),n===De.Binary&&typeof XMLHttpRequest!="undefined"&&typeof new XMLHttpRequest().responseType!="string")throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[s,i]=bt(),o=H({[s]:i},this._options.headers),r={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._options.withCredentials};n===De.Binary&&(r.responseType="arraybuffer");const c=`${e}&_=${Date.now()}`;this._logger.log(g.Trace,`(LongPolling transport) polling: ${c}.`);const a=yield this._httpClient.get(c,r);a.statusCode!==200?(this._logger.log(g.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new rt(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,r)})}_poll(e,n){return v(this,null,function*(){try{for(;this._running;)try{const s=`${e}&_=${Date.now()}`;this._logger.log(g.Trace,`(LongPolling transport) polling: ${s}.`);const i=yield this._httpClient.get(s,n);i.statusCode===204?(this._logger.log(g.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):i.statusCode!==200?(this._logger.log(g.Error,`(LongPolling transport) Unexpected response code: ${i.statusCode}.`),this._closeError=new rt(i.statusText||"",i.statusCode),this._running=!1):i.content?(this._logger.log(g.Trace,`(LongPolling transport) data received. ${Dt(i.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(i.content)):this._logger.log(g.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(s){this._running?s instanceof fn?this._logger.log(g.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=s,this._running=!1):this._logger.log(g.Trace,`(LongPolling transport) Poll errored after shutdown: ${s.message}`)}}finally{this._logger.log(g.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}})}send(e){return v(this,null,function*(){return this._running?qn(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))})}stop(){return v(this,null,function*(){this._logger.log(g.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{yield this._receiving,this._logger.log(g.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[n,s]=bt();e[n]=s;const i={headers:H(H({},e),this._options.headers),timeout:this._options.timeout,withCredentials:this._options.withCredentials};let o;try{yield this._httpClient.delete(this._url,i)}catch(r){o=r}o?o instanceof rt&&(o.statusCode===404?this._logger.log(g.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(g.Trace,`(LongPolling transport) Error sending a DELETE request: ${o}`)):this._logger.log(g.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(g.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}})}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(g.Trace,e),this.onclose(this._closeError)}}}class Ho{constructor(e,n,s,i){this._httpClient=e,this._accessToken=n,this._logger=s,this._options=i,this.onreceive=null,this.onclose=null}connect(e,n){return v(this,null,function*(){return Ee.isRequired(e,"url"),Ee.isRequired(n,"transferFormat"),Ee.isIn(n,De,"transferFormat"),this._logger.log(g.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise((s,i)=>{let o=!1;if(n!==De.Text){i(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));return}let r;if(ve.isBrowser||ve.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const c=this._httpClient.getCookieString(e),a={};a.Cookie=c;const[d,u]=bt();a[d]=u,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:H(H({},a),this._options.headers)})}try{r.onmessage=c=>{if(this.onreceive)try{this._logger.log(g.Trace,`(SSE transport) data received. ${Dt(c.data,this._options.logMessageContent)}.`),this.onreceive(c.data)}catch(a){this._close(a);return}},r.onerror=c=>{o?this._close():i(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."))},r.onopen=()=>{this._logger.log(g.Information,`SSE connected to ${this._url}`),this._eventSource=r,o=!0,s()}}catch(c){i(c);return}})})}send(e){return v(this,null,function*(){return this._eventSource?qn(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))})}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class Lo{constructor(e,n,s,i,o,r){this._logger=s,this._accessTokenFactory=n,this._logMessageContent=i,this._webSocketConstructor=o,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=r}connect(e,n){return v(this,null,function*(){Ee.isRequired(e,"url"),Ee.isRequired(n,"transferFormat"),Ee.isIn(n,De,"transferFormat"),this._logger.log(g.Trace,"(WebSockets transport) Connecting.");let s;return this._accessTokenFactory&&(s=yield this._accessTokenFactory()),new Promise((i,o)=>{e=e.replace(/^http/,"ws");let r;const c=this._httpClient.getCookieString(e);let a=!1;if(ve.isNode||ve.isReactNative){const d={},[u,f]=bt();d[u]=f,s&&(d[ct.Authorization]=`Bearer ${s}`),c&&(d[ct.Cookie]=c),r=new this._webSocketConstructor(e,void 0,{headers:H(H({},d),this._headers)})}else s&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(s)}`);r||(r=new this._webSocketConstructor(e)),n===De.Binary&&(r.binaryType="arraybuffer"),r.onopen=d=>{this._logger.log(g.Information,`WebSocket connected to ${e}.`),this._webSocket=r,a=!0,i()},r.onerror=d=>{let u=null;typeof ErrorEvent!="undefined"&&d instanceof ErrorEvent?u=d.error:u="There was an error with the transport",this._logger.log(g.Information,`(WebSockets transport) ${u}.`)},r.onmessage=d=>{if(this._logger.log(g.Trace,`(WebSockets transport) data received. ${Dt(d.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(d.data)}catch(u){this._close(u);return}},r.onclose=d=>{if(a)this._close(d);else{let u=null;typeof ErrorEvent!="undefined"&&d instanceof ErrorEvent?u=d.error:u="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.",o(new Error(u))}}})})}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(g.Trace,`(WebSockets transport) sending data. ${Dt(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(g.Trace,"(WebSockets transport) socket closed."),this.onclose&&(this._isCloseEvent(e)&&(e.wasClean===!1||e.code!==1e3)?this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)):e instanceof Error?this.onclose(e):this.onclose())}_isCloseEvent(e){return e&&typeof e.wasClean=="boolean"&&typeof e.code=="number"}}const Gn=100;class Fo{constructor(e,n={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Ee.isRequired(e,"url"),this._logger=Co(n.logger),this.baseUrl=this._resolveUrl(e),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 s=null,i=null;if(ve.isNode&&typeof require!="undefined"){const o=typeof __webpack_require__=="function"?__non_webpack_require__:require;s=o("ws"),i=o("eventsource")}!ve.isNode&&typeof WebSocket!="undefined"&&!n.WebSocket?n.WebSocket=WebSocket:ve.isNode&&!n.WebSocket&&s&&(n.WebSocket=s),!ve.isNode&&typeof EventSource!="undefined"&&!n.EventSource?n.EventSource=EventSource:ve.isNode&&!n.EventSource&&typeof i!="undefined"&&(n.EventSource=i),this._httpClient=new Do(n.httpClient||new xo(this._logger),n.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=n,this.onreceive=null,this.onclose=null}start(e){return v(this,null,function*(){if(e=e||De.Binary,Ee.isIn(e,De,"transferFormat"),this._logger.log(g.Debug,`Starting connection with transfer format '${De[e]}'.`),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(e),yield this._startInternalPromise,this._connectionState==="Disconnecting"){const n="Failed to start the HttpConnection before stop() was called.";return this._logger.log(g.Error,n),yield this._stopPromise,Promise.reject(new qe(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(g.Error,n),Promise.reject(new qe(n))}this._connectionStarted=!0})}send(e){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 Cn(this.transport)),this._sendQueue.send(e))}stop(e){return v(this,null,function*(){if(this._connectionState==="Disconnected")return this._logger.log(g.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve();if(this._connectionState==="Disconnecting")return this._logger.log(g.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;this._connectionState="Disconnecting",this._stopPromise=new Promise(n=>{this._stopPromiseResolver=n}),yield this._stopInternal(e),yield this._stopPromise})}_stopInternal(e){return v(this,null,function*(){this._stopError=e;try{yield this._startInternalPromise}catch(n){}if(this.transport){try{yield this.transport.stop()}catch(n){this._logger.log(g.Error,`HttpConnection.transport.stop() threw error '${n}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(g.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")})}_startInternal(e){return v(this,null,function*(){let n=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation)if(this._options.transport===Re.WebSockets)this.transport=this._constructTransport(Re.WebSockets),yield this._startTransport(n,e);else throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");else{let s=null,i=0;do{if(s=yield this._getNegotiationResponse(n),this._connectionState==="Disconnecting"||this._connectionState==="Disconnected")throw new qe("The connection was stopped during negotiation.");if(s.error)throw new Error(s.error);if(s.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(s.url&&(n=s.url),s.accessToken){const o=s.accessToken;this._accessTokenFactory=()=>o,this._httpClient._accessToken=o,this._httpClient._accessTokenFactory=void 0}i++}while(s.url&&i<Gn);if(i===Gn&&s.url)throw new Error("Negotiate redirection limit exceeded.");yield this._createTransport(n,this._options.transport,s,e)}this.transport instanceof Xn&&(this.features.inherentKeepAlive=!0),this._connectionState==="Connecting"&&(this._logger.log(g.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(s){return this._logger.log(g.Error,"Failed to start the connection: "+s),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(s)}})}_getNegotiationResponse(e){return v(this,null,function*(){const n={},[s,i]=bt();n[s]=i;const o=this._resolveNegotiateUrl(e);this._logger.log(g.Debug,`Sending negotiation request: ${o}.`);try{const r=yield this._httpClient.post(o,{content:"",headers:H(H({},n),this._options.headers),timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(r.statusCode!==200)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${r.statusCode}'`));const c=JSON.parse(r.content);return(!c.negotiateVersion||c.negotiateVersion<1)&&(c.connectionToken=c.connectionId),c.useStatefulReconnect&&this._options._useStatefulReconnect!==!0?Promise.reject(new Vn("Client didn't negotiate Stateful Reconnect but the server did.")):c}catch(r){let c="Failed to complete negotiation with the server: "+r;return r instanceof rt&&r.statusCode===404&&(c=c+" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(g.Error,c),Promise.reject(new Vn(c))}})}_createConnectUrl(e,n){return n?e+(e.indexOf("?")===-1?"?":"&")+`id=${n}`:e}_createTransport(e,n,s,i){return v(this,null,function*(){let o=this._createConnectUrl(e,s.connectionToken);if(this._isITransport(n)){this._logger.log(g.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=n,yield this._startTransport(o,i),this.connectionId=s.connectionId;return}const r=[],c=s.availableTransports||[];let a=s;for(const d of c){const u=this._resolveTransportOrError(d,n,i,(a==null?void 0:a.useStatefulReconnect)===!0);if(u instanceof Error)r.push(`${d.transport} failed:`),r.push(u);else if(this._isITransport(u)){if(this.transport=u,!a){try{a=yield this._getNegotiationResponse(e)}catch(f){return Promise.reject(f)}o=this._createConnectUrl(e,a.connectionToken)}try{yield this._startTransport(o,i),this.connectionId=a.connectionId;return}catch(f){if(this._logger.log(g.Error,`Failed to start the transport '${d.transport}': ${f}`),a=void 0,r.push(new ho(`${d.transport} failed: ${f}`,Re[d.transport])),this._connectionState!=="Connecting"){const j="Failed to select transport before stop() was called.";return this._logger.log(g.Debug,j),Promise.reject(new qe(j))}}}}return r.length>0?Promise.reject(new fo(`Unable to connect to the server with any of the available transports. ${r.join(" ")}`,r)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))})}_constructTransport(e){switch(e){case Re.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Lo(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case Re.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Ho(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case Re.LongPolling:return new Xn(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,n){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=s=>v(this,null,function*(){let i=!1;if(this.features.reconnect)try{this.features.disconnected(),yield this.transport.connect(e,n),yield this.features.resend()}catch(o){i=!0}else{this._stopConnection(s);return}i&&this._stopConnection(s)}):this.transport.onclose=s=>this._stopConnection(s),this.transport.connect(e,n)}_resolveTransportOrError(e,n,s,i){const o=Re[e.transport];if(o==null)return this._logger.log(g.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(Oo(n,o))if(e.transferFormats.map(c=>De[c]).indexOf(s)>=0){if(o===Re.WebSockets&&!this._options.WebSocket||o===Re.ServerSentEvents&&!this._options.EventSource)return this._logger.log(g.Debug,`Skipping transport '${Re[o]}' because it is not supported in your environment.'`),new lo(`'${Re[o]}' is not supported in your environment.`,o);this._logger.log(g.Debug,`Selecting transport '${Re[o]}'.`);try{return this.features.reconnect=o===Re.WebSockets?i:void 0,this._constructTransport(o)}catch(c){return c}}else return this._logger.log(g.Debug,`Skipping transport '${Re[o]}' because it does not support the requested transfer format '${De[s]}'.`),new Error(`'${Re[o]}' does not support ${De[s]}.`);else return this._logger.log(g.Debug,`Skipping transport '${Re[o]}' because it was disabled by the client.`),new uo(`'${Re[o]}' is disabled by the client.`,o)}_isITransport(e){return e&&typeof e=="object"&&"connect"in e}_stopConnection(e){if(this._logger.log(g.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,this._connectionState==="Disconnected"){this._logger.log(g.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`);return}if(this._connectionState==="Connecting")throw this._logger.log(g.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if(this._connectionState==="Disconnecting"&&this._stopPromiseResolver(),e?this._logger.log(g.Error,`Connection disconnected with error '${e}'.`):this._logger.log(g.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch(n=>{this._logger.log(g.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(e)}catch(n){this._logger.log(g.Error,`HttpConnection.onclose(${e}) threw error '${n}'.`)}}}_resolveUrl(e){if(e.lastIndexOf("https://",0)===0||e.lastIndexOf("http://",0)===0)return e;if(!ve.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const n=window.document.createElement("a");return n.href=e,this._logger.log(g.Information,`Normalizing '${e}' to '${n.href}'.`),n.href}_resolveNegotiateUrl(e){const n=new URL(e);n.pathname.endsWith("/")?n.pathname+="negotiate":n.pathname+="/negotiate";const s=new URLSearchParams(n.searchParams);return s.has("negotiateVersion")||s.append("negotiateVersion",this._negotiateVersion.toString()),s.has("useStatefulReconnect")?s.get("useStatefulReconnect")==="true"&&(this._options._useStatefulReconnect=!0):this._options._useStatefulReconnect===!0&&s.append("useStatefulReconnect","true"),n.search=s.toString(),n.toString()}}function Oo(t,e){return!t||(e&t)!==0}class Cn{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Qt,this._transportResult=new Qt,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Qt),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}_sendLoop(){return v(this,null,function*(){for(;;){if(yield this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new Qt;const e=this._transportResult;this._transportResult=void 0;const n=typeof this._buffer[0]=="string"?this._buffer.join(""):Cn._concatBuffers(this._buffer);this._buffer.length=0;try{yield this._transport.send(n),e.resolve()}catch(s){e.reject(s)}}})}static _concatBuffers(e){const n=e.map(o=>o.byteLength).reduce((o,r)=>o+r),s=new Uint8Array(n);let i=0;for(const o of e)s.set(new Uint8Array(o),i),i+=o.byteLength;return s.buffer}}class Qt{constructor(){this.promise=new Promise((e,n)=>[this._resolver,this._rejecter]=[e,n])}resolve(){this._resolver()}reject(e){this._rejecter(e)}}const No="json";class Uo{constructor(){this.name=No,this.version=2,this.transferFormat=De.Text}parseMessages(e,n){if(typeof e!="string")throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!e)return[];n===null&&(n=$t.instance);const s=Ne.parse(e),i=[];for(const o of s){const r=JSON.parse(o);if(typeof r.type!="number")throw new Error("Invalid payload.");switch(r.type){case q.Invocation:this._isInvocationMessage(r);break;case q.StreamItem:this._isStreamItemMessage(r);break;case q.Completion:this._isCompletionMessage(r);break;case q.Ping:break;case q.Close:break;case q.Ack:this._isAckMessage(r);break;case q.Sequence:this._isSequenceMessage(r);break;default:n.log(g.Information,"Unknown message type '"+r.type+"' ignored.");continue}i.push(r)}return i}writeMessage(e){return Ne.write(JSON.stringify(e))}_isInvocationMessage(e){this._assertNotEmptyString(e.target,"Invalid payload for Invocation message."),e.invocationId!==void 0&&this._assertNotEmptyString(e.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(e){if(this._assertNotEmptyString(e.invocationId,"Invalid payload for StreamItem message."),e.item===void 0)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(e){if(e.result&&e.error)throw new Error("Invalid payload for Completion message.");!e.result&&e.error&&this._assertNotEmptyString(e.error,"Invalid payload for Completion message."),this._assertNotEmptyString(e.invocationId,"Invalid payload for Completion message.")}_isAckMessage(e){if(typeof e.sequenceId!="number")throw new Error("Invalid SequenceId for Ack message.")}_isSequenceMessage(e){if(typeof e.sequenceId!="number")throw new Error("Invalid SequenceId for Sequence message.")}_assertNotEmptyString(e,n){if(typeof e!="string"||e==="")throw new Error(n)}}const jo={trace:g.Trace,debug:g.Debug,info:g.Information,information:g.Information,warn:g.Warning,warning:g.Warning,error:g.Error,critical:g.Critical,none:g.None};function zo(t){const e=jo[t.toLowerCase()];if(typeof e!="undefined")return e;throw new Error(`Unknown log level: ${t}`)}class Vo{configureLogging(e){if(Ee.isRequired(e,"logging"),Wo(e))this.logger=e;else if(typeof e=="string"){const n=zo(e);this.logger=new Kt(n)}else this.logger=new Kt(e);return this}withUrl(e,n){return Ee.isRequired(e,"url"),Ee.isNotEmpty(e,"url"),this.url=e,typeof n=="object"?this.httpConnectionOptions=H(H({},this.httpConnectionOptions),n):this.httpConnectionOptions=ee(H({},this.httpConnectionOptions),{transport:n}),this}withHubProtocol(e){return Ee.isRequired(e,"protocol"),this.protocol=e,this}withAutomaticReconnect(e){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return e?Array.isArray(e)?this.reconnectPolicy=new Yn(e):this.reconnectPolicy=e:this.reconnectPolicy=new Yn,this}withServerTimeout(e){return Ee.isRequired(e,"milliseconds"),this._serverTimeoutInMilliseconds=e,this}withKeepAliveInterval(e){return Ee.isRequired(e,"milliseconds"),this._keepAliveIntervalInMilliseconds=e,this}withStatefulReconnect(e){return this.httpConnectionOptions===void 0&&(this.httpConnectionOptions={}),this.httpConnectionOptions._useStatefulReconnect=!0,this._statefulReconnectBufferSize=e==null?void 0:e.bufferSize,this}build(){const e=this.httpConnectionOptions||{};if(e.logger===void 0&&(e.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const n=new Fo(this.url,e);return pn.create(n,this.logger||$t.instance,this.protocol||new Uo,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}function Wo(t){return t.log!==void 0}function Be(t,e={}){var c;const{popupRequestInfo:n}=window;t=It(t);const s=(c=n==null?void 0:n.credentialType)==null?void 0:c.toUpperCase(),i=n==null?void 0:n.accessToken,r=H(H({},{method:"GET",headers:{}}),e);switch(r.body&&typeof r.body=="object"&&(r.body instanceof FormData?r.headers=ee(H({},r.headers),{"Content-Type":"multipart/form-data"}):(r.headers=ee(H({},r.headers),{"Content-Type":"application/json"}),r.body=JSON.stringify(r.body))),s){case"COOKIE":r.credentials="include";break;case"QUERY":break;default:i&&(r.headers=ee(H({},r.headers),{Authorization:`Bearer ${i}`}));break}return fetch(t,r).then(a=>{if(!a.ok){console.error(`HTTP error! status: ${a.status}`);return}return a.json()}).then(a=>{if(a&&a.code){if(a.code!=="0"){console.error(`API error! code: ${a.code}, message: ${a.message}`);return}return a.data}return a}).catch(a=>{console.error("Error fetching data:",a)})}function Bt(t,e){if(!e)return t;let n="";for(let s in e){const i=e[s];i!=null&&(n.length>0&&(n+="&"),n+=`${encodeURIComponent(s)}=${encodeURIComponent(i)}`)}return t.indexOf("?")===-1?t+="?"+n:t+="&"+n,t}function Kn(t){return v(this,null,function*(){if(!t||t.length===0)return[];const s=yield Be("user/batch/get",{method:"POST",body:{ids:t}});return!s||!Array.isArray(s)?[]:s.map(i=>({id:i.id,username:i.username,fullName:i.fullName,avatarUrl:i.avatarUrl}))})}const Ht=window,qo=Ht.indexedDB||Ht.mozIndexedDB||Ht.webkitIndexedDB||Ht.msIndexedDB||Ht.shimIndexedDB,Zo="chatPopupDb",Yo=1,Jt="users";function Xo(t){if(!t.objectStoreNames.contains(Jt)){const e=t.createObjectStore(Jt,{keyPath:"id",autoIncrement:!1});["username","fullName","avatarUrl"].forEach(n=>e.createIndex(n,n,{unique:!1}))}}let en;function Go(){return new Promise((t,e)=>{if(en)t(en);else{const n=qo.open(Zo,Yo);n.onerror=s=>e(s.target.error),n.onsuccess=s=>{en=s.target.result,t(en)},n.onupgradeneeded=s=>{const i=s.target.result;Xo(i)}}})}function Qn(t,e){return v(this,null,function*(){const n=yield Go();return n?n.transaction(Jt,t,e).objectStore(Jt):void 0})}function Ko(t){return new Promise((e,n)=>v(null,null,function*(){if(t==="SYSTEM"){e({id:"SYSTEM",username:"system",fullName:"Hệ thống"});return}const s=yield Qn("readonly");if(!s){n(new Error("User object store not found"));return}const i=s.get(t);i.onsuccess=o=>v(null,null,function*(){const r=o.target.result;e(r)}),i.onerror=o=>n(o.target.error)}))}function Qo(t){return v(this,null,function*(){const e=yield Qn("readwrite");if(!e)throw new Error("User object store not found");return new Promise((n,s)=>{const i=e.put(t);i.onsuccess=o=>n(o.target.result),i.onerror=o=>s(o.target.error)})})}function Jo(t){return v(this,null,function*(){const e=t.map(s=>Ko(s));return(yield Promise.all(e)).filter(s=>s!==void 0)})}function _t(t){return v(this,null,function*(){const e=Array.from(new Set(t.filter(r=>typeof r=="string"&&r.length>0))),n=yield Jo(e),s=e.filter(r=>!n.some(c=>c.id===r)),i=yield Kn(s);yield Promise.all(i.map(r=>Qo(r)));const o=[...n,...i];return new Map(o.map(r=>[r.id,r]))})}function tn(t){return{id:t.id||t.conversationId,name:t.name,lastMessage:t.lastMessage,updatedAt:t.updatedAt||t.dateTime,type:t.type,membersCount:t.membersCount,status:t.status,isPinned:t.isPinned,isRead:t.isRead,traceId:t.traceId}}function tt(t,e){if(!t)return;let n;e||t.quotedMessage&&(n=tt(t.quotedMessage,!0));const s=t.body;return s&&Array.isArray(s.files)&&(s.files=s.files.map(i=>{const o=i.thumbId?It(`file/${i.thumbId}`):void 0,r=It(`file/${i.id||i.fileId}`);return{id:i.id||i.fileId,thumbId:i.thumbId,url:r,name:i.name,contentType:i.contentType,thumbUrl:o}})),{id:t.id||t.messageId,conversationId:t.conversationId,senderId:t.senderId||t.editedBy,sender:t.sender,body:s,sentAt:t.sentAt,deleted:t.deleted,edited:t.edited,mentions:t.mentions,deletedFor:t.deletedFor,quotedMessage:n,traceId:t.traceId}}function nn(t){return v(this,null,function*(){const e=t.lastMessage?[t.lastMessage.senderId]:[],n=yield _t(e);if(t.lastMessage){const s=n.get(t.lastMessage.senderId);s&&(t.lastMessage.sender=s,t.lastMessage.sentAt=t.lastMessage.sentAt?new Date(t.lastMessage.sentAt):new Date)}return{id:t.id,name:t.name,lastMessage:t.lastMessage,updatedAt:new Date(t.updatedAt),type:t.type,membersCount:t.membersCount,status:t.status,isPinned:t.isPinned,isRead:t.isRead,traceId:t.traceId}})}function St(t,e=new Set){return t.senderId&&e.add(t.senderId),t.quotedMessage&&St(t.quotedMessage,e),e}function At(t,e){const n=t.sender||e.get(t.senderId),s=t.quotedMessage?At(t.quotedMessage,e):void 0;return t.sender=n,s&&(t.quotedMessage=s),t}function xt(t){if(!t)return;const e=t.quotedMessage?xt(t.quotedMessage):void 0,n={id:t.id,conversationId:t.conversationId,sender:t.sender,body:t.body,sentAt:t.sentAt?new Date(t.sentAt):new Date,deleted:t.deleted,edited:t.edited,mentions:t.mentions,deletedFor:t.deletedFor,traceId:t.traceId};return e&&(n.quotedMessage=e),n}function Jn(t,e){var c;if(!t)return console.error("URL base is not defined."),"";e=e?e.startsWith("/")?e.slice(1):e:"";let n=t.endsWith("/")?`${t}${e}`:`${t}/${e}`;n.endsWith("/")&&(n=n.slice(0,-1));const{popupRequestInfo:s}=window,i=(c=s==null?void 0:s.credentialType)==null?void 0:c.toUpperCase(),o=s==null?void 0:s.credentialName,r=s==null?void 0:s.accessToken;switch(i){case"COOKIE":const a=new URL(n);a.searchParams.append("credentialType",i),a.searchParams.append("credentialName",o||""),n=a.toString();break;case"QUERY":if(r){const d=new URL(n);d.searchParams.append("access_token",r),n=d.toString()}break}return n}function It(t){const{popupRequestInfo:e}=window,n=e==null?void 0:e.apiUrlBase;return Jn(n,t)}function er(t){const{popupRequestInfo:e}=window,n=t||(e==null?void 0:e.hubUrlBase);return Jn(n)}function tr(t){var i;let e=er(t);const{popupRequestInfo:n}=window,s=(i=n==null?void 0:n.credentialType)==null?void 0:i.toUpperCase();if(s!="COOKIE"&&s!="QUERY"){const o=n==null?void 0:n.accessToken;if(o){const r=new URL(e);r.searchParams.append("access_token",o),e=r.toString()}}return new Vo().withUrl(e).configureLogging(g.Information).withAutomaticReconnect().build()}const mn=window;mn.messagesCache={};function nr(t,e,n,s){return v(this,null,function*(){const i=Bt(`message/conversation/${t}/user`,{direction:e,messageId:n,top:s}),o=yield Be(i);return!o||!Array.isArray(o)?[]:o.filter(r=>!!r).map(r=>tt(r))})}function sr(t){return v(this,null,function*(){const e="message";let n;t.quotedMessage&&(n=t.quotedMessage.id,n&&(mn.messagesCache[n]=t.quotedMessage));const s={conversationId:t.conversationId,body:t.body,quotedId:n,traceId:t.traceId},i=yield Be(e,{method:"POST",body:s});return i.quotedMessage=t.quotedMessage,tt(i)})}function ir(t){return v(this,null,function*(){if(!t||!t.id)return;const e=`message/${t.id}`;let n;t.quotedMessage&&(n=t.quotedMessage.id,n&&(mn.messagesCache[n]=t.quotedMessage));const s={body:t.body,quotedId:n,mentions:t.mentions},i=yield Be(e,{method:"POST",body:s});return i.quotedMessage=t.quotedMessage,tt(i)})}function or(t,e){return v(this,null,function*(){if(!t)return!1;e||(e="Recall");const n=`message/${t}/delete`;return!!(yield Be(n,{method:"POST",body:{type:e}}))})}function es(t){return v(this,null,function*(){if(!t)return;const e=`message/${t}`,n=yield Be(e);if(n)return tt(n)})}function rr(t){return v(this,null,function*(){if(!t||t.length===0)return[];const s=yield Be("message/batch/get",{method:"POST",body:{ids:t}});return!s||!Array.isArray(s)?[]:s.map(i=>tt(i))})}function ar(t,e,n,s){return v(this,null,function*(){var c;const i=Bt("aggregate/search",{conversationId:t,keyword:e,from:n,top:s,type:"MESSAGE"}),r=(c=(yield Be(i)).filter(a=>a.type==="MESSAGE").at(0))==null?void 0:c.items;return r?r.map(a=>tt(a)):[]})}const sn=window;function cr(t,e){return v(this,null,function*(){if(!e||!t)return;if(!t.quotedMessage&&t.quotedId){const c=sn.messagesCache[t.quotedId];c?(t.quotedMessage=c,delete sn.messagesCache[t.quotedId]):t.quotedMessage=yield es(t.quotedId)}const n=tt(t);if(!n)return;const s=St(n),i=yield _t(Array.from(s)),o=At(n,i),r=xt(o);e(r)})}function lr(t,e){return v(this,null,function*(){if(!e||!t)return;const n=tn(t);if(!n)return;const s=yield nn(n);e(s)})}function dr(t,e){if(!e||!t)return;const{conversationId:n,name:s}=t;!n||!s||e(n,s)}function ur(t,e){if(!e||!t)return;const{conversationId:n}=t;n&&e(n)}function hr(t,e){return v(this,null,function*(){if(!e||!t)return;if(!t.quotedMessage&&t.quotedId){const c=sn.messagesCache[t.quotedId];c?(t.quotedMessage=c,delete sn.messagesCache[t.quotedId]):t.quotedMessage=yield es(t.quotedId)}const n=tt(t);if(!n)return;const s=St(n),i=yield _t(Array.from(s)),o=At(n,i),r=xt(o);e(r)})}function fr(t,e){if(!e||!t)return;const{messageId:n,conversationId:s,type:i,deletedBy:o}=t;!n||!s||e({messageId:n,conversationId:s,deleteType:i||"Recall",deletedBy:o||""})}let Fe;function gr(t){return Fe&&Fe.stop(),Fe=tr(t),Fe?(Fe.on("UserStatusChanged",n=>console.log("UserStatusChanged",n)),{onConnected(n){Fe.on("Connected",n)},onMessageSent(n){Fe.on("MessageSent",s=>v(null,null,function*(){yield cr(s,n)}))},onMessageEdited(n){Fe.on("MessageEdited",s=>v(null,null,function*(){yield hr(s,n)}))},onMessageDeleted(n){Fe.on("MessageDeleted",s=>{fr(s,n)})},onConversationCreated(n){Fe.on("ConversationCreated",s=>v(null,null,function*(){yield lr(s,n)}))},onConversationBasicInfoChanged(n){Fe.on("ConversationBasicInfoChanged",s=>{dr(s,n)})},onConversationDeleted(n){Fe.on("ConversationDeleted",s=>{ur(s,n)})},start:()=>Fe.start(),stop:()=>Fe.stop()}):void 0}function pr(){return new Promise(t=>{t([{name:"Khiếu nại và hỗ trợ",description:"Tạo khiếu nại của khách hàng và được trợ giúp bởi hỗ trợ viên",conversationType:"HELP",icon:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABGCAYAAABbnhMrAAAAAXNSR0IArs4c6QAAG/hJREFUeF7tXHk8lNv/n2HGPggRcVEporihuvJttVaylW6khlJdKfuaJbJlK2QZVBSVdlFp0WZJkmgh5ep+lSWSyBIGv9fnMcd3cmds6d7++D2v1zTT85xzPue8z2f/nAce9//XdyGA/67eP7jzwMAACw6HY8XhcH14PL7/B5Ob0PD/OoCvXr0iNTY2ylVXV8s0NDRIf/z4Uby5uVmgvb19Sk9PDyesioWFhcrFxdXNx8fXws/P/1FYWPidpKTkWxERkYrffvutHI/H901o9ZPQ6V8BsLq6WuTevXuaJSUl/6mqqlJpaWmZ8enTJ1JXVxdwGw6PxwNo2Ad+DwwM4Pr7+3F9fX3YB+7x8PDgSCTSZ3Fx8VIFBYUiNTW13NmzZ9+SkZHpngRcxjzEPwpgTk7O0uvXr+vn5eWta2homAWgEAiEHlFR0XczZsx4Pn369LfAXSIiIvX8/Pyfubm5O9jY2Pp6enpYgSM/ffok8PHjx2m1tbWS1dXVc2tra+Wam5unwjisrKw4KSmpEi0trQs6OjqZ8+fPfz5mFL6j4T8CYHp6ul5mZqbp06dPdVpaWviFhITalZSUcuXk5O4vWrSoWEhIqGT+/Pkt413Hs2fPZlRWViqVlZWpFRYWrqipqVnQ1dWFExYWfquhoXFFV1c3ffny5Q/HO+542v9QAAsKChbGx8fvKSsrM/rw4QPXrFmz3q1cuTJ12bJlWatWrSoYz0RHa1tXV8f18OFDjRs3bqwvLCw0am1t5ebh4XlvZGR0ysTE5Mi8efPejTbGRJ7/EADBekZERLgeO3bM9suXLyK//PJLtZaWVsrq1auTVVRUaiYy0fH0ycnJUbt48eKW3Nxc0+bmZpKsrGyRpaVlmJmZ2bnxjDOWtpMOYFFRkXxUVJTnvXv3fufl5e1dvXo1Zc2aNZQVK1a8GMuEJrNNdna2xtGjR20KCwv1OTk5W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cuộc hội thoại để bắt đầu nhận được các tư vấn đầu tư",botId:"BOT~rasaconnector",isDefault:!0,icon:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABZCAYAAACpHqNlAAAAAXNSR0IArs4c6QAAG71JREFUeF7tXAlYU0fXnpuQBAgCURFRqQvwsbhABUGgoihFoAhal7pUxaVaQVvr8nXRPvWrUpdafxcEra0VFVwQRRG1LqAoS63WBRcgAQSV1QbByBIg+f8zNxNuYoDEBfX7e5+HhyR3ljPvnG3OnBkK/fO8EALUi9SOjY3tW1paOlRGydhyOUtOIZlMJqfkzDZZlFzlu1ztvab+KblqnbZolFOUyjgoSo6/y+T07yy17/AbRckouZzV1M3cvMLCwiK/c+fOOY6Ojk/b6kv9vc4ALl669ItLly4uKyoq6lRWVobbY46X+VltXLrS1i7l5U0y1KlTJ9StW7eKvn37Jvv7+x9ydnY+1q9fP6k2BOgEoLGpSUF1VVUv0jCLzQaeo7/qxjTa0NY+ZeTAjZSSCYyMOyCHvn3zJk6cFL7o889/a4sIrQC0sbHpIxQJ7xjy+byamhoMFkePgxoaGhDSqoW2yHh977kcLmpqasJ/zKdLV3Pk5up2/Nvly0NdXV3vt0Rhm8PndzC6+/Tp038huZwFjXC4dIeyRrpDis1SEeHXB8Vz9ixTUdGIw+Hg8TQ2NeIGXQa5in5YtSrE19c3TaO+bqnbkJAQv13RuxIQQjwQVRailLNE9Jyenh5qbKQ7elsfLpeLJQnGxGaz8X+ilgDMhsYGZN61a9Xe3Xv83n///Uz1cWrkwKVffx24ft3aOLlcrs9isZAM2Ft1opR6g6k/mI2/DQaEVt30wJjjgDHDdyzWLAoBozjYO2THxsR49+vXr1RlnOqIRkdHDwidH5byVCLpiMALUGPxt5XTXoRuzERyGRoVHHwgMeHoxFYBHPCuY+rtW7eHYFbWwHkvQsjbWBeLcUMDYumxkUAgQKvCf/ho3pw5B8lYVER4w4YN0xctXrQLdB74Rzr6s28jPs84EWqaCmHuI64aQmiwh/tfGWnprhRFYSu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M7bWVlJbr211+DEo8enVJYWGhJTskD1zAPKzKPSSjb12KUTHGF4n369CkKDAzcFxgYeMDHx+cmuQNVi6ZaLdImgMzaJ86cGZwQHzfhzNlzwYX37vVhnitj6icAC99ZUFurEpAkgVSsW/T08FGx1i4gVD8uS/Qb87AOOXCtfkAcfjcyMpK4uLhcCAgIOOLr65ukfgf0i4KnZmO0by4nJ6f7sWPHAk6cOjnx8h+XB9fU1hiSs2YtnrvVcAaX3NVK9CoxVEr1oLi/mTjf8B+DqnbvPTOCDAmcdnZ21/39/RKHDxt+2NfXF1v0V/XoxIGaiEg4fnxIYuLRib+fPOVfUlLSWyne5IZwcjBbYYwYh5FonaXhom/mGTtwI9Sj0SQEjw8ySqXYTzM3Ny95z9Pz1IdjPozz9PQ8/7wnj3QF+oUBJB1mZWVZnjh1Kvjw4UPjr1+/Mbi+ro6r3ARiHjBU2/OAi8oASOI20JeG0QeesXjK6TWu+qlyAJXPN6xxGeSa5uPzfoLfqFHHXfr1K9IVgBct/9IAJIRAtCbheMLw+IOHJySnJAcWFxd3I2JNgg8kEEpWEsxBPLP8IhQqDBJwWx+rPnc+CAhMDBjld8jXm74943U9Lx1A5kAu37zc5+TR38ecOXN6fGZmphsAxtydI8dlweAAqPgOa8WqgOzdwsXXYKEFAoF4iJfX6fEfjo339PQ827t378evCzSVCW8PIiCrIC4uzvfwkSMTU86njC4rLTVRbmMydKD6+hWuv7Pva5/uH+Af/8HoDxJcB7jmtwe9uvTxSjlQEyHpV9Otjx85MSY5+dx4kUjkVCN5yiGcB4eyQe9ZWFjk+fr6Hvfz8zsUFBR0SZcBtXfZdgeQOcALGRfs7+fdtxKLxRa1tbVUx44dq6ytrfMsLCxy7OzsnrQ3GM/T32sF8HkIftPq/C/BcWIskM+NvgAAAABJRU5ErkJggg=="}])})}function Cr(t,e){return v(this,null,function*(){var a,d;const n=Bt("conversation/user/pinned",{top:t,type:e,ignoredFields:"members"}),s=Bt("conversation/user",{top:t,type:e,ignoredFields:"members"}),i=yield Promise.all([Be(n),Be(s)]);let o=(a=i[0])==null?void 0:a.items,r=(d=i[1])==null?void 0:d.items;return o||(o=[]),r||(r=[]),[...o,...r].map(u=>tn(u))})}function mr(t){return v(this,null,function*(){const e=`conversation/${t}?ignoredFields=members`,n=yield Be(e);if(n)return tn(n)})}function wr(t){return v(this,null,function*(){const e=t.type?t.type:"BOT";let n="conversation";const s={name:t.name,traceId:t.traceId};switch(e){case"BOT":n+="/bot",s.botId=t.members?t.members.filter(f=>{var j;return(j=f.userId)==null?void 0:j.startsWith("BOT~")}).map(f=>f.userId)[0]:null;break;case"SURVEY":n+="/survey",s.botId=t.members?t.members.filter(f=>{var j;return(j=f.userId)==null?void 0:j.startsWith("BOT~")}).map(f=>f.userId)[0]:null;break;case"GROUP":n+="/group",s.memberIds=t.members?t.members.filter(f=>f.id!=="me").map(f=>f.userId):[];break;case"HELP":n+="/help";break}const i=yield Be(n,{method:"POST",body:s}),{conversationId:o,name:r,type:c,membersCount:a,updatedAt:d,traceId:u}=i;return{id:o,name:r,type:c,membersCount:a,updatedAt:d,traceId:u}})}function vr(t,e){return v(this,null,function*(){let n="conversation";return e?n+=`/${t}/pin`:n+=`/${t}/unpin`,yield Be(n,{method:"POST",body:{}}),!0})}function yr(t,e){return v(this,null,function*(){const n=`conversation/${t}`;return yield Be(n,{method:"PATCH",body:{name:e}}),!0})}function br(t){return v(this,null,function*(){const e=`conversation/${t}/delete`;return yield Be(e,{method:"POST",body:{}}),!0})}function _r(t,e,n){return v(this,null,function*(){var c;const s=Bt("aggregate/search",{keyword:t,from:e,top:n,type:"CONVERSATION"}),o=(c=(yield Be(s)).filter(a=>a.type==="CONVERSATION").at(0))==null?void 0:c.items;if(!o)return[];const r=[...new Set(o.map(a=>a.lastMessageId))];if(r.length>0){const a=yield rr(r),d={};a.forEach(u=>{u&&(d[u.id]=u)}),o.forEach(u=>{u.lastMessageId&&(u.lastMessage=d[u.lastMessageId])})}return o.map(a=>tn(a))})}function Sr(t,e){return v(this,null,function*(){const n=yield Cr(t,e);return yield Promise.all(n.map(nn))})}function Ar(t){return v(this,null,function*(){const e=yield mr(t);return e?yield nn(e):void 0})}function xr(t,e,n){return v(this,null,function*(){const s=yield _r(t,e,n);return yield Promise.all(s.map(nn))})}function Ir(t){return v(this,null,function*(){const e=yield wr(t);return{id:e.id,name:e.name,type:e.type,membersCount:e.membersCount,updatedAt:new Date(e.updatedAt)}})}function Mr(t,e){return vr(t,e)}function kr(t,e){return yr(t,e)}function Er(t){return br(t)}function Tr(t,e){var a;if(!t)return;const{popupRequestInfo:n}=window,s=It("file"),i=new XMLHttpRequest,o=(a=n==null?void 0:n.credentialType)==null?void 0:a.toUpperCase(),r=n==null?void 0:n.accessToken;switch(o){case"COOKIE":i.withCredentials=!0;break;case"QUERY":break;default:i.setRequestHeader("Authorization",`Bearer ${r}`);break}const c=new FormData;c.append("file",t),e&&(i.upload.onprogress=function(d){if(d.lengthComputable){const u=d.loaded/d.total*80;e({loaded:d.loaded,total:d.total,percent:u,status:"uploading"})}}),i.onload=function(){if(i.status===200){const d=JSON.parse(i.responseText);if(e){const u=d.thumbId?It(`file/${d.thumbId}`):void 0,f=It(`file/${d.fileId}`);e({loaded:d.size,total:d.size,percent:100,status:"done",httpCode:i.status,fileItem:{id:d.fileId,name:d.fileName,contentType:d.contentType,thumbId:d.thumbId,thumbUrl:u,url:f}})}}else e&&e({loaded:0,total:0,percent:0,status:"error",error:i.statusText,httpCode:i.status})},i.open("POST",s,!0),i.send(c),console.log(`------- Uploading file: ${t.name} to ${s}`)}function Rr(t,e){Tr(t,e)}function Pr(t,e,n,s){return v(this,null,function*(){const i=(yield nr(t,e,n,s)).filter(a=>!!a);if(!i||!Array.isArray(i))return[];const o=new Set;i.forEach(a=>St(a,o));const r=yield _t(Array.from(o));return i.map(a=>At(a,r)).map(a=>xt(a))})}function $r(t){return v(this,null,function*(){const e=yield sr(t);if(!e)return;const n=St(e),s=yield _t(Array.from(n)),i=At(e,s);return xt(i)})}function Dr(t){return v(this,null,function*(){return!!(yield ir(t))})}function Br(t,e){return or(t,e)}function Hr(t,e,n,s){return v(this,null,function*(){const i=yield ar(t,e,n,s);if(!i||!Array.isArray(i))return[];const o=new Set;i.forEach(a=>St(a,o));const r=yield _t(Array.from(o));return i.map(a=>At(a,r)).map(a=>xt(a))})}function Lr(t){return Kn(t)}class Fr{constructor(e){me(this,"hubConnection");me(this,"onHubConnected",e=>{this.hubConnection.onConnected(n=>{window.currentUserId=n.userId,e(n)})});me(this,"onMessageSent",e=>{this.hubConnection.onMessageSent(n=>{n.conversationId=this.normalizeConvId(n.conversationId),this.normalizeSender(n.sender),e(n)})});me(this,"onMessageEdited",e=>{this.hubConnection.onMessageEdited(n=>{n.conversationId=this.normalizeConvId(n.conversationId),this.normalizeSender(n.sender),e(n)})});me(this,"onMessageDeleted",e=>{this.hubConnection.onMessageDeleted(e)});me(this,"onConversationCreated",e=>{this.hubConnection.onConversationCreated(n=>{this.normalizeConversation(n),e(n)})});me(this,"onConversationBasicInfoChanged",e=>{this.hubConnection.onConversationBasicInfoChanged((n,s)=>{n=this.normalizeConvId(n),e(n,s)})});me(this,"onConversationDeleted",e=>{this.hubConnection.onConversationDeleted(n=>{n=this.normalizeConvId(n),e(n)})});me(this,"getConversationAsync",e=>v(this,null,function*(){const n=this.denormalizeConvId(e),s=yield Ar(n);if(s)return this.normalizeConversation(s),s}));me(this,"listConversationAsync",(e,n)=>v(this,null,function*(){const s=yield Sr(e,n);return s.forEach(i=>this.normalizeConversation(i)),s}));me(this,"searchConversationsAsync",(e,n,s)=>v(this,null,function*(){const i=yield xr(e,n,s);return i.forEach(o=>this.normalizeConversation(o)),i}));me(this,"pinConversationAsync",(e,n)=>{const s=this.denormalizeConvId(e);return Mr(s,n)});me(this,"createConversationAsync",e=>Ir(e));me(this,"updateConversationNameAsync",(e,n)=>{const s=this.denormalizeConvId(e);return kr(s,n)});me(this,"deleteConversationAsync",e=>{const n=this.denormalizeConvId(e);return Er(n)});me(this,"sendMessageAsync",e=>v(this,null,function*(){const n=H({},e);n.conversationId=this.denormalizeConvId(n.conversationId);const s=yield $r(n);return this.normalizeSender(s.sender),s}));me(this,"listMessagesAsync",(e,n,s,i)=>v(this,null,function*(){const o=this.denormalizeConvId(e),r=yield Pr(o,n,s,i);return this.normalizeMessages(r),r}));me(this,"searchMessagesAsync",(e,n,s,i)=>v(this,null,function*(){const o=this.denormalizeConvId(e),r=yield Hr(o,n,s,i);return this.normalizeMessages(r),r}));me(this,"updateMessageAsync",e=>Dr(e));me(this,"batchGetUsersAsync",e=>Lr(e));me(this,"deleteMessageAsync",(e,n)=>Br(e,n));me(this,"uploadFile",(e,n)=>{Rr(e,n)});me(this,"listChatTypesAsync",()=>v(null,null,function*(){return yield pr()}));const n=gr(e);if(!n)throw new Error("Connect to hub error");this.hubConnection=n,this.hubConnection.start()}get currentUserId(){return window.currentUserId}normalizeConvId(e){return e.startsWith(`${this.currentUserId}~`)?e.replace(new RegExp(`^${this.currentUserId}`),"me"):e}denormalizeConvId(e){return e.replace(/^me/,this.currentUserId)}normalizeSender(e){e&&e.id===this.currentUserId&&(e.id="me")}normalizeConversation(e){e.id=this.normalizeConvId(e.id),e.lastMessage&&this.normalizeSender(e.lastMessage.sender)}normalizeMessages(e){e.forEach(n=>this.normalizeSender(n.sender))}}var Or=F("<div>Loading...");const[wn,Nr]=L(null),[Ur,jr]=L(null),Pe={},ts={apiUrlBase:"http://gateway-dev.chat.fpts.com.vn/chatapi/api",hubUrlBase:"http://gateway-dev.chat.fpts.com.vn/chathub/hub/notification",credentialType:"cookie",credentialName:"aspfpt_sessiontoken"};window.popupRequestInfo=ts;const ns=ts.hubUrlBase,ss=()=>{var s;const t=window.popupRequestInfo;if(!ns)throw new Error("VITE_PUBLIC_HUB_URL is not defined");const e=(s=t==null?void 0:t.credentialType)==null?void 0:s.toLowerCase();if(e!=="cookie"&&!(t!=null&&t.accessToken))throw new Error("Missing JWT token: accessToken chưa được gán vào popupRequestInfo");if(e!=="cookie"&&!window.currentUserId)throw new Error("Missing currentUserId: chưa chọn user");const n=new Fr(ns);Nr(n),n.onHubConnected(i=>{console.log("SignalR: Hub connected",i)}),n.onMessageSent(i=>{var o;console.log("SignalR: Message sent event received",i),(o=Pe.appendMessage)==null||o.call(Pe,i)}),n.onMessageEdited(i=>{var o;console.log("SignalR: Message edited event received",i),(o=Pe.updateMessage)==null||o.call(Pe,i)}),n.onMessageDeleted(i=>{var o;console.log("SignalR: Message deleted event received",i),(o=Pe.deleteMessage)==null||o.call(Pe,i)}),n.onConversationCreated(i=>{var o;console.log("SignalR: Conversation created event received",i),(o=Pe.appendConversation)==null||o.call(Pe,i)}),n.onConversationBasicInfoChanged((i,o)=>{var r;console.log("SignalR: Conversation name changed",i,o),(r=Pe.updateConversationName)==null||r.call(Pe,i,o)}),n.onConversationDeleted(i=>{var o;console.log("SignalR: Conversation deleted",i),(o=Pe.deleteConversation)==null||o.call(Pe,i)})};function is(t,e){const n=typeof t=="string"?document.querySelector(t):t;if(!n)throw new Error(`Element "${t}" not found.`);e!=null&&e.credentialType&&(window.popupRequestInfo.credentialType=e.credentialType),e!=null&&e.accessToken&&(window.popupRequestInfo.accessToken=e.accessToken),e!=null&&e.currentUserId&&(window.currentUserId=e.currentUserId),jr(e),ss(),bs(()=>ie(Ye,{get when(){return wn()},get fallback(){return Or()},get children(){return ie(zi,{get remoteRepository(){return wn()},exportMethods:Pe,get children(){return ie(co,{get remoteRepo(){return wn()},get options(){return Ur()}})}})}}),n)}typeof window!="undefined"&&(window.EzChat={createPopup:is}),window.addEventListener("startChat",()=>{ss()}),Me.createPopup=is,Object.defineProperty(Me,Symbol.toStringTag,{value:"Module"})}));
13
13
  //# sourceMappingURL=ezchat.umd.js.map