@echo-sdk/view 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -1128,7 +1128,9 @@ var te = /* @__PURE__ */ ((e) => (e.TEXT = "text", e.IMAGE = "image", e.FILE = "
1128
1128
  }
1129
1129
  };
1130
1130
  class Tt {
1131
- constructor(t = "http://localhost:3000") {
1131
+ //https://chat-mcp-agent.fly.dev
1132
+ //http://localhost:3000
1133
+ constructor(t = "https://chat-mcp-agent.fly.dev") {
1132
1134
  this.baseUrl = t, this.client = new it({
1133
1135
  retries: 3,
1134
1136
  backoff: 1e3
@@ -1150,7 +1152,9 @@ class Tt {
1150
1152
  }
1151
1153
  }
1152
1154
  class It {
1153
- constructor(t = "http://localhost:3000") {
1155
+ //https://chat-mcp-agent.fly.dev
1156
+ //http://localhost:3000
1157
+ constructor(t = "https://chat-mcp-agent.fly.dev") {
1154
1158
  this.baseUrl = t, this.httpClient = new it({
1155
1159
  // baseURL is not supported in HttpClientConfig
1156
1160
  });
@@ -1196,7 +1200,7 @@ class It {
1196
1200
  const Fe = 5e3, ot = pt(null), Nt = ({ children: e, sdkConfig: t }) => {
1197
1201
  const [n, r] = N(!1), [o, i] = N("disconnected"), [s, h] = N(!1), [u, l] = N(!0), [_, a] = N(null), [g, d] = N([]), [C, I] = N([]), [w, p] = N(null), [f, A] = N(null), [P, M] = N(!1), [L, W] = N(null), [O, F] = N({}), E = Y(null), v = Y(null), q = Y(null), K = Y(/* @__PURE__ */ new Map()), B = Y(null);
1198
1202
  if (v.current || (v.current = new rt({ prefix: "EchoSDK" })), !q.current) {
1199
- const m = "http://localhost:3000";
1203
+ const m = "https://chat-mcp-agent.fly.dev";
1200
1204
  q.current = new It(m);
1201
1205
  }
1202
1206
  et(() => {
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- (function(K,O){typeof exports=="object"&&typeof module<"u"?O(exports):typeof define=="function"&&define.amd?define(["exports"],O):(K=typeof globalThis<"u"?globalThis:K||self,O(K.EchoView={}))})(this,(function(K){"use strict";var O,w,Ee,G,ke,Te,$e,Ie,ge,fe,me,Ne,ne={},De=[],ut=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,se=Array.isArray;function W(e,t){for(var n in t)e[n]=t[n];return e}function pe(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function dt(e,t,n){var r,o,i,s={};for(i in t)i=="key"?r=t[i]:i=="ref"?o=t[i]:s[i]=t[i];if(arguments.length>2&&(s.children=arguments.length>3?O.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)s[i]===void 0&&(s[i]=e.defaultProps[i]);return ae(e,s,r,o,null)}function ae(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++Ee,__i:-1,__u:0};return o==null&&w.vnode!=null&&w.vnode(i),i}function re(e){return e.children}function ce(e,t){this.props=e,this.context=t}function ee(e,t){if(t==null)return e.__?ee(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?ee(e):null}function Re(e){var t,n;if((e=e.__)!=null&&e.__c!=null){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null){e.__e=e.__c.base=n.__e;break}return Re(e)}}function ve(e){(!e.__d&&(e.__d=!0)&&G.push(e)&&!le.__r++||ke!=w.debounceRendering)&&((ke=w.debounceRendering)||Te)(le)}function le(){for(var e,t,n,r,o,i,s,h=1;G.length;)G.length>h&&G.sort($e),e=G.shift(),h=G.length,e.__d&&(n=void 0,r=void 0,o=(r=(t=e).__v).__e,i=[],s=[],t.__P&&((n=W({},r)).__v=r.__v+1,w.vnode&&w.vnode(n),ye(t.__P,n,r,t.__n,t.__P.namespaceURI,32&r.__u?[o]:null,i,o??ee(r),!!(32&r.__u),s),n.__v=r.__v,n.__.__k[n.__i]=n,Pe(i,n,s),r.__e=r.__=null,n.__e!=o&&Re(n)));le.__r=0}function Ae(e,t,n,r,o,i,s,h,u,l,_){var a,g,d,C,N,b,p,m=r&&r.__k||De,A=t.length;for(u=_t(n,t,m,u,A),a=0;a<A;a++)(d=n.__k[a])!=null&&(g=d.__i==-1?ne:m[d.__i]||ne,d.__i=a,b=ye(e,d,g,o,i,s,h,u,l,_),C=d.__e,d.ref&&g.ref!=d.ref&&(g.ref&&be(g.ref,null,d),_.push(d.ref,d.__c||C,d)),N==null&&C!=null&&(N=C),(p=!!(4&d.__u))||g.__k===d.__k?u=Me(d,u,e,p):typeof d.type=="function"&&b!==void 0?u=b:C&&(u=C.nextSibling),d.__u&=-7);return n.__e=N,u}function _t(e,t,n,r,o){var i,s,h,u,l,_=n.length,a=_,g=0;for(e.__k=new Array(o),i=0;i<o;i++)(s=t[i])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[i]=ae(null,s,null,null,null):se(s)?s=e.__k[i]=ae(re,{children:s},null,null,null):s.constructor==null&&s.__b>0?s=e.__k[i]=ae(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,u=i+g,s.__=e,s.__b=e.__b+1,(l=s.__i=gt(s,n,u,a))!=-1&&(a--,(h=n[l])&&(h.__u|=2)),h==null||h.__v==null?(l==-1&&(o>_?g--:o<_&&g++),typeof s.type!="function"&&(s.__u|=4)):l!=u&&(l==u-1?g--:l==u+1?g++:(l>u?g--:g++,s.__u|=4))):e.__k[i]=null;if(a)for(i=0;i<_;i++)(h=n[i])!=null&&(2&h.__u)==0&&(h.__e==r&&(r=ee(h)),Fe(h,h));return r}function Me(e,t,n,r){var o,i;if(typeof e.type=="function"){for(o=e.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=e,t=Me(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=ee(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function gt(e,t,n,r){var o,i,s,h=e.key,u=e.type,l=t[n],_=l!=null&&(2&l.__u)==0;if(l===null&&h==null||_&&h==l.key&&u==l.type)return n;if(r>(_?1:0)){for(o=n-1,i=n+1;o>=0||i<t.length;)if((l=t[s=o>=0?o--:i++])!=null&&(2&l.__u)==0&&h==l.key&&u==l.type)return s}return-1}function qe(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||ut.test(t)?n:n+"px"}function he(e,t,n,r,o){var i,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||qe(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||qe(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(Ie,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r?n.u=r.u:(n.u=ge,e.addEventListener(t,i?me:fe,i)):e.removeEventListener(t,i?me:fe,i);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function He(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t.t==null)t.t=ge++;else if(t.t<n.u)return;return n(w.event?w.event(t):t)}}}function ye(e,t,n,r,o,i,s,h,u,l){var _,a,g,d,C,N,b,p,m,A,P,M,L,j,B,F,k,v=t.type;if(t.constructor!=null)return null;128&n.__u&&(u=!!(32&n.__u),i=[h=t.__e=n.__e]),(_=w.__b)&&_(t);e:if(typeof v=="function")try{if(p=t.props,m="prototype"in v&&v.prototype.render,A=(_=v.contextType)&&r[_.__c],P=_?A?A.props.value:_.__:r,n.__c?b=(a=t.__c=n.__c).__=a.__E:(m?t.__c=a=new v(p,P):(t.__c=a=new ce(p,P),a.constructor=v,a.render=mt),A&&A.sub(a),a.state||(a.state={}),a.__n=r,g=a.__d=!0,a.__h=[],a._sb=[]),m&&a.__s==null&&(a.__s=a.state),m&&v.getDerivedStateFromProps!=null&&(a.__s==a.state&&(a.__s=W({},a.__s)),W(a.__s,v.getDerivedStateFromProps(p,a.__s))),d=a.props,C=a.state,a.__v=t,g)m&&v.getDerivedStateFromProps==null&&a.componentWillMount!=null&&a.componentWillMount(),m&&a.componentDidMount!=null&&a.__h.push(a.componentDidMount);else{if(m&&v.getDerivedStateFromProps==null&&p!==d&&a.componentWillReceiveProps!=null&&a.componentWillReceiveProps(p,P),t.__v==n.__v||!a.__e&&a.shouldComponentUpdate!=null&&a.shouldComponentUpdate(p,a.__s,P)===!1){for(t.__v!=n.__v&&(a.props=p,a.state=a.__s,a.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(q){q&&(q.__=t)}),M=0;M<a._sb.length;M++)a.__h.push(a._sb[M]);a._sb=[],a.__h.length&&s.push(a);break e}a.componentWillUpdate!=null&&a.componentWillUpdate(p,a.__s,P),m&&a.componentDidUpdate!=null&&a.__h.push(function(){a.componentDidUpdate(d,C,N)})}if(a.context=P,a.props=p,a.__P=e,a.__e=!1,L=w.__r,j=0,m){for(a.state=a.__s,a.__d=!1,L&&L(t),_=a.render(a.props,a.state,a.context),B=0;B<a._sb.length;B++)a.__h.push(a._sb[B]);a._sb=[]}else do a.__d=!1,L&&L(t),_=a.render(a.props,a.state,a.context),a.state=a.__s;while(a.__d&&++j<25);a.state=a.__s,a.getChildContext!=null&&(r=W(W({},r),a.getChildContext())),m&&!g&&a.getSnapshotBeforeUpdate!=null&&(N=a.getSnapshotBeforeUpdate(d,C)),F=_,_!=null&&_.type===re&&_.key==null&&(F=Le(_.props.children)),h=Ae(e,se(F)?F:[F],t,n,r,o,i,s,h,u,l),a.base=t.__e,t.__u&=-161,a.__h.length&&s.push(a),b&&(a.__E=a.__=null)}catch(q){if(t.__v=null,u||i!=null)if(q.then){for(t.__u|=u?160:128;h&&h.nodeType==8&&h.nextSibling;)h=h.nextSibling;i[i.indexOf(h)]=null,t.__e=h}else{for(k=i.length;k--;)pe(i[k]);we(t)}else t.__e=n.__e,t.__k=n.__k,q.then||we(t);w.__e(q,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):h=t.__e=ft(n.__e,t,n,r,o,i,s,u,l);return(_=w.diffed)&&_(t),128&t.__u?void 0:h}function we(e){e&&e.__c&&(e.__c.__e=!0),e&&e.__k&&e.__k.forEach(we)}function Pe(e,t,n){for(var r=0;r<n.length;r++)be(n[r],n[++r],n[++r]);w.__c&&w.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){w.__e(i,o.__v)}})}function Le(e){return typeof e!="object"||e==null||e.__b&&e.__b>0?e:se(e)?e.map(Le):W({},e)}function ft(e,t,n,r,o,i,s,h,u){var l,_,a,g,d,C,N,b=n.props||ne,p=t.props,m=t.type;if(m=="svg"?o="http://www.w3.org/2000/svg":m=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),i!=null){for(l=0;l<i.length;l++)if((d=i[l])&&"setAttribute"in d==!!m&&(m?d.localName==m:d.nodeType==3)){e=d,i[l]=null;break}}if(e==null){if(m==null)return document.createTextNode(p);e=document.createElementNS(o,m,p.is&&p),h&&(w.__m&&w.__m(t,i),h=!1),i=null}if(m==null)b===p||h&&e.data==p||(e.data=p);else{if(i=i&&O.call(e.childNodes),!h&&i!=null)for(b={},l=0;l<e.attributes.length;l++)b[(d=e.attributes[l]).name]=d.value;for(l in b)if(d=b[l],l!="children"){if(l=="dangerouslySetInnerHTML")a=d;else if(!(l in p)){if(l=="value"&&"defaultValue"in p||l=="checked"&&"defaultChecked"in p)continue;he(e,l,null,d,o)}}for(l in p)d=p[l],l=="children"?g=d:l=="dangerouslySetInnerHTML"?_=d:l=="value"?C=d:l=="checked"?N=d:h&&typeof d!="function"||b[l]===d||he(e,l,d,b[l],o);if(_)h||a&&(_.__html==a.__html||_.__html==e.innerHTML)||(e.innerHTML=_.__html),t.__k=[];else if(a&&(e.innerHTML=""),Ae(t.type=="template"?e.content:e,se(g)?g:[g],t,n,r,m=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&ee(n,0),h,u),i!=null)for(l=i.length;l--;)pe(i[l]);h||(l="value",m=="progress"&&C==null?e.removeAttribute("value"):C!=null&&(C!==e[l]||m=="progress"&&!C||m=="option"&&C!=b[l])&&he(e,l,C,b[l],o),l="checked",N!=null&&N!=e[l]&&he(e,l,N,b[l],o))}return e}function be(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(o){w.__e(o,n)}}function Fe(e,t,n){var r,o;if(w.unmount&&w.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||be(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){w.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Fe(r[o],t,n||typeof e.type!="function");n||pe(e.__e),e.__c=e.__=e.__e=void 0}function mt(e,t,n){return this.constructor(e,n)}function Ue(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),w.__&&w.__(e,t),o=(r=!1)?null:t.__k,i=[],s=[],ye(t,e=t.__k=dt(re,null,[e]),o||ne,ne,t.namespaceURI,o?null:t.firstChild?O.call(t.childNodes):null,i,o?o.__e:t.firstChild,r,s),Pe(i,e,s)}function pt(e){function t(n){var r,o;return this.getChildContext||(r=new Set,(o={})[t.__c]=this,this.getChildContext=function(){return o},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(i){this.props.value!=i.value&&r.forEach(function(s){s.__e=!0,ve(s)})},this.sub=function(i){r.add(i);var s=i.componentWillUnmount;i.componentWillUnmount=function(){r&&r.delete(i),s&&s.call(i)}}),n.children}return t.__c="__cC"+Ne++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}O=De.slice,w={__e:function(e,t,n,r){for(var o,i,s;t=t.__;)if((o=t.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(e)),s=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,r||{}),s=o.__d),s)return o.__E=o}catch(h){e=h}throw e}},Ee=0,ce.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=W({},this.state),typeof e=="function"&&(e=e(W({},n),this.props)),e&&W(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),ve(this))},ce.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),ve(this))},ce.prototype.render=re,G=[],Te=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,$e=function(e,t){return e.__v.__b-t.__v.__b},le.__r=0,Ie=/(PointerCapture)$|Capture$/i,ge=0,fe=He(!1),me=He(!0),Ne=0;var vt=0;function c(e,t,n,r,o,i){t||(t={});var s,h,u=t;if("ref"in u)for(h in u={},t)h=="ref"?s=t[h]:u[h]=t[h];var l={type:e,props:u,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--vt,__i:-1,__u:0,__source:o,__self:i};if(typeof e=="function"&&(s=e.defaultProps))for(h in s)u[h]===void 0&&(u[h]=s[h]);return w.vnode&&w.vnode(l),l}var te,x,xe,We,ue=0,je=[],E=w,ze=E.__b,Qe=E.__r,Oe=E.diffed,Be=E.__c,Ve=E.unmount,Ke=E.__;function de(e,t){E.__h&&E.__h(x,e,ue||t),ue=0;var n=x.__H||(x.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function I(e){return ue=1,yt(Xe,e)}function yt(e,t,n){var r=de(te++,2);if(r.t=e,!r.__c&&(r.__=[Xe(void 0,t),function(h){var u=r.__N?r.__N[0]:r.__[0],l=r.t(u,h);u!==l&&(r.__N=[l,r.__[1]],r.__c.setState({}))}],r.__c=x,!x.__f)){var o=function(h,u,l){if(!r.__c.__H)return!0;var _=r.__c.__H.__.filter(function(g){return!!g.__c});if(_.every(function(g){return!g.__N}))return!i||i.call(this,h,u,l);var a=r.__c.props!==h;return _.forEach(function(g){if(g.__N){var d=g.__[0];g.__=g.__N,g.__N=void 0,d!==g.__[0]&&(a=!0)}}),i&&i.call(this,h,u,l)||a};x.__f=!0;var i=x.shouldComponentUpdate,s=x.componentWillUpdate;x.componentWillUpdate=function(h,u,l){if(this.__e){var _=i;i=void 0,o(h,u,l),i=_}s&&s.call(this,h,u,l)},x.shouldComponentUpdate=o}return r.__N||r.__}function Ge(e,t){var n=de(te++,3);!E.__s&&Ye(n.__H,t)&&(n.__=e,n.u=t,x.__H.__h.push(n))}function J(e){return ue=5,wt(function(){return{current:e}},[])}function wt(e,t){var n=de(te++,7);return Ye(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function bt(e){var t=x.context[e.__c],n=de(te++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(x)),t.props.value):e.__}function xt(){for(var e;e=je.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(_e),e.__H.__h.forEach(Se),e.__H.__h=[]}catch(t){e.__H.__h=[],E.__e(t,e.__v)}}E.__b=function(e){x=null,ze&&ze(e)},E.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Ke&&Ke(e,t)},E.__r=function(e){Qe&&Qe(e),te=0;var t=(x=e.__c).__H;t&&(xe===x?(t.__h=[],x.__h=[],t.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.forEach(_e),t.__h.forEach(Se),t.__h=[],te=0)),xe=x},E.diffed=function(e){Oe&&Oe(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(je.push(t)!==1&&We===E.requestAnimationFrame||((We=E.requestAnimationFrame)||St)(xt)),t.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),xe=x=null},E.__c=function(e,t){t.some(function(n){try{n.__h.forEach(_e),n.__h=n.__h.filter(function(r){return!r.__||Se(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],E.__e(r,n.__v)}}),Be&&Be(e,t)},E.unmount=function(e){Ve&&Ve(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(r){try{_e(r)}catch(o){t=o}}),n.__H=void 0,t&&E.__e(t,n.__v))};var Je=typeof requestAnimationFrame=="function";function St(e){var t,n=function(){clearTimeout(r),Je&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Je&&(t=requestAnimationFrame(n))}function _e(e){var t=x,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),x=t}function Se(e){var t=x;e.__c=e.__(),x=t}function Ye(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Xe(e,t){return typeof t=="function"?t(e):t}var ie=(e=>(e.TEXT="text",e.IMAGE="image",e.FILE="file",e.SYSTEM="system",e.TYPING="typing",e.CUSTOM="custom",e))(ie||{}),Y=(e=>(e.PENDING="pending",e.SENT="sent",e.DELIVERED="delivered",e.READ="read",e.FAILED="failed",e))(Y||{}),Ze=class{constructor(e){this.defaultLogger=(t,n,...r)=>{const o=new Date().toISOString(),i=this.config.prefix?`[${this.config.prefix}] [${o}] [${t.toUpperCase()}]`:`[ChatBot SDK ${o}] [${t.toUpperCase()}]`;switch(t){case"debug":console.debug(i,n,...r);break;case"info":console.info(i,n,...r);break;case"warn":console.warn(i,n,...r);break;case"error":console.error(i,n,...r);break}},this.config={enabled:e?.enabled??!0,level:e?.level??"info",customLogger:e?.customLogger??this.defaultLogger,prefix:e?.prefix??""}}shouldLog(e){if(!this.config.enabled)return!1;const t=["debug","info","warn","error"],n=t.indexOf(this.config.level);return t.indexOf(e)>=n}debug(e,...t){this.shouldLog("debug")&&this.config.customLogger("debug",e,...t)}info(e,...t){this.shouldLog("info")&&this.config.customLogger("info",e,...t)}warn(e,...t){this.shouldLog("warn")&&this.config.customLogger("warn",e,...t)}error(e,...t){this.shouldLog("error")&&this.config.customLogger("error",e,...t)}updateConfig(e){this.config={...this.config,...e}}},Ct=class{constructor(e){this.listeners={},this.eventHistory=[],this.maxHistorySize=100,this.logger=e}on(e,t){return this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t),this.logger.debug(`Event listener added for: ${e}`),()=>this.off(e,t)}onAny(e){return this.listeners["*"]||(this.listeners["*"]=new Set),this.listeners["*"].add(e),this.logger.debug("Wildcard event listener added"),()=>this.offAny(e)}once(e,t){const n=r=>{t(r),this.off(e,n)};return this.on(e,n)}off(e,t){const n=this.listeners[e];n&&(n.delete(t),n.size===0&&delete this.listeners[e],this.logger.debug(`Event listener removed for: ${e}`))}offAny(e){const t=this.listeners["*"];t&&(t.delete(e),t.size===0&&delete this.listeners["*"],this.logger.debug("Wildcard event listener removed"))}emit(e,t){const n={type:e,data:t};this.eventHistory.push(n),this.eventHistory.length>this.maxHistorySize&&this.eventHistory.shift(),this.logger.debug(`Event emitted: ${e}`,t);const r=this.listeners[e];r&&r.forEach(i=>{try{i(t)}catch(s){this.logger.error(`Error in event listener for ${e}:`,s)}});const o=this.listeners["*"];o&&o.forEach(i=>{try{i(n)}catch(s){this.logger.error("Error in wildcard event listener:",s)}})}removeAllListeners(e){e?(delete this.listeners[e],this.logger.debug(`All listeners removed for: ${e}`)):(this.listeners={},this.logger.debug("All event listeners removed"))}getEventHistory(){return[...this.eventHistory]}clearEventHistory(){this.eventHistory=[],this.logger.debug("Event history cleared")}listenerCount(e){return this.listeners[e]?.size??0}},Et=class{constructor(e={},t){this.currentAttempt=0,this.config={enabled:e.enabled??!0,maxAttempts:e.maxAttempts??1/0,baseDelay:e.baseDelay??1e3,maxDelay:e.maxDelay??1e4,jitter:e.jitter??.3},this.logger=t}shouldReconnect(){return this.config.enabled?this.currentAttempt>=this.config.maxAttempts?(this.logger.warn(`Max reconnection attempts (${this.config.maxAttempts}) reached`),!1):!0:(this.logger.debug("Reconnection is disabled"),!1)}getNextDelay(){const e=this.config.baseDelay*Math.pow(2,this.currentAttempt),t=Math.min(e,this.config.maxDelay),n=t*this.config.jitter,r=(Math.random()*2-1)*n,o=Math.max(0,t+r);return this.logger.debug(`Reconnection delay calculated: ${o.toFixed(0)}ms (attempt ${this.currentAttempt+1})`),o}incrementAttempt(){this.currentAttempt++,this.logger.info(`Reconnection attempt ${this.currentAttempt}/${this.config.maxAttempts}`)}reset(){this.logger.debug("Reconnection strategy reset"),this.currentAttempt=0}getCurrentAttempt(){return this.currentAttempt}updateConfig(e){this.config={...this.config,...e},this.logger.debug("Reconnection config updated",this.config)}},kt=class{constructor(e){this.queue=[],this.maxQueueSize=1e3,this.defaultMaxRetries=3,this.logger=e}enqueue(e,t=this.defaultMaxRetries){this.queue.length>=this.maxQueueSize&&(this.logger.warn("Message queue is full, removing oldest message"),this.queue.shift());const n={message:e,timestamp:Date.now(),retries:0,maxRetries:t};this.queue.push(n),this.logger.debug(`Message queued: ${e.id} (queue size: ${this.queue.length})`)}dequeueAll(){const e=this.queue.map(t=>t.message);return this.queue=[],this.logger.info(`Dequeued ${e.length} messages`),e}getRetryableMessages(){return this.queue.filter(t=>t.retries<t.maxRetries).map(t=>t.message)}markAsFailed(e){const t=this.queue.findIndex(n=>n.message.id===e);t!==-1&&(this.queue[t].retries++,this.queue[t].retries>=this.queue[t].maxRetries?(this.logger.warn(`Message ${e} exceeded max retries, removing from queue`),this.queue.splice(t,1)):this.logger.debug(`Message ${e} retry count: ${this.queue[t].retries}/${this.queue[t].maxRetries}`))}remove(e){const t=this.queue.findIndex(n=>n.message.id===e);t!==-1&&(this.queue.splice(t,1),this.logger.debug(`Message ${e} removed from queue`))}clear(){const e=this.queue.length;this.queue=[],this.logger.info(`Message queue cleared (${e} messages removed)`)}size(){return this.queue.length}isEmpty(){return this.queue.length===0}peek(){return this.queue.map(e=>e.message)}setMaxQueueSize(e){if(e<1)throw new Error("Max queue size must be at least 1");for(this.maxQueueSize=e,this.logger.debug(`Max queue size set to ${e}`);this.queue.length>this.maxQueueSize;)this.queue.shift()}},Tt=class{constructor(e,t,n,r){this.ws=null,this.eventQueue=[],this.connectionState="disconnected",this.lastEmittedState="disconnected",this.reconnectTimer=null,this.heartbeatTimer=null,this.connectionTimeoutTimer=null,this.stateChangeTimer=null,this.pendingAcks=new Map,this.config=e,this.logger=n,this.eventEmitter=r,this.reconnectionStrategy=new Et(t,n),this.messageQueue=new kt(n)}updateConfig(e){this.config=e}async connect(e){if(this.ws?.readyState===WebSocket.OPEN){this.logger.warn("WebSocket is already connected");return}if(this.ws?.readyState===WebSocket.CONNECTING){this.logger.warn("WebSocket is already connecting");return}return this.updateConnectionState("connecting"),this.updateConnectionState("connecting"),new Promise((t,n)=>{try{e&&(this.username=e);let r=this.config.url;if(this.username){const o=r.includes("?")?"&":"?";r=`${r}${o}username=${encodeURIComponent(this.username)}`}this.ws=new WebSocket(r,this.config.protocols),this.setupEventHandlers(t,n),this.setupConnectionTimeout(n)}catch(r){this.logger.error("Failed to create WebSocket connection:",r),this.handleConnectionError(r),n(r)}})}disconnect(){this.logger.info("Disconnecting WebSocket"),this.updateConnectionState("disconnecting"),this.clearTimers(),this.reconnectionStrategy.reset(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.updateConnectionState("disconnected")}async sendEvent(e,t){if(this.connectionState!=="connected"){this.logger.warn("WebSocket not connected, queuing event"),this.eventQueue.push({event:e,data:t});return}try{const n=JSON.stringify({event:e,data:t});this.ws?.send(n),this.logger.debug(`Event sent: ${e}`,t)}catch(n){throw this.logger.error(`Failed to send event ${e}:`,n),n}}async send(e,t=!0,n=5e3){if(this.connectionState!=="connected"){this.logger.warn("WebSocket not connected, queuing message"),this.messageQueue.enqueue(e);return}try{const r={roomId:e.metadata?.roomId||"general",message:e.content,username:e.sender==="user"?e.metadata?.username:void 0};return await this.sendEvent("sendMessage",r),this.eventEmitter.emit("messageSent",{message:e,timestamp:Date.now()}),{ackId:"simulated_"+Date.now(),messageId:e.id,status:"received",timestamp:Date.now()}}catch(r){throw this.logger.error("Failed to send message:",r),this.messageQueue.enqueue(e),r}}async joinRoom(e){this.currentRoom=e,this.logger.info(`Joining room: ${e}`),await this.sendEvent("joinRoom",{roomId:e})}async leaveRoom(e){await this.sendEvent("leaveRoom",{roomId:e})}async getRoomInfo(e){await this.sendEvent("getRoomInfo",{roomId:e})}async sendJoinConversation(e){this.logger.info(`Joining conversation stream: ${e}`),await this.sendEvent("joinConversation",{conversationId:e})}async sendLeaveConversation(e){this.logger.info(`Leaving conversation stream: ${e}`),await this.sendEvent("leaveConversation",{conversationId:e})}getConnectionState(){return this.connectionState}isConnected(){return this.connectionState==="connected"}getMessageQueue(){return this.messageQueue}setupEventHandlers(e,t){this.ws&&(this.ws.onopen=()=>{this.logger.info("WebSocket connected"),this.clearConnectionTimeout(),this.updateConnectionState("connected"),this.reconnectionStrategy.reset(),this.startHeartbeat(),this.reconnectionStrategy.reset(),this.startHeartbeat(),this.currentRoom&&(this.logger.info(`Re-joining room: ${this.currentRoom}`),this.sendEvent("joinRoom",{roomId:this.currentRoom}).catch(n=>{this.logger.error(`Failed to re-join room ${this.currentRoom}:`,n)})),this.flushMessageQueue(),e&&e()},this.ws.onmessage=n=>{this.handleMessage(n.data)},this.ws.onerror=n=>{this.logger.error("WebSocket error:",n);const r=new Error("WebSocket error");this.eventEmitter.emit("error",{error:r,timestamp:Date.now(),context:"websocket"}),this.connectionState==="connecting"&&t&&t(r)},this.ws.onclose=n=>{this.logger.info(`WebSocket closed: ${n.code} - ${n.reason}`),this.stopHeartbeat(),this.updateConnectionState("disconnected"),n.code!==1e3&&this.reconnectionStrategy.shouldReconnect()&&this.attemptReconnection()})}handleMessage(e){try{const t=JSON.parse(e),{event:n,data:r}=t;switch(this.logger.debug(`Received event: ${n}`,r),n){case"pong":this.logger.debug("Heartbeat pong received");break;case"newMessage":const o={id:`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"text",content:r.message,sender:"user",timestamp:new Date(r.timestamp).getTime(),status:"delivered",metadata:{roomId:r.roomId,username:r.username}};this.eventEmitter.emit("message",{message:o,timestamp:Date.now()});break;case"joinedRoom":this.eventEmitter.emit("joinedRoom",r);break;case"userJoined":this.eventEmitter.emit("userJoined",r);break;case"leftRoom":this.eventEmitter.emit("leftRoom",r);break;case"userLeft":this.eventEmitter.emit("userLeft",r);break;case"roomInfo":this.eventEmitter.emit("roomInfo",r);break;case"error":this.eventEmitter.emit("error",{error:new Error(r.message),timestamp:Date.now(),context:"server_error"});break;case"agentEvent":this.eventEmitter.emit("agentEvent",{...r,conversationId:t.conversationId});break;default:this.logger.warn(`Unknown event received: ${n}`)}}catch(t){this.logger.error("Failed to parse message:",t),this.eventEmitter.emit("error",{error:t,timestamp:Date.now(),context:"message_parsing"})}}startHeartbeat(){const e=this.config.heartbeatInterval??3e4;this.heartbeatTimer=setInterval(()=>{if(this.ws?.readyState===WebSocket.OPEN)try{this.sendEvent("ping",{}),this.logger.debug("Heartbeat ping sent")}catch(t){this.logger.error("Failed to send heartbeat:",t)}},e),this.logger.debug(`Heartbeat started with interval: ${e}ms`)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.logger.debug("Heartbeat stopped"))}setupConnectionTimeout(e){const t=this.config.connectionTimeout??1e4;this.connectionTimeoutTimer=setTimeout(()=>{if(this.connectionState==="connecting"){this.logger.error("Connection timeout"),this.ws?.close();const n=new Error("Connection timeout");this.handleConnectionError(n),e&&e(n)}},t)}clearConnectionTimeout(){this.connectionTimeoutTimer&&(clearTimeout(this.connectionTimeoutTimer),this.connectionTimeoutTimer=null)}attemptReconnection(){if(!this.reconnectionStrategy.shouldReconnect()){this.logger.error("Reconnection failed: max attempts reached"),this.updateConnectionState("failed"),this.eventEmitter.emit("reconnectFailed",{state:"failed",timestamp:Date.now(),attempt:this.reconnectionStrategy.getCurrentAttempt()});return}this.updateConnectionState("reconnecting"),this.reconnectionStrategy.incrementAttempt();const e=this.reconnectionStrategy.getNextDelay();this.eventEmitter.emit("reconnecting",{state:"reconnecting",timestamp:Date.now(),attempt:this.reconnectionStrategy.getCurrentAttempt()}),this.reconnectTimer=setTimeout(()=>{this.logger.info("Attempting to reconnect..."),this.connect().catch(t=>{this.logger.error("Reconnection attempt failed:",t)})},e)}handleConnectionError(e){this.eventEmitter.emit("error",{error:e,timestamp:Date.now(),context:"connection"}),this.reconnectionStrategy.shouldReconnect()?this.attemptReconnection():this.updateConnectionState("failed")}flushMessageQueue(){if(this.eventQueue.length>0){this.logger.info(`Flushing ${this.eventQueue.length} queued events`);const t=[...this.eventQueue];this.eventQueue=[],t.forEach(({event:n,data:r})=>{this.sendEvent(n,r).catch(o=>{this.logger.error(`Failed to send queued event ${n}:`,o)})})}const e=this.messageQueue.dequeueAll();e.length>0&&(this.logger.info(`Flushing ${e.length} queued messages`),e.forEach(t=>{this.send(t,!1).catch(n=>{this.logger.error(`Failed to send queued message ${t.id}:`,n),this.messageQueue.markAsFailed(t.id)})}))}updateConnectionState(e){const t=this.connectionState;this.connectionState=e,t!==e&&this.logger.info(`Connection state changed: ${t} -> ${e}`);const n=this.config.disconnectGracePeriod??0;e==="connected"?(this.stateChangeTimer&&(clearTimeout(this.stateChangeTimer),this.stateChangeTimer=null,this.logger.debug("Reconnected within grace period, suppressing disconnection event")),this.lastEmittedState!=="connected"&&this.emitConnectionChange(e)):this.lastEmittedState==="connected"&&n>0?this.stateChangeTimer||(this.logger.debug(`Starting disconnection grace period (${n}ms)`),this.stateChangeTimer=setTimeout(()=>{this.stateChangeTimer=null,this.emitConnectionChange(this.connectionState)},n)):this.emitConnectionChange(e)}emitConnectionChange(e){this.lastEmittedState!==e&&(this.lastEmittedState=e,this.eventEmitter.emit("connection",{state:e,timestamp:Date.now()}))}clearTimers(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.connectionTimeoutTimer&&(clearTimeout(this.connectionTimeoutTimer),this.connectionTimeoutTimer=null),this.pendingAcks.forEach(e=>{clearTimeout(e.timeout),e.reject(new Error("Connection closed"))}),this.pendingAcks.clear()}},et=()=>{const e="echo_device_hash";try{let t=localStorage.getItem(e);return t||(t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=Math.random()*16|0;return(n==="x"?r:r&3|8).toString(16)}),localStorage.setItem(e,t)),t}catch{return"unknown-device-"+Date.now()}},tt=class{constructor(e={},t){this.config={retries:3,backoff:1e3,...e},this.logger=t}async get(e,t={}){return this.request(e,{method:"GET",headers:t})}async post(e,t,n={}){return this.request(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(t)})}async request(e,t,n=0){const r={...this.config.headers,...t.headers};try{const o=await fetch(e,{...t,headers:r});if(!o.ok){if(o.status>=500&&n<(this.config.retries??3))return this.logger?.warn(`Request failed with status ${o.status}. Retrying... (${n+1}/${this.config.retries})`),await this.delay(this.getErrorDelay(n)),this.request(e,t,n+1);const i=await o.text();throw new Error(`HTTP Error ${o.status}: ${i}`)}return o.json()}catch(o){if(n<(this.config.retries??3))return this.logger?.warn(`Request failed with error: ${o}. Retrying... (${n+1}/${this.config.retries})`),await this.delay(this.getErrorDelay(n)),this.request(e,t,n+1);throw o}}getErrorDelay(e){return(this.config.backoff??1e3)*Math.pow(2,e)}delay(e){return new Promise(t=>setTimeout(t,e))}};class $t{constructor(t="http://localhost:3000"){this.baseUrl=t,this.client=new tt({retries:3,backoff:1e3},new Ze({prefix:"ConfigService"}))}async fetchConfig(t,n,r){const o=`${this.baseUrl}/${t}/api/v1/client/configuration`,i={"x-api-key":n};r&&(i["x-external-id"]=r);try{const s=await this.client.get(o,i);if(s.success&&s.data)return s.data.finger_print&&localStorage.setItem("echo_finger_print",s.data.finger_print),s.data;throw new Error("Invalid configuration response")}catch(s){throw console.error("Failed to fetch configuration:",s),s}}}class It{constructor(t="http://localhost:3000"){this.baseUrl=t,this.httpClient=new tt({})}async getConversations(t,n,r){const o={"x-api-key":n};r&&(o["x-external-id"]=r);const i=`${this.baseUrl}/${t}/api/v1/client/conversations`;try{return(await this.httpClient.get(i,o)).data}catch(s){throw console.error("Failed to get conversations",s),s}}async createConversation(t,n,r,o,i){const s={"x-api-key":n,"Content-Type":"application/json"};o&&(s["x-external-id"]=o),i&&(s["x-device-hash"]=i);const h=`${this.baseUrl}/${t}/api/v1/client/conversations/new`,u={prompt:r};try{return(await this.httpClient.post(h,u,s)).data}catch(l){throw console.error("Failed to create conversation",l),l}}async getMessages(t,n,r,o){const i={"x-api-key":n};o&&(i["x-external-id"]=o);const s=`${this.baseUrl}/${t}/api/v1/client/conversations/${r}/messages`;try{return(await this.httpClient.get(s,i)).data}catch(h){throw console.error("Failed to get messages",h),h}}}const nt=5e3,rt=pt(null),Nt=({children:e,sdkConfig:t})=>{const[n,r]=I(!1),[o,i]=I("disconnected"),[s,h]=I(!1),[u,l]=I(!0),[_,a]=I(null),[g,d]=I([]),[C,N]=I([]),[b,p]=I(null),[m,A]=I(null),[P,M]=I(!1),[L,j]=I(null),[B,F]=I({}),k=J(null),v=J(null),q=J(null),X=J(new Map),V=J(null);if(v.current||(v.current=new Ze({prefix:"EchoSDK"})),!q.current){const f="http://localhost:3000";q.current=new It(f)}Ge(()=>{const f=async()=>{l(!0),a(null);try{const D=await new $t().fetchConfig(t.companyUrl,t.apiKey,t.externalId);A(D);const H=await q.current.getConversations(t.companyUrl,t.apiKey,t.externalId);N(H),h(!0),await Bt(D,t)}catch(S){v.current?.error("Initialization failed:",S),a(S.message||"Failed to initialize SDK")}finally{l(!1)}};return t.apiKey&&t.companyUrl?f():(a("Missing required configuration (apiKey or companyUrl)"),l(!1)),()=>{k.current?.disconnect()}},[t.apiKey,t.companyUrl,t.externalId]);const Bt=async(f,S)=>{const D=f.finger_print||localStorage.getItem("echo_finger_print")||et(),H="ws://localhost:3000",T=new URLSearchParams;T.append("api_key",S.apiKey),T.append("device_hash",D),S.externalId&&T.append("external_id",S.externalId),S.authToken&&T.append("x-auth-token",S.authToken);const Z=`${H}?${T.toString()}`,U=new Ct(v.current),Ce={url:Z,heartbeatInterval:3e4,connectionTimeout:1e4},z={maxAttempts:1/0,baseDelay:1e3,maxDelay:3e4},oe=new Tt(Ce,z,v.current,U);k.current=oe,U.on("connection",y=>{r(y.state==="connected"),i(y.state),console.log("connection triggered custom",y.state,V.current),y.state==="connected"&&V.current&&(v.current?.info(`Reconnected. Re-joining conversation: ${V.current}`),setTimeout(()=>{V.current&&oe.sendJoinConversation(V.current)},1e3))}),U.on("message",y=>{d($=>{if($.some(Q=>Q.id===y.message.id))return $;if(y.message.sender==="user"){const Q=$.findIndex(R=>R.sender==="user"&&R.status===Y.PENDING&&R.content===y.message.content);if(Q!==-1){const R=[...$];return R[Q]=y.message,R}}return[...$,y.message]})}),U.on("messageSent",y=>{d($=>{if($.some(R=>R.id===y.message.id))return $;const Q=$.findIndex(R=>R.sender==="user"&&R.status===Y.PENDING&&R.content===y.message.content);if(Q!==-1){const R=[...$];return R[Q]=y.message,R}return[...$,y.message]})}),U.on("agentEvent",y=>{if(y.type==="first_response")M(!0),j(y.runId),F($=>({...$,[y.runId]:[]}));else if(["thought","action_start","action_end"].includes(y.type))M(!0),j($=>$||y.runId),F($=>({...$,[y.runId]:[...$[y.runId]||[],y]}));else if(y.type==="final_response"&&(M(!1),j(null),y.content)){const $={id:y.messageId||Date.now().toString(),content:y.content,sender:"bot",type:ie.TEXT,status:Y.DELIVERED,timestamp:Date.now(),metadata:{roomId:y.conversationId,runId:y.runId}};d(Q=>[...Q,$])}}),await oe.connect()},lt=async f=>{const S=b;if(X.current.has(f)&&(clearTimeout(X.current.get(f)),X.current.delete(f),v.current?.info(`Cancelled pending leave for conversation: ${f}`)),S&&S!==f){const D=setTimeout(()=>{k.current&&k.current.sendLeaveConversation(S).catch(H=>v.current?.error(`Failed to leave conversation ${S}`,H)),X.current.delete(S)},nt);X.current.set(S,D)}l(!0);try{const H=(await q.current.getMessages(t.companyUrl,t.apiKey,f,t.externalId)).map(T=>({id:T.id,content:T.content,sender:T.role==="user"?"user":"bot",type:ie.TEXT,status:Y.DELIVERED,timestamp:new Date(T.created_at).getTime(),metadata:{roomId:f}}));d(T=>{const Z=T.filter(z=>z.metadata?.roomId===f),U=new Set(H.map(z=>z.id)),Ce=Z.filter(z=>!U.has(z.id));return[...H,...Ce].sort((z,oe)=>z.timestamp-oe.timestamp)}),p(f),V.current=f,k.current&&await k.current.sendJoinConversation(f)}catch(D){v.current?.error("Failed to load conversation",D)}finally{l(!1)}},Vt=()=>{const f=b;if(f){const S=setTimeout(()=>{k.current&&k.current.sendLeaveConversation(f).catch(D=>v.current?.error(`Failed to leave conversation ${f}`,D)),X.current.delete(f)},nt);X.current.set(f,S)}p(null),V.current=null,d([]),M(!1),j(null),F({})},ht=async f=>{const S=Date.now().toString(),D={id:S,content:f,sender:"user",type:ie.TEXT,status:Y.PENDING,timestamp:Date.now(),metadata:{}};d([D]),M(!0);try{const H=m?.finger_print||localStorage.getItem("echo_finger_print")||et(),T=await q.current?.createConversation(t.companyUrl,t.apiKey,f,t.externalId,H);if(!T)throw new Error("Failed to create conversation");N(Z=>[T,...Z]),p(T.id),V.current=T.id,d(Z=>Z.filter(U=>U.id===S||U.metadata?.roomId===T.id)),k.current&&await k.current.sendJoinConversation(T.id),await lt(T.id)}catch(H){v.current?.error("Failed to create conversation",H),a("Failed to start new conversation")}finally{l(!1)}},Kt=async f=>{if(!b){await ht(f);return}if(!k.current)return;const S={id:Date.now().toString(),content:f,sender:"user",type:ie.TEXT,status:Y.PENDING,timestamp:Date.now(),metadata:{roomId:b}};d(D=>[...D,S]),await k.current.sendEvent("sendMessage",{conversationId:b,message:f})};return c(rt.Provider,{value:{isConnected:n,connectionState:o,isInitialized:s,isLoading:u,error:_,config:m,messages:g,conversations:C,activeConversationId:b,isStreaming:P,activeRunId:L,streamedThoughts:B,sendMessage:Kt,joinRoom:async f=>{await k.current?.joinRoom(f)},leaveRoom:async f=>{await k.current?.leaveRoom(f)},loadConversation:lt,createNewChat:Vt,startNewConversation:ht},children:e})},it=()=>{const e=bt(rt);if(!e)throw new Error("useChat must be used within a ChatProvider");return e},Dt=()=>c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[c("circle",{cx:"12",cy:"12",r:"1"}),c("circle",{cx:"19",cy:"12",r:"1"}),c("circle",{cx:"5",cy:"12",r:"1"})]}),ot=({size:e=20})=>c("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[c("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),Rt=()=>c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[c("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),c("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),At=()=>c("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:c("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),Mt=()=>c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[c("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),c("polyline",{points:"14 2 14 8 20 8"}),c("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),c("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]}),qt=()=>c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[c("circle",{cx:"12",cy:"12",r:"10"}),c("path",{d:"M8 14s1.5 2 4 2 4-2 4-2"}),c("line",{x1:"9",y1:"9",x2:"9.01",y2:"9"}),c("line",{x1:"15",y1:"9",x2:"15.01",y2:"9"})]}),Ht=()=>c("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[c("line",{x1:"19",y1:"12",x2:"5",y2:"12"}),c("polyline",{points:"12 19 5 12 12 5"})]}),Pt=({title:e="Annie Smith",greeting:t,connectionStatus:n="connected",onToggleSidebar:r,onCloseChat:o,showBackButton:i,onBack:s})=>c("div",{class:"echo-header",children:[i&&c("button",{className:"echo-back-btn",onClick:s,style:"background: none; border: none; color: white; cursor: pointer; opacity: 0.9; padding: 4px; margin-right: 2px;",children:c(Ht,{})}),c("div",{class:"echo-avatar",children:[c("img",{src:"https://api.dicebear.com/7.x/avataaars/svg?seed=Annie",alt:"Avatar",style:"width: 100%; height: 100%; border-radius: 50%;"}),c("div",{style:{position:"absolute",bottom:"0",right:"0",width:"10px",height:"10px",borderRadius:"50%",backgroundColor:(u=>{switch(u){case"connected":return"#10b981";case"reconnecting":return"#f59e0b";case"disconnected":return"#ef4444";default:return"#9ca3af"}})(n),border:"2px solid white"},title:n})]}),c("div",{class:"echo-header-info",children:[c("h3",{class:"echo-header-title",children:e}),!i&&c("p",{class:"echo-header-subtitle",children:t||"We typically reply in a few minute"})]}),c("button",{class:"echo-menu-btn",onClick:r,style:"background: none; border: none; color: white; cursor: pointer; opacity: 0.8; padding: 4px;",children:c(Dt,{})}),c("button",{class:"echo-close-btn",onClick:o,style:"background: none; border: none; color: white; cursor: pointer; opacity: 0.8; margin-left: 8px;",children:c(ot,{})})]}),st=({events:e,isExpanded:t=!1})=>{const[n,r]=I(t);return e.length===0?null:c("div",{className:"echo-thought-chain",children:[c("div",{className:"echo-thought-header",onClick:()=>r(!n),role:"button",tabIndex:0,children:[c("span",{className:"echo-thought-icon",children:"🧠"}),c("span",{className:"echo-thought-title",children:["Thinking Process (",e.length," steps)"]}),c("span",{className:`echo-thought-chevron ${n?"expanded":""}`,children:"▼"})]}),n&&c("div",{className:"echo-thought-content",children:e.map((o,i)=>c("div",{className:`echo-thought-item ${o.type}`,children:[c("div",{className:"echo-thought-type",children:Lt(o.type)}),c("div",{className:"echo-thought-text",children:o.content})]},i))})]})},Lt=e=>{switch(e){case"action_start":return"Starting Action";case"action_end":return"Action Completed";case"thought":return"Reasoning";case"error":return"Error";case"first_response":return"Started";default:return e}},Ft=({messages:e,isStreaming:t,activeRunId:n,streamedThoughts:r})=>{const o=J(null),i=J(null);return Ge(()=>{i.current&&i.current.scrollIntoView({behavior:"smooth"})},[e,t,r]),c("div",{className:"echo-message-list",ref:o,children:[e.map(s=>c("div",{className:`echo-message ${s.sender==="user"?"user":"bot"}`,children:[c("div",{className:"echo-message-content",children:s.type==="text"?s.content:c("img",{src:s.content,alt:"sent image",className:"echo-message-image"})}),c("div",{className:"echo-message-time",children:new Date(s.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),s.metadata?.runId&&r[s.metadata.runId]&&c(st,{events:r[s.metadata.runId],isExpanded:!1})]},s.id)),t&&c("div",{className:"echo-message bot echo-streaming-container",children:[n&&c(st,{events:r[n]||[],isExpanded:!1}),c("div",{className:"echo-typing-indicator",children:[c("span",{children:"."}),c("span",{children:"."}),c("span",{children:"."})]})]}),c("div",{ref:i})]})},Ut=({onSendMessage:e,isLoading:t})=>{const[n,r]=I(""),o=()=>{n.trim()&&!t&&(e(n.trim()),r(""))};return c("div",{class:"echo-input-area",children:[c("input",{type:"text",class:"echo-input",placeholder:"Type a Message...",value:n,onInput:s=>r(s.currentTarget.value),onKeyPress:s=>{s.key==="Enter"&&!t&&o()},disabled:t}),c("div",{style:"display: flex; gap: 8px; align-items: center;",children:[c("button",{style:"background: none; border: none; cursor: pointer; color: #9ca3af; padding: 4px;",disabled:t,children:c(Mt,{})}),c("button",{style:"background: none; border: none; cursor: pointer; color: #9ca3af; padding: 4px;",disabled:t,children:c(qt,{})}),c("button",{class:"echo-send-btn",onClick:o,disabled:!n.trim()||t,children:c(Rt,{})})]})]})},Wt=({conversations:e,activeConversationId:t,onSelectConversation:n,onNewChat:r,isOpen:o})=>o?c("div",{className:"echo-sidebar",children:[c("div",{className:"echo-sidebar-header",children:c("button",{className:"echo-new-chat-btn",onClick:r,children:"+ New Chat"})}),c("div",{className:"echo-conversation-list",children:e.map(i=>c("div",{className:`echo-conversation-item ${t===i.id?"active":""}`,onClick:()=>n(i.id),role:"button",tabIndex:0,children:[c("div",{className:"echo-conversation-summary",children:i.summary||"New Conversation"}),c("div",{className:"echo-conversation-date",children:(()=>{const s=new Date(i.updated_at||i.created_at),h=new Date;return s.getDate()===h.getDate()&&s.getMonth()===h.getMonth()&&s.getFullYear()===h.getFullYear()?s.toLocaleTimeString([],{year:"2-digit",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):s.toLocaleDateString()})()})]},i.id))})]}):null,jt=({config:e,onQuerySelect:t})=>{if(!e)return null;const{display_name:n,example_queries:r}=e,o=r?r.slice(0,3):[];return c("div",{className:"echo-home-view",children:[n&&c("h2",{className:"echo-home-greeting",children:["Hi ",n," 👋"]}),o.length>0&&c("div",{className:"echo-query-list",children:o.map((i,s)=>c("button",{className:"echo-query-chip",onClick:()=>t(i),children:i},s))})]})},zt=({isOpen:e,onClose:t,title:n})=>{const{messages:r,sendMessage:o,config:i,connectionState:s,conversations:h,activeConversationId:u,loadConversation:l,createNewChat:_,startNewConversation:a,isStreaming:g,activeRunId:d,streamedThoughts:C,isInitialized:N,isLoading:b,error:p}=it(),[m,A]=I(!1),P=async v=>{await o(v)},M=async v=>{await l(v),A(!1)},L=()=>{_(),A(!1)},j=v=>{a(v)},B=N&&!b&&r.length===0,k=h.find(v=>v.id===u)?.summary||n||i?.brand_name||"Support";return c("div",{className:`echo-chat-window ${e?"open":""}`,children:[c(Pt,{title:k,greeting:i?.greeting_message,connectionStatus:s,onToggleSidebar:()=>A(!m),onCloseChat:t,showBackButton:!!u,onBack:L}),c("div",{className:"echo-chat-body-container",children:[c("div",{className:`echo-sidebar-container ${m?"open":""}`,children:c(Wt,{conversations:h,activeConversationId:u||void 0,onSelectConversation:M,onNewChat:L,isOpen:m})}),c("div",{className:"echo-chat-main",children:[p?c("div",{className:"echo-error-message",children:[p,c("button",{onClick:()=>window.location.reload(),children:"Retry"})]}):c(re,{children:B?c(jt,{config:i,onQuerySelect:j}):c(Ft,{messages:r,isStreaming:g,activeRunId:d||void 0,streamedThoughts:C})}),c(Ut,{onSendMessage:P,isLoading:b||g})]})]})]})},Qt=({isOpen:e,onClick:t})=>c("button",{class:"echo-launcher",onClick:t,children:e?c(ot,{size:24}):c(At,{})}),Ot=({config:e})=>{const[t,n]=I(!1),{config:r,isLoading:o,error:i,isInitialized:s}=it();if(i)return r?.environment==="dev"?c("div",{className:"echo-error-toast",style:{position:"fixed",bottom:"20px",right:"20px",background:"red",color:"white",padding:"10px",borderRadius:"5px",zIndex:1e4},children:["Error: ",i]}):null;if(!s&&o)return null;const h=e.bgColor||r?.primary_color||"#0165d2",u={"--echo-primary":h,"--echo-primary-gradient":`linear-gradient(135deg, ${h} 0%, ${h} 100%)`,"--echo-background":"#ffffff","--echo-foreground":"#000000"};return e.width&&(u.width=e.width),e.height&&(u.height=e.height),c("div",{className:`echo-chat-container ${e.position||"bottom-right"}`,style:u,children:[c(zt,{isOpen:t,onClose:()=>n(!1),title:r?.brand_name||"Support"}),c(Qt,{isOpen:t,onClick:()=>n(!t)})]})},at=e=>c(Nt,{sdkConfig:e,children:c(Ot,{config:e})});function ct(e,t){const n=document.createElement("div");return e.appendChild(n),Ue(c(at,{...t}),n),{destroy:()=>{Ue(null,n),n.remove()}}}typeof window<"u"&&(window.mountChatPopup=ct),K.ChatPopup=at,K.mountChatPopup=ct,Object.defineProperty(K,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(K,O){typeof exports=="object"&&typeof module<"u"?O(exports):typeof define=="function"&&define.amd?define(["exports"],O):(K=typeof globalThis<"u"?globalThis:K||self,O(K.EchoView={}))})(this,(function(K){"use strict";var O,w,Ee,G,ke,Te,$e,Ie,ge,fe,me,Ne,ne={},De=[],ut=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,se=Array.isArray;function W(e,t){for(var n in t)e[n]=t[n];return e}function pe(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function dt(e,t,n){var r,o,i,s={};for(i in t)i=="key"?r=t[i]:i=="ref"?o=t[i]:s[i]=t[i];if(arguments.length>2&&(s.children=arguments.length>3?O.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)s[i]===void 0&&(s[i]=e.defaultProps[i]);return ae(e,s,r,o,null)}function ae(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++Ee,__i:-1,__u:0};return o==null&&w.vnode!=null&&w.vnode(i),i}function re(e){return e.children}function ce(e,t){this.props=e,this.context=t}function ee(e,t){if(t==null)return e.__?ee(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?ee(e):null}function Re(e){var t,n;if((e=e.__)!=null&&e.__c!=null){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null){e.__e=e.__c.base=n.__e;break}return Re(e)}}function ve(e){(!e.__d&&(e.__d=!0)&&G.push(e)&&!le.__r++||ke!=w.debounceRendering)&&((ke=w.debounceRendering)||Te)(le)}function le(){for(var e,t,n,r,o,i,s,h=1;G.length;)G.length>h&&G.sort($e),e=G.shift(),h=G.length,e.__d&&(n=void 0,r=void 0,o=(r=(t=e).__v).__e,i=[],s=[],t.__P&&((n=W({},r)).__v=r.__v+1,w.vnode&&w.vnode(n),ye(t.__P,n,r,t.__n,t.__P.namespaceURI,32&r.__u?[o]:null,i,o??ee(r),!!(32&r.__u),s),n.__v=r.__v,n.__.__k[n.__i]=n,Pe(i,n,s),r.__e=r.__=null,n.__e!=o&&Re(n)));le.__r=0}function Ae(e,t,n,r,o,i,s,h,u,l,_){var a,g,d,C,N,b,p,m=r&&r.__k||De,A=t.length;for(u=_t(n,t,m,u,A),a=0;a<A;a++)(d=n.__k[a])!=null&&(g=d.__i==-1?ne:m[d.__i]||ne,d.__i=a,b=ye(e,d,g,o,i,s,h,u,l,_),C=d.__e,d.ref&&g.ref!=d.ref&&(g.ref&&be(g.ref,null,d),_.push(d.ref,d.__c||C,d)),N==null&&C!=null&&(N=C),(p=!!(4&d.__u))||g.__k===d.__k?u=Me(d,u,e,p):typeof d.type=="function"&&b!==void 0?u=b:C&&(u=C.nextSibling),d.__u&=-7);return n.__e=N,u}function _t(e,t,n,r,o){var i,s,h,u,l,_=n.length,a=_,g=0;for(e.__k=new Array(o),i=0;i<o;i++)(s=t[i])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[i]=ae(null,s,null,null,null):se(s)?s=e.__k[i]=ae(re,{children:s},null,null,null):s.constructor==null&&s.__b>0?s=e.__k[i]=ae(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,u=i+g,s.__=e,s.__b=e.__b+1,(l=s.__i=gt(s,n,u,a))!=-1&&(a--,(h=n[l])&&(h.__u|=2)),h==null||h.__v==null?(l==-1&&(o>_?g--:o<_&&g++),typeof s.type!="function"&&(s.__u|=4)):l!=u&&(l==u-1?g--:l==u+1?g++:(l>u?g--:g++,s.__u|=4))):e.__k[i]=null;if(a)for(i=0;i<_;i++)(h=n[i])!=null&&(2&h.__u)==0&&(h.__e==r&&(r=ee(h)),Fe(h,h));return r}function Me(e,t,n,r){var o,i;if(typeof e.type=="function"){for(o=e.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=e,t=Me(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=ee(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function gt(e,t,n,r){var o,i,s,h=e.key,u=e.type,l=t[n],_=l!=null&&(2&l.__u)==0;if(l===null&&h==null||_&&h==l.key&&u==l.type)return n;if(r>(_?1:0)){for(o=n-1,i=n+1;o>=0||i<t.length;)if((l=t[s=o>=0?o--:i++])!=null&&(2&l.__u)==0&&h==l.key&&u==l.type)return s}return-1}function qe(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||ut.test(t)?n:n+"px"}function he(e,t,n,r,o){var i,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||qe(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||qe(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(Ie,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r?n.u=r.u:(n.u=ge,e.addEventListener(t,i?me:fe,i)):e.removeEventListener(t,i?me:fe,i);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function He(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t.t==null)t.t=ge++;else if(t.t<n.u)return;return n(w.event?w.event(t):t)}}}function ye(e,t,n,r,o,i,s,h,u,l){var _,a,g,d,C,N,b,p,m,A,P,M,L,j,B,F,k,v=t.type;if(t.constructor!=null)return null;128&n.__u&&(u=!!(32&n.__u),i=[h=t.__e=n.__e]),(_=w.__b)&&_(t);e:if(typeof v=="function")try{if(p=t.props,m="prototype"in v&&v.prototype.render,A=(_=v.contextType)&&r[_.__c],P=_?A?A.props.value:_.__:r,n.__c?b=(a=t.__c=n.__c).__=a.__E:(m?t.__c=a=new v(p,P):(t.__c=a=new ce(p,P),a.constructor=v,a.render=mt),A&&A.sub(a),a.state||(a.state={}),a.__n=r,g=a.__d=!0,a.__h=[],a._sb=[]),m&&a.__s==null&&(a.__s=a.state),m&&v.getDerivedStateFromProps!=null&&(a.__s==a.state&&(a.__s=W({},a.__s)),W(a.__s,v.getDerivedStateFromProps(p,a.__s))),d=a.props,C=a.state,a.__v=t,g)m&&v.getDerivedStateFromProps==null&&a.componentWillMount!=null&&a.componentWillMount(),m&&a.componentDidMount!=null&&a.__h.push(a.componentDidMount);else{if(m&&v.getDerivedStateFromProps==null&&p!==d&&a.componentWillReceiveProps!=null&&a.componentWillReceiveProps(p,P),t.__v==n.__v||!a.__e&&a.shouldComponentUpdate!=null&&a.shouldComponentUpdate(p,a.__s,P)===!1){for(t.__v!=n.__v&&(a.props=p,a.state=a.__s,a.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(q){q&&(q.__=t)}),M=0;M<a._sb.length;M++)a.__h.push(a._sb[M]);a._sb=[],a.__h.length&&s.push(a);break e}a.componentWillUpdate!=null&&a.componentWillUpdate(p,a.__s,P),m&&a.componentDidUpdate!=null&&a.__h.push(function(){a.componentDidUpdate(d,C,N)})}if(a.context=P,a.props=p,a.__P=e,a.__e=!1,L=w.__r,j=0,m){for(a.state=a.__s,a.__d=!1,L&&L(t),_=a.render(a.props,a.state,a.context),B=0;B<a._sb.length;B++)a.__h.push(a._sb[B]);a._sb=[]}else do a.__d=!1,L&&L(t),_=a.render(a.props,a.state,a.context),a.state=a.__s;while(a.__d&&++j<25);a.state=a.__s,a.getChildContext!=null&&(r=W(W({},r),a.getChildContext())),m&&!g&&a.getSnapshotBeforeUpdate!=null&&(N=a.getSnapshotBeforeUpdate(d,C)),F=_,_!=null&&_.type===re&&_.key==null&&(F=Le(_.props.children)),h=Ae(e,se(F)?F:[F],t,n,r,o,i,s,h,u,l),a.base=t.__e,t.__u&=-161,a.__h.length&&s.push(a),b&&(a.__E=a.__=null)}catch(q){if(t.__v=null,u||i!=null)if(q.then){for(t.__u|=u?160:128;h&&h.nodeType==8&&h.nextSibling;)h=h.nextSibling;i[i.indexOf(h)]=null,t.__e=h}else{for(k=i.length;k--;)pe(i[k]);we(t)}else t.__e=n.__e,t.__k=n.__k,q.then||we(t);w.__e(q,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):h=t.__e=ft(n.__e,t,n,r,o,i,s,u,l);return(_=w.diffed)&&_(t),128&t.__u?void 0:h}function we(e){e&&e.__c&&(e.__c.__e=!0),e&&e.__k&&e.__k.forEach(we)}function Pe(e,t,n){for(var r=0;r<n.length;r++)be(n[r],n[++r],n[++r]);w.__c&&w.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){w.__e(i,o.__v)}})}function Le(e){return typeof e!="object"||e==null||e.__b&&e.__b>0?e:se(e)?e.map(Le):W({},e)}function ft(e,t,n,r,o,i,s,h,u){var l,_,a,g,d,C,N,b=n.props||ne,p=t.props,m=t.type;if(m=="svg"?o="http://www.w3.org/2000/svg":m=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),i!=null){for(l=0;l<i.length;l++)if((d=i[l])&&"setAttribute"in d==!!m&&(m?d.localName==m:d.nodeType==3)){e=d,i[l]=null;break}}if(e==null){if(m==null)return document.createTextNode(p);e=document.createElementNS(o,m,p.is&&p),h&&(w.__m&&w.__m(t,i),h=!1),i=null}if(m==null)b===p||h&&e.data==p||(e.data=p);else{if(i=i&&O.call(e.childNodes),!h&&i!=null)for(b={},l=0;l<e.attributes.length;l++)b[(d=e.attributes[l]).name]=d.value;for(l in b)if(d=b[l],l!="children"){if(l=="dangerouslySetInnerHTML")a=d;else if(!(l in p)){if(l=="value"&&"defaultValue"in p||l=="checked"&&"defaultChecked"in p)continue;he(e,l,null,d,o)}}for(l in p)d=p[l],l=="children"?g=d:l=="dangerouslySetInnerHTML"?_=d:l=="value"?C=d:l=="checked"?N=d:h&&typeof d!="function"||b[l]===d||he(e,l,d,b[l],o);if(_)h||a&&(_.__html==a.__html||_.__html==e.innerHTML)||(e.innerHTML=_.__html),t.__k=[];else if(a&&(e.innerHTML=""),Ae(t.type=="template"?e.content:e,se(g)?g:[g],t,n,r,m=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&ee(n,0),h,u),i!=null)for(l=i.length;l--;)pe(i[l]);h||(l="value",m=="progress"&&C==null?e.removeAttribute("value"):C!=null&&(C!==e[l]||m=="progress"&&!C||m=="option"&&C!=b[l])&&he(e,l,C,b[l],o),l="checked",N!=null&&N!=e[l]&&he(e,l,N,b[l],o))}return e}function be(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(o){w.__e(o,n)}}function Fe(e,t,n){var r,o;if(w.unmount&&w.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||be(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){w.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Fe(r[o],t,n||typeof e.type!="function");n||pe(e.__e),e.__c=e.__=e.__e=void 0}function mt(e,t,n){return this.constructor(e,n)}function Ue(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),w.__&&w.__(e,t),o=(r=!1)?null:t.__k,i=[],s=[],ye(t,e=t.__k=dt(re,null,[e]),o||ne,ne,t.namespaceURI,o?null:t.firstChild?O.call(t.childNodes):null,i,o?o.__e:t.firstChild,r,s),Pe(i,e,s)}function pt(e){function t(n){var r,o;return this.getChildContext||(r=new Set,(o={})[t.__c]=this,this.getChildContext=function(){return o},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(i){this.props.value!=i.value&&r.forEach(function(s){s.__e=!0,ve(s)})},this.sub=function(i){r.add(i);var s=i.componentWillUnmount;i.componentWillUnmount=function(){r&&r.delete(i),s&&s.call(i)}}),n.children}return t.__c="__cC"+Ne++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}O=De.slice,w={__e:function(e,t,n,r){for(var o,i,s;t=t.__;)if((o=t.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(e)),s=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,r||{}),s=o.__d),s)return o.__E=o}catch(h){e=h}throw e}},Ee=0,ce.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=W({},this.state),typeof e=="function"&&(e=e(W({},n),this.props)),e&&W(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),ve(this))},ce.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),ve(this))},ce.prototype.render=re,G=[],Te=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,$e=function(e,t){return e.__v.__b-t.__v.__b},le.__r=0,Ie=/(PointerCapture)$|Capture$/i,ge=0,fe=He(!1),me=He(!0),Ne=0;var vt=0;function c(e,t,n,r,o,i){t||(t={});var s,h,u=t;if("ref"in u)for(h in u={},t)h=="ref"?s=t[h]:u[h]=t[h];var l={type:e,props:u,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--vt,__i:-1,__u:0,__source:o,__self:i};if(typeof e=="function"&&(s=e.defaultProps))for(h in s)u[h]===void 0&&(u[h]=s[h]);return w.vnode&&w.vnode(l),l}var te,x,xe,We,ue=0,je=[],E=w,ze=E.__b,Qe=E.__r,Oe=E.diffed,Be=E.__c,Ve=E.unmount,Ke=E.__;function de(e,t){E.__h&&E.__h(x,e,ue||t),ue=0;var n=x.__H||(x.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function I(e){return ue=1,yt(Xe,e)}function yt(e,t,n){var r=de(te++,2);if(r.t=e,!r.__c&&(r.__=[Xe(void 0,t),function(h){var u=r.__N?r.__N[0]:r.__[0],l=r.t(u,h);u!==l&&(r.__N=[l,r.__[1]],r.__c.setState({}))}],r.__c=x,!x.__f)){var o=function(h,u,l){if(!r.__c.__H)return!0;var _=r.__c.__H.__.filter(function(g){return!!g.__c});if(_.every(function(g){return!g.__N}))return!i||i.call(this,h,u,l);var a=r.__c.props!==h;return _.forEach(function(g){if(g.__N){var d=g.__[0];g.__=g.__N,g.__N=void 0,d!==g.__[0]&&(a=!0)}}),i&&i.call(this,h,u,l)||a};x.__f=!0;var i=x.shouldComponentUpdate,s=x.componentWillUpdate;x.componentWillUpdate=function(h,u,l){if(this.__e){var _=i;i=void 0,o(h,u,l),i=_}s&&s.call(this,h,u,l)},x.shouldComponentUpdate=o}return r.__N||r.__}function Ge(e,t){var n=de(te++,3);!E.__s&&Ye(n.__H,t)&&(n.__=e,n.u=t,x.__H.__h.push(n))}function J(e){return ue=5,wt(function(){return{current:e}},[])}function wt(e,t){var n=de(te++,7);return Ye(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function bt(e){var t=x.context[e.__c],n=de(te++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(x)),t.props.value):e.__}function xt(){for(var e;e=je.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(_e),e.__H.__h.forEach(Se),e.__H.__h=[]}catch(t){e.__H.__h=[],E.__e(t,e.__v)}}E.__b=function(e){x=null,ze&&ze(e)},E.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Ke&&Ke(e,t)},E.__r=function(e){Qe&&Qe(e),te=0;var t=(x=e.__c).__H;t&&(xe===x?(t.__h=[],x.__h=[],t.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.forEach(_e),t.__h.forEach(Se),t.__h=[],te=0)),xe=x},E.diffed=function(e){Oe&&Oe(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(je.push(t)!==1&&We===E.requestAnimationFrame||((We=E.requestAnimationFrame)||St)(xt)),t.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),xe=x=null},E.__c=function(e,t){t.some(function(n){try{n.__h.forEach(_e),n.__h=n.__h.filter(function(r){return!r.__||Se(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],E.__e(r,n.__v)}}),Be&&Be(e,t)},E.unmount=function(e){Ve&&Ve(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(r){try{_e(r)}catch(o){t=o}}),n.__H=void 0,t&&E.__e(t,n.__v))};var Je=typeof requestAnimationFrame=="function";function St(e){var t,n=function(){clearTimeout(r),Je&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Je&&(t=requestAnimationFrame(n))}function _e(e){var t=x,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),x=t}function Se(e){var t=x;e.__c=e.__(),x=t}function Ye(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Xe(e,t){return typeof t=="function"?t(e):t}var ie=(e=>(e.TEXT="text",e.IMAGE="image",e.FILE="file",e.SYSTEM="system",e.TYPING="typing",e.CUSTOM="custom",e))(ie||{}),Y=(e=>(e.PENDING="pending",e.SENT="sent",e.DELIVERED="delivered",e.READ="read",e.FAILED="failed",e))(Y||{}),Ze=class{constructor(e){this.defaultLogger=(t,n,...r)=>{const o=new Date().toISOString(),i=this.config.prefix?`[${this.config.prefix}] [${o}] [${t.toUpperCase()}]`:`[ChatBot SDK ${o}] [${t.toUpperCase()}]`;switch(t){case"debug":console.debug(i,n,...r);break;case"info":console.info(i,n,...r);break;case"warn":console.warn(i,n,...r);break;case"error":console.error(i,n,...r);break}},this.config={enabled:e?.enabled??!0,level:e?.level??"info",customLogger:e?.customLogger??this.defaultLogger,prefix:e?.prefix??""}}shouldLog(e){if(!this.config.enabled)return!1;const t=["debug","info","warn","error"],n=t.indexOf(this.config.level);return t.indexOf(e)>=n}debug(e,...t){this.shouldLog("debug")&&this.config.customLogger("debug",e,...t)}info(e,...t){this.shouldLog("info")&&this.config.customLogger("info",e,...t)}warn(e,...t){this.shouldLog("warn")&&this.config.customLogger("warn",e,...t)}error(e,...t){this.shouldLog("error")&&this.config.customLogger("error",e,...t)}updateConfig(e){this.config={...this.config,...e}}},Ct=class{constructor(e){this.listeners={},this.eventHistory=[],this.maxHistorySize=100,this.logger=e}on(e,t){return this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t),this.logger.debug(`Event listener added for: ${e}`),()=>this.off(e,t)}onAny(e){return this.listeners["*"]||(this.listeners["*"]=new Set),this.listeners["*"].add(e),this.logger.debug("Wildcard event listener added"),()=>this.offAny(e)}once(e,t){const n=r=>{t(r),this.off(e,n)};return this.on(e,n)}off(e,t){const n=this.listeners[e];n&&(n.delete(t),n.size===0&&delete this.listeners[e],this.logger.debug(`Event listener removed for: ${e}`))}offAny(e){const t=this.listeners["*"];t&&(t.delete(e),t.size===0&&delete this.listeners["*"],this.logger.debug("Wildcard event listener removed"))}emit(e,t){const n={type:e,data:t};this.eventHistory.push(n),this.eventHistory.length>this.maxHistorySize&&this.eventHistory.shift(),this.logger.debug(`Event emitted: ${e}`,t);const r=this.listeners[e];r&&r.forEach(i=>{try{i(t)}catch(s){this.logger.error(`Error in event listener for ${e}:`,s)}});const o=this.listeners["*"];o&&o.forEach(i=>{try{i(n)}catch(s){this.logger.error("Error in wildcard event listener:",s)}})}removeAllListeners(e){e?(delete this.listeners[e],this.logger.debug(`All listeners removed for: ${e}`)):(this.listeners={},this.logger.debug("All event listeners removed"))}getEventHistory(){return[...this.eventHistory]}clearEventHistory(){this.eventHistory=[],this.logger.debug("Event history cleared")}listenerCount(e){return this.listeners[e]?.size??0}},Et=class{constructor(e={},t){this.currentAttempt=0,this.config={enabled:e.enabled??!0,maxAttempts:e.maxAttempts??1/0,baseDelay:e.baseDelay??1e3,maxDelay:e.maxDelay??1e4,jitter:e.jitter??.3},this.logger=t}shouldReconnect(){return this.config.enabled?this.currentAttempt>=this.config.maxAttempts?(this.logger.warn(`Max reconnection attempts (${this.config.maxAttempts}) reached`),!1):!0:(this.logger.debug("Reconnection is disabled"),!1)}getNextDelay(){const e=this.config.baseDelay*Math.pow(2,this.currentAttempt),t=Math.min(e,this.config.maxDelay),n=t*this.config.jitter,r=(Math.random()*2-1)*n,o=Math.max(0,t+r);return this.logger.debug(`Reconnection delay calculated: ${o.toFixed(0)}ms (attempt ${this.currentAttempt+1})`),o}incrementAttempt(){this.currentAttempt++,this.logger.info(`Reconnection attempt ${this.currentAttempt}/${this.config.maxAttempts}`)}reset(){this.logger.debug("Reconnection strategy reset"),this.currentAttempt=0}getCurrentAttempt(){return this.currentAttempt}updateConfig(e){this.config={...this.config,...e},this.logger.debug("Reconnection config updated",this.config)}},kt=class{constructor(e){this.queue=[],this.maxQueueSize=1e3,this.defaultMaxRetries=3,this.logger=e}enqueue(e,t=this.defaultMaxRetries){this.queue.length>=this.maxQueueSize&&(this.logger.warn("Message queue is full, removing oldest message"),this.queue.shift());const n={message:e,timestamp:Date.now(),retries:0,maxRetries:t};this.queue.push(n),this.logger.debug(`Message queued: ${e.id} (queue size: ${this.queue.length})`)}dequeueAll(){const e=this.queue.map(t=>t.message);return this.queue=[],this.logger.info(`Dequeued ${e.length} messages`),e}getRetryableMessages(){return this.queue.filter(t=>t.retries<t.maxRetries).map(t=>t.message)}markAsFailed(e){const t=this.queue.findIndex(n=>n.message.id===e);t!==-1&&(this.queue[t].retries++,this.queue[t].retries>=this.queue[t].maxRetries?(this.logger.warn(`Message ${e} exceeded max retries, removing from queue`),this.queue.splice(t,1)):this.logger.debug(`Message ${e} retry count: ${this.queue[t].retries}/${this.queue[t].maxRetries}`))}remove(e){const t=this.queue.findIndex(n=>n.message.id===e);t!==-1&&(this.queue.splice(t,1),this.logger.debug(`Message ${e} removed from queue`))}clear(){const e=this.queue.length;this.queue=[],this.logger.info(`Message queue cleared (${e} messages removed)`)}size(){return this.queue.length}isEmpty(){return this.queue.length===0}peek(){return this.queue.map(e=>e.message)}setMaxQueueSize(e){if(e<1)throw new Error("Max queue size must be at least 1");for(this.maxQueueSize=e,this.logger.debug(`Max queue size set to ${e}`);this.queue.length>this.maxQueueSize;)this.queue.shift()}},Tt=class{constructor(e,t,n,r){this.ws=null,this.eventQueue=[],this.connectionState="disconnected",this.lastEmittedState="disconnected",this.reconnectTimer=null,this.heartbeatTimer=null,this.connectionTimeoutTimer=null,this.stateChangeTimer=null,this.pendingAcks=new Map,this.config=e,this.logger=n,this.eventEmitter=r,this.reconnectionStrategy=new Et(t,n),this.messageQueue=new kt(n)}updateConfig(e){this.config=e}async connect(e){if(this.ws?.readyState===WebSocket.OPEN){this.logger.warn("WebSocket is already connected");return}if(this.ws?.readyState===WebSocket.CONNECTING){this.logger.warn("WebSocket is already connecting");return}return this.updateConnectionState("connecting"),this.updateConnectionState("connecting"),new Promise((t,n)=>{try{e&&(this.username=e);let r=this.config.url;if(this.username){const o=r.includes("?")?"&":"?";r=`${r}${o}username=${encodeURIComponent(this.username)}`}this.ws=new WebSocket(r,this.config.protocols),this.setupEventHandlers(t,n),this.setupConnectionTimeout(n)}catch(r){this.logger.error("Failed to create WebSocket connection:",r),this.handleConnectionError(r),n(r)}})}disconnect(){this.logger.info("Disconnecting WebSocket"),this.updateConnectionState("disconnecting"),this.clearTimers(),this.reconnectionStrategy.reset(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.updateConnectionState("disconnected")}async sendEvent(e,t){if(this.connectionState!=="connected"){this.logger.warn("WebSocket not connected, queuing event"),this.eventQueue.push({event:e,data:t});return}try{const n=JSON.stringify({event:e,data:t});this.ws?.send(n),this.logger.debug(`Event sent: ${e}`,t)}catch(n){throw this.logger.error(`Failed to send event ${e}:`,n),n}}async send(e,t=!0,n=5e3){if(this.connectionState!=="connected"){this.logger.warn("WebSocket not connected, queuing message"),this.messageQueue.enqueue(e);return}try{const r={roomId:e.metadata?.roomId||"general",message:e.content,username:e.sender==="user"?e.metadata?.username:void 0};return await this.sendEvent("sendMessage",r),this.eventEmitter.emit("messageSent",{message:e,timestamp:Date.now()}),{ackId:"simulated_"+Date.now(),messageId:e.id,status:"received",timestamp:Date.now()}}catch(r){throw this.logger.error("Failed to send message:",r),this.messageQueue.enqueue(e),r}}async joinRoom(e){this.currentRoom=e,this.logger.info(`Joining room: ${e}`),await this.sendEvent("joinRoom",{roomId:e})}async leaveRoom(e){await this.sendEvent("leaveRoom",{roomId:e})}async getRoomInfo(e){await this.sendEvent("getRoomInfo",{roomId:e})}async sendJoinConversation(e){this.logger.info(`Joining conversation stream: ${e}`),await this.sendEvent("joinConversation",{conversationId:e})}async sendLeaveConversation(e){this.logger.info(`Leaving conversation stream: ${e}`),await this.sendEvent("leaveConversation",{conversationId:e})}getConnectionState(){return this.connectionState}isConnected(){return this.connectionState==="connected"}getMessageQueue(){return this.messageQueue}setupEventHandlers(e,t){this.ws&&(this.ws.onopen=()=>{this.logger.info("WebSocket connected"),this.clearConnectionTimeout(),this.updateConnectionState("connected"),this.reconnectionStrategy.reset(),this.startHeartbeat(),this.reconnectionStrategy.reset(),this.startHeartbeat(),this.currentRoom&&(this.logger.info(`Re-joining room: ${this.currentRoom}`),this.sendEvent("joinRoom",{roomId:this.currentRoom}).catch(n=>{this.logger.error(`Failed to re-join room ${this.currentRoom}:`,n)})),this.flushMessageQueue(),e&&e()},this.ws.onmessage=n=>{this.handleMessage(n.data)},this.ws.onerror=n=>{this.logger.error("WebSocket error:",n);const r=new Error("WebSocket error");this.eventEmitter.emit("error",{error:r,timestamp:Date.now(),context:"websocket"}),this.connectionState==="connecting"&&t&&t(r)},this.ws.onclose=n=>{this.logger.info(`WebSocket closed: ${n.code} - ${n.reason}`),this.stopHeartbeat(),this.updateConnectionState("disconnected"),n.code!==1e3&&this.reconnectionStrategy.shouldReconnect()&&this.attemptReconnection()})}handleMessage(e){try{const t=JSON.parse(e),{event:n,data:r}=t;switch(this.logger.debug(`Received event: ${n}`,r),n){case"pong":this.logger.debug("Heartbeat pong received");break;case"newMessage":const o={id:`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"text",content:r.message,sender:"user",timestamp:new Date(r.timestamp).getTime(),status:"delivered",metadata:{roomId:r.roomId,username:r.username}};this.eventEmitter.emit("message",{message:o,timestamp:Date.now()});break;case"joinedRoom":this.eventEmitter.emit("joinedRoom",r);break;case"userJoined":this.eventEmitter.emit("userJoined",r);break;case"leftRoom":this.eventEmitter.emit("leftRoom",r);break;case"userLeft":this.eventEmitter.emit("userLeft",r);break;case"roomInfo":this.eventEmitter.emit("roomInfo",r);break;case"error":this.eventEmitter.emit("error",{error:new Error(r.message),timestamp:Date.now(),context:"server_error"});break;case"agentEvent":this.eventEmitter.emit("agentEvent",{...r,conversationId:t.conversationId});break;default:this.logger.warn(`Unknown event received: ${n}`)}}catch(t){this.logger.error("Failed to parse message:",t),this.eventEmitter.emit("error",{error:t,timestamp:Date.now(),context:"message_parsing"})}}startHeartbeat(){const e=this.config.heartbeatInterval??3e4;this.heartbeatTimer=setInterval(()=>{if(this.ws?.readyState===WebSocket.OPEN)try{this.sendEvent("ping",{}),this.logger.debug("Heartbeat ping sent")}catch(t){this.logger.error("Failed to send heartbeat:",t)}},e),this.logger.debug(`Heartbeat started with interval: ${e}ms`)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.logger.debug("Heartbeat stopped"))}setupConnectionTimeout(e){const t=this.config.connectionTimeout??1e4;this.connectionTimeoutTimer=setTimeout(()=>{if(this.connectionState==="connecting"){this.logger.error("Connection timeout"),this.ws?.close();const n=new Error("Connection timeout");this.handleConnectionError(n),e&&e(n)}},t)}clearConnectionTimeout(){this.connectionTimeoutTimer&&(clearTimeout(this.connectionTimeoutTimer),this.connectionTimeoutTimer=null)}attemptReconnection(){if(!this.reconnectionStrategy.shouldReconnect()){this.logger.error("Reconnection failed: max attempts reached"),this.updateConnectionState("failed"),this.eventEmitter.emit("reconnectFailed",{state:"failed",timestamp:Date.now(),attempt:this.reconnectionStrategy.getCurrentAttempt()});return}this.updateConnectionState("reconnecting"),this.reconnectionStrategy.incrementAttempt();const e=this.reconnectionStrategy.getNextDelay();this.eventEmitter.emit("reconnecting",{state:"reconnecting",timestamp:Date.now(),attempt:this.reconnectionStrategy.getCurrentAttempt()}),this.reconnectTimer=setTimeout(()=>{this.logger.info("Attempting to reconnect..."),this.connect().catch(t=>{this.logger.error("Reconnection attempt failed:",t)})},e)}handleConnectionError(e){this.eventEmitter.emit("error",{error:e,timestamp:Date.now(),context:"connection"}),this.reconnectionStrategy.shouldReconnect()?this.attemptReconnection():this.updateConnectionState("failed")}flushMessageQueue(){if(this.eventQueue.length>0){this.logger.info(`Flushing ${this.eventQueue.length} queued events`);const t=[...this.eventQueue];this.eventQueue=[],t.forEach(({event:n,data:r})=>{this.sendEvent(n,r).catch(o=>{this.logger.error(`Failed to send queued event ${n}:`,o)})})}const e=this.messageQueue.dequeueAll();e.length>0&&(this.logger.info(`Flushing ${e.length} queued messages`),e.forEach(t=>{this.send(t,!1).catch(n=>{this.logger.error(`Failed to send queued message ${t.id}:`,n),this.messageQueue.markAsFailed(t.id)})}))}updateConnectionState(e){const t=this.connectionState;this.connectionState=e,t!==e&&this.logger.info(`Connection state changed: ${t} -> ${e}`);const n=this.config.disconnectGracePeriod??0;e==="connected"?(this.stateChangeTimer&&(clearTimeout(this.stateChangeTimer),this.stateChangeTimer=null,this.logger.debug("Reconnected within grace period, suppressing disconnection event")),this.lastEmittedState!=="connected"&&this.emitConnectionChange(e)):this.lastEmittedState==="connected"&&n>0?this.stateChangeTimer||(this.logger.debug(`Starting disconnection grace period (${n}ms)`),this.stateChangeTimer=setTimeout(()=>{this.stateChangeTimer=null,this.emitConnectionChange(this.connectionState)},n)):this.emitConnectionChange(e)}emitConnectionChange(e){this.lastEmittedState!==e&&(this.lastEmittedState=e,this.eventEmitter.emit("connection",{state:e,timestamp:Date.now()}))}clearTimers(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.connectionTimeoutTimer&&(clearTimeout(this.connectionTimeoutTimer),this.connectionTimeoutTimer=null),this.pendingAcks.forEach(e=>{clearTimeout(e.timeout),e.reject(new Error("Connection closed"))}),this.pendingAcks.clear()}},et=()=>{const e="echo_device_hash";try{let t=localStorage.getItem(e);return t||(t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=Math.random()*16|0;return(n==="x"?r:r&3|8).toString(16)}),localStorage.setItem(e,t)),t}catch{return"unknown-device-"+Date.now()}},tt=class{constructor(e={},t){this.config={retries:3,backoff:1e3,...e},this.logger=t}async get(e,t={}){return this.request(e,{method:"GET",headers:t})}async post(e,t,n={}){return this.request(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(t)})}async request(e,t,n=0){const r={...this.config.headers,...t.headers};try{const o=await fetch(e,{...t,headers:r});if(!o.ok){if(o.status>=500&&n<(this.config.retries??3))return this.logger?.warn(`Request failed with status ${o.status}. Retrying... (${n+1}/${this.config.retries})`),await this.delay(this.getErrorDelay(n)),this.request(e,t,n+1);const i=await o.text();throw new Error(`HTTP Error ${o.status}: ${i}`)}return o.json()}catch(o){if(n<(this.config.retries??3))return this.logger?.warn(`Request failed with error: ${o}. Retrying... (${n+1}/${this.config.retries})`),await this.delay(this.getErrorDelay(n)),this.request(e,t,n+1);throw o}}getErrorDelay(e){return(this.config.backoff??1e3)*Math.pow(2,e)}delay(e){return new Promise(t=>setTimeout(t,e))}};class $t{constructor(t="https://chat-mcp-agent.fly.dev"){this.baseUrl=t,this.client=new tt({retries:3,backoff:1e3},new Ze({prefix:"ConfigService"}))}async fetchConfig(t,n,r){const o=`${this.baseUrl}/${t}/api/v1/client/configuration`,i={"x-api-key":n};r&&(i["x-external-id"]=r);try{const s=await this.client.get(o,i);if(s.success&&s.data)return s.data.finger_print&&localStorage.setItem("echo_finger_print",s.data.finger_print),s.data;throw new Error("Invalid configuration response")}catch(s){throw console.error("Failed to fetch configuration:",s),s}}}class It{constructor(t="https://chat-mcp-agent.fly.dev"){this.baseUrl=t,this.httpClient=new tt({})}async getConversations(t,n,r){const o={"x-api-key":n};r&&(o["x-external-id"]=r);const i=`${this.baseUrl}/${t}/api/v1/client/conversations`;try{return(await this.httpClient.get(i,o)).data}catch(s){throw console.error("Failed to get conversations",s),s}}async createConversation(t,n,r,o,i){const s={"x-api-key":n,"Content-Type":"application/json"};o&&(s["x-external-id"]=o),i&&(s["x-device-hash"]=i);const h=`${this.baseUrl}/${t}/api/v1/client/conversations/new`,u={prompt:r};try{return(await this.httpClient.post(h,u,s)).data}catch(l){throw console.error("Failed to create conversation",l),l}}async getMessages(t,n,r,o){const i={"x-api-key":n};o&&(i["x-external-id"]=o);const s=`${this.baseUrl}/${t}/api/v1/client/conversations/${r}/messages`;try{return(await this.httpClient.get(s,i)).data}catch(h){throw console.error("Failed to get messages",h),h}}}const nt=5e3,rt=pt(null),Nt=({children:e,sdkConfig:t})=>{const[n,r]=I(!1),[o,i]=I("disconnected"),[s,h]=I(!1),[u,l]=I(!0),[_,a]=I(null),[g,d]=I([]),[C,N]=I([]),[b,p]=I(null),[m,A]=I(null),[P,M]=I(!1),[L,j]=I(null),[B,F]=I({}),k=J(null),v=J(null),q=J(null),X=J(new Map),V=J(null);if(v.current||(v.current=new Ze({prefix:"EchoSDK"})),!q.current){const f="https://chat-mcp-agent.fly.dev";q.current=new It(f)}Ge(()=>{const f=async()=>{l(!0),a(null);try{const D=await new $t().fetchConfig(t.companyUrl,t.apiKey,t.externalId);A(D);const H=await q.current.getConversations(t.companyUrl,t.apiKey,t.externalId);N(H),h(!0),await Bt(D,t)}catch(S){v.current?.error("Initialization failed:",S),a(S.message||"Failed to initialize SDK")}finally{l(!1)}};return t.apiKey&&t.companyUrl?f():(a("Missing required configuration (apiKey or companyUrl)"),l(!1)),()=>{k.current?.disconnect()}},[t.apiKey,t.companyUrl,t.externalId]);const Bt=async(f,S)=>{const D=f.finger_print||localStorage.getItem("echo_finger_print")||et(),H="ws://localhost:3000",T=new URLSearchParams;T.append("api_key",S.apiKey),T.append("device_hash",D),S.externalId&&T.append("external_id",S.externalId),S.authToken&&T.append("x-auth-token",S.authToken);const Z=`${H}?${T.toString()}`,U=new Ct(v.current),Ce={url:Z,heartbeatInterval:3e4,connectionTimeout:1e4},z={maxAttempts:1/0,baseDelay:1e3,maxDelay:3e4},oe=new Tt(Ce,z,v.current,U);k.current=oe,U.on("connection",y=>{r(y.state==="connected"),i(y.state),console.log("connection triggered custom",y.state,V.current),y.state==="connected"&&V.current&&(v.current?.info(`Reconnected. Re-joining conversation: ${V.current}`),setTimeout(()=>{V.current&&oe.sendJoinConversation(V.current)},1e3))}),U.on("message",y=>{d($=>{if($.some(Q=>Q.id===y.message.id))return $;if(y.message.sender==="user"){const Q=$.findIndex(R=>R.sender==="user"&&R.status===Y.PENDING&&R.content===y.message.content);if(Q!==-1){const R=[...$];return R[Q]=y.message,R}}return[...$,y.message]})}),U.on("messageSent",y=>{d($=>{if($.some(R=>R.id===y.message.id))return $;const Q=$.findIndex(R=>R.sender==="user"&&R.status===Y.PENDING&&R.content===y.message.content);if(Q!==-1){const R=[...$];return R[Q]=y.message,R}return[...$,y.message]})}),U.on("agentEvent",y=>{if(y.type==="first_response")M(!0),j(y.runId),F($=>({...$,[y.runId]:[]}));else if(["thought","action_start","action_end"].includes(y.type))M(!0),j($=>$||y.runId),F($=>({...$,[y.runId]:[...$[y.runId]||[],y]}));else if(y.type==="final_response"&&(M(!1),j(null),y.content)){const $={id:y.messageId||Date.now().toString(),content:y.content,sender:"bot",type:ie.TEXT,status:Y.DELIVERED,timestamp:Date.now(),metadata:{roomId:y.conversationId,runId:y.runId}};d(Q=>[...Q,$])}}),await oe.connect()},lt=async f=>{const S=b;if(X.current.has(f)&&(clearTimeout(X.current.get(f)),X.current.delete(f),v.current?.info(`Cancelled pending leave for conversation: ${f}`)),S&&S!==f){const D=setTimeout(()=>{k.current&&k.current.sendLeaveConversation(S).catch(H=>v.current?.error(`Failed to leave conversation ${S}`,H)),X.current.delete(S)},nt);X.current.set(S,D)}l(!0);try{const H=(await q.current.getMessages(t.companyUrl,t.apiKey,f,t.externalId)).map(T=>({id:T.id,content:T.content,sender:T.role==="user"?"user":"bot",type:ie.TEXT,status:Y.DELIVERED,timestamp:new Date(T.created_at).getTime(),metadata:{roomId:f}}));d(T=>{const Z=T.filter(z=>z.metadata?.roomId===f),U=new Set(H.map(z=>z.id)),Ce=Z.filter(z=>!U.has(z.id));return[...H,...Ce].sort((z,oe)=>z.timestamp-oe.timestamp)}),p(f),V.current=f,k.current&&await k.current.sendJoinConversation(f)}catch(D){v.current?.error("Failed to load conversation",D)}finally{l(!1)}},Vt=()=>{const f=b;if(f){const S=setTimeout(()=>{k.current&&k.current.sendLeaveConversation(f).catch(D=>v.current?.error(`Failed to leave conversation ${f}`,D)),X.current.delete(f)},nt);X.current.set(f,S)}p(null),V.current=null,d([]),M(!1),j(null),F({})},ht=async f=>{const S=Date.now().toString(),D={id:S,content:f,sender:"user",type:ie.TEXT,status:Y.PENDING,timestamp:Date.now(),metadata:{}};d([D]),M(!0);try{const H=m?.finger_print||localStorage.getItem("echo_finger_print")||et(),T=await q.current?.createConversation(t.companyUrl,t.apiKey,f,t.externalId,H);if(!T)throw new Error("Failed to create conversation");N(Z=>[T,...Z]),p(T.id),V.current=T.id,d(Z=>Z.filter(U=>U.id===S||U.metadata?.roomId===T.id)),k.current&&await k.current.sendJoinConversation(T.id),await lt(T.id)}catch(H){v.current?.error("Failed to create conversation",H),a("Failed to start new conversation")}finally{l(!1)}},Kt=async f=>{if(!b){await ht(f);return}if(!k.current)return;const S={id:Date.now().toString(),content:f,sender:"user",type:ie.TEXT,status:Y.PENDING,timestamp:Date.now(),metadata:{roomId:b}};d(D=>[...D,S]),await k.current.sendEvent("sendMessage",{conversationId:b,message:f})};return c(rt.Provider,{value:{isConnected:n,connectionState:o,isInitialized:s,isLoading:u,error:_,config:m,messages:g,conversations:C,activeConversationId:b,isStreaming:P,activeRunId:L,streamedThoughts:B,sendMessage:Kt,joinRoom:async f=>{await k.current?.joinRoom(f)},leaveRoom:async f=>{await k.current?.leaveRoom(f)},loadConversation:lt,createNewChat:Vt,startNewConversation:ht},children:e})},it=()=>{const e=bt(rt);if(!e)throw new Error("useChat must be used within a ChatProvider");return e},Dt=()=>c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[c("circle",{cx:"12",cy:"12",r:"1"}),c("circle",{cx:"19",cy:"12",r:"1"}),c("circle",{cx:"5",cy:"12",r:"1"})]}),ot=({size:e=20})=>c("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[c("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),Rt=()=>c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[c("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),c("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),At=()=>c("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:c("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),Mt=()=>c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[c("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),c("polyline",{points:"14 2 14 8 20 8"}),c("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),c("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]}),qt=()=>c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[c("circle",{cx:"12",cy:"12",r:"10"}),c("path",{d:"M8 14s1.5 2 4 2 4-2 4-2"}),c("line",{x1:"9",y1:"9",x2:"9.01",y2:"9"}),c("line",{x1:"15",y1:"9",x2:"15.01",y2:"9"})]}),Ht=()=>c("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[c("line",{x1:"19",y1:"12",x2:"5",y2:"12"}),c("polyline",{points:"12 19 5 12 12 5"})]}),Pt=({title:e="Annie Smith",greeting:t,connectionStatus:n="connected",onToggleSidebar:r,onCloseChat:o,showBackButton:i,onBack:s})=>c("div",{class:"echo-header",children:[i&&c("button",{className:"echo-back-btn",onClick:s,style:"background: none; border: none; color: white; cursor: pointer; opacity: 0.9; padding: 4px; margin-right: 2px;",children:c(Ht,{})}),c("div",{class:"echo-avatar",children:[c("img",{src:"https://api.dicebear.com/7.x/avataaars/svg?seed=Annie",alt:"Avatar",style:"width: 100%; height: 100%; border-radius: 50%;"}),c("div",{style:{position:"absolute",bottom:"0",right:"0",width:"10px",height:"10px",borderRadius:"50%",backgroundColor:(u=>{switch(u){case"connected":return"#10b981";case"reconnecting":return"#f59e0b";case"disconnected":return"#ef4444";default:return"#9ca3af"}})(n),border:"2px solid white"},title:n})]}),c("div",{class:"echo-header-info",children:[c("h3",{class:"echo-header-title",children:e}),!i&&c("p",{class:"echo-header-subtitle",children:t||"We typically reply in a few minute"})]}),c("button",{class:"echo-menu-btn",onClick:r,style:"background: none; border: none; color: white; cursor: pointer; opacity: 0.8; padding: 4px;",children:c(Dt,{})}),c("button",{class:"echo-close-btn",onClick:o,style:"background: none; border: none; color: white; cursor: pointer; opacity: 0.8; margin-left: 8px;",children:c(ot,{})})]}),st=({events:e,isExpanded:t=!1})=>{const[n,r]=I(t);return e.length===0?null:c("div",{className:"echo-thought-chain",children:[c("div",{className:"echo-thought-header",onClick:()=>r(!n),role:"button",tabIndex:0,children:[c("span",{className:"echo-thought-icon",children:"🧠"}),c("span",{className:"echo-thought-title",children:["Thinking Process (",e.length," steps)"]}),c("span",{className:`echo-thought-chevron ${n?"expanded":""}`,children:"▼"})]}),n&&c("div",{className:"echo-thought-content",children:e.map((o,i)=>c("div",{className:`echo-thought-item ${o.type}`,children:[c("div",{className:"echo-thought-type",children:Lt(o.type)}),c("div",{className:"echo-thought-text",children:o.content})]},i))})]})},Lt=e=>{switch(e){case"action_start":return"Starting Action";case"action_end":return"Action Completed";case"thought":return"Reasoning";case"error":return"Error";case"first_response":return"Started";default:return e}},Ft=({messages:e,isStreaming:t,activeRunId:n,streamedThoughts:r})=>{const o=J(null),i=J(null);return Ge(()=>{i.current&&i.current.scrollIntoView({behavior:"smooth"})},[e,t,r]),c("div",{className:"echo-message-list",ref:o,children:[e.map(s=>c("div",{className:`echo-message ${s.sender==="user"?"user":"bot"}`,children:[c("div",{className:"echo-message-content",children:s.type==="text"?s.content:c("img",{src:s.content,alt:"sent image",className:"echo-message-image"})}),c("div",{className:"echo-message-time",children:new Date(s.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),s.metadata?.runId&&r[s.metadata.runId]&&c(st,{events:r[s.metadata.runId],isExpanded:!1})]},s.id)),t&&c("div",{className:"echo-message bot echo-streaming-container",children:[n&&c(st,{events:r[n]||[],isExpanded:!1}),c("div",{className:"echo-typing-indicator",children:[c("span",{children:"."}),c("span",{children:"."}),c("span",{children:"."})]})]}),c("div",{ref:i})]})},Ut=({onSendMessage:e,isLoading:t})=>{const[n,r]=I(""),o=()=>{n.trim()&&!t&&(e(n.trim()),r(""))};return c("div",{class:"echo-input-area",children:[c("input",{type:"text",class:"echo-input",placeholder:"Type a Message...",value:n,onInput:s=>r(s.currentTarget.value),onKeyPress:s=>{s.key==="Enter"&&!t&&o()},disabled:t}),c("div",{style:"display: flex; gap: 8px; align-items: center;",children:[c("button",{style:"background: none; border: none; cursor: pointer; color: #9ca3af; padding: 4px;",disabled:t,children:c(Mt,{})}),c("button",{style:"background: none; border: none; cursor: pointer; color: #9ca3af; padding: 4px;",disabled:t,children:c(qt,{})}),c("button",{class:"echo-send-btn",onClick:o,disabled:!n.trim()||t,children:c(Rt,{})})]})]})},Wt=({conversations:e,activeConversationId:t,onSelectConversation:n,onNewChat:r,isOpen:o})=>o?c("div",{className:"echo-sidebar",children:[c("div",{className:"echo-sidebar-header",children:c("button",{className:"echo-new-chat-btn",onClick:r,children:"+ New Chat"})}),c("div",{className:"echo-conversation-list",children:e.map(i=>c("div",{className:`echo-conversation-item ${t===i.id?"active":""}`,onClick:()=>n(i.id),role:"button",tabIndex:0,children:[c("div",{className:"echo-conversation-summary",children:i.summary||"New Conversation"}),c("div",{className:"echo-conversation-date",children:(()=>{const s=new Date(i.updated_at||i.created_at),h=new Date;return s.getDate()===h.getDate()&&s.getMonth()===h.getMonth()&&s.getFullYear()===h.getFullYear()?s.toLocaleTimeString([],{year:"2-digit",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):s.toLocaleDateString()})()})]},i.id))})]}):null,jt=({config:e,onQuerySelect:t})=>{if(!e)return null;const{display_name:n,example_queries:r}=e,o=r?r.slice(0,3):[];return c("div",{className:"echo-home-view",children:[n&&c("h2",{className:"echo-home-greeting",children:["Hi ",n," 👋"]}),o.length>0&&c("div",{className:"echo-query-list",children:o.map((i,s)=>c("button",{className:"echo-query-chip",onClick:()=>t(i),children:i},s))})]})},zt=({isOpen:e,onClose:t,title:n})=>{const{messages:r,sendMessage:o,config:i,connectionState:s,conversations:h,activeConversationId:u,loadConversation:l,createNewChat:_,startNewConversation:a,isStreaming:g,activeRunId:d,streamedThoughts:C,isInitialized:N,isLoading:b,error:p}=it(),[m,A]=I(!1),P=async v=>{await o(v)},M=async v=>{await l(v),A(!1)},L=()=>{_(),A(!1)},j=v=>{a(v)},B=N&&!b&&r.length===0,k=h.find(v=>v.id===u)?.summary||n||i?.brand_name||"Support";return c("div",{className:`echo-chat-window ${e?"open":""}`,children:[c(Pt,{title:k,greeting:i?.greeting_message,connectionStatus:s,onToggleSidebar:()=>A(!m),onCloseChat:t,showBackButton:!!u,onBack:L}),c("div",{className:"echo-chat-body-container",children:[c("div",{className:`echo-sidebar-container ${m?"open":""}`,children:c(Wt,{conversations:h,activeConversationId:u||void 0,onSelectConversation:M,onNewChat:L,isOpen:m})}),c("div",{className:"echo-chat-main",children:[p?c("div",{className:"echo-error-message",children:[p,c("button",{onClick:()=>window.location.reload(),children:"Retry"})]}):c(re,{children:B?c(jt,{config:i,onQuerySelect:j}):c(Ft,{messages:r,isStreaming:g,activeRunId:d||void 0,streamedThoughts:C})}),c(Ut,{onSendMessage:P,isLoading:b||g})]})]})]})},Qt=({isOpen:e,onClick:t})=>c("button",{class:"echo-launcher",onClick:t,children:e?c(ot,{size:24}):c(At,{})}),Ot=({config:e})=>{const[t,n]=I(!1),{config:r,isLoading:o,error:i,isInitialized:s}=it();if(i)return r?.environment==="dev"?c("div",{className:"echo-error-toast",style:{position:"fixed",bottom:"20px",right:"20px",background:"red",color:"white",padding:"10px",borderRadius:"5px",zIndex:1e4},children:["Error: ",i]}):null;if(!s&&o)return null;const h=e.bgColor||r?.primary_color||"#0165d2",u={"--echo-primary":h,"--echo-primary-gradient":`linear-gradient(135deg, ${h} 0%, ${h} 100%)`,"--echo-background":"#ffffff","--echo-foreground":"#000000"};return e.width&&(u.width=e.width),e.height&&(u.height=e.height),c("div",{className:`echo-chat-container ${e.position||"bottom-right"}`,style:u,children:[c(zt,{isOpen:t,onClose:()=>n(!1),title:r?.brand_name||"Support"}),c(Qt,{isOpen:t,onClick:()=>n(!t)})]})},at=e=>c(Nt,{sdkConfig:e,children:c(Ot,{config:e})});function ct(e,t){const n=document.createElement("div");return e.appendChild(n),Ue(c(at,{...t}),n),{destroy:()=>{Ue(null,n),n.remove()}}}typeof window<"u"&&(window.mountChatPopup=ct),K.ChatPopup=at,K.mountChatPopup=ct,Object.defineProperty(K,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@echo-sdk/view",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "main": "./dist/index.umd.js",
6
6
  "module": "./dist/index.es.js",