@smarter.sh/ui-chat 0.2.13 → 0.2.14

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.
@@ -595,5 +595,5 @@ See https://s-c.sh/2BAXzed for more info.`),window[na]+=1);const ii=nn.div`
595
595
  `,bt={INCOMING:"incoming",OUTGOING:"outgoing"},tt={SYSTEM:"system",ASSISTANT:"assistant",USER:"user",TOOL:"tool",SMARTER:"smarter"},rl=[tt.SYSTEM,tt.ASSISTANT,tt.USER,tt.TOOL];function ra(e,t=null){if(e.value!==null)return e.value;let r=null;if(window.location.hostname.endsWith(e.domain)&&document.cookie&&document.cookie!==""){const n=document.cookie.split(";").map(a=>a.trim());for(let a=0;a<n.length;a++){const o=n[a];if(o.startsWith(`${e.name}=`)){r=decodeURIComponent(o.substring(e.name.length+1));break}}}return r||t}function aa(e,t){const r=window.location.pathname;if(t){const n=new Date;n.setTime(n.getTime()+e.expiration);const a=n.toUTCString(),o=`${e.name}=${t}; path=${r}; SameSite=Lax; expires=${a}`;document.cookie=o}else{const a=new Date(0).toUTCString(),o=`${e.name}=; path=${r}; SameSite=Lax; expires=${a}`;document.cookie=o}}function oa(e,t,r,n=null){return{name:e,expiration:t,domain:r,value:n}}const si=!1;let Vt=si;const Am="SmarterChat/1.0",ci="application/json";function Mm(e,t){const r={session_key:t.session_key,messages:e};return JSON.stringify(r)}function al(e){Vt&&console.log("requestHeadersFactory(): cookies",e);function t(i){return document.cookie.split(";").filter(l=>!l.trim().startsWith(`${i.csrfCookie.name}=`)).join("; ")}const r=t(e),n=ra(e.csrfCookie,""),a=ra(e.authTokenCookie,""),o={Accept:ci,"Content-Type":ci,"X-CSRFToken":n,Origin:window.location.origin,Cookie:r,Authorization:`Bearer ${a}`,"User-Agent":Am};return Vt&&console.log("requestHeadersFactory(): requestHeaders",o),o}function ol(e,t){return{method:"POST",credentials:"include",mode:"cors",headers:e,body:t}}function il(e,t,r){e.endsWith("/")||(e+="/"),t=t||"";let n=new URL(t,e);return r&&n.searchParams.append("session_key",r),n.toString()}async function sl(e,t,r){try{Vt&&console.log("getJsonResponse(): url: ",e,", init: ",t,", cookies: ",r);const n=await fetch(e,t),a=n.headers.get("content-type");if(a&&a.includes(ci)){const o=await n.status;if(n.ok){const i=await n.json(),s=await i.data;return Vt&&console.log("getJsonResponse(): response: ",i),s}else return console.error("getJsonResponse(): error: ",o,n.statusText),n}else{const o=await n.text();throw new Error(`getJsonResponse() Unexpected response format: ${o}`)}}catch(n){return n}}async function Im(e,t,r){Vt=e.debug_mode||si,Vt&&console.log("fetchPrompt(): config",e);const n=e.chatbot.url_chatbot,a=ra(r.sessionCookie,""),o=il(n,null,a),i=al(r),s=Mm(t,e),c=ol(i,s),l=await sl(o,c,r);return l&&l.body?(Vt&&console.log("fetchPrompt(): parsing responseJson.body "),await JSON.parse(l.body)):null}async function $m(e,t){const r=ra(t.sessionCookie,""),n=al(t),a=JSON.stringify({session_key:r}),o=ol(n,a),i=il(e,"config/",r),s=await sl(i,o,t);return s?(aa(t.sessionCookie,s.session_key),aa(t.debugCookie,s.debug_mode),Vt=s.debug_mode||si,s):null}function Lm(e,t){try{const r=(e||[]).map(n=>{if(n.role===tt.USER)return _t(n,n.content,bt.OUTGOING,n.role);if(n.role===tt.SYSTEM)return _t(n,n.content,bt.INCOMING,n.role);if(n.role===tt.ASSISTANT)return _t(n,n.content,bt.INCOMING,n.role);if(n.role===tt.SMARTER)return _t(n,n.content,bt.INCOMING,n.role);if(n.role===tt.TOOL)return _t(n,n.content,bt.INCOMING,n.role);console.error(`chatRestoreFromBackend() Invalid role received: ${n.role}`)}).filter(n=>n&&typeof n=="object"&&!Array.isArray(n));if(t?.choices?.[0]?.message?.content){const n=t.choices[0].message,a=n.content;r.push(_t(n,a,bt.INCOMING,tt.ASSISTANT))}return r}catch(r){return console.error(`chatRestoreFromBackend() Error occurred while restoring chat from backend: ${r}`),[]}}const Dm=e=>e.length==0?"":`Some example prompts to get you started:\r
596
596
  \r
597
597
  `+e.map(t=>t+`\r
598
- `).join("");function Rm(e,t,r){let n=[_t({},t,bt.INCOMING,tt.SYSTEM)];n.push(_t({},e,bt.INCOMING,tt.ASSISTANT));const a=Dm(r);return a&&n.push(_t({},a,bt.INCOMING,tt.ASSISTANT)),n}function Fm(e){if(typeof e!="string")return console.error(`convertMarkdownLinksToHTML() Expected a string but received ${typeof e}`),console.error("convertMarkdownLinksToHTML() broke here",e),e;const t=/\[([^\]]+)\]\(([^)]+)\)/g;return e.replace(t,'<a href="$2">$1</a>')}function _t(e,t,r,n){const a=typeof t=="string"&&t!==null,i={message:a?Fm(t):t,direction:r,sender:n,sentTime:new Date().toLocaleString(),display:a};return e?i.originalMessage=e:i.originalMessage=i,i}function zm(e){let t=e.originalMessage||{};return t.role=e.originalMessage&&e.originalMessage.role?e.originalMessage.role:e.sender,t.content=e.originalMessage&&e.originalMessage.message?e.originalMessage.message:e.message,t}function Wm(e){return e.filter(t=>rl.includes(t.sender)).map((t,r)=>zm(t))}function Bm(e,t,r,n,a,o){let i=[];return i=Lm(a,o),i.length===0&&(i=Rm(e,t,r)),i}class cl extends w.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t,r){console.error(t,r)}render(){return this.state.hasError?ne.jsx("h1",{children:"Something went wrong."}):this.props.children}}cl.propTypes={children:d.node};function Hm({apiUrl:e,apiKey:t,toggleMetadata:r,csrfCookieName:n="csrftoken",csrftoken:a,debugCookieName:o,debugCookieExpiration:i,debugMode:s=!1,sessionCookieName:c="session_key",sessionCookieExpiration:l,authSessionCookieName:u="sessionid",showConsole:h=!0,cookieDomain:b}){const[g,_]=w.useState(e),[E,L]=w.useState(r),[I,P]=w.useState(!1),[z,f]=w.useState({}),[S,D]=w.useState(""),[F,K]=w.useState(""),[C,M]=w.useState(""),[B,J]=w.useState(!1),[N,de]=w.useState(""),[oe,$]=w.useState(""),[ce,_e]=w.useState(!1),[he,A]=w.useState(!1),[q,X]=w.useState(s),[re,te]=w.useState([]),[le,V]=w.useState(!1),[Q,ee]=w.useState(!1),[ie,ue]=w.useState(""),[Ce,G]=w.useState(""),Pe=w.useRef(null),Xe=oa(n,null,b,a),nt=oa(u,null,b,null),ut=oa(c,l,b,null),Ut=oa(o,i,b,null),wt={authTokenCookie:nt,csrfCookie:Xe,sessionCookie:ut,debugCookie:Ut},Et=async()=>{const ae=await $m(g,wt);return X(ae?.debug_mode),aa(wt.debugCookie,debugModeStateState),q&&console.log("refetchConfig() config:",ae),d.checkPropTypes(Oa,ae,"prop","SmarterChat"),f(ae),ae},Rt=async()=>{try{const ae=await Et();q&&console.log("fetchAndSetConfig() config:",ae),D(ae.chatbot.app_placeholder),_(ae.chatbot.url_chatbot),K(ae.chatbot.app_assistant),M(ae.chatbot.app_info_url),J(ae.chatbot.app_file_attachment),_e(ae.meta_data.is_valid),A(ae.meta_data.is_deployed),X(ae.debug_mode);const Se=ae.history?.chat_history||[],ge=Bm(ae.chatbot.app_welcome_message,ae.chatbot.default_system_role,ae.chatbot.app_example_prompts,ae.session_key,Se,"BACKEND_CHAT_MOST_RECENT_RESPONSE");te(ge);const Ye=`${ae.chatbot.app_name} v${ae.chatbot.version||"1.0.0"}`;de(Ye);let Fe=`${ae.chatbot.provider} ${ae.chatbot.default_model}`;ae.plugins.meta_data.total_plugins>0&&(Fe+=` with ${ae.plugins.meta_data.total_plugins} additional plugins`),$(Fe),P(!0),V(!1),q&&console.log("fetchAndSetConfig() done!")}catch(ae){console.error("Failed to fetch config:",ae)}};w.useEffect(()=>(q&&console.log("ChatApp() component mounted"),Rt(),()=>{q&&console.log("ChatApp() component unmounted")}),[]);function St(ae,Se){ee(!0),G(ae),ue(Se)}function ct(){ee(!1)}const Ve=()=>{const ae=!E;L(ae),q&&console.log("showMetadata:",ae);const Se=re.map(ge=>ge.message===null?{...ge,display:!1}:["smarter","system","tool"].includes(ge.sender)?{...ge,display:ae}:{...ge,display:!0});te(Se)},Tt=()=>{aa(wt.sessionCookie,""),Rt()};async function H(ae,Se=!1){const ge=_t({},ae,bt.OUTGOING,tt.USER);Se&&console.error("base64 encoding not implemented yet."),te(Ye=>{const Fe=[...Ye,ge];return V(!0),(async()=>{try{q&&console.log("handleApiRequest() messages:",Fe);const rt=Wm(Fe),at=await Im(z,rt,wt);if(at){const ze=at.smarter.messages.filter(me=>me.content!==null).map(me=>_t(me,me.content,bt.INCOMING,me.role));te(me=>[...me,...ze]),V(!1),Et()}}catch(rt){V(!1),console.error("Api error: ",rt),St("Api error",rt.message)}})(),Fe})}const k=async()=>{Pe.current.click()};function T(ae){const Se=ae.target.files[0],ge=new FileReader;ge.onload=Ye=>{const Fe=Ye.target.result;H(Fe,!0)},ge.readAsText(Se)}const Y=ae=>{const Se=ae.replace(/<[^>]+>/g,"");Se.trim()&&H(Se,!1)};function Z({title:ae,isValid:Se,isDeployed:ge}){return ne.jsx("div",{children:I?ne.jsxs(ne.Fragment,{children:[ae," ",Se?ne.jsx(Ze,{icon:xu,style:{color:"green"}}):ne.jsx(Ze,{icon:Mu,style:{color:"red"}}),ge?ne.jsxs(ne.Fragment,{children:[" ",ne.jsx(Ze,{icon:ku,style:{color:"orange"}})]}):null]}):ne.jsx("div",{children:"Loading..."})})}function se({i:ae,message:Se}){let ge="";return Se.sender==="smarter"?ge="smarter-message":["tool","system"].includes(Se.sender)&&(ge="system-message"),ne.jsx(Lt,{model:Se,className:ge},ae)}const we={width:"100%"},be={backgroundColor:"rgba(0,0,0,0.10)",color:"lightgray"},Me={width:"100%",height:"100%"},Re={...we,...be};return ne.jsx("div",{id:"smarter_chat_component_container",className:"SmarterChat",children:ne.jsx(Cm,{children:ne.jsx(xm,{children:ne.jsxs(Nm,{children:[ne.jsx(km,{children:ne.jsx("div",{className:"chat-app",children:ne.jsxs(ic,{style:Me,children:[ne.jsx(cl,{children:ne.jsx(pc,{isModalOpen:Q,title:Ce,message:ie,onCloseClick:ct})}),ne.jsxs(nc,{style:Re,children:[ne.jsxs(xt,{children:[ne.jsx(xt.Content,{userName:I?ne.jsx(Z,{title:N,isValid:ce,isDeployed:he}):"Configuring workbench...",info:I?oe:""}),ne.jsxs(xt.Actions,{children:[ne.jsx(Os,{onClick:Tt,title:"Start a new chat"}),r&&ne.jsx(ys,{onClick:Ve,title:"Toggle system meta data"})]})]}),ne.jsx(Yt,{style:be,scrollBehavior:"auto",typingIndicator:le?ne.jsx(fc,{content:F+" is typing"}):null,children:re.filter(ae=>ae.display).map((ae,Se)=>ne.jsx(se,{i:Se,message:ae}))}),ne.jsx(_n,{placeholder:S,onSend:Y,onAttachClick:k,attachButton:B,fancyScroll:!1})]}),ne.jsx("input",{type:"file",accept:".py",title:"Select a Python file",ref:Pe,style:{display:"none"},onChange:T})]})})}),h&&ne.jsx(Tm,{children:ne.jsx(Bo,{config:z})})]})})})})}const Ym="0.2.13";Ge.ConfigPropTypes=Oa,Ge.Console=Bo,Ge.MenuItems=gt,Ge.MessageDirectionEnum=bt,Ge.SenderRoleEnum=tt,Ge.SmarterChat=Hm,Ge.ValidMessageRolesEnum=rl,Ge.version=Ym,Object.defineProperty(Ge,Symbol.toStringTag,{value:"Module"})}));
598
+ `).join("");function Rm(e,t,r){let n=[_t({},t,bt.INCOMING,tt.SYSTEM)];n.push(_t({},e,bt.INCOMING,tt.ASSISTANT));const a=Dm(r);return a&&n.push(_t({},a,bt.INCOMING,tt.ASSISTANT)),n}function Fm(e){if(typeof e!="string")return console.error(`convertMarkdownLinksToHTML() Expected a string but received ${typeof e}`),console.error("convertMarkdownLinksToHTML() broke here",e),e;const t=/\[([^\]]+)\]\(([^)]+)\)/g;return e.replace(t,'<a href="$2">$1</a>')}function _t(e,t,r,n){const a=typeof t=="string"&&t!==null,i={message:a?Fm(t):t,direction:r,sender:n,sentTime:new Date().toLocaleString(),display:a};return e?i.originalMessage=e:i.originalMessage=i,i}function zm(e){let t=e.originalMessage||{};return t.role=e.originalMessage&&e.originalMessage.role?e.originalMessage.role:e.sender,t.content=e.originalMessage&&e.originalMessage.message?e.originalMessage.message:e.message,t}function Wm(e){return e.filter(t=>rl.includes(t.sender)).map((t,r)=>zm(t))}function Bm(e,t,r,n,a,o){let i=[];return i=Lm(a,o),i.length===0&&(i=Rm(e,t,r)),i}class cl extends w.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t,r){console.error(t,r)}render(){return this.state.hasError?ne.jsx("h1",{children:"Something went wrong."}):this.props.children}}cl.propTypes={children:d.node};function Hm({apiUrl:e,apiKey:t,toggleMetadata:r,csrfCookieName:n="csrftoken",csrftoken:a,debugCookieName:o,debugCookieExpiration:i,debugMode:s=!1,sessionCookieName:c="session_key",sessionCookieExpiration:l,authSessionCookieName:u="sessionid",showConsole:h=!0,cookieDomain:b}){const[g,_]=w.useState(e),[E,L]=w.useState(r),[I,P]=w.useState(!1),[z,f]=w.useState({}),[S,D]=w.useState(""),[F,K]=w.useState(""),[C,M]=w.useState(""),[B,J]=w.useState(!1),[N,de]=w.useState(""),[oe,$]=w.useState(""),[ce,_e]=w.useState(!1),[he,A]=w.useState(!1),[q,X]=w.useState(s),[re,te]=w.useState([]),[le,V]=w.useState(!1),[Q,ee]=w.useState(!1),[ie,ue]=w.useState(""),[Ce,G]=w.useState(""),Pe=w.useRef(null),Xe=oa(n,null,b,a),nt=oa(u,null,b,null),ut=oa(c,l,b,null),Ut=oa(o,i,b,null),wt={authTokenCookie:nt,csrfCookie:Xe,sessionCookie:ut,debugCookie:Ut},Et=async()=>{const ae=await $m(g,wt);return X(ae?.debug_mode),aa(wt.debugCookie,q),q&&console.log("refetchConfig() config:",ae),d.checkPropTypes(Oa,ae,"prop","SmarterChat"),f(ae),ae},Rt=async()=>{try{const ae=await Et();q&&console.log("fetchAndSetConfig() config:",ae),D(ae.chatbot.app_placeholder),_(ae.chatbot.url_chatbot),K(ae.chatbot.app_assistant),M(ae.chatbot.app_info_url),J(ae.chatbot.app_file_attachment),_e(ae.meta_data.is_valid),A(ae.meta_data.is_deployed),X(ae.debug_mode);const Se=ae.history?.chat_history||[],ge=Bm(ae.chatbot.app_welcome_message,ae.chatbot.default_system_role,ae.chatbot.app_example_prompts,ae.session_key,Se,"BACKEND_CHAT_MOST_RECENT_RESPONSE");te(ge);const Ye=`${ae.chatbot.app_name} v${ae.chatbot.version||"1.0.0"}`;de(Ye);let Fe=`${ae.chatbot.provider} ${ae.chatbot.default_model}`;ae.plugins.meta_data.total_plugins>0&&(Fe+=` with ${ae.plugins.meta_data.total_plugins} additional plugins`),$(Fe),P(!0),V(!1),q&&console.log("fetchAndSetConfig() done!")}catch(ae){console.error("Failed to fetch config:",ae)}};w.useEffect(()=>(q&&console.log("ChatApp() component mounted"),Rt(),()=>{q&&console.log("ChatApp() component unmounted")}),[]);function St(ae,Se){ee(!0),G(ae),ue(Se)}function ct(){ee(!1)}const Ve=()=>{const ae=!E;L(ae),q&&console.log("showMetadata:",ae);const Se=re.map(ge=>ge.message===null?{...ge,display:!1}:["smarter","system","tool"].includes(ge.sender)?{...ge,display:ae}:{...ge,display:!0});te(Se)},Tt=()=>{aa(wt.sessionCookie,""),Rt()};async function H(ae,Se=!1){const ge=_t({},ae,bt.OUTGOING,tt.USER);Se&&console.error("base64 encoding not implemented yet."),te(Ye=>{const Fe=[...Ye,ge];return V(!0),(async()=>{try{q&&console.log("handleApiRequest() messages:",Fe);const rt=Wm(Fe),at=await Im(z,rt,wt);if(at){const ze=at.smarter.messages.filter(me=>me.content!==null).map(me=>_t(me,me.content,bt.INCOMING,me.role));te(me=>[...me,...ze]),V(!1),Et()}}catch(rt){V(!1),console.error("Api error: ",rt),St("Api error",rt.message)}})(),Fe})}const k=async()=>{Pe.current.click()};function T(ae){const Se=ae.target.files[0],ge=new FileReader;ge.onload=Ye=>{const Fe=Ye.target.result;H(Fe,!0)},ge.readAsText(Se)}const Y=ae=>{const Se=ae.replace(/<[^>]+>/g,"");Se.trim()&&H(Se,!1)};function Z({title:ae,isValid:Se,isDeployed:ge}){return ne.jsx("div",{children:I?ne.jsxs(ne.Fragment,{children:[ae," ",Se?ne.jsx(Ze,{icon:xu,style:{color:"green"}}):ne.jsx(Ze,{icon:Mu,style:{color:"red"}}),ge?ne.jsxs(ne.Fragment,{children:[" ",ne.jsx(Ze,{icon:ku,style:{color:"orange"}})]}):null]}):ne.jsx("div",{children:"Loading..."})})}function se({i:ae,message:Se}){let ge="";return Se.sender==="smarter"?ge="smarter-message":["tool","system"].includes(Se.sender)&&(ge="system-message"),ne.jsx(Lt,{model:Se,className:ge},ae)}const we={width:"100%"},be={backgroundColor:"rgba(0,0,0,0.10)",color:"lightgray"},Me={width:"100%",height:"100%"},Re={...we,...be};return ne.jsx("div",{id:"smarter_chat_component_container",className:"SmarterChat",children:ne.jsx(Cm,{children:ne.jsx(xm,{children:ne.jsxs(Nm,{children:[ne.jsx(km,{children:ne.jsx("div",{className:"chat-app",children:ne.jsxs(ic,{style:Me,children:[ne.jsx(cl,{children:ne.jsx(pc,{isModalOpen:Q,title:Ce,message:ie,onCloseClick:ct})}),ne.jsxs(nc,{style:Re,children:[ne.jsxs(xt,{children:[ne.jsx(xt.Content,{userName:I?ne.jsx(Z,{title:N,isValid:ce,isDeployed:he}):"Configuring workbench...",info:I?oe:""}),ne.jsxs(xt.Actions,{children:[ne.jsx(Os,{onClick:Tt,title:"Start a new chat"}),r&&ne.jsx(ys,{onClick:Ve,title:"Toggle system meta data"})]})]}),ne.jsx(Yt,{style:be,scrollBehavior:"auto",typingIndicator:le?ne.jsx(fc,{content:F+" is typing"}):null,children:re.filter(ae=>ae.display).map((ae,Se)=>ne.jsx(se,{i:Se,message:ae}))}),ne.jsx(_n,{placeholder:S,onSend:Y,onAttachClick:k,attachButton:B,fancyScroll:!1})]}),ne.jsx("input",{type:"file",accept:".py",title:"Select a Python file",ref:Pe,style:{display:"none"},onChange:T})]})})}),h&&ne.jsx(Tm,{children:ne.jsx(Bo,{config:z})})]})})})})}const Ym="0.2.14";Ge.ConfigPropTypes=Oa,Ge.Console=Bo,Ge.MenuItems=gt,Ge.MessageDirectionEnum=bt,Ge.SenderRoleEnum=tt,Ge.SmarterChat=Hm,Ge.ValidMessageRolesEnum=rl,Ge.version=Ym,Object.defineProperty(Ge,Symbol.toStringTag,{value:"Module"})}));
599
599
  //# sourceMappingURL=smarter-chat-library.umd.js.map