@hsafa/ui-sdk 0.4.2 → 0.4.4
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.cjs +14 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +20 -200
- package/dist/index.d.ts +20 -200
- package/dist/index.js +14 -14
- package/dist/index.js.map +1 -1
- package/package.json +4 -2
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var jsxRuntime=require('react/jsx-runtime'),st=require('react'),react=require('@ai-sdk/react'),ai=require('ai'),client=require('react-dom/client'),dt=require('fast-json-patch'),reactDom=require('react-dom'),lucideReact=require('lucide-react');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var st__default=/*#__PURE__*/_interopDefault(st);var dt__namespace=/*#__PURE__*/_interopNamespace(dt);var we={};var Zo=({variant:n="primary",size:e="md",loading:t=false,disabled:o,children:r,className:i,...c})=>{let d=[we.button,we[n],we[e],t&&we.loading,i].filter(Boolean).join(" ");return jsxRuntime.jsxs("button",{className:d,disabled:o||t,...c,children:[t&&jsxRuntime.jsx("span",{className:we.spinner}),jsxRuntime.jsx("span",{className:t?we.hiddenText:void 0,children:r})]})};function nn({show:n,onClick:e,resolvedColors:t,floatingButtonPosition:o}){if(!n)return null;let r={position:"fixed",bottom:typeof o.bottom=="number"?`${o.bottom}px`:o.bottom,right:o.right?typeof o.right=="number"?`${o.right}px`:o.right:void 0,top:o.top?typeof o.top=="number"?`${o.top}px`:o.top:void 0,left:o.left?typeof o.left=="number"?`${o.left}px`:o.left:void 0,zIndex:1e3};return jsxRuntime.jsx("button",{"aria-label":"Open chat",onClick:e,style:{...r,borderColor:t.borderColor,backgroundColor:t.accentColor,color:t.textColor,borderRadius:"50%",border:`1px solid ${t.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:i=>{i.currentTarget.style.borderColor=t.primaryColor,i.currentTarget.style.backgroundColor=`${t.accentColor}dd`;},onMouseLeave:i=>{i.currentTarget.style.borderColor=t.borderColor,i.currentTarget.style.backgroundColor=t.accentColor;},children:jsxRuntime.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function an(n=true){let e=st.useRef(null),t=st.useRef(n);return st.useEffect(()=>{t.current=n;},[n]),st.useEffect(()=>{let o=e.current;if(!o)return;let r=new MutationObserver(()=>{t.current&&(o.scrollTop=o.scrollHeight);});return r.observe(o,{childList:true,subtree:true}),t.current&&(o.scrollTop=o.scrollHeight),()=>r.disconnect()},[]),e}function sn(n,e){if(!n)return e;let t=n.endsWith("/")?n.slice(0,-1):n,o=e.startsWith("/")?e:`/${e}`;return `${t}${o}`}var ln=st.createContext(void 0);function Cr({baseUrl:n,dir:e="ltr",theme:t="dark",children:o}){let[r,i]=st.useState(new Map),[c,d]=st.useState(new Map),[u,x]=st.useState(new Map),[g,T]=st.useState(new Map),[y,C]=st.useState(void 0),[a,p]=st.useState(new Map),s=y?a.get(y)||[]:[],l=st.useCallback((S,A)=>(i(F=>{let M=new Map(F);return M.set(String(S),A),M}),()=>{i(F=>{let M=new Map(F),$=M.get(String(S));return (!A||$===A)&&M.delete(String(S)),M});}),[]),m=st.useCallback((S,A)=>{i(F=>{let M=new Map(F),$=M.get(String(S));return (!A||$===A)&&M.delete(String(S)),M});},[]),f=st.useCallback((S,A)=>(d(F=>{let M=new Map(F);return M.set(String(S),A),M}),()=>{d(F=>{let M=new Map(F),$=M.get(String(S));return (!A||$===A)&&M.delete(String(S)),M});}),[]),v=st.useCallback((S,A)=>{d(F=>{let M=new Map(F),$=M.get(String(S));return (!A||$===A)&&M.delete(String(S)),M});},[]),I=st.useCallback((S,A)=>{x(F=>{let M=new Map(F);return A?M.set(S,true):M.delete(S),M});},[]),k=st.useCallback((S,A)=>{T(F=>{let M=new Map(F);return M.set(S,A),M});},[]),b=st.useCallback((S,A)=>{p(F=>{let M=new Map(F);return M.set(S,A),M});},[]),h=st.useCallback(S=>{p(A=>{let F=new Map(A);return F.delete(S),F});},[]),E=st.useMemo(()=>Array.from(u.values()).some(S=>S),[u]),w=st.useMemo(()=>Array.from(g.values()).some(S=>S),[g]),P=st.useMemo(()=>({baseUrl:n,dir:e,theme:t,actions:r,components:c,registerAction:l,unregisterAction:m,registerComponent:f,unregisterComponent:v,isAnyStreaming:E,setStreamingState:I,isAnyChatOpen:w,setChatOpenState:k,currentChatId:y,setCurrentChatId:C,dynamicPageTypes:s,registerDynamicPageTypes:b,unregisterDynamicPageTypes:h}),[n,e,t,r,c,l,m,f,v,E,I,w,k,y,s,b,h]);return jsxRuntime.jsx(ln.Provider,{value:P,children:o})}function ne(){let n=st.useContext(ln);return n||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{},currentChatId:void 0,setCurrentChatId:()=>{},dynamicPageTypes:[],registerDynamicPageTypes:()=>{},unregisterDynamicPageTypes:()=>{}}}var _t=25*1024*1024;function dn(n){let{baseUrl:e}=ne(),t=n||e||"",[o,r]=st.useState([]),[i,c]=st.useState(false),d=st.useRef(null),u=st.useCallback(a=>{if(!a||Number.isNaN(a))return "0 B";let p=["B","KB","MB","GB","TB"],s=Math.min(p.length-1,Math.floor(Math.log(a)/Math.log(1024)));return `${(a/Math.pow(1024,s)).toFixed(s===0?0:1)} ${p[s]}`},[]),x=st.useCallback(async a=>{let p=new FormData;p.append("file",a);let s=await fetch(sn(t,"/api/uploads"),{method:"POST",body:p});if(!s.ok){let m=await s.text().catch(()=>"");throw new Error(m||`Failed to upload ${a.name}`)}let l=await s.json();return {id:l.id,name:l.name||a.name,url:l.url,mimeType:l.mimeType||a.type||"application/octet-stream",size:typeof l.size=="number"?l.size:a.size}},[t]),g=st.useCallback(a=>{r(p=>p.filter(s=>s.id!==a));},[]),T=st.useCallback(async(a,p)=>{if(!a)return;let s=Array.isArray(a)?a:Array.from(a);p(null),c(true);let l=[];try{for(let m of s){if(m.size>_t){p(`"${m.name}" exceeds the ${u(_t)} limit.`);continue}try{let f=await x(m);l.push(f);}catch(f){console.error("Failed to upload attachment:",f),p(String(f?.message??`Failed to upload ${m.name}`));}}l.length&&r(m=>[...m,...l]);}finally{c(false);}},[x,u]),y=st.useCallback((a,p)=>{let s=[],l=(a||"").trim();l&&s.push({type:"text",text:l});for(let m of p||[]){let f=m.mimeType||"application/octet-stream";f.startsWith("image/")?s.push({type:"image",image:new URL(m.url),mediaType:f}):s.push({type:"file",data:m.url,mediaType:f,name:m.name});}return s},[]),C=st.useCallback(()=>{r([]);},[]);return {attachments:o,uploading:i,fileInputRef:d,formatBytes:u,handleRemoveAttachment:g,handleFileSelection:T,buildUserContent:y,clearAttachments:C,setAttachments:r,MAX_UPLOAD_SIZE:_t}}function un(n,e,t){return new ai.DefaultChatTransport({api:`${n}/api/run/${e}`,fetch:async(o,r)=>{let c={...r?.body?JSON.parse(r.body):{},chatId:t};return fetch(o,{...r,body:JSON.stringify(c)})}})}function Tr(n){if(!(n instanceof HTMLElement))return true;let e=window.getComputedStyle(n);return e.display!=="none"&&e.visibility!=="hidden"&&e.opacity!=="0"&&n.offsetParent!==null}function Sr(n){if(n.id){let t=document.querySelector(`label[for="${n.id}"]`);if(t)return t.textContent?.trim()}let e=n.closest("label");if(e){let t=e.cloneNode(true),o=t.querySelector("input, select, textarea");return o&&o.remove(),t.textContent?.trim()}}function jt(n){if(n.textContent&&n.textContent.trim())return n.textContent.trim().slice(0,100)}function Dt(n){if(n instanceof HTMLInputElement){let e=n.type.toLowerCase();return e==="checkbox"||e==="radio"?n.checked:n.value}if(n instanceof HTMLTextAreaElement)return n.value;if(n instanceof HTMLSelectElement)return n.multiple?Array.from(n.selectedOptions).map(e=>e.value):n.value;if(n instanceof HTMLElement&&n.isContentEditable)return n.textContent||void 0}function Er(n){if(n.id)return `#${n.id}`;let e=[],t=n;for(;t&&t!==document.body;){let o=t.tagName.toLowerCase();if(t.className&&typeof t.className=="string"){let i=t.className.split(" ").filter(c=>c.trim()).slice(0,2);i.length>0&&(o+="."+i.join("."));}let r=t.parentElement;if(r){let i=Array.from(r.children).filter(c=>c.tagName===t.tagName);if(i.length>1){let c=i.indexOf(t)+1;o+=`:nth-child(${c})`;}}e.unshift(o),t=r;}return e.slice(-3).join(" > ")}async function Ue(n={}){try{let{includeHidden:e=!1,selector:t,what:o="content",limit:r}=n,i=document.querySelector(".hsafa-content-container");if(!i)return {ok:!1,components:[],count:0,total:0,containerFound:!1,error:"ContentContainer not found on page. Make sure you have wrapped your app with <ContentContainer>."};let c=t&&i.querySelector(t)||i,d=[],u=[];o==="inputs"?u=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:u=["header","nav","main","section","article","aside","footer","h1","h2","h3","h4","h5","h6","p","img[alt]","ul","ol","li","table","thead","tbody","tr","td","th","form","label","input","textarea","select",'[contenteditable="true"]','[contenteditable=""]',"a[href]","button",'[role="button"]','[role="link"]',"[onclick]","[tabindex]","div"],c.querySelectorAll(u.join(", ")).forEach(s=>{let l=Tr(s);if(!l&&!e)return;let m={id:s.id||null,tag:s.tagName.toLowerCase(),className:s.className&&typeof s.className=="string"?s.className:void 0,isVisible:l,isInteractive:!0,selector:Er(s)};s instanceof HTMLInputElement?(m.type=s.type,m.name=s.name||void 0,m.placeholder=s.placeholder||void 0,m.value=Dt(s),m.checked=s.type==="checkbox"||s.type==="radio"?s.checked:void 0,m.disabled=s.disabled,m.required=s.required):s instanceof HTMLTextAreaElement?(m.name=s.name||void 0,m.placeholder=s.placeholder||void 0,m.value=Dt(s),m.disabled=s.disabled,m.required=s.required):s instanceof HTMLSelectElement?(m.name=s.name||void 0,m.value=Dt(s),m.disabled=s.disabled,m.required=s.required,m.options=Array.from(s.options).map(f=>({value:f.value,label:f.text,selected:f.selected,disabled:f.disabled}))):s instanceof HTMLButtonElement?(m.type=s.type,m.disabled=s.disabled,m.text=jt(s)):s instanceof HTMLAnchorElement?(m.href=s.href,m.text=jt(s)):s instanceof HTMLImageElement?(m.text=s.alt||void 0,m.label=s.alt||m.label):m.text=jt(s),m.label=Sr(s),m.role=s.getAttribute("role")||void 0,m.ariaLabel=s.getAttribute("aria-label")||void 0,d.push(m);});let g=s=>s.isVisible?o==="inputs"?s.tag==="input"||s.tag==="textarea"||s.tag==="select"||s.role==="textbox"?3:s.tag==="button"||s.tag==="a"?2:1:["header","nav","main","footer"].includes(s.tag)?5:["section","article","aside"].includes(s.tag)||["h1","h2","h3"].includes(s.tag)?4:["h4","h5","h6"].includes(s.tag)?3:s.tag==="form"?4:s.tag==="label"?3:s.tag==="input"||s.tag==="textarea"||s.tag==="select"?4:s.tag==="p"||s.tag==="img"||s.tag==="button"||s.tag==="a"?3:1:0;d.sort((s,l)=>g(l)-g(s));let T=d.length,C=Math.max(1,Math.min(200,typeof r=="number"?Math.floor(r):o==="inputs"?100:150)),a=T>C,p=a?d.slice(0,C):d;return {ok:!0,components:p,count:p.length,total:T,truncated:a,containerFound:!0}}catch(e){return {ok:false,components:[],count:0,total:0,containerFound:false,error:e?.message||String(e)}}}typeof window<"u"&&(window.getDomComponents=Ue);async function Te(n,e={}){if(typeof window>"u")return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"guideCursor only works in browser environment"}]};let t=window.__cursorGuide;if(!t)return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"CursorController not initialized. Make sure to mount <CursorController /> component."}]};try{return await t(n,e)}catch(o){return {ok:false,steps:[{ok:false,action:e.action||"none",targetKind:"position",durationMs:0,error:o?.message||String(o)}]}}}typeof window<"u"&&(window.guideCursor=Te);function pn(n){return !!n&&n.nodeType===1}function le(n,e){n.dispatchEvent(new Event(e,{bubbles:true}));}function mn(n,e){let t=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(n),"value")?.set;t?t.call(n,e):n.value=e,le(n,"input");}function Ir(n,e){n.checked!==e&&n.click();}function Mr(n,e){if(typeof e=="object"&&e&&"index"in e&&typeof e.index=="number")n.selectedIndex=Math.max(0,Math.min(n.options.length-1,e.index));else if(typeof e=="object"&&e&&"label"in e&&typeof e.label=="string"){let t=Array.from(n.options).findIndex(o=>o.text===e.label);n.selectedIndex=t>=0?t:0;}else n.value=String(e);le(n,"input"),le(n,"change");}function Ar(n,e){let t=new Set(e.map(String));Array.from(n.options).forEach(o=>{o.selected=t.has(o.value)||t.has(o.text);}),le(n,"input"),le(n,"change");}function Rr(n){return n?n instanceof Date?n.toISOString().slice(0,10):String(n):""}function _r(n,e){let t=Array.isArray(e)?e:[e],o=new DataTransfer;for(let r of t)o.items.add(r);Object.defineProperty(n,"files",{value:o.files,configurable:true}),le(n,"input"),le(n,"change");}async function Ge(n,e={}){let t=document.activeElement||null;if(t&&pn(t)){let o=t.closest('[contenteditable="true"], [contenteditable=""]');o&&(t=o);}if(!t||t===document.body)return {ok:false,filled:[{key:"active",status:"skipped",message:"No active input element"}],errors:["No active input element"]};try{let o=t.tagName.toLowerCase();if(o==="input"){let r=t,i=(r.type||"text").toLowerCase();if(i==="checkbox")Ir(r,!!n);else if(i==="radio"){let c=r.name;if(c&&n!=null&&String(r.value)!==String(n)){let d=document.querySelector(`input[type="radio"][name="${CSS.escape(c)}"][value="${CSS.escape(String(n))}"]`);d?d.click():r.click();}else r.click();}else if(i==="file")if(n instanceof File||Array.isArray(n)&&n.every(c=>c instanceof File))_r(r,n);else return {ok:!1,filled:[{key:"active",status:"skipped",message:"Provide File or File[] for file input"}],errors:["Provide File or File[] for file input"]};else {let c=i==="date"?Rr(n):String(n??"");mn(r,c),le(r,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(o==="textarea"){let r=t,i=String(n??"");return mn(r,i),le(r,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(o==="select"){let r=t;return r.multiple?Ar(r,Array.isArray(n)?n:[n]):Mr(r,n),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(pn(t)&&t.isContentEditable){let r=t;return r.focus(),r.textContent=String(n??""),le(r,"input"),le(r,"change"),r.blur?.(),{ok:!0,filled:[{key:"active",status:"ok"}]}}return {ok:!1,filled:[{key:"active",status:"skipped",message:`Unsupported active element: ${o}`}],errors:[`Unsupported active element: ${o}`]}}catch(o){return {ok:false,filled:[{key:"active",status:"error",message:o?.message??String(o)}],errors:[o?.message??String(o)]}}}typeof window<"u"&&(window.FillActiveInput=Ge);var qe=null,et={},fn=false,De=null,nt=false;function $t(n){n.classList.add("visible");}function vn(){nt=true,De!=null&&(clearTimeout(De),De=null);}function Dr(n,e=1500){nt||(De!=null&&clearTimeout(De),De=window.setTimeout(()=>{nt||n.classList.remove("visible");},e));}function $r(n,e=1200){nt=false,Dr(n,e);}function Fr(n){let e=[],t=n?.parentElement;for(;t;){let o=getComputedStyle(t),r=o.overflow+o.overflowY+o.overflowX;/(auto|scroll)/.test(r)&&e.push(t),t=t.parentElement;}return e}async function Pr(n,e=1500,t=160){let o=performance.now(),r=n?Fr(n):[],i=()=>{let g=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return r.forEach(T=>{g.push(T.scrollLeft,T.scrollTop);}),g},c=()=>{if(!n)return {x:0,y:0};let g=n.getBoundingClientRect();return {x:g.left,y:g.top}},d=i(),u=c(),x=performance.now();return new Promise(g=>{function T(y){let C=i(),a=c(),p=false;for(let s=0;s<C.length;s++)if(C[s]!==d[s]){p=true;break}if(!p&&n&&(a.x!==u.x||a.y!==u.y)&&(p=true),p&&(d=C,u=a,x=y),y-x>=t||y-o>=e){g();return}requestAnimationFrame(T);}requestAnimationFrame(T);})}var Lr='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32px" height="32px"><path d="M 7.2304688 4.9863281 C 5.9215232 4.8276681 4.8053213 6.0177722 5.0234375 7.3066406 A 1.0001 1.0001 0 0 0 5.0253906 7.3085938 C 5.9996339 12.981516 7.7205826 18.716222 10 24.515625 A 1.0001 1.0001 0 0 0 10 24.517578 C 10.26886 25.199332 10.914322 25.653844 11.5625 25.738281 C 12.210678 25.822721 12.879213 25.592031 13.359375 25.09375 C 14.505165 23.921134 15.214424 22.695429 15.90625 21.498047 C 17.56565 23.217848 19.256845 24.909775 21.0625 26.484375 L 21.060547 26.480469 C 21.799528 27.12933 22.841378 27.205969 23.673828 26.78125 A 1.0001 1.0001 0 0 0 23.691406 26.771484 C 24.987999 26.077693 26.028685 25.052256 26.71875 23.746094 L 26.71875 23.744141 C 27.174557 22.900924 27.06954 21.854242 26.439453 21.119141 A 1.0001 1.0001 0 0 0 26.433594 21.113281 C 24.867416 19.313474 23.193611 17.633865 21.488281 15.986328 C 22.714141 15.237691 23.933938 14.51508 25.158203 13.414062 A 1.0001 1.0001 0 0 0 25.162109 13.410156 C 26.052979 12.600274 25.977319 11.169141 25.101562 10.404297 A 1.0001 1.0001 0 0 0 24.669922 10.042969 C 18.793373 7.4738953 12.973806 5.6931843 7.2324219 4.9882812 A 1.0001 1.0001 0 0 0 7.2304688 4.9863281 z M 6.9960938 6.9746094 C 12.468883 7.6474978 18.081513 9.3573116 23.796875 11.849609 A 1.0001 1.0001 0 0 0 23.867188 11.884766 C 23.901248 11.899796 23.884276 11.867987 23.816406 11.929688 C 22.403891 13.198979 20.999383 14.076858 19.457031 14.976562 A 1.0001 1.0001 0 0 0 19.275391 16.568359 C 21.250864 18.425305 23.134972 20.36916 24.919922 22.419922 C 25.009402 22.524309 25.024026 22.676488 24.960938 22.792969 A 1.0001 1.0001 0 0 0 24.955078 22.804688 C 24.446951 23.770198 23.730542 24.476149 22.755859 25 C 22.611605 25.06851 22.457885 25.047856 22.378906 24.978516 A 1.0001 1.0001 0 0 0 22.376953 24.976562 C 20.293628 23.159824 18.307991 21.233373 16.419922 19.216797 A 1.0001 1.0001 0 0 0 14.835938 19.378906 C 13.841812 21.004716 13.152668 22.447221 11.925781 23.701172 A 1.0001 1.0001 0 0 0 11.919922 23.707031 C 11.883822 23.744501 11.865156 23.739957 11.847656 23.742188 C 9.6161121 18.057657 7.9395914 12.46667 6.9960938 6.9746094 z"/></svg>',Hr='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="32px" height="32px"><path d="M 22.5 3 C 19.480226 3 17 5.4802259 17 8.5 L 17 23.412109 L 14.871094 22.697266 C 13.308963 22.172461 11.892528 22 10.703125 22 C 9.5908429 22 8.5540295 22.197475 7.640625 22.65625 C 5.2906802 23.831199 3.9427678 26.197397 4.0019531 28.90625 C 4.0019531 28.90625 4.0019531 28.908203 4.0019531 28.908203 C 4.0019531 28.908203 4.0019531 28.910156 4.0019531 28.910156 C 4.0184171 29.660452 4.4596385 30.354695 5.1328125 30.6875 A 1.50015 1.50015 0 0 0 5.1367188 30.689453 C 5.1367188 30.689453 9.4097266 32.789754 11.599609 33.949219 C 12.445613 34.397848 13.696939 34.926046 15.210938 36.09375 C 16.724935 37.261454 18.423179 39.012543 19.826172 41.792969 C 21.023611 44.165544 23.672779 45.195669 26.144531 44.955078 A 1.50015 1.50015 0 0 0 26.146484 44.955078 C 31.427085 44.439215 32.081856 44.381732 35.59375 44.023438 C 37.044229 43.875625 38.276993 43.213524 39.111328 42.289062 C 39.945663 41.364602 40.422895 40.257718 40.798828 39.125 C 41.561218 36.826116 42.933037 33.169846 43.671875 30.599609 C 45.018525 25.913269 41.884024 21.194549 37.246094 19.953125 L 37.242188 19.951172 C 36.99827 19.885452 36.756736 19.832884 36.521484 19.789062 A 1.50015 1.50015 0 0 0 36.513672 19.787109 L 28 18.248047 L 28 8.5 C 28 5.4802259 25.519774 3 22.5 3 z M 22.5 6 C 23.898226 6 25 7.1017741 25 8.5 L 25 19.5 A 1.50015 1.50015 0 0 0 26.232422 20.976562 L 35.980469 22.740234 C 36.14895 22.771804 36.312663 22.808524 36.464844 22.849609 A 1.50015 1.50015 0 0 0 36.46875 22.849609 C 39.614436 23.689967 41.641993 26.803286 40.789062 29.771484 C 40.115901 32.113248 38.752735 35.768572 37.953125 38.179688 C 37.641059 39.119968 37.279727 39.837554 36.882812 40.277344 C 36.485898 40.717133 36.095584 40.956874 35.289062 41.039062 C 31.783676 41.396695 31.135884 41.452908 25.855469 41.96875 C 24.423221 42.108159 23.024467 41.472831 22.503906 40.441406 C 20.887905 37.238832 18.854971 35.116296 17.042969 33.71875 C 15.230967 32.321204 13.560902 31.594199 13.003906 31.298828 C 10.939171 30.205625 7.8041786 28.665144 7.1035156 28.320312 C 7.1954033 26.8809 7.6810328 25.989859 8.9824219 25.339844 A 1.50015 1.50015 0 0 0 8.9863281 25.337891 C 9.3949198 25.132713 9.9434071 25 10.703125 25 C 11.605722 25 12.680146 25.12582 13.916016 25.541016 L 18.021484 26.921875 A 1.50015 1.50015 0 0 0 20 25.5 L 20 8.5 C 20 7.1017741 21.101774 6 22.5 6 z"/></svg>';async function Br(){if(!et.arrow)try{et.arrow=Lr,et.pointer=Hr;}catch(n){console.warn("Failed to set cursor SVGs",n);}return et}function yn({arrowSvg:n,pointerSvg:e}){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[n&&jsxRuntime.jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:n}}),e&&jsxRuntime.jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:e}})]})}async function Or(){let n="demo-fake-cursor",e=document.getElementById(n),t=await Br();if(!fn){let o="cursor-controller-styles";if(!document.getElementById(o)){let r=document.createElement("style");r.id=o,r.textContent=`
|
|
1
|
+
'use strict';var jsxRuntime=require('react/jsx-runtime'),tt=require('react'),react=require('@ai-sdk/react'),ai=require('ai'),client=require('react-dom/client'),reactDom=require('react-dom'),lucideReact=require('lucide-react');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var tt__default=/*#__PURE__*/_interopDefault(tt);var be={};var Mr=({variant:e="primary",size:t="md",loading:n=false,disabled:r,children:o,className:i,...p})=>{let c=[be.button,be[e],be[t],n&&be.loading,i].filter(Boolean).join(" ");return jsxRuntime.jsxs("button",{className:c,disabled:r||n,...p,children:[n&&jsxRuntime.jsx("span",{className:be.spinner}),jsxRuntime.jsx("span",{className:n?be.hiddenText:void 0,children:o})]})};function Wt({show:e,onClick:t,resolvedColors:n,floatingButtonPosition:r}){if(!e)return null;let o={position:"fixed",bottom:typeof r.bottom=="number"?`${r.bottom}px`:r.bottom,right:r.right?typeof r.right=="number"?`${r.right}px`:r.right:void 0,top:r.top?typeof r.top=="number"?`${r.top}px`:r.top:void 0,left:r.left?typeof r.left=="number"?`${r.left}px`:r.left:void 0,zIndex:1e3};return jsxRuntime.jsx("button",{"aria-label":"Open chat",onClick:t,style:{...o,borderColor:n.borderColor,backgroundColor:n.accentColor,color:n.textColor,borderRadius:"50%",border:`1px solid ${n.borderColor}`,padding:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",transition:"all 0.2s",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:i=>{i.currentTarget.style.borderColor=n.primaryColor,i.currentTarget.style.backgroundColor=`${n.accentColor}dd`;},onMouseLeave:i=>{i.currentTarget.style.borderColor=n.borderColor,i.currentTarget.style.backgroundColor=n.accentColor;},children:jsxRuntime.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}function _t(e=true){let t=tt.useRef(null),n=tt.useRef(e);return tt.useEffect(()=>{n.current=e;},[e]),tt.useEffect(()=>{let r=t.current;if(!r)return;let o=new MutationObserver(()=>{n.current&&(r.scrollTop=r.scrollHeight);});return o.observe(r,{childList:true,subtree:true}),n.current&&(r.scrollTop=r.scrollHeight),()=>o.disconnect()},[]),t}function jt(e,t){if(!e)return t;let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`;return `${n}${r}`}var qt=tt.createContext(void 0);function ro({baseUrl:e,dir:t="ltr",theme:n="dark",children:r}){let[o,i]=tt.useState(new Map),[p,c]=tt.useState(new Map),[b,T]=tt.useState(new Map),[h,S]=tt.useState(new Map),[x,k]=tt.useState(void 0),a=tt.useCallback((l,u)=>(i(w=>{let f=new Map(w);return f.set(String(l),u),f}),()=>{i(w=>{let f=new Map(w),A=f.get(String(l));return (!u||A===u)&&f.delete(String(l)),f});}),[]),v=tt.useCallback((l,u)=>{i(w=>{let f=new Map(w),A=f.get(String(l));return (!u||A===u)&&f.delete(String(l)),f});},[]),s=tt.useCallback((l,u)=>(c(w=>{let f=new Map(w);return f.set(String(l),u),f}),()=>{c(w=>{let f=new Map(w),A=f.get(String(l));return (!u||A===u)&&f.delete(String(l)),f});}),[]),d=tt.useCallback((l,u)=>{c(w=>{let f=new Map(w),A=f.get(String(l));return (!u||A===u)&&f.delete(String(l)),f});},[]),g=tt.useCallback((l,u)=>{T(w=>{let f=new Map(w);return u?f.set(l,true):f.delete(l),f});},[]),y=tt.useCallback((l,u)=>{S(w=>{let f=new Map(w);return f.set(l,u),f});},[]),m=tt.useMemo(()=>Array.from(b.values()).some(l=>l),[b]),I=tt.useMemo(()=>Array.from(h.values()).some(l=>l),[h]),C=tt.useMemo(()=>({baseUrl:e,dir:t,theme:n,actions:o,components:p,registerAction:a,unregisterAction:v,registerComponent:s,unregisterComponent:d,isAnyStreaming:m,setStreamingState:g,isAnyChatOpen:I,setChatOpenState:y,currentChatId:x,setCurrentChatId:k}),[e,t,n,o,p,a,v,s,d,m,g,I,y,x]);return jsxRuntime.jsx(qt.Provider,{value:C,children:r})}function re(){let e=tt.useContext(qt);return e||{baseUrl:void 0,actions:new Map,components:new Map,registerAction:()=>()=>{},unregisterAction:()=>{},registerComponent:()=>()=>{},unregisterComponent:()=>{},isAnyStreaming:false,setStreamingState:()=>{},isAnyChatOpen:false,setChatOpenState:()=>{},currentChatId:void 0,setCurrentChatId:()=>{}}}var Ct=25*1024*1024;function Kt(e){let{baseUrl:t}=re(),n=e||t||"",[r,o]=tt.useState([]),[i,p]=tt.useState(false),c=tt.useRef(null),b=tt.useCallback(a=>{if(!a||Number.isNaN(a))return "0 B";let v=["B","KB","MB","GB","TB"],s=Math.min(v.length-1,Math.floor(Math.log(a)/Math.log(1024)));return `${(a/Math.pow(1024,s)).toFixed(s===0?0:1)} ${v[s]}`},[]),T=tt.useCallback(async a=>{let v=new FormData;v.append("file",a);let s=await fetch(jt(n,"/api/uploads"),{method:"POST",body:v});if(!s.ok){let g=await s.text().catch(()=>"");throw new Error(g||`Failed to upload ${a.name}`)}let d=await s.json();return {id:d.id,name:d.name||a.name,url:d.url,mimeType:d.mimeType||a.type||"application/octet-stream",size:typeof d.size=="number"?d.size:a.size}},[n]),h=tt.useCallback(a=>{o(v=>v.filter(s=>s.id!==a));},[]),S=tt.useCallback(async(a,v)=>{if(!a)return;let s=Array.isArray(a)?a:Array.from(a);v(null),p(true);let d=[];try{for(let g of s){if(g.size>Ct){v(`"${g.name}" exceeds the ${b(Ct)} limit.`);continue}try{let y=await T(g);d.push(y);}catch(y){console.error("Failed to upload attachment:",y),v(String(y?.message??`Failed to upload ${g.name}`));}}d.length&&o(g=>[...g,...d]);}finally{p(false);}},[T,b]),x=tt.useCallback((a,v)=>{let s=[],d=(a||"").trim();d&&s.push({type:"text",text:d});for(let g of v||[]){let y=g.mimeType||"application/octet-stream";y.startsWith("image/")?s.push({type:"image",image:new URL(g.url),mediaType:y}):s.push({type:"file",data:g.url,mediaType:y,name:g.name});}return s},[]),k=tt.useCallback(()=>{o([]);},[]);return {attachments:r,uploading:i,fileInputRef:c,formatBytes:b,handleRemoveAttachment:h,handleFileSelection:S,buildUserContent:x,clearAttachments:k,setAttachments:o,MAX_UPLOAD_SIZE:Ct}}function Xt(e,t,n){return new ai.DefaultChatTransport({api:`${e}/api/run/${t}`,fetch:async(r,o)=>{let p={...o?.body?JSON.parse(o.body):{},chatId:n};return fetch(r,{...o,body:JSON.stringify(p)})}})}function lo(e){if(!(e instanceof HTMLElement))return true;let t=window.getComputedStyle(e);return t.display!=="none"&&t.visibility!=="hidden"&&t.opacity!=="0"&&e.offsetParent!==null}function co(e){if(e.id){let n=document.querySelector(`label[for="${e.id}"]`);if(n)return n.textContent?.trim()}let t=e.closest("label");if(t){let n=t.cloneNode(true),r=n.querySelector("input, select, textarea");return r&&r.remove(),n.textContent?.trim()}}function vt(e){if(e.textContent&&e.textContent.trim())return e.textContent.trim().slice(0,100)}function kt(e){if(e instanceof HTMLInputElement){let t=e.type.toLowerCase();return t==="checkbox"||t==="radio"?e.checked:e.value}if(e instanceof HTMLTextAreaElement)return e.value;if(e instanceof HTMLSelectElement)return e.multiple?Array.from(e.selectedOptions).map(t=>t.value):e.value;if(e instanceof HTMLElement&&e.isContentEditable)return e.textContent||void 0}function uo(e){if(e.id)return `#${e.id}`;let t=[],n=e;for(;n&&n!==document.body;){let r=n.tagName.toLowerCase();if(n.className&&typeof n.className=="string"){let i=n.className.split(" ").filter(p=>p.trim()).slice(0,2);i.length>0&&(r+="."+i.join("."));}let o=n.parentElement;if(o){let i=Array.from(o.children).filter(p=>p.tagName===n.tagName);if(i.length>1){let p=i.indexOf(n)+1;r+=`:nth-child(${p})`;}}t.unshift(r),n=o;}return t.slice(-3).join(" > ")}async function ze(e={}){try{let{includeHidden:t=!1,selector:n,what:r="content",limit:o}=e,i=document.querySelector(".hsafa-content-container");if(!i)return {ok:!1,components:[],count:0,total:0,containerFound:!1,error:"ContentContainer not found on page. Make sure you have wrapped your app with <ContentContainer>."};let p=n&&i.querySelector(n)||i,c=[],b=[];r==="inputs"?b=["input","textarea","select",'[contenteditable="true"]','[contenteditable=""]']:b=["header","nav","main","section","article","aside","footer","h1","h2","h3","h4","h5","h6","p","img[alt]","ul","ol","li","table","thead","tbody","tr","td","th","form","label","input","textarea","select",'[contenteditable="true"]','[contenteditable=""]',"a[href]","button",'[role="button"]','[role="link"]',"[onclick]","[tabindex]","div"],p.querySelectorAll(b.join(", ")).forEach(s=>{let d=lo(s);if(!d&&!t)return;let g={id:s.id||null,tag:s.tagName.toLowerCase(),className:s.className&&typeof s.className=="string"?s.className:void 0,isVisible:d,isInteractive:!0,selector:uo(s)};s instanceof HTMLInputElement?(g.type=s.type,g.name=s.name||void 0,g.placeholder=s.placeholder||void 0,g.value=kt(s),g.checked=s.type==="checkbox"||s.type==="radio"?s.checked:void 0,g.disabled=s.disabled,g.required=s.required):s instanceof HTMLTextAreaElement?(g.name=s.name||void 0,g.placeholder=s.placeholder||void 0,g.value=kt(s),g.disabled=s.disabled,g.required=s.required):s instanceof HTMLSelectElement?(g.name=s.name||void 0,g.value=kt(s),g.disabled=s.disabled,g.required=s.required,g.options=Array.from(s.options).map(y=>({value:y.value,label:y.text,selected:y.selected,disabled:y.disabled}))):s instanceof HTMLButtonElement?(g.type=s.type,g.disabled=s.disabled,g.text=vt(s)):s instanceof HTMLAnchorElement?(g.href=s.href,g.text=vt(s)):s instanceof HTMLImageElement?(g.text=s.alt||void 0,g.label=s.alt||g.label):g.text=vt(s),g.label=co(s),g.role=s.getAttribute("role")||void 0,g.ariaLabel=s.getAttribute("aria-label")||void 0,c.push(g);});let h=s=>s.isVisible?r==="inputs"?s.tag==="input"||s.tag==="textarea"||s.tag==="select"||s.role==="textbox"?3:s.tag==="button"||s.tag==="a"?2:1:["header","nav","main","footer"].includes(s.tag)?5:["section","article","aside"].includes(s.tag)||["h1","h2","h3"].includes(s.tag)?4:["h4","h5","h6"].includes(s.tag)?3:s.tag==="form"?4:s.tag==="label"?3:s.tag==="input"||s.tag==="textarea"||s.tag==="select"?4:s.tag==="p"||s.tag==="img"||s.tag==="button"||s.tag==="a"?3:1:0;c.sort((s,d)=>h(d)-h(s));let S=c.length,k=Math.max(1,Math.min(200,typeof o=="number"?Math.floor(o):r==="inputs"?100:150)),a=S>k,v=a?c.slice(0,k):c;return {ok:!0,components:v,count:v.length,total:S,truncated:a,containerFound:!0}}catch(t){return {ok:false,components:[],count:0,total:0,containerFound:false,error:t?.message||String(t)}}}typeof window<"u"&&(window.getDomComponents=ze);async function Ce(e,t={}){if(typeof window>"u")return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"guideCursor only works in browser environment"}]};let n=window.__cursorGuide;if(!n)return {ok:false,steps:[{ok:false,action:"none",targetKind:"position",durationMs:0,error:"CursorController not initialized. Make sure to mount <CursorController /> component."}]};try{return await n(e,t)}catch(r){return {ok:false,steps:[{ok:false,action:t.action||"none",targetKind:"position",durationMs:0,error:r?.message||String(r)}]}}}typeof window<"u"&&(window.guideCursor=Ce);function Yt(e){return !!e&&e.nodeType===1}function ae(e,t){e.dispatchEvent(new Event(t,{bubbles:true}));}function Jt(e,t){let n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value")?.set;n?n.call(e,t):e.value=t,ae(e,"input");}function po(e,t){e.checked!==t&&e.click();}function mo(e,t){if(typeof t=="object"&&t&&"index"in t&&typeof t.index=="number")e.selectedIndex=Math.max(0,Math.min(e.options.length-1,t.index));else if(typeof t=="object"&&t&&"label"in t&&typeof t.label=="string"){let n=Array.from(e.options).findIndex(r=>r.text===t.label);e.selectedIndex=n>=0?n:0;}else e.value=String(t);ae(e,"input"),ae(e,"change");}function go(e,t){let n=new Set(t.map(String));Array.from(e.options).forEach(r=>{r.selected=n.has(r.value)||n.has(r.text);}),ae(e,"input"),ae(e,"change");}function fo(e){return e?e instanceof Date?e.toISOString().slice(0,10):String(e):""}function yo(e,t){let n=Array.isArray(t)?t:[t],r=new DataTransfer;for(let o of n)r.items.add(o);Object.defineProperty(e,"files",{value:r.files,configurable:true}),ae(e,"input"),ae(e,"change");}async function Ue(e,t={}){let n=document.activeElement||null;if(n&&Yt(n)){let r=n.closest('[contenteditable="true"], [contenteditable=""]');r&&(n=r);}if(!n||n===document.body)return {ok:false,filled:[{key:"active",status:"skipped",message:"No active input element"}],errors:["No active input element"]};try{let r=n.tagName.toLowerCase();if(r==="input"){let o=n,i=(o.type||"text").toLowerCase();if(i==="checkbox")po(o,!!e);else if(i==="radio"){let p=o.name;if(p&&e!=null&&String(o.value)!==String(e)){let c=document.querySelector(`input[type="radio"][name="${CSS.escape(p)}"][value="${CSS.escape(String(e))}"]`);c?c.click():o.click();}else o.click();}else if(i==="file")if(e instanceof File||Array.isArray(e)&&e.every(p=>p instanceof File))yo(o,e);else return {ok:!1,filled:[{key:"active",status:"skipped",message:"Provide File or File[] for file input"}],errors:["Provide File or File[] for file input"]};else {let p=i==="date"?fo(e):String(e??"");Jt(o,p),ae(o,"change");}return {ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="textarea"){let o=n,i=String(e??"");return Jt(o,i),ae(o,"change"),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(r==="select"){let o=n;return o.multiple?go(o,Array.isArray(e)?e:[e]):mo(o,e),{ok:!0,filled:[{key:"active",status:"ok"}]}}if(Yt(n)&&n.isContentEditable){let o=n;return o.focus(),o.textContent=String(e??""),ae(o,"input"),ae(o,"change"),o.blur?.(),{ok:!0,filled:[{key:"active",status:"ok"}]}}return {ok:!1,filled:[{key:"active",status:"skipped",message:`Unsupported active element: ${r}`}],errors:[`Unsupported active element: ${r}`]}}catch(r){return {ok:false,filled:[{key:"active",status:"error",message:r?.message??String(r)}],errors:[r?.message??String(r)]}}}typeof window<"u"&&(window.FillActiveInput=Ue);var We=null,Xe={},Qt=false,Ae=null,Je=false;function wt(e){e.classList.add("visible");}function an(){Je=true,Ae!=null&&(clearTimeout(Ae),Ae=null);}function xo(e,t=1500){Je||(Ae!=null&&clearTimeout(Ae),Ae=window.setTimeout(()=>{Je||e.classList.remove("visible");},t));}function bo(e,t=1200){Je=false,xo(e,t);}function Co(e){let t=[],n=e?.parentElement;for(;n;){let r=getComputedStyle(n),o=r.overflow+r.overflowY+r.overflowX;/(auto|scroll)/.test(o)&&t.push(n),n=n.parentElement;}return t}async function vo(e,t=1500,n=160){let r=performance.now(),o=e?Co(e):[],i=()=>{let h=[window.scrollX||document.documentElement.scrollLeft||0,window.scrollY||document.documentElement.scrollTop||0];return o.forEach(S=>{h.push(S.scrollLeft,S.scrollTop);}),h},p=()=>{if(!e)return {x:0,y:0};let h=e.getBoundingClientRect();return {x:h.left,y:h.top}},c=i(),b=p(),T=performance.now();return new Promise(h=>{function S(x){let k=i(),a=p(),v=false;for(let s=0;s<k.length;s++)if(k[s]!==c[s]){v=true;break}if(!v&&e&&(a.x!==b.x||a.y!==b.y)&&(v=true),v&&(c=k,b=a,T=x),x-T>=n||x-r>=t){h();return}requestAnimationFrame(S);}requestAnimationFrame(S);})}var ko='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32px" height="32px"><path d="M 7.2304688 4.9863281 C 5.9215232 4.8276681 4.8053213 6.0177722 5.0234375 7.3066406 A 1.0001 1.0001 0 0 0 5.0253906 7.3085938 C 5.9996339 12.981516 7.7205826 18.716222 10 24.515625 A 1.0001 1.0001 0 0 0 10 24.517578 C 10.26886 25.199332 10.914322 25.653844 11.5625 25.738281 C 12.210678 25.822721 12.879213 25.592031 13.359375 25.09375 C 14.505165 23.921134 15.214424 22.695429 15.90625 21.498047 C 17.56565 23.217848 19.256845 24.909775 21.0625 26.484375 L 21.060547 26.480469 C 21.799528 27.12933 22.841378 27.205969 23.673828 26.78125 A 1.0001 1.0001 0 0 0 23.691406 26.771484 C 24.987999 26.077693 26.028685 25.052256 26.71875 23.746094 L 26.71875 23.744141 C 27.174557 22.900924 27.06954 21.854242 26.439453 21.119141 A 1.0001 1.0001 0 0 0 26.433594 21.113281 C 24.867416 19.313474 23.193611 17.633865 21.488281 15.986328 C 22.714141 15.237691 23.933938 14.51508 25.158203 13.414062 A 1.0001 1.0001 0 0 0 25.162109 13.410156 C 26.052979 12.600274 25.977319 11.169141 25.101562 10.404297 A 1.0001 1.0001 0 0 0 24.669922 10.042969 C 18.793373 7.4738953 12.973806 5.6931843 7.2324219 4.9882812 A 1.0001 1.0001 0 0 0 7.2304688 4.9863281 z M 6.9960938 6.9746094 C 12.468883 7.6474978 18.081513 9.3573116 23.796875 11.849609 A 1.0001 1.0001 0 0 0 23.867188 11.884766 C 23.901248 11.899796 23.884276 11.867987 23.816406 11.929688 C 22.403891 13.198979 20.999383 14.076858 19.457031 14.976562 A 1.0001 1.0001 0 0 0 19.275391 16.568359 C 21.250864 18.425305 23.134972 20.36916 24.919922 22.419922 C 25.009402 22.524309 25.024026 22.676488 24.960938 22.792969 A 1.0001 1.0001 0 0 0 24.955078 22.804688 C 24.446951 23.770198 23.730542 24.476149 22.755859 25 C 22.611605 25.06851 22.457885 25.047856 22.378906 24.978516 A 1.0001 1.0001 0 0 0 22.376953 24.976562 C 20.293628 23.159824 18.307991 21.233373 16.419922 19.216797 A 1.0001 1.0001 0 0 0 14.835938 19.378906 C 13.841812 21.004716 13.152668 22.447221 11.925781 23.701172 A 1.0001 1.0001 0 0 0 11.919922 23.707031 C 11.883822 23.744501 11.865156 23.739957 11.847656 23.742188 C 9.6161121 18.057657 7.9395914 12.46667 6.9960938 6.9746094 z"/></svg>',wo='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="32px" height="32px"><path d="M 22.5 3 C 19.480226 3 17 5.4802259 17 8.5 L 17 23.412109 L 14.871094 22.697266 C 13.308963 22.172461 11.892528 22 10.703125 22 C 9.5908429 22 8.5540295 22.197475 7.640625 22.65625 C 5.2906802 23.831199 3.9427678 26.197397 4.0019531 28.90625 C 4.0019531 28.90625 4.0019531 28.908203 4.0019531 28.908203 C 4.0019531 28.908203 4.0019531 28.910156 4.0019531 28.910156 C 4.0184171 29.660452 4.4596385 30.354695 5.1328125 30.6875 A 1.50015 1.50015 0 0 0 5.1367188 30.689453 C 5.1367188 30.689453 9.4097266 32.789754 11.599609 33.949219 C 12.445613 34.397848 13.696939 34.926046 15.210938 36.09375 C 16.724935 37.261454 18.423179 39.012543 19.826172 41.792969 C 21.023611 44.165544 23.672779 45.195669 26.144531 44.955078 A 1.50015 1.50015 0 0 0 26.146484 44.955078 C 31.427085 44.439215 32.081856 44.381732 35.59375 44.023438 C 37.044229 43.875625 38.276993 43.213524 39.111328 42.289062 C 39.945663 41.364602 40.422895 40.257718 40.798828 39.125 C 41.561218 36.826116 42.933037 33.169846 43.671875 30.599609 C 45.018525 25.913269 41.884024 21.194549 37.246094 19.953125 L 37.242188 19.951172 C 36.99827 19.885452 36.756736 19.832884 36.521484 19.789062 A 1.50015 1.50015 0 0 0 36.513672 19.787109 L 28 18.248047 L 28 8.5 C 28 5.4802259 25.519774 3 22.5 3 z M 22.5 6 C 23.898226 6 25 7.1017741 25 8.5 L 25 19.5 A 1.50015 1.50015 0 0 0 26.232422 20.976562 L 35.980469 22.740234 C 36.14895 22.771804 36.312663 22.808524 36.464844 22.849609 A 1.50015 1.50015 0 0 0 36.46875 22.849609 C 39.614436 23.689967 41.641993 26.803286 40.789062 29.771484 C 40.115901 32.113248 38.752735 35.768572 37.953125 38.179688 C 37.641059 39.119968 37.279727 39.837554 36.882812 40.277344 C 36.485898 40.717133 36.095584 40.956874 35.289062 41.039062 C 31.783676 41.396695 31.135884 41.452908 25.855469 41.96875 C 24.423221 42.108159 23.024467 41.472831 22.503906 40.441406 C 20.887905 37.238832 18.854971 35.116296 17.042969 33.71875 C 15.230967 32.321204 13.560902 31.594199 13.003906 31.298828 C 10.939171 30.205625 7.8041786 28.665144 7.1035156 28.320312 C 7.1954033 26.8809 7.6810328 25.989859 8.9824219 25.339844 A 1.50015 1.50015 0 0 0 8.9863281 25.337891 C 9.3949198 25.132713 9.9434071 25 10.703125 25 C 11.605722 25 12.680146 25.12582 13.916016 25.541016 L 18.021484 26.921875 A 1.50015 1.50015 0 0 0 20 25.5 L 20 8.5 C 20 7.1017741 21.101774 6 22.5 6 z"/></svg>';async function To(){if(!Xe.arrow)try{Xe.arrow=ko,Xe.pointer=wo;}catch(e){console.warn("Failed to set cursor SVGs",e);}return Xe}function en({arrowSvg:e,pointerSvg:t}){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[e&&jsxRuntime.jsx("div",{className:"arrow",dangerouslySetInnerHTML:{__html:e}}),t&&jsxRuntime.jsx("div",{className:"pointer",dangerouslySetInnerHTML:{__html:t}})]})}async function Io(){let e="demo-fake-cursor",t=document.getElementById(e),n=await To();if(!Qt){let r="cursor-controller-styles";if(!document.getElementById(r)){let o=document.createElement("style");o.id=r,o.textContent=`
|
|
2
2
|
.fake-cursor { pointer-events: none; opacity: 0; transition: opacity 0.2s ease; z-index: 2147483647; }
|
|
3
3
|
.fake-cursor.visible { opacity: 1; }
|
|
4
4
|
.fake-cursor .arrow { display: none; }
|
|
@@ -8,19 +8,19 @@
|
|
|
8
8
|
.fake-cursor.as-pointer .arrow { display: none; }
|
|
9
9
|
.fake-cursor.as-pointer .pointer { display: block; }
|
|
10
10
|
.fake-cursor.pressing .pointer svg path { filter: brightness(0.9); }
|
|
11
|
-
`,document.head.appendChild(r);}fn=true;}return e?(e.classList.add("as-arrow"),qe||(qe=client.createRoot(e),qe.render(jsxRuntime.jsx(yn,{arrowSvg:t.arrow,pointerSvg:t.pointer})))):(e=document.createElement("div"),e.id=n,e.className="fake-cursor as-arrow",e.style.position="fixed",e.style.left="20px",e.style.top="20px",document.body.appendChild(e),qe=client.createRoot(e),qe.render(jsxRuntime.jsx(yn,{arrowSvg:t.arrow,pointerSvg:t.pointer}))),e}function $e(n,e,t){return Math.max(e,Math.min(t,n))}function zr(n){return n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2}function kn(n){if(!n)return null;let e=document.createElement("canvas").getContext("2d");if(!e)return null;e.fillStyle="#000",e.fillStyle=n;let o=e.fillStyle.match(/rgba?\(([^)]+)\)/i);if(!o)return null;let r=o[1].split(/\s*,\s*/).map(Number),[i,c,d,u=1]=r;return {r:i,g:c,b:d,a:u}}function Nr({r:n,g:e,b:t}){let o=[n,e,t].map(r=>r/255).map(r=>r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4));return .2126*o[0]+.7152*o[1]+.0722*o[2]}function Wr(n){let e=n?kn(n):null;return !e||e.a===0?false:Nr(e)<.5}function Ur(n,e){let t=document.elementFromPoint(n,e),o=new Set;for(;t&&!o.has(t);){o.add(t);let c=getComputedStyle(t).backgroundColor,d=kn(c);if(d&&d.a>0)return c;t=t.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Ft(n,e,t){let o=Ur(e,t),r=Wr(o),i=r?"#ffffff":"#000000";n.querySelectorAll("svg path").forEach(d=>{d.style.fill="white",d.style.stroke=i,d.style.strokeWidth="1";}),n.style.filter=r?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function tt(n,e,t,o,r="ease-in-out",i="curve",c=.25,d="auto",u){vn(),$t(n);let x=performance.now(),g=r==="linear"?C=>C:zr,T=i!=="straight",y={x:0,y:0};if(T){let C=t.x-e.x,a=t.y-e.y,p=Math.hypot(C,a)||1,s=(e.x+t.x)/2,l=(e.y+t.y)/2,m=-a/p,f=C/p,v=1;d==="left"?v=-1:d==="right"?v=1:v=Math.random()<.5?-1:1;let I=$e(c,0,1)*p;y={x:s+v*m*I,y:l+v*f*I};}return new Promise(C=>{function a(p){let s=$e((p-x)/o,0,1),l=g(s),m,f;if(T){let h=1-l;m=h*h*e.x+2*h*l*y.x+l*l*t.x,f=h*h*e.y+2*h*l*y.y+l*l*t.y;}else m=e.x+(t.x-e.x)*l,f=e.y+(t.y-e.y)*l;let I=.35*(1-l),k=Math.sin(p*.02)*I,b=Math.cos(p*.018)*I;n.style.left=`${m+k}px`,n.style.top=`${f+b}px`,Ft(n,m+k,f+b),u&&u({x:m+k,y:f+b,t:s,now:p}),s<1?requestAnimationFrame(a):C();}requestAnimationFrame(a);})}function hn(n,e){return {x:n.x+(e?.x??0),y:n.y+(e?.y??0)}}function me(n,e,t,o){let r={bubbles:true,cancelable:true,view:window,clientX:t.x,clientY:t.y,...o};try{let i=e==="pointerdown"||e==="mousedown",c=e==="pointerup"||e==="mouseup",d={button:0,buttons:i?1:0,isPrimary:!0,...r};if("PointerEvent"in window){let u=new PointerEvent(e,{pointerId:1,pointerType:"mouse",...d});n.dispatchEvent(u);}else {let u=new MouseEvent(e,d);n.dispatchEvent(u);}}catch{let i=new MouseEvent(e,r);n.dispatchEvent(i);}}function wn(n){return n&&typeof n=="object"&&n.nodeType===1}function Gr(n){if(!n)return document;if(wn(n))return n;if(typeof n=="string"){let e=document.getElementById(n);if(e)return e;let t=document.querySelector(n);if(t)return t}return document}function bn(n){if(wn(n))return {kind:"element",element:n};if(typeof n=="string"){let e=document.getElementById(n);if(e)return {kind:"element",element:e};let t=document.querySelector(n);return {kind:t?"element":"position",element:t??null}}if(typeof n=="object"&&"position"in n)return {kind:"position",point:n.position};if(typeof n=="object"&&"selector"in n){let t=Gr(n.within??null).querySelectorAll(n.selector),o=Math.max(0,Math.min(t.length-1,n.nth??0)),r=t[o]??null;return {kind:r?"element":"position",element:r}}return {kind:"position",point:{x:0,y:0}}}function xn(n,e){let t=n.getBoundingClientRect();if(!e||e==="center")return {x:t.left+t.width/2,y:t.top+t.height/2};if(e==="top-left")return {x:t.left,y:t.top};if(e==="bottom-right")return {x:t.right,y:t.bottom};let o=$e(e.x,0,1),r=$e(e.y,0,1);return {x:t.left+t.width*o,y:t.top+t.height*r}}function Cn(n){return {x:$e(n.x,0,window.innerWidth),y:$e(n.y,0,window.innerHeight)}}function qr(){return st.useEffect(()=>(window.__cursorGuide=async(n,e={})=>{let t=Array.isArray(n)?n:[{target:n,action:e.action??"none",options:e}],o=[],r=await Or();r.classList.add("visible","as-arrow"),r.classList.remove("as-pointer","pressing"),$t(r),vn();let i=parseFloat(r.style.left||"20")||20,c=parseFloat(r.style.top||"20")||20;Ft(r,i,c);for(let d of t){let{durationMs:u=800,easing:x="ease-in-out",offset:g,highlight:T=true,path:y="curve",curveStrength:C=.25,curveDirection:a="auto",anchor:p,cursorHotspot:s,dragTo:l}=d.options??{},m=d.action??d.options?.action??"none",f=performance.now(),v=bn(d.target),I=null,k=null;if(v.kind==="element"&&v.element?(k=v.element,r.classList.remove("visible"),k.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await Pr(k,1500,180),$t(r),I=xn(k,p)):v.kind==="position"&&v.point&&(I=v.point),!I){o.push({ok:false,action:m,targetKind:v.kind,durationMs:Math.round(performance.now()-f),error:"Target not found"});continue}let b={x:parseFloat(r.style.left||"20")||20,y:parseFloat(r.style.top||"20")||20},h=Cn(hn(I,g));await tt(r,b,h,u,x,y,C,a);let E=h.x-b.x,w=h.y-b.y,P=Math.hypot(E,w)||1,S=E/P,A=w/P,F=Math.min(6,Math.max(3,P*.02)),M={x:h.x+S*F,y:h.y+A*F};await tt(r,h,M,Math.max(70,u*.1),"ease-out","straight",0,"right"),await tt(r,M,h,120,"ease-out","straight",0,"left"),T&&(r.classList?.add("click"),setTimeout(()=>r.classList?.remove("click"),180));let $=null;try{if(m==="click"){r.classList.remove("as-arrow"),r.classList.add("as-pointer","pressing");let D={x:s?.x??0,y:s?.y??0},R={x:h.x+D.x,y:h.y+D.y};r.style.left=`${R.x}px`,r.style.top=`${R.y}px`,Ft(r,R.x,R.y);let O=k??document.elementFromPoint(R.x,R.y)??document.body;me(O,"pointerdown",R),me(O,"mousedown",R),await new Promise(N=>setTimeout(N,90)),r.classList.remove("pressing"),me(O,"mouseup",R),me(O,"click",R),setTimeout(()=>{r.classList.remove("as-pointer"),r.classList.add("as-arrow");},140),O instanceof HTMLElement&&O.focus?.(),$=O?.id??null;}else if(m==="drag"){if(!l)throw new Error("dragTo is required for action 'drag'");let D=bn(l),R=null;if(D.kind==="element"&&D.element&&(R=xn(D.element,p)),D.kind==="position"&&D.point&&(R=D.point),!R)throw new Error("dragTo target not found");let O=Cn(hn(R,g)),N={x:h.x,y:h.y},J=k??document.elementFromPoint(N.x,N.y)??document.body;r.classList.remove("as-arrow"),r.classList.add("as-pointer","pressing"),me(J,"pointerdown",N),me(J,"mousedown",N),await tt(r,N,O,Math.max(200,u),x,y,C,a,({x:H,y:K})=>{let ae=document.elementFromPoint(H,K)??document.body,Ne={x:H,y:K};me(ae,"pointermove",Ne),me(ae,"mousemove",Ne);});let V=document.elementFromPoint(O.x,O.y)??document.body;r.classList.remove("pressing"),me(V,"pointerup",O),me(V,"mouseup",O);}o.push({ok:!0,action:m,targetKind:v.kind,durationMs:Math.round(performance.now()-f),clickedElementId:$});}catch(D){o.push({ok:false,action:m,targetKind:v.kind,durationMs:Math.round(performance.now()-f),error:D?.message??String(D)});}}return $r(r,2e3),{ok:o.every(d=>d.ok),steps:o}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var ot=qr;function Tn(){return {getDomComponents:{tool:async({includeHidden:n,selector:e})=>await Ue({includeHidden:n,selector:e}),executeEachToken:false},controlCursor:{tool:async({target:n,action:e,anchor:t,durationMs:o,dragTo:r})=>{let i=await Te(n,{action:e,anchor:t,durationMs:o,dragTo:r});if(i&&i.ok){let c=Array.isArray(i.steps)&&i.steps.length?i.steps[i.steps.length-1]:void 0,d=c?.clickedElementId?` (clicked element id: ${c.clickedElementId})`:"",u=e||c?.action||"none";return {success:true,message:u==="click"?`Cursor moved and clicked successfully${d}`:u==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:i}}return {success:false,message:"Cursor action failed",details:i}},executeEachToken:false},fillActiveInput:{tool:async({value:n})=>{let e=await Ge(n);return {success:!!e?.ok,message:e?.ok?"Active input filled successfully":e?.errors?.[0]||"Failed to fill active input",details:e}},executeEachToken:true},requestInput:{tool:async n=>({ok:true}),executeEachToken:true}}}function In({chart:n,theme:e}){let t=st.useRef(null),[o,r]=st.useState(null),[i,c]=st.useState(true);st.useEffect(()=>{let y=true;return (async()=>{try{c(!0),r(null);let a;try{a=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!y)return;if(a.default?.initialize({startOnLoad:!1,theme:e==="dark"?"dark":"default",themeVariables:{darkMode:e==="dark",primaryColor:e==="dark"?"#3B82F6":"#1D4ED8",primaryTextColor:e==="dark"?"#F3F4F6":"#1F2937",primaryBorderColor:e==="dark"?"#374151":"#D1D5DB"},flowchart:{useMaxWidth:!0},sequence:{useMaxWidth:!0},gantt:{useMaxWidth:!0}}),t.current&&y){let p=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:s}=await a.default.render(p,n);if(t.current&&y){t.current.innerHTML=s;let l=t.current.querySelector("svg");l&&(l.style.maxWidth="100%",l.style.height="auto",l.style.display="block");}}}catch(a){y&&r(a instanceof Error?a.message:"Failed to render diagram");}finally{y&&c(false);}})(),()=>{y=false;}},[n,e]);let d=e==="dark"?"#374151":"#D1D5DB",u=e==="dark"?"#1F2937":"#F9FAFB",x=e==="dark"?"#7F1D1D":"#FEF2F2",g=e==="dark"?"#FCA5A5":"#DC2626",T=e==="dark"?"#9CA3AF":"#6B7280";return o?jsxRuntime.jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${d}`,backgroundColor:x,padding:"16px",margin:"8px 0"},children:[jsxRuntime.jsx("div",{style:{fontSize:"14px",color:g,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsxRuntime.jsx("div",{style:{fontSize:"12px",color:g,opacity:.8},children:o})]}):jsxRuntime.jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${d}`,backgroundColor:u,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[i&&jsxRuntime.jsx("div",{style:{fontSize:"14px",color:T,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsxRuntime.jsx("div",{ref:t,style:{display:i?"none":"block",textAlign:"center",minHeight:i?"0":"50px"}})]})}function ce(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Fe(n){return n=n.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer" style="text-decoration: underline; color: inherit; opacity: 0.8;">$1</a>'),n=n.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),n=n.replace(/\*([^*\n]+)\*/g,"<em>$1</em>"),n=n.replace(/`([^`]+)`/g,'<code style="padding: 2px 4px; border-radius: 4px; background-color: rgba(0,0,0,0.1); font-family: monospace;">$1</code>'),n}function Zr(n,e="dark"){let t=(n||"").replace(/\r\n/g,`
|
|
11
|
+
`,document.head.appendChild(o);}Qt=true;}return t?(t.classList.add("as-arrow"),We||(We=client.createRoot(t),We.render(jsxRuntime.jsx(en,{arrowSvg:n.arrow,pointerSvg:n.pointer})))):(t=document.createElement("div"),t.id=e,t.className="fake-cursor as-arrow",t.style.position="fixed",t.style.left="20px",t.style.top="20px",document.body.appendChild(t),We=client.createRoot(t),We.render(jsxRuntime.jsx(en,{arrowSvg:n.arrow,pointerSvg:n.pointer}))),t}function Re(e,t,n){return Math.max(t,Math.min(n,e))}function Mo(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}function sn(e){if(!e)return null;let t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle="#000",t.fillStyle=e;let r=t.fillStyle.match(/rgba?\(([^)]+)\)/i);if(!r)return null;let o=r[1].split(/\s*,\s*/).map(Number),[i,p,c,b=1]=o;return {r:i,g:p,b:c,a:b}}function So({r:e,g:t,b:n}){let r=[e,t,n].map(o=>o/255).map(o=>o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4));return .2126*r[0]+.7152*r[1]+.0722*r[2]}function Eo(e){let t=e?sn(e):null;return !t||t.a===0?false:So(t)<.5}function Ao(e,t){let n=document.elementFromPoint(e,t),r=new Set;for(;n&&!r.has(n);){r.add(n);let p=getComputedStyle(n).backgroundColor,c=sn(p);if(c&&c.a>0)return p;n=n.parentElement;}return getComputedStyle(document.body).backgroundColor||"rgb(255,255,255)"}function Tt(e,t,n){let r=Ao(t,n),o=Eo(r),i=o?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(c=>{c.style.fill="white",c.style.stroke=i,c.style.strokeWidth="1";}),e.style.filter=o?"drop-shadow(0 1px 2px rgba(0,0,0,0.8))":"drop-shadow(0 1px 2px rgba(255,255,255,0.9))";}async function Ye(e,t,n,r,o="ease-in-out",i="curve",p=.25,c="auto",b){an(),wt(e);let T=performance.now(),h=o==="linear"?k=>k:Mo,S=i!=="straight",x={x:0,y:0};if(S){let k=n.x-t.x,a=n.y-t.y,v=Math.hypot(k,a)||1,s=(t.x+n.x)/2,d=(t.y+n.y)/2,g=-a/v,y=k/v,m=1;c==="left"?m=-1:c==="right"?m=1:m=Math.random()<.5?-1:1;let I=Re(p,0,1)*v;x={x:s+m*g*I,y:d+m*y*I};}return new Promise(k=>{function a(v){let s=Re((v-T)/r,0,1),d=h(s),g,y;if(S){let u=1-d;g=u*u*t.x+2*u*d*x.x+d*d*n.x,y=u*u*t.y+2*u*d*x.y+d*d*n.y;}else g=t.x+(n.x-t.x)*d,y=t.y+(n.y-t.y)*d;let I=.35*(1-d),C=Math.sin(v*.02)*I,l=Math.cos(v*.018)*I;e.style.left=`${g+C}px`,e.style.top=`${y+l}px`,Tt(e,g+C,y+l),b&&b({x:g+C,y:y+l,t:s,now:v}),s<1?requestAnimationFrame(a):k();}requestAnimationFrame(a);})}function tn(e,t){return {x:e.x+(t?.x??0),y:e.y+(t?.y??0)}}function de(e,t,n,r){let o={bubbles:true,cancelable:true,view:window,clientX:n.x,clientY:n.y,...r};try{let i=t==="pointerdown"||t==="mousedown",p=t==="pointerup"||t==="mouseup",c={button:0,buttons:i?1:0,isPrimary:!0,...o};if("PointerEvent"in window){let b=new PointerEvent(t,{pointerId:1,pointerType:"mouse",...c});e.dispatchEvent(b);}else {let b=new MouseEvent(t,c);e.dispatchEvent(b);}}catch{let i=new MouseEvent(t,o);e.dispatchEvent(i);}}function ln(e){return e&&typeof e=="object"&&e.nodeType===1}function Ro(e){if(!e)return document;if(ln(e))return e;if(typeof e=="string"){let t=document.getElementById(e);if(t)return t;let n=document.querySelector(e);if(n)return n}return document}function nn(e){if(ln(e))return {kind:"element",element:e};if(typeof e=="string"){let t=document.getElementById(e);if(t)return {kind:"element",element:t};let n=document.querySelector(e);return {kind:n?"element":"position",element:n??null}}if(typeof e=="object"&&"position"in e)return {kind:"position",point:e.position};if(typeof e=="object"&&"selector"in e){let n=Ro(e.within??null).querySelectorAll(e.selector),r=Math.max(0,Math.min(n.length-1,e.nth??0)),o=n[r]??null;return {kind:o?"element":"position",element:o}}return {kind:"position",point:{x:0,y:0}}}function on(e,t){let n=e.getBoundingClientRect();if(!t||t==="center")return {x:n.left+n.width/2,y:n.top+n.height/2};if(t==="top-left")return {x:n.left,y:n.top};if(t==="bottom-right")return {x:n.right,y:n.bottom};let r=Re(t.x,0,1),o=Re(t.y,0,1);return {x:n.left+n.width*r,y:n.top+n.height*o}}function rn(e){return {x:Re(e.x,0,window.innerWidth),y:Re(e.y,0,window.innerHeight)}}function Fo(){return tt.useEffect(()=>(window.__cursorGuide=async(e,t={})=>{let n=Array.isArray(e)?e:[{target:e,action:t.action??"none",options:t}],r=[],o=await Io();o.classList.add("visible","as-arrow"),o.classList.remove("as-pointer","pressing"),wt(o),an();let i=parseFloat(o.style.left||"20")||20,p=parseFloat(o.style.top||"20")||20;Tt(o,i,p);for(let c of n){let{durationMs:b=800,easing:T="ease-in-out",offset:h,highlight:S=true,path:x="curve",curveStrength:k=.25,curveDirection:a="auto",anchor:v,cursorHotspot:s,dragTo:d}=c.options??{},g=c.action??c.options?.action??"none",y=performance.now(),m=nn(c.target),I=null,C=null;if(m.kind==="element"&&m.element?(C=m.element,o.classList.remove("visible"),C.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),await vo(C,1500,180),wt(o),I=on(C,v)):m.kind==="position"&&m.point&&(I=m.point),!I){r.push({ok:false,action:g,targetKind:m.kind,durationMs:Math.round(performance.now()-y),error:"Target not found"});continue}let l={x:parseFloat(o.style.left||"20")||20,y:parseFloat(o.style.top||"20")||20},u=rn(tn(I,h));await Ye(o,l,u,b,T,x,k,a);let w=u.x-l.x,f=u.y-l.y,A=Math.hypot(w,f)||1,B=w/A,H=f/A,K=Math.min(6,Math.max(3,A*.02)),R={x:u.x+B*K,y:u.y+H*K};await Ye(o,u,R,Math.max(70,b*.1),"ease-out","straight",0,"right"),await Ye(o,R,u,120,"ease-out","straight",0,"left"),S&&(o.classList?.add("click"),setTimeout(()=>o.classList?.remove("click"),180));let O=null;try{if(g==="click"){o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing");let F={x:s?.x??0,y:s?.y??0},L={x:u.x+F.x,y:u.y+F.y};o.style.left=`${L.x}px`,o.style.top=`${L.y}px`,Tt(o,L.x,L.y);let N=C??document.elementFromPoint(L.x,L.y)??document.body;de(N,"pointerdown",L),de(N,"mousedown",L),await new Promise(G=>setTimeout(G,90)),o.classList.remove("pressing"),de(N,"mouseup",L),de(N,"click",L),setTimeout(()=>{o.classList.remove("as-pointer"),o.classList.add("as-arrow");},140),N instanceof HTMLElement&&N.focus?.(),O=N?.id??null;}else if(g==="drag"){if(!d)throw new Error("dragTo is required for action 'drag'");let F=nn(d),L=null;if(F.kind==="element"&&F.element&&(L=on(F.element,v)),F.kind==="position"&&F.point&&(L=F.point),!L)throw new Error("dragTo target not found");let N=rn(tn(L,h)),G={x:u.x,y:u.y},D=C??document.elementFromPoint(G.x,G.y)??document.body;o.classList.remove("as-arrow"),o.classList.add("as-pointer","pressing"),de(D,"pointerdown",G),de(D,"mousedown",G),await Ye(o,G,N,Math.max(200,b),T,x,k,a,({x:pe,y:ue})=>{let we=document.elementFromPoint(pe,ue)??document.body,J={x:pe,y:ue};de(we,"pointermove",J),de(we,"mousemove",J);});let Y=document.elementFromPoint(N.x,N.y)??document.body;o.classList.remove("pressing"),de(Y,"pointerup",N),de(Y,"mouseup",N);}r.push({ok:!0,action:g,targetKind:m.kind,durationMs:Math.round(performance.now()-y),clickedElementId:O});}catch(F){r.push({ok:false,action:g,targetKind:m.kind,durationMs:Math.round(performance.now()-y),error:F?.message??String(F)});}}return bo(o,2e3),{ok:r.every(c=>c.ok),steps:r}},()=>{try{delete window.__cursorGuide;}catch{window.__cursorGuide=void 0;}}),[]),null}var Qe=Fo;function cn(){return {getDomComponents:{tool:async({includeHidden:e,selector:t})=>await ze({includeHidden:e,selector:t}),executeEachToken:false},controlCursor:{tool:async({target:e,action:t,anchor:n,durationMs:r,dragTo:o})=>{let i=await Ce(e,{action:t,anchor:n,durationMs:r,dragTo:o});if(i&&i.ok){let p=Array.isArray(i.steps)&&i.steps.length?i.steps[i.steps.length-1]:void 0,c=p?.clickedElementId?` (clicked element id: ${p.clickedElementId})`:"",b=t||p?.action||"none";return {success:true,message:b==="click"?`Cursor moved and clicked successfully${c}`:b==="drag"?"Cursor dragged successfully":"Cursor moved successfully",details:i}}return {success:false,message:"Cursor action failed",details:i}},executeEachToken:false},fillActiveInput:{tool:async({value:e})=>{let t=await Ue(e);return {success:!!t?.ok,message:t?.ok?"Active input filled successfully":t?.errors?.[0]||"Failed to fill active input",details:t}},executeEachToken:true},requestInput:{tool:async e=>({ok:true}),executeEachToken:true}}}function pn({chart:e,theme:t}){let n=tt.useRef(null),[r,o]=tt.useState(null),[i,p]=tt.useState(true);tt.useEffect(()=>{let x=true;return (async()=>{try{p(!0),o(null);let a;try{a=await import('mermaid');}catch{throw new Error("Mermaid library not available")}if(!x)return;if(a.default?.initialize({startOnLoad:!1,theme:t==="dark"?"dark":"default",themeVariables:{darkMode:t==="dark",primaryColor:t==="dark"?"#3B82F6":"#1D4ED8",primaryTextColor:t==="dark"?"#F3F4F6":"#1F2937",primaryBorderColor:t==="dark"?"#374151":"#D1D5DB"},flowchart:{useMaxWidth:!0},sequence:{useMaxWidth:!0},gantt:{useMaxWidth:!0}}),n.current&&x){let v=`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,{svg:s}=await a.default.render(v,e);if(n.current&&x){n.current.innerHTML=s;let d=n.current.querySelector("svg");d&&(d.style.maxWidth="100%",d.style.height="auto",d.style.display="block");}}}catch(a){x&&o(a instanceof Error?a.message:"Failed to render diagram");}finally{x&&p(false);}})(),()=>{x=false;}},[e,t]);let c=t==="dark"?"#374151":"#D1D5DB",b=t==="dark"?"#1F2937":"#F9FAFB",T=t==="dark"?"#7F1D1D":"#FEF2F2",h=t==="dark"?"#FCA5A5":"#DC2626",S=t==="dark"?"#9CA3AF":"#6B7280";return r?jsxRuntime.jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:T,padding:"16px",margin:"8px 0"},children:[jsxRuntime.jsx("div",{style:{fontSize:"14px",color:h,marginBottom:"8px",fontWeight:"500"},children:"Failed to render diagram"}),jsxRuntime.jsx("div",{style:{fontSize:"12px",color:h,opacity:.8},children:r})]}):jsxRuntime.jsxs("div",{style:{borderRadius:"12px",border:`1px solid ${c}`,backgroundColor:b,padding:"16px",margin:"8px 0",overflow:"hidden"},children:[i&&jsxRuntime.jsx("div",{style:{fontSize:"14px",color:S,textAlign:"center",padding:"32px"},children:"Rendering diagram..."}),jsxRuntime.jsx("div",{ref:n,style:{display:i?"none":"block",textAlign:"center",minHeight:i?"0":"50px"}})]})}function se(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Fe(e){return e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer" style="text-decoration: underline; color: inherit; opacity: 0.8;">$1</a>'),e=e.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*([^*\n]+)\*/g,"<em>$1</em>"),e=e.replace(/`([^`]+)`/g,'<code style="padding: 2px 4px; border-radius: 4px; background-color: rgba(0,0,0,0.1); font-family: monospace;">$1</code>'),e}function Po(e,t="dark"){let n=(e||"").replace(/\r\n/g,`
|
|
12
12
|
`).split(`
|
|
13
|
-
`),
|
|
14
|
-
<table style="width: 100%; min-width: max-content; border-collapse: separate; border-spacing: 0; margin: 0;"
|
|
15
|
-
`);
|
|
16
|
-
`)),
|
|
17
|
-
`);
|
|
18
|
-
`)),h=i?`language-${i}`:"";o+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${y}; color: ${C}; border: 1px solid ${g}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${h}">${b}</code></pre>`;}return d&&(o+="</ul>"),u&&(o+="</ol>"),{html:o,hasMermaid:x}}function Ve({content:n,theme:e}){let{html:t,hasMermaid:o}=st.useMemo(()=>Zr(n,e),[n,e]);if(!o)return jsxRuntime.jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:t}});let r=t.split(/(<div class="mermaid-placeholder"[^>]*><\/div>)/g),i=[];return r.forEach((c,d)=>{if(c.includes("mermaid-placeholder")){let u=c.match(/data-mermaid="([^"]*)"/);if(u){let x=u[1].replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'");i.push(st__default.default.createElement(In,{key:`mermaid-${d}`,chart:x,theme:e}));}}else c.trim()&&i.push(st__default.default.createElement("div",{key:`html-${d}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:c}}));}),st__default.default.createElement(st__default.default.Fragment,{},...i)}function eo({input:n}){return jsxRuntime.jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsxRuntime.jsx(Ve,{content:n?.text||"",theme:"dark"})})}function An(){return {plainText:eo}}function Rn(n,e,t,o,r,i){let c=t.get(e);if(c){let v=c.parentElement,I=document.querySelector(`[data-get-from-user-host="${e}"]`);if(I&&v!==I){try{v?.removeChild(c);}catch{}I.innerHTML="",I.appendChild(c);}}else {c=document.createElement("div"),c.className="hsafa-inline-form";let v=document.querySelector(`[data-get-from-user-host="${e}"]`);v?(v.innerHTML="",v.appendChild(c)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(c),t.set(e,c);}let d=n?.title||"Provide input",u=n?.description||"",x=n?.submitLabel||"Submit",g=n?.skipLabel||"Skip",T=Array.isArray(n?.fields)?n.fields:n?.label||n?.placeholder?[{id:"value",label:n?.label||"Value",type:"text",placeholder:n?.placeholder||""}]:[],y=o.get(e)||{submitted:false,skipped:false,values:void 0};c.innerHTML="";let C=document.createElement("form");C.style.margin="12px 0",C.style.padding="14px",C.style.border="1px solid var(--hsafa-border, #2A2C33)",C.style.borderRadius="12px",C.style.background="var(--hsafa-card, #121318)",C.style.color="var(--hsafa-text, #EDEEF0)",C.style.boxShadow="0 6px 20px rgba(0,0,0,0.25)";let a=document.createElement("div");if(a.style.fontWeight="600",a.style.marginBottom="6px",a.textContent=d,C.appendChild(a),u){let v=document.createElement("div");v.style.fontSize="12px",v.style.opacity="0.8",v.style.marginBottom="10px",v.textContent=u,C.appendChild(v);}T.forEach(v=>{let I=document.createElement("div");if(I.style.margin="10px 0",v.label){let w=document.createElement("label");w.style.display="block",w.style.fontSize="12px",w.style.marginBottom="6px",w.style.opacity="0.9",w.textContent=v.label,I.appendChild(w);}let k,b=(v.type||"text").toLowerCase();if(b==="textarea"){let w=document.createElement("textarea");w.placeholder=v.placeholder||"",w.value=v.value??"",w.style.width="100%",w.style.minHeight="72px",w.style.padding="10px 12px",w.style.border="1px solid var(--hsafa-border, #2A2C33)",w.style.borderRadius="10px",w.style.background="var(--hsafa-input-bg, #17181C)",w.style.color="inherit",k=w;}else if(b==="select"&&Array.isArray(v.options)){let w=document.createElement("select");w.style.width="100%",w.style.padding="10px 12px",w.style.border="1px solid var(--hsafa-border, #2A2C33)",w.style.borderRadius="10px",w.style.background="var(--hsafa-input-bg, #17181C)",w.style.color="inherit",v.options.forEach(P=>{let S=document.createElement("option");S.value=String(P.value),S.text=String(P.label??P.value),w.appendChild(S);}),w.value=v.value??"",k=w;}else if(b==="checkbox"){let w=document.createElement("input");w.type="checkbox",w.checked=!!v.value,w.style.transform="scale(1.1)",k=w;}else {let w=document.createElement("input");w.type=b,w.placeholder=v.placeholder||"",w.value=v.value??"",w.style.width="100%",w.style.padding="10px 12px",w.style.border="1px solid var(--hsafa-border, #2A2C33)",w.style.borderRadius="10px",w.style.background="var(--hsafa-input-bg, #17181C)",w.style.color="inherit",k=w;}let h=v.id||"value";k.dataset.fieldId=h;let E=y.values&&Object.prototype.hasOwnProperty.call(y.values,h)?y.values[h]:void 0;typeof E<"u"&&(k.type==="checkbox"?k.checked=!!E:k.value=String(E)),(y.submitted||y.skipped)&&(k.setAttribute("disabled","true"),k.style.opacity="0.7"),I.appendChild(k),C.appendChild(I);});let p=String(x).trim(),s=String(g).trim(),l=!!(p||s),m=null,f=null;if(l){let v=document.createElement("div");v.style.display="flex",v.style.gap="8px",v.style.marginTop="10px",m=document.createElement("button"),m.type="submit",m.textContent=p||"Submit",m.style.padding="6px 10px",m.style.borderRadius="8px",m.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",m.style.color="#000000",f=document.createElement("button"),f.type="button",f.textContent=s||"Skip",f.style.padding="6px 10px",f.style.borderRadius="8px",f.style.background="transparent",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.color="inherit",v.appendChild(m),v.appendChild(f),C.appendChild(v);}if(C.onsubmit=v=>{v.preventDefault();let I={};C.querySelectorAll("[data-field-id]").forEach(k=>{let b=k.dataset.fieldId||"value";k.type==="checkbox"?I[b]=k.checked:I[b]=k.value??"";}),o.set(e,{submitted:true,skipped:false,values:I}),r({tool:"requestInput",toolCallId:e,output:{success:true,submitted:true,values:I}}),C.querySelectorAll("[data-field-id]").forEach(k=>{k.disabled=true,k.style.opacity="0.7";}),m&&(m.textContent=`${p||"Submit"} \u2713`,m.style.opacity="0.8",m.disabled=true),f&&(f.disabled=true);},f&&(f.onclick=()=>{o.set(e,{submitted:false,skipped:true,values:void 0}),r({tool:"requestInput",toolCallId:e,output:{success:true,submitted:false,skipped:true}}),C.querySelectorAll("[data-field-id]").forEach(v=>{v.disabled=true,v.style.opacity="0.7";}),f&&(f.textContent=`${s||"Skip"} \u2713`,f.style.opacity="0.8",f.disabled=true),m&&(m.disabled=true);}),y.submitted||y.skipped){let v=document.createElement("div");v.style.marginTop="10px",v.style.fontSize="12px",v.style.display="flex",v.style.alignItems="center",v.style.gap="8px";let I=document.createElement("span");I.style.display="inline-flex",I.style.alignItems="center",I.style.padding="2px 8px",I.style.borderRadius="999px",I.style.fontWeight="600",I.style.fontSize="11px",y.submitted?(I.style.background="rgba(16,185,129,0.15)",I.style.color="#10b981",I.textContent="Submitted"):(I.style.background="rgba(234,179,8,0.15)",I.style.color="#eab308",I.textContent="Skipped"),v.appendChild(I),C.appendChild(v);try{m&&(m.disabled=!0,m.style.opacity="0.8",y.submitted&&(m.textContent=`${p||"Submit"} \u2713`)),f&&(f.disabled=!0,f.style.opacity="0.8",y.skipped&&(f.textContent=`${s||"Skip"} \u2713`));}catch{}}c.appendChild(C);}function _n(n,e,t){let o=st.useRef(new Map),r=st.useRef(true),i=st.useRef(e),c=st.useRef(t);i.current=e,c.current=t,st.useEffect(()=>{if(r.current){r.current=false;return}let d=0;n.forEach(u=>{u.role==="assistant"&&u.parts?.forEach(x=>{if(!x.toolCallId)return;let g=x.toolName;if(!g&&x.type?.startsWith("tool-")&&(g=x.type.replace(/^tool-/,"")),!g)return;d++;let T=i.current[g];if(T&&typeof T=="object"&&T.executeEachToken&&T.tool){let y=x.input||x.args||{},C=JSON.stringify(y),a=o.current.get(x.toolCallId);if(C!==a&&C!=="{}"){o.current.set(x.toolCallId,C);try{g==="requestInput"?c.current(y,x.toolCallId):T.tool({...y,toolCallNumber:d});}catch{}}}});});},[n]);}var no="hsafa_dynamic_page_";function lt(n){return `${no}${n}`}function Se(n,e){try{let t=lt(n);localStorage.setItem(t,JSON.stringify(e));}catch(t){console.error("Failed to save dynamic page state:",t);}}function Ee(n){try{let e=lt(n),t=localStorage.getItem(e);return t?JSON.parse(t):null}catch(e){return console.error("Failed to load dynamic page state:",e),null}}function ro(n){try{let e=lt(n);localStorage.removeItem(e);}catch(e){console.error("Failed to delete dynamic page state:",e);}}function Pt(n){try{let e=lt(n);return localStorage.getItem(e)!==null}catch{return false}}function Z(n,e={}){return {success:true,message:n,...e}}function oo(n){if(n){if(n&&typeof n=="object"&&"_def"in n)try{let e=n._def,t=e.typeName||"unknown",o=e.description||void 0;return {type:"zod",zodType:t,description:o,schemaString:String(n)}}catch{return {type:"schema",note:"Schema provided but not serializable",raw:String(n)}}return typeof n=="object"?n:{type:"unknown",raw:String(n)}}}function ao(n){if(!n)return;let e=String(n).trim();if(e.length===0)return;if(e.includes('"'))return e;let t=e.split(/\r?\n+/).filter(Boolean);return (t.length>0?t:[e]).map(i=>i.trim().replace(/\s+/g," ")).map(i=>`"${i}"`).join(" ")}function X(n,e={}){return {success:false,message:n,...e}}function ct(n){let e=new Set;if(!n)return e;let t=/"([^"]+)"/g,o;for(;(o=t.exec(n))!==null;){let r=o[1].trim();r&&r.split(/\s+/).forEach(i=>{i&&i!=="."&&e.add(i);});}return e.size===0&&n.split(/\s+/).map(r=>r.replace(/"/g,"")).filter(r=>r&&r!==".").forEach(r=>e.add(r)),e}function so(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}function Lt(n,e){if(e===""||e==="/")return n;if(!e.startsWith("/"))throw new Error(`Invalid pointer: ${e}`);let t=e.split("/").slice(1).map(so),o=n;for(let r of t){if(o==null||typeof o!="object")throw new Error(`Invalid pointer path at ${r}`);o=o[r];}return o}function io(n,e){try{if(e.endsWith("/-")){let t=e.slice(0,-2)||"/",o=Lt(n,t);return Array.isArray(o)}return Lt(n,e),!0}catch{return false}}function jn(n,e){if(e===null)return null;if(typeof e!="object"||Array.isArray(e))return e;let t=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{};for(let o of Object.keys(e)){let r=e[o];r===null?delete t[o]:t[o]=jn(t[o],r);}return t}var Pe=class{constructor(e,t,o,r){this.chatId=e;this.state=t;this.availableTypes=o;this.onStateChange=r;}updateState(e){this.state=e,this.onStateChange(e),Se(this.chatId,e);}setGrid(e){let t={gridTemplateColumns:e.gridTemplateColumns,gridTemplateRows:e.gridTemplateRows,gap:e.gap||"0px 0px",gridTemplateAreas:ao(e.gridTemplateAreas)};this.updateState({...this.state,grid:t});let o=ct(t.gridTemplateAreas),r=Array.from(o);return Z(`Grid configured successfully with ${r.length} named area(s). When adding objects, use these area names: [${r.join(", ")}]`,{config:t,areas:r,area_count:r.length})}readGrid(){return this.state.grid?Z("Grid configuration retrieved",{grid:this.state.grid}):X("No grid configuration found. Use setGrid to create one.",{grid:null})}readAvailableTypes(){let e=this.availableTypes.map(t=>{let o={type:t.type,description:t.description,variants:t.variants};return t.schema?(o.schema=oo(t.schema),o.has_schema=true):o.has_schema=false,t.examples&&t.examples.length>0&&(o.examples=t.examples,o.example_count=t.examples.length),o});return Z(`Found ${e.length} registered component type(s). IMPORTANT: Only use these types when creating objects with setObject, or the component will not render correctly.`,{types:e,available_types:e.map(t=>t.type),total_count:e.length,types_with_schema:e.filter(t=>t.has_schema).length})}setObject(e){if(!e.object_name||typeof e.object_name!="string"||e.object_name.trim().length===0)return X("object_name is required and must be a non-empty string",{received_object_name:e.object_name,streaming_hint:"Waiting for complete object_name..."});if(e.type!==void 0&&(typeof e.type!="string"||e.type.trim().length===0))return X("type must be a non-empty string when provided",{object_name:e.object_name,received_type:e.type,streaming_hint:"Waiting for complete type..."});if(e.data===void 0)return X("data is required and cannot be undefined",{object_name:e.object_name,streaming_hint:"Waiting for data field to arrive..."});if(e.data===null)return X("Object data cannot be null",{object_name:e.object_name});let t=this.state.objects[e.object_name],o=!!t,r=[],i=[];if(e.type&&!this.availableTypes.some(a=>a.type===e.type)){let a=this.availableTypes.map(p=>p.type).join(", ");i.push(`TYPE MISMATCH: Type "${e.type}" is NOT registered. Available types: [${a}]. The object will render as raw JSON until you use a valid type. Call readAvailableTypes to see all registered types.`);}let c={object_name:e.object_name,area:e.area||e.object_name,data:e.data,type:e.type,meta:e.meta,version:o?(t.version||1)+1:1,updatedAt:new Date().toISOString()};if(this.state.grid?.gridTemplateAreas){let a=ct(this.state.grid.gridTemplateAreas),p=c.area||c.object_name;if(!a.has(p)){let s=Array.from(a).join(", ");r.push(`AREA WARNING: Area "${p}" is not defined in gridTemplateAreas. Available areas: [${s}]. The object may not be visible.`);}}this.updateState({...this.state,objects:{...this.state.objects,[e.object_name]:c}});let d=i.length>0||r.length>0,u=o?"reset":"added",x=d?`Object "${e.object_name}" ${u} with ${i.length} error(s) and ${r.length} warning(s). Review the issues below.`:`Object "${e.object_name}" ${u} successfully to area "${c.area}".`,g=(this.state.componentErrors||[]).filter(a=>a.object_name===e.object_name),T=new Date().getTime(),y=g.filter(a=>{let p=new Date(a.timestamp).getTime();return T-p<5e3}),C=y.length>0?{component_has_errors:true,component_error_count:g.length,recent_component_errors:y.slice(-3),latest_component_error:g[g.length-1],warning:`\u26A0\uFE0F This object has ${y.length} recent rendering error(s). Check component_errors field for details.`}:g.length>0?{component_has_errors:true,component_error_count:g.length,component_errors_note:`Object has ${g.length} past rendering error(s). Call readComponentErrors for details.`}:{component_has_errors:false};return {success:true,message:x,object:c,warnings:r,errors:i,has_issues:d||y.length>0,type_valid:i.length===0,area_valid:r.length===0,was_updated:o,previous_type:o?t.type:void 0,...C}}editObject(e){if(!e.object_name||typeof e.object_name!="string"||e.object_name.trim().length===0)return X("object_name is required and must be a non-empty string",{received_object_name:e.object_name,streaming_hint:"Waiting for complete object_name..."});let t=Array.isArray(e.json_patch)&&e.json_patch.length>0,o=e.merge_patch!==void 0&&e.merge_patch!==null,r=e.replace_entire_data===true&&e.new_data!==void 0;if(!t&&!o&&!r)return X("No complete edit operation provided. Waiting for json_patch, merge_patch, or replace_entire_data with new_data.",{object_name:e.object_name,has_json_patch:!!e.json_patch,has_merge_patch:e.merge_patch!==void 0,has_replace_data:!!e.replace_entire_data,streaming_hint:"Waiting for complete operation parameters..."});if(t){let d=e.json_patch.filter(u=>!u||typeof u!="object"||!u.op||typeof u.op!="string");if(d.length>0)return X('json_patch contains incomplete operations. Each operation must have an "op" field.',{object_name:e.object_name,incomplete_ops_count:d.length,total_ops:e.json_patch.length,streaming_hint:"Waiting for complete json_patch operations..."})}if(o&&typeof e.merge_patch!="object")return X("merge_patch must be an object",{object_name:e.object_name,received_type:typeof e.merge_patch,streaming_hint:"Waiting for complete merge_patch object..."});let i=this.state.objects[e.object_name];if(!i)return X(`Object "${e.object_name}" not found. Cannot edit non-existent object.`);let c=e.options?.expected_version;if(typeof c=="number"&&c!==i.version)return X(`Version conflict: expected ${c}, current ${i.version}.`,{current_version:i.version});try{let d=e.options?.patch_target==="object"?"object":"data",u={...i,data:i.data};if(e.replace_entire_data&&e.new_data!==void 0)u.data=e.new_data;else if(e.json_patch&&e.json_patch.length>0){let a=!!e.options?.strict_paths,p=e.json_patch.map(s=>{let l=s.path||"/",m=l;return d==="data"&&!l.startsWith("/data")&&(m=l==="/"?"/data":`/data${l}`),{...s,path:m}});if(a)p.forEach(l=>{if(["replace","remove","move","copy"].includes(l.op)){let m=d==="data"?{data:u.data}:u;if(!io(m,l.path))throw new Error(`Path does not exist for strict ${l.op}: ${l.path}`)}}),u=dt__namespace.applyPatch(u,p,!0).newDocument;else {let s=[],l=[],m=u;for(let f of p)try{m=dt__namespace.applyOperation(m,f,!1).newDocument,s.push({op:f,note:"applied"});}catch(v){l.push({op:f,error:v?.message||String(v)});}u=m,u.__edit_diagnostics={applied_ops_count:s.length,failed_ops_count:l.length,failed_ops:l};}}else if(e.merge_patch){let a=e.merge_patch?.data??e.merge_patch;u.data=jn(u.data,a);}u.version=(i.version||1)+1,u.updatedAt=new Date().toISOString();let x=!!e.options?.dry_run;x||this.updateState({...this.state,objects:{...this.state.objects,[e.object_name]:u}});let g=(this.state.componentErrors||[]).filter(a=>a.object_name===e.object_name),T=new Date().getTime(),y=g.filter(a=>{let p=new Date(a.timestamp).getTime();return T-p<5e3}),C=y.length>0?{component_has_errors:!0,recent_component_errors:y.slice(-3),warning:`\u26A0\uFE0F This object has ${y.length} recent rendering error(s) after edit.`}:g.length>0?{component_has_errors:!0,component_error_count:g.length}:{component_has_errors:!1};return Z(x?"Dry run completed":`Object "${e.object_name}" updated successfully`,{updated_object:e.options?.return_updated_object?u:void 0,applied_patch:e.options?.return_applied_patch?e.json_patch:void 0,dry_run:x,...C})}catch(d){return X(`Failed to edit object "${e.object_name}": ${d.message}`,{error:d.message})}}deleteObject(e){if(!this.state.objects[e.object_name])return X(`Object "${e.object_name}" not found. There is no object to delete with this name.`);let{[e.object_name]:o,...r}=this.state.objects;return this.updateState({...this.state,objects:r}),Z(`Object "${e.object_name}" deleted successfully`,{deleted:e.object_name})}readAllObjects(){let e=Object.values(this.state.objects);if(e.length===0)return Z("No objects found in the grid. Use setObject to add objects.",{objects:[],...this.getRecentErrorsSummary()});let t=this.getRecentErrorsSummary(),o=t.has_errors?`Found ${e.length} object(s) in the grid. Warning: ${t.total_error_count} component rendering error(s) detected.`:`Found ${e.length} object(s) in the grid`;return Z(o,{objects:e,...t})}readObject(e){let t=this.state.objects[e.object_name];if(!t)return X(`Object "${e.object_name}" not found. Use readAllObjects to see available objects.`);let o=(this.state.componentErrors||[]).filter(c=>c.object_name===e.object_name),r=o.length>0?{component_has_errors:true,component_errors:o.slice(-3).reverse(),component_error_count:o.length}:{component_has_errors:false},i=r.component_has_errors?`Object "${e.object_name}" retrieved. Warning: This component has ${o.length} rendering error(s).`:`Object "${e.object_name}" retrieved successfully`;return Z(i,{object:t,version:t.version,updatedAt:t.updatedAt,...r})}readAtPointer(e){let t=this.state.objects[e.object_name];if(!t)return {success:false,message:`Object "${e.object_name}" not found.`};let o=e.pointer||"/";try{let r=t.data,c=Lt(r,o==="/"?"/":o);return Z(`Value at pointer "${o}" retrieved successfully`,{value:c,pointer:o})}catch(r){return X(`Failed to read at pointer "${o}": ${r.message}`)}}renameObject(e){if(!this.state.objects[e.current_name])return X(`Object "${e.current_name}" not found. Cannot rename non-existent object.`);if(this.state.objects[e.new_name])return X(`Object "${e.new_name}" already exists. Choose a different name.`);let{[e.current_name]:o,...r}=this.state.objects,i={...o,object_name:e.new_name,area:e.new_area||e.new_name,version:o.version+1,updatedAt:new Date().toISOString()};return this.updateState({...this.state,objects:{...r,[e.new_name]:i}}),Z(`Object renamed from "${e.current_name}" to "${e.new_name}"`,{old_name:e.current_name,new_name:e.new_name})}moveObject(e){let t=this.state.objects[e.object_name];if(!t)return X(`Object "${e.object_name}" not found. Cannot move non-existent object.`);let o={...t,area:e.target_area,version:t.version+1,updatedAt:new Date().toISOString()};this.updateState({...this.state,objects:{...this.state.objects,[e.object_name]:o}});let r=[];return this.state.grid?.gridTemplateAreas&&(ct(this.state.grid.gridTemplateAreas).has(e.target_area)||r.push(`Area "${e.target_area}" is not defined in gridTemplateAreas`)),Z(`Object "${e.object_name}" moved to area "${e.target_area}"`,{object_name:e.object_name,target_area:e.target_area,warnings:r})}validateGrid(){if(!this.state.grid||!this.state.grid.gridTemplateAreas)return Z("No grid template areas defined. Validation skipped.",{valid:true,orphaned_objects:[],unused_areas:[],conflicts:[],warnings:[]});let e=ct(this.state.grid.gridTemplateAreas),t=[],o=new Set;Object.values(this.state.objects).forEach(u=>{let x=u.area||u.object_name;o.add(x),e.has(x)||t.push(u.object_name);});let r=[];e.forEach(u=>{o.has(u)||r.push(u);});let i=[];t.length>0&&i.push(`${t.length} object(s) reference non-existent grid areas`),r.length>0&&i.push(`${r.length} grid area(s) have no objects`);let c={};Object.values(this.state.objects).forEach(u=>{let x=u.area||u.object_name;c[x]=c[x]||[],c[x].push(u.object_name);});let d=[];for(let[u,x]of Object.entries(c))x.length>1&&d.push({area:u,objects:x});return Z(i.length>0?i.join(". "):"Grid is valid",{valid:t.length===0&&d.length===0,orphaned_objects:t,unused_areas:r,conflicts:d,warnings:i})}readComponentErrors(e){let t=this.state.componentErrors||[],o=e?.limit||10,r=Math.min(Math.max(1,o),50);if(t.length===0)return Z("No component errors found. All components are rendering successfully.",{errors:[],total_count:0,returned_count:0});let i=t.slice(-r).reverse();return Z(`Found ${t.length} component error(s). Returning ${i.length} most recent error(s).`,{errors:i,total_count:t.length,returned_count:i.length,limit:r,has_more:t.length>r})}clearComponentErrors(){let e=(this.state.componentErrors||[]).length;return this.updateState({...this.state,componentErrors:[]}),Z(e>0?`Cleared ${e} component error(s)`:"No component errors to clear",{cleared_count:e})}getRecentErrorsSummary(e=3){let t=this.state.componentErrors||[];return t.length===0?{has_errors:false}:{has_errors:true,recent_errors:t.slice(-e).reverse(),total_error_count:t.length}}};function Bt(n,e){let{currentChatId:t}=ne(),o=t||n,r=!!(o&&e&&e.length>0),[i,c]=st.useState(()=>!r||!o?{grid:null,objects:{},componentErrors:[]}:Ee(o)||{grid:null,objects:{},componentErrors:[]}),[d,u]=st.useState(()=>Pt(o)),x=st.useRef(null);st.useEffect(()=>{if(!r||!o){x.current=null;return}x.current=new Pe(o,i,e,a=>{c(a),u(true);});},[o,e,r]),st.useEffect(()=>{!r||!o||x.current&&(x.current=new Pe(o,i,e,a=>{c(a),u(true);}));},[i,o,e,r]),st.useEffect(()=>{if(!r||!o){c({grid:null,objects:{},componentErrors:[]}),u(false);return}let a=Ee(o);a?(c(a),u(true)):(c({grid:null,objects:{},componentErrors:[]}),u(false));},[o,r]);let g=st.useCallback(()=>x.current,[]),T=st.useCallback(()=>{u(false);},[]),y=st.useCallback(()=>{u(true);},[]),C=st.useCallback(a=>{!r||!o||c(p=>{let l=[...p.componentErrors||[],a].slice(-50),m={...p,componentErrors:l};return Se(o,m),m});},[o,r]);return {state:i,isDynamicPageOpen:d,getOperations:g,closeDynamicPage:T,openDynamicPage:y,handleError:C}}function he(n){return n&&typeof n=="object"&&"input"in n?{input:n.input,toolCallId:n.toolCallId}:{input:n}}function Ot(n,e){return {setGrid:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.setGrid(r)},readGrid:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");return o.readGrid()},readAvailableTypes:async()=>{let t=n();if(!t)throw new Error("Dynamic page operations not initialized");return t.readAvailableTypes()},setObject:{executeEachToken:true,tool:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.setObject(r)}},editObject:{executeEachToken:true,tool:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t),i=r?.options||{},c={...r,options:{return_updated_object:i.return_updated_object??true,return_applied_patch:i.return_applied_patch??true,strict_paths:i.strict_paths??false,...i}};return o.editObject(c)}},deleteObject:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.deleteObject(r)},readAllObjects:async()=>{let t=n();if(!t)throw new Error("Dynamic page operations not initialized");return t.readAllObjects()},readObject:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.readObject(r)},readAtPointer:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.readAtPointer(r)},renameObject:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.renameObject(r)},moveObject:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.moveObject(r)},validateGrid:async()=>{let t=n();if(!t)throw new Error("Dynamic page operations not initialized");return t.validateGrid()},readComponentErrors:async t=>{let o=n();if(!o)throw new Error("Dynamic page operations not initialized");let{input:r}=he(t);return o.readComponentErrors(r)},clearComponentErrors:async()=>{let t=n();if(!t)throw new Error("Dynamic page operations not initialized");return t.clearComponentErrors()}}}function zt(n){let{agentId:e,baseUrl:t="",tools:o={},uiComponents:r={},dynamicPageTypes:i=[],onFinish:c,onError:d,initialMessages:u=[],onMessagesChange:x}=n,{baseUrl:g,setCurrentChatId:T,registerDynamicPageTypes:y,unregisterDynamicPageTypes:C}=ne(),a=t&&t.length>0?t:g||"",[p,s]=st.useState(""),[l,m]=st.useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`);st.useEffect(()=>{try{T(l);}catch{}return ()=>{try{T(void 0);}catch{}}},[l,T]);let f=!!(i&&i.length>0);st.useEffect(()=>{if(f)return y(l,i),()=>{C(l);}},[l,f,i,y,C]);let v=Bt(f?l:"",f?i:[]),I=st.useMemo(()=>f?Ot(v.getOperations):{},[f,v.getOperations]),k=st.useMemo(()=>un(a,e,l),[a,e,l]),b=st.useCallback(_=>{console.log("Message finished:",_),c?.(_);},[c]),h=st.useCallback(_=>{console.error("Chat error:",_),d?.(_);},[d]),E=st.useMemo(()=>Tn(),[]),w=st.useMemo(()=>({...E,...I,...o}),[E,I,o]),P=st.useMemo(()=>An(),[]),S=st.useMemo(()=>({...P,...r}),[P,r]),A=st.useRef(new Map),F=st.useRef(new Map),M=st.useCallback(()=>{try{A.current.forEach(_=>{try{_.remove();}catch{}}),A.current.clear(),F.current.clear();}catch{}},[]),$=st.useCallback((_,z)=>{Rn(_,z,A.current,F.current,U=>D.current.addToolResult(U));},[]),D=st.useRef(null),R=st.useRef(new Set),O=st.useCallback((_,z,U)=>{console.error(`UI Error [${z}]:`,U),D.current&&R.current.has(_)&&(R.current.delete(_),D.current.addToolResult({tool:z,toolCallId:_,state:"output-error",errorText:U?.message||String(U)}));},[]),N=st.useCallback((_,z)=>{D.current&&R.current.has(_)&&(R.current.delete(_),D.current.addToolResult({tool:z,toolCallId:_,output:{status:"ok",rendered:true,component:z,logs:[]}}));},[]),J=st.useCallback(_=>{let z=w[_];return z?typeof z=="object"&&"tool"in z?z.tool:typeof z=="function"?z:null:null},[w]),V=react.useChat({transport:k,onFinish:b,onError:h,experimental_throttle:10,sendAutomaticallyWhen:ai.lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:_}){let z=J(_.toolName);if(_.toolName==="requestInput"){try{$(_.input,_.toolCallId);}catch(ee){console.error("requestInput render error",ee);}return}let U=_.toolName==="ui";_?.input;let se=S&&_.toolName in S;if(U||se){R.current.add(_.toolCallId);return}if(z)try{let ee=await z(_.input);V.addToolResult({tool:_.toolName,toolCallId:_.toolCallId,output:ee});}catch(ee){V.addToolResult({tool:_.toolName,toolCallId:_.toolCallId,state:"output-error",errorText:ee?.message||String(ee)});}}}),{messages:H,sendMessage:K,status:ae,stop:Ne,error:kt}=V;D.current=V,_n(H,w,$),st.useEffect(()=>{try{let _=new Set,z=[];if(H.forEach(U=>{U.role==="assistant"&&(U.parts||[]).forEach(G=>{if((G?.toolName||(typeof G?.type=="string"&&G.type.startsWith("tool-")?String(G.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let ee=G?.toolCallId||"";if(!ee)return;_.add(ee);let oe=G?.output;if(oe&&(oe.submitted||oe.skipped||oe.values)){let Ze={submitted:!!oe.submitted,skipped:!!oe.skipped,values:oe.values||void 0};F.current.set(ee,Ze);}let Ye=G?.input||G?.args||{};z.push({input:Ye,toolCallId:ee});});}),A.current.forEach((U,G)=>{if(!_.has(G)){let se=A.current.get(G);try{se?.remove();}catch{}A.current.delete(G),F.current.delete(G);}}),z.length>0){let U=requestAnimationFrame(()=>{z.forEach(({input:G,toolCallId:se})=>{try{$(G,se);}catch{}});});return ()=>cancelAnimationFrame(U)}}catch{}},[H,$]),st.useEffect(()=>{u&&u.length>0&&H.length===0&&console.log("Initial messages:",u);},[u,H.length]);let Xe=st.useRef(x);st.useEffect(()=>{Xe.current=x;},[x]);let Ae=st.useRef([]);st.useEffect(()=>{(H.length!==Ae.current.length||H.length>0&&Ae.current.length>0&&H[H.length-1]?.id!==Ae.current[Ae.current.length-1]?.id)&&Xe.current&&(Ae.current=H,Xe.current(H));},[H]);let ye=ae==="submitted"||ae==="streaming",wt=st.useCallback(async _=>{let z=_?.text!==void 0?_.text:p,U=_?.files||[],G=z.trim();if(!(!G&&U.length===0)&&!ye){_?.text===void 0&&s("");try{await K({text:G,files:U});}catch(se){throw console.error("Failed to send message:",se),se}}},[p,ye,K]),Tt=st.useCallback(()=>{if(ye)return;M(),s("");try{V?.setMessages?.([]);}catch{}let _=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;m(_);},[ye,V,M]),St=st.useCallback(_=>{try{V?.setMessages?.(_);}catch{}},[V]);return {input:p,setInput:s,messages:H,isLoading:ye,status:ae,error:kt,sendMessage:wt,stop:Ne,newChat:Tt,setMessages:St,chatApi:V,chatId:l,setChatId:m,tools:w,uiComponents:S,dynamicPage:f?v:null,formHostRef:A,formStateRef:F,cleanupForms:M,onUISuccess:N,onUIError:O}}function pt(n){let e=`hsafaChat_${n}`,t=`${e}.chats`,o=f=>`${e}.chat.${f}`,r=`${e}.currentChatId`,i=`${e}.showChat`,c=()=>{try{let f=localStorage.getItem(t);return f?JSON.parse(f):[]}catch{return []}},d=f=>{try{localStorage.setItem(t,JSON.stringify(f));}catch{}},u=f=>{try{let v=localStorage.getItem(o(f));return v?JSON.parse(v):null}catch{return null}},x=f=>{try{localStorage.setItem(o(f.id),JSON.stringify(f));}catch{}},g=f=>{let v=c(),I=v.findIndex(k=>k.id===f.id);I>=0?v[I]=f:v.unshift(f),d(v);},T=f=>{let I=c().filter(k=>k.id!==f);d(I);},y=f=>{try{localStorage.removeItem(o(f));}catch{}};return {loadChatsIndex:c,saveChatsIndex:d,loadChat:u,saveChat:x,upsertChatMeta:g,deleteChatMeta:T,deleteChatData:y,deleteChat:f=>{y(f),T(f);},loadShowChatPreference:f=>{try{let v=localStorage.getItem(i);return v!==null?v==="true":f}catch{return f}},saveShowChatPreference:f=>{try{localStorage.setItem(i,String(f));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(r)}catch{return null}},saveCurrentChatId:f=>{try{localStorage.setItem(r,f);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(r);}catch{}}}}function Wt(n){let{agentId:e,chatId:t,messages:o,isLoading:r=false,autoSave:i=true,autoRestore:c=true}=n,d=st.useMemo(()=>pt(e),[e]),[u,x]=st.useState([]),[g,T]=st.useState(null),y=st.useRef(false),C=st.useRef(false),a=st.useCallback(()=>{try{let k=d.loadChatsIndex();x(k);let b=k.find(h=>h.id===t);T(b||null);}catch(k){console.error("Failed to refresh chat list:",k);}},[d,t]);st.useEffect(()=>{a();},[a]),st.useEffect(()=>{if(!(!c||C.current)){try{d.loadCurrentChatId()&&(y.current=!0);}catch(k){console.error("Failed to restore chat:",k);}C.current=true;}},[d,c]),st.useEffect(()=>{if(!(!i||o.length===0))if(y.current){if(!r){let k=Date.now();try{d.saveChat({id:t,messages:o,agentId:e});let h=d.loadChatsIndex().find(E=>E.id===t);h&&(d.upsertChatMeta({...h,updatedAt:k}),a());}catch(b){console.error("Failed to save chat:",b);}}}else {let k=o.find(b=>b.role==="user");if(k){let b="";if(Array.isArray(k.parts)){let w=k.parts.find(P=>P&&P.type==="text");b=w&&typeof w.text=="string"?w.text:"";}let h=(b||"New chat").slice(0,80),E=Date.now();try{d.upsertChatMeta({id:t,title:h,createdAt:E,updatedAt:E}),d.saveChat({id:t,messages:o,agentId:e}),d.saveCurrentChatId(t),y.current=!0,a();}catch(w){console.error("Failed to create chat:",w);}}}},[o,e,t,d,r,i,a]);let p=st.useRef(false);st.useEffect(()=>{if(r){p.current=true;return}if(p.current&&i){p.current=false;try{let k=Date.now();d.saveChat({id:t,messages:o,agentId:e});let h=d.loadChatsIndex().find(E=>E.id===t);h&&(d.upsertChatMeta({...h,updatedAt:k}),a());}catch(k){console.error("Failed to save chat on completion:",k);}}},[r,o,t,e,d,i,a]);let s=st.useCallback(k=>{try{let b=d.loadChat(k);return b?{id:b.id,messages:b.messages,agentId:b.agentId||e}:null}catch(b){return console.error("Failed to load chat:",b),null}},[d,e]),l=st.useCallback(()=>{if(o.length!==0)try{let k=Date.now();d.saveChat({id:t,messages:o,agentId:e});let h=d.loadChatsIndex().find(E=>E.id===t);h&&(d.upsertChatMeta({...h,updatedAt:k}),a());}catch(k){console.error("Failed to save chat:",k);}},[d,t,o,e,a]),m=st.useCallback(k=>{try{d.deleteChat(k),a();}catch(b){console.error("Failed to delete chat:",b);}},[d,a]),f=st.useCallback((k,b)=>{if(k!==t)try{y.current=!0,d.saveCurrentChatId(k);let h=d.loadChat(k),E=h&&Array.isArray(h.messages)?h.messages:[];b(E),a();}catch(h){console.error("Failed to switch chat:",h);}},[d,t,a]),v=st.useCallback(k=>{y.current=false,k();},[]),I=st.useCallback(k=>{if(!k.trim())return u;let b=k.toLowerCase();return u.filter(h=>h.title.toLowerCase().includes(b))},[u]);return {chatList:u,currentChatMeta:g,refreshChatList:a,loadChat:s,saveCurrentChat:l,deleteChat:m,switchToChat:f,createNewChat:v,searchChats:I,storage:d}}function mo(n){let{messages:e,isLoading:t,sendMessage:o,setMessages:r,baseUrl:i}=n,{baseUrl:c}=ne(),d=i||c||"",[u,x]=st.useState(null),[g,T]=st.useState(""),[y,C]=st.useState([]),[a,p]=st.useState(false),s=st.useCallback((k,b,h=[])=>{x(k),T(b),C(h);},[]),l=st.useCallback(()=>{x(null),T(""),C([]);},[]),m=st.useCallback(async k=>{if(!t)try{let b=e.findIndex(E=>E.id===k);if(b===-1)return;let h=e.slice(0,b);r(h),await o({text:g.trim(),files:y.map(E=>({type:"file",url:E.url,mediaType:E.mimeType||"application/octet-stream",...E.name?{name:E.name}:{},...E.size?{size:E.size}:{}}))}),l();}catch(b){throw console.error("Failed to save edit:",b),b}},[t,e,o,g,y,r,l]),f=st.useCallback(k=>u===k,[u]),v=st.useCallback(async k=>{if(!d){console.warn("baseUrl not provided, cannot upload attachments");return}p(true);try{let b=Array.from(k).map(async E=>{if(E.size>26214400)throw new Error(`${E.name} is too large (max 25MB)`);let w=new FormData;w.append("file",E);let P=await fetch(`${d}/api/upload`,{method:"POST",body:w});if(!P.ok)throw new Error(`Upload failed: ${P.statusText}`);let S=await P.json();return {id:S.url||`${Date.now()}-${Math.random()}`,name:E.name,url:S.url,mimeType:E.type,size:E.size}}),h=await Promise.all(b);C(E=>[...E,...h]);}catch(b){throw console.error("Failed to upload files:",b),b}finally{p(false);}},[d]),I=st.useCallback(k=>{C(b=>b.filter(h=>h.id!==k));},[]);return {editingMessageId:u,editingText:g,setEditingText:T,editAttachments:y,setEditAttachments:C,editUploading:a,startEdit:s,cancelEdit:l,saveEdit:m,isEditing:f,addEditAttachments:v,removeEditAttachment:I}}function Q({IconComponent:n,...e}){return st__default.default.createElement(n,e)}function Ut({icon:n,onClick:e,ariaLabel:t,resolvedColors:o,disabled:r=false,title:i}){return jsxRuntime.jsx("button",{"aria-label":t,title:i,disabled:r,style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:c=>{r||(c.currentTarget.style.backgroundColor=o.hoverBackground,c.currentTarget.style.color=o.textColor);},onMouseLeave:c=>{c.currentTarget.style.backgroundColor="transparent",c.currentTarget.style.color=o.mutedTextColor;},onClick:e,children:n})}function Ln({title:n,alwaysOpen:e,streaming:t,dir:o,resolvedColors:r,onNew:i,onToggleHistory:c,onClose:d,historyBtnRef:u,t:x}){return jsxRuntime.jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:o==="rtl"?"rtl":"ltr"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0"},children:jsxRuntime.jsx("h1",{title:n,style:{color:r.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:n})}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:r.mutedTextColor},children:[jsxRuntime.jsx(Ut,{icon:jsxRuntime.jsx(Q,{IconComponent:lucideReact.Plus,size:"20",strokeWidth:"2"}),onClick:()=>{t||i();},ariaLabel:x("header.new"),resolvedColors:r,disabled:t}),jsxRuntime.jsx("button",{ref:u,"aria-label":x("header.history"),style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:g=>{g.currentTarget.style.backgroundColor=r.hoverBackground,g.currentTarget.style.color=r.textColor;},onMouseLeave:g=>{g.currentTarget.style.backgroundColor="transparent",g.currentTarget.style.color=r.mutedTextColor;},onClick:c,children:jsxRuntime.jsx(Q,{IconComponent:lucideReact.History,size:"20",strokeWidth:"2"})}),!e&&jsxRuntime.jsx(Ut,{icon:jsxRuntime.jsx(Q,{IconComponent:lucideReact.ChevronRight,size:"20",strokeWidth:"2",style:{transform:o==="rtl"?"rotate(180deg)":"none"}}),onClick:d,ariaLabel:x("header.close"),resolvedColors:r})]})]})}var ht=class extends st.Component{constructor(e){super(e),this.state={hasError:false,error:null,errorInfo:null};}static getDerivedStateFromError(e){return {hasError:true,error:e,errorInfo:null}}componentDidMount(){let{toolCallId:e,toolName:t,onSuccess:o}=this.props;e&&t&&o&&!this.state.hasError&&setTimeout(()=>{this.state.hasError||o(e,t);},0);}componentDidCatch(e,t){console.error(`UI Component Error (${this.props.componentName}):`,e,t),this.setState({error:e,errorInfo:t});let{toolCallId:o,toolName:r,onError:i}=this.props;o&&r&&i&&i(o,r,e);}render(){if(this.state.hasError&&this.state.error){let{resolvedColors:e,componentName:t}=this.props;return jsxRuntime.jsxs("div",{style:{padding:"16px",backgroundColor:"#fee2e2",border:"2px solid #ef4444",borderRadius:"12px",color:"#991b1b"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsxRuntime.jsx("span",{style:{fontSize:"20px"},children:"\u26A0\uFE0F"}),jsxRuntime.jsxs("strong",{style:{fontSize:"16px"},children:["Component Error: ",t]})]}),jsxRuntime.jsx("div",{style:{fontSize:"14px",marginBottom:"8px",fontFamily:"monospace"},children:this.state.error.message}),this.state.errorInfo&&jsxRuntime.jsxs("details",{style:{fontSize:"12px",marginTop:"8px"},children:[jsxRuntime.jsx("summary",{style:{cursor:"pointer",fontWeight:"bold"},children:"Stack Trace"}),jsxRuntime.jsx("pre",{style:{marginTop:"8px",padding:"8px",backgroundColor:"#fef2f2",borderRadius:"4px",overflow:"auto",maxHeight:"200px",fontSize:"11px"},children:this.state.errorInfo.componentStack})]})]})}return this.props.children}};var Co=n=>{let e={"input-streaming":{color:"#eab308",text:"Inputting"},"input-available":{color:"#3b82f6",text:"Running"},error:{color:"#ef4444",text:"Error"},"output-available":{color:"#10b981",text:"Called"},finished:{color:"#10b981",text:"Called"}};return e[n||"output-available"]||e["output-available"]},vo=n=>{let e=/^(.+?)_([a-f0-9]{6})_(.+)$/,t=n.match(e);if(t){let[,o,,r]=t;return {isMCP:true,mcpName:o.replace(/_/g," "),toolName:r.replace(/_/g," ")}}return {isMCP:false,toolName:n}},ko=n=>n.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,e=>e.toUpperCase());function Hn({parts:n,messageId:e,openReasoningIds:t,toggleReasoning:o,resolvedColors:r,HsafaUI:i,onUIError:c,onUISuccess:d,addToolResult:u}){let x=[],g=[],T,y,C=false;for(let a of Array.isArray(n)?n:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){g.push(a.text),T||(T=a.startDate),y=a.endDate,a.state==="done"&&(C=true);continue}if(a.type==="text"&&typeof a.text=="string"){g.length&&(x.push({type:"reasoning",texts:g,startDate:T,endDate:y,isCompleted:C}),g=[],T=void 0,y=void 0,C=false),x.push({type:"text",text:a.text,startDate:a.startDate,endDate:a.endDate});continue}let p=a.type==="dynamic-tool",s=typeof a.type=="string"&&a.type.startsWith("tool-");if(p||s||a.type==="tool-call"){g.length&&(x.push({type:"reasoning",texts:g,startDate:T,endDate:y,isCompleted:C}),g=[],T=void 0,y=void 0,C=false);let l=String(p?a.toolName||"dynamic-tool":s?a.type?.slice(5)||"tool":a.toolName||"tool");l==="requestInput"?x.push({type:"tool",toolName:l,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId}):x.push({type:"tool",toolName:l,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId});continue}}return g.length&&x.push({type:"reasoning",texts:g,startDate:T,endDate:y,isCompleted:C}),x.length?jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[x.map((a,p)=>{let s=`${e}-${p}`,l=t.has(s);if(a.type==="reasoning"){let b=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",h=a.texts&&a.texts.length>0&&a.texts.some(w=>w.trim().length>0),E=()=>{h&&o(s);};return b&&!h?null:jsxRuntime.jsx("div",{onClick:E,style:{cursor:h?"pointer":"default",padding:"0"},children:jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:l?"4px":"0px"},children:[jsxRuntime.jsxs("div",{style:{fontSize:"13px",color:r.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"6px",overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:[jsxRuntime.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px"},children:[!b&&jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsxRuntime.jsx("span",{style:{color:r.textColor,fontWeight:600,opacity:.9,background:b?"none":`linear-gradient(90deg, ${r.textColor}, ${r.mutedTextColor}, ${r.mutedTextColor})`,backgroundSize:b?"auto":"200% 100%",backgroundClip:b?"unset":"text",WebkitBackgroundClip:b?"unset":"text",WebkitTextFillColor:b?r.mutedTextColor:"transparent",animation:b?void 0:"shimmer 2s ease-in-out infinite"},children:b?"Finish Thinking":"Thinking"})]}),h&&jsxRuntime.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:l?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s ease-out"},children:jsxRuntime.jsx("polyline",{points:"9 18 15 12 9 6"})})]}),jsxRuntime.jsx("div",{style:{display:"grid",gridTemplateRows:l||!b?"1fr":"0fr",transition:"grid-template-rows 0.2s ease-out",overflow:"hidden"},children:jsxRuntime.jsx("div",{style:{minHeight:0},children:a.texts&&a.texts.length>0?jsxRuntime.jsx("div",{style:{fontSize:"13px",color:r.mutedTextColor,lineHeight:"1.6",maxWidth:"100%"},children:(!b&&l?a.texts:b?l?a.texts:[]:[a.texts[a.texts.length-1]]).map((w,P)=>jsxRuntime.jsx("div",{style:{marginBottom:"6px"},children:jsxRuntime.jsx(Ve,{content:w,theme:"dark"})},`rg-line-${p}-${P}`))}):jsxRuntime.jsxs("div",{style:{fontSize:"12px",color:r.mutedTextColor,opacity:.7,display:"flex",alignItems:"center",gap:"8px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsxRuntime.jsx("span",{style:{letterSpacing:"2px",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"},children:"..."})]})})})]})},s)}if(a.type==="text")return jsxRuntime.jsx("div",{style:{fontSize:"15px",color:r.textColor,lineHeight:"1.6"},children:jsxRuntime.jsx(Ve,{content:a.text,theme:"dark"})},s);let{color:m,text:f}=Co(a.status),v=a.status==="input-streaming"||a.status==="input-available";if(a.toolName==="requestInput")return jsxRuntime.jsx("div",{style:{display:"block",position:"relative"},children:jsxRuntime.jsx("div",{"data-get-from-user-host":a.toolCallId||s,style:{width:"100%"}})},s);let I=i?.[a.toolName||""];if(I)return jsxRuntime.jsx("div",{style:{display:"block",position:"relative"},children:jsxRuntime.jsx(ht,{componentName:a.toolName||"Unknown",resolvedColors:r,toolCallId:a.toolCallId,toolName:a.toolName||"unknown",onError:c,onSuccess:d,children:jsxRuntime.jsx(I,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:u})})},s);let k=vo(a.toolName||"tool");return jsxRuntime.jsx("div",{style:{display:"flex",gap:"12px",position:"relative"},children:jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:jsxRuntime.jsxs("div",{style:{fontSize:"13px",color:r.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxRuntime.jsxs("span",{style:{fontWeight:600,color:m,display:"flex",alignItems:"center",gap:"6px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:m,animation:v?"pulse 1.5s ease-in-out infinite":void 0}}),f]}),k.isMCP?jsxRuntime.jsxs("span",{style:{fontWeight:500,color:r.textColor},children:[jsxRuntime.jsx("span",{style:{fontWeight:600},children:k.toolName}),jsxRuntime.jsx("span",{style:{opacity:.7,margin:"0 4px"},children:"from"}),jsxRuntime.jsx("span",{style:{fontWeight:600,opacity:.85},children:k.mcpName})]}):jsxRuntime.jsx("span",{style:{fontWeight:500,color:r.textColor},children:ko(k.toolName)})]})})},s)}),jsxRuntime.jsx("style",{children:`
|
|
13
|
+
`),r="",o=false,i="",p=[],c=false,b=false,T=false,h=t==="dark"?"#374151":"#D1D5DB",x=t==="dark"?"#111827":"#F3F4F6",k=t==="dark"?"#E5E7EB":"#374151",a=t==="dark"?"#374151":"#F3F4F6",v=t==="dark"?"#F9FAFB":"#111827",s=()=>{c&&(r+="</ul>",c=false),b&&(r+="</ol>",b=false);},d=l=>{for(let u=l;u<n.length;u++)if(n[u].trim().length>0)return u;return -1},g=l=>{let u=l.trim(),w=u.startsWith("|")?u.slice(1):u;return (w.endsWith("|")?w.slice(0,-1):w).split("|").map(A=>A.trim())},y=l=>{let u=l.trim();if(!u.startsWith("|"))return false;let w=g(u);return w.length>=2&&w.some(f=>f.length>0)},m=l=>{let u=g(l);return u.length===0?false:u.every(w=>/^:?-{3,}:?$/.test(w))},I=l=>{let u=l.startsWith(":"),w=l.endsWith(":");return u&&w?"center":!u&&w?"right":"left"},C=l=>{let u=l,w=d(u+1);if(w===-1)return {tableHtml:"",endIndex:l};let f=g(n[u]),A=g(n[w]),B=Math.max(f.length,A.length),H=[];for(let F=0;F<B;F++){let L=A[F]||"---";H.push(I(L));}let K=[],R=w+1;for(;R<n.length;){let F=n[R].trim();if(F.length===0){R++;continue}if(!F.startsWith("|"))break;let L=g(n[R]),N=[];for(let G=0;G<B;G++)N.push(L[G]??"");K.push(N),R++;}let O=`<div style="overflow: auto; max-width: 100%; max-height: 60vh; border-radius: 10px; margin: 8px 0;">
|
|
14
|
+
<table style="width: 100%; min-width: max-content; border-collapse: separate; border-spacing: 0; margin: 0;">`;O+="<thead><tr>";for(let F=0;F<B;F++){let L=Fe(se(f[F]??"")),N=H[F],G=F===0,D=F===B-1;O+=`<th style="text-align: ${N}; padding: 10px 12px; border-bottom: 1px solid ${h}; background-color: ${a}; color: ${v}; position: sticky; top: 0; z-index: 1; ${`${G?"border-top-left-radius: 10px;":""}${D?"border-top-right-radius: 10px;":""}`}">${L}</th>`;}O+="</tr></thead>",O+="<tbody>";for(let F of K){O+="<tr>";for(let L=0;L<B;L++){let N=Fe(se(F[L]??"")),G=H[L],D=L===0;O+=`<td style="text-align: ${G}; padding: 10px 12px; border-bottom: 1px solid ${h}; ${D?`border-left: 1px solid ${h};`:""} border-right: 1px solid ${h};">${N}</td>`;}O+="</tr>";}return O+="</tbody></table></div>",{tableHtml:O,endIndex:R-1}};for(let l=0;l<n.length;l++){let u=n[l],w=u.match(/^```\s*(\w+)?\s*$/);if(w){if(!o)s(),o=true,i=w[1]?String(w[1]):"",p=[];else {if(i==="mermaid"){T=true;let H=p.join(`
|
|
15
|
+
`);r+=`<div class="mermaid-placeholder" data-mermaid="${se(H)}"></div>`;}else {let H=se(p.join(`
|
|
16
|
+
`)),K=i?`language-${i}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${x}; color: ${k}; border: 1px solid ${h}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${K}">${H}</code></pre>`;}o=false,i="",p=[];}continue}if(o){p.push(u);continue}if(/^\s*(---|\*\*\*|___)\s*$/.test(u)){s(),r+='<hr style="margin: 12px 0; opacity: 0.6; border: none; border-top: 1px solid currentColor;" />';continue}let f=u.match(/^(#{1,6})\s+(.+)$/);if(f){s();let H=f[1].length,K=Fe(se(f[2].trim())),R=H<=2?"18px":H===3?"16px":"14px";r+=`<h${H} style="font-size: ${R}; font-weight: 600; margin: 8px 0 4px 0;">${K}</h${H}>`;continue}if(y(u)){let H=d(l+1);if(H!==-1&&m(n[H])){s();let{tableHtml:K,endIndex:R}=C(l);if(K){r+=K,l=R;continue}}}let A=u.match(/^\s*[-*]\s+(.+)$/),B=u.match(/^\s*\d+\.\s+(.+)$/);if(A){c||(s(),r+='<ul style="list-style-type: disc; padding-left: 24px; margin: 4px 0;">',c=true);let H=Fe(se(A[1]));r+=`<li style="margin: 2px 0;">${H}</li>`;continue}if(B){b||(s(),r+='<ol style="list-style-type: decimal; padding-left: 24px; margin: 4px 0;">',b=true);let H=Fe(se(B[1]));r+=`<li style="margin: 2px 0;">${H}</li>`;continue}if(u.trim().length===0)s(),r+='<div style="height: 8px;"></div>';else {s();let H=Fe(se(u));r+=`<p style="line-height: 1.6; margin: 4px 0; word-break: break-word;">${H}</p>`;}}if(o)if(i==="mermaid"){T=true;let l=p.join(`
|
|
17
|
+
`);r+=`<div class="mermaid-placeholder" data-mermaid="${se(l)}"></div>`;}else {let l=se(p.join(`
|
|
18
|
+
`)),u=i?`language-${i}`:"";r+=`<pre style="border-radius: 8px; padding: 12px; background-color: ${x}; color: ${k}; border: 1px solid ${h}; overflow-x: auto; white-space: pre-wrap; word-break: break-all;"><code class="${u}">${l}</code></pre>`;}return c&&(r+="</ul>"),b&&(r+="</ol>"),{html:r,hasMermaid:T}}function Oe({content:e,theme:t}){let{html:n,hasMermaid:r}=tt.useMemo(()=>Po(e,t),[e,t]);if(!r)return jsxRuntime.jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:n}});let o=n.split(/(<div class="mermaid-placeholder"[^>]*><\/div>)/g),i=[];return o.forEach((p,c)=>{if(p.includes("mermaid-placeholder")){let b=p.match(/data-mermaid="([^"]*)"/);if(b){let T=b[1].replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'");i.push(tt__default.default.createElement(pn,{key:`mermaid-${c}`,chart:T,theme:t}));}}else p.trim()&&i.push(tt__default.default.createElement("div",{key:`html-${c}`,style:{fontSize:"14px",lineHeight:"1.6",wordBreak:"break-word",maxWidth:"100%",overflow:"hidden"},dangerouslySetInnerHTML:{__html:p}}));}),tt__default.default.createElement(tt__default.default.Fragment,{},...i)}function zo({input:e}){return jsxRuntime.jsx("div",{style:{fontSize:"14px",lineHeight:"1.6",width:"100%"},children:jsxRuntime.jsx(Oe,{content:e?.text||"",theme:"dark"})})}function gn(){return {plainText:zo}}function fn(e,t,n,r,o,i){let p=n.get(t);if(p){let m=p.parentElement,I=document.querySelector(`[data-get-from-user-host="${t}"]`);if(I&&m!==I){try{m?.removeChild(p);}catch{}I.innerHTML="",I.appendChild(p);}}else {p=document.createElement("div"),p.className="hsafa-inline-form";let m=document.querySelector(`[data-get-from-user-host="${t}"]`);m?(m.innerHTML="",m.appendChild(p)):(document.querySelector(".chat-scroll-container")||document.body).appendChild(p),n.set(t,p);}let c=e?.title||"Provide input",b=e?.description||"",T=e?.submitLabel||"Submit",h=e?.skipLabel||"Skip",S=Array.isArray(e?.fields)?e.fields:e?.label||e?.placeholder?[{id:"value",label:e?.label||"Value",type:"text",placeholder:e?.placeholder||""}]:[],x=r.get(t)||{submitted:false,skipped:false,values:void 0};p.innerHTML="";let k=document.createElement("form");k.style.margin="12px 0",k.style.padding="14px",k.style.border="1px solid var(--hsafa-border, #2A2C33)",k.style.borderRadius="12px",k.style.background="var(--hsafa-card, #121318)",k.style.color="var(--hsafa-text, #EDEEF0)",k.style.boxShadow="0 6px 20px rgba(0,0,0,0.25)";let a=document.createElement("div");if(a.style.fontWeight="600",a.style.marginBottom="6px",a.textContent=c,k.appendChild(a),b){let m=document.createElement("div");m.style.fontSize="12px",m.style.opacity="0.8",m.style.marginBottom="10px",m.textContent=b,k.appendChild(m);}S.forEach(m=>{let I=document.createElement("div");if(I.style.margin="10px 0",m.label){let f=document.createElement("label");f.style.display="block",f.style.fontSize="12px",f.style.marginBottom="6px",f.style.opacity="0.9",f.textContent=m.label,I.appendChild(f);}let C,l=(m.type||"text").toLowerCase();if(l==="textarea"){let f=document.createElement("textarea");f.placeholder=m.placeholder||"",f.value=m.value??"",f.style.width="100%",f.style.minHeight="72px",f.style.padding="10px 12px",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.borderRadius="10px",f.style.background="var(--hsafa-input-bg, #17181C)",f.style.color="inherit",C=f;}else if(l==="select"&&Array.isArray(m.options)){let f=document.createElement("select");f.style.width="100%",f.style.padding="10px 12px",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.borderRadius="10px",f.style.background="var(--hsafa-input-bg, #17181C)",f.style.color="inherit",m.options.forEach(A=>{let B=document.createElement("option");B.value=String(A.value),B.text=String(A.label??A.value),f.appendChild(B);}),f.value=m.value??"",C=f;}else if(l==="checkbox"){let f=document.createElement("input");f.type="checkbox",f.checked=!!m.value,f.style.transform="scale(1.1)",C=f;}else {let f=document.createElement("input");f.type=l,f.placeholder=m.placeholder||"",f.value=m.value??"",f.style.width="100%",f.style.padding="10px 12px",f.style.border="1px solid var(--hsafa-border, #2A2C33)",f.style.borderRadius="10px",f.style.background="var(--hsafa-input-bg, #17181C)",f.style.color="inherit",C=f;}let u=m.id||"value";C.dataset.fieldId=u;let w=x.values&&Object.prototype.hasOwnProperty.call(x.values,u)?x.values[u]:void 0;typeof w<"u"&&(C.type==="checkbox"?C.checked=!!w:C.value=String(w)),(x.submitted||x.skipped)&&(C.setAttribute("disabled","true"),C.style.opacity="0.7"),I.appendChild(C),k.appendChild(I);});let v=String(T).trim(),s=String(h).trim(),d=!!(v||s),g=null,y=null;if(d){let m=document.createElement("div");m.style.display="flex",m.style.gap="8px",m.style.marginTop="10px",g=document.createElement("button"),g.type="submit",g.textContent=v||"Submit",g.style.padding="6px 10px",g.style.borderRadius="8px",g.style.background="var(--hsafa-button-bg, var(--hsafa-primary, #2563eb))",g.style.color="#000000",y=document.createElement("button"),y.type="button",y.textContent=s||"Skip",y.style.padding="6px 10px",y.style.borderRadius="8px",y.style.background="transparent",y.style.border="1px solid var(--hsafa-border, #2A2C33)",y.style.color="inherit",m.appendChild(g),m.appendChild(y),k.appendChild(m);}if(k.onsubmit=m=>{m.preventDefault();let I={};k.querySelectorAll("[data-field-id]").forEach(C=>{let l=C.dataset.fieldId||"value";C.type==="checkbox"?I[l]=C.checked:I[l]=C.value??"";}),r.set(t,{submitted:true,skipped:false,values:I}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:true,values:I}}),k.querySelectorAll("[data-field-id]").forEach(C=>{C.disabled=true,C.style.opacity="0.7";}),g&&(g.textContent=`${v||"Submit"} \u2713`,g.style.opacity="0.8",g.disabled=true),y&&(y.disabled=true);},y&&(y.onclick=()=>{r.set(t,{submitted:false,skipped:true,values:void 0}),o({tool:"requestInput",toolCallId:t,output:{success:true,submitted:false,skipped:true}}),k.querySelectorAll("[data-field-id]").forEach(m=>{m.disabled=true,m.style.opacity="0.7";}),y&&(y.textContent=`${s||"Skip"} \u2713`,y.style.opacity="0.8",y.disabled=true),g&&(g.disabled=true);}),x.submitted||x.skipped){let m=document.createElement("div");m.style.marginTop="10px",m.style.fontSize="12px",m.style.display="flex",m.style.alignItems="center",m.style.gap="8px";let I=document.createElement("span");I.style.display="inline-flex",I.style.alignItems="center",I.style.padding="2px 8px",I.style.borderRadius="999px",I.style.fontWeight="600",I.style.fontSize="11px",x.submitted?(I.style.background="rgba(16,185,129,0.15)",I.style.color="#10b981",I.textContent="Submitted"):(I.style.background="rgba(234,179,8,0.15)",I.style.color="#eab308",I.textContent="Skipped"),m.appendChild(I),k.appendChild(m);try{g&&(g.disabled=!0,g.style.opacity="0.8",x.submitted&&(g.textContent=`${v||"Submit"} \u2713`)),y&&(y.disabled=!0,y.style.opacity="0.8",x.skipped&&(y.textContent=`${s||"Skip"} \u2713`));}catch{}}p.appendChild(k);}function yn(e,t,n){let r=tt.useRef(new Map),o=tt.useRef(new Map),i=tt.useRef(t),p=tt.useRef(n);i.current=t,p.current=n,tt.useEffect(()=>{e.forEach(c=>{c.role==="assistant"&&c.parts?.forEach(b=>{if(!b.toolCallId)return;let T=b.toolName;if(!T&&b.type?.startsWith("tool-")&&(T=b.type.replace(/^tool-/,"")),!T)return;let h=i.current[T];if(h&&typeof h=="object"&&h.executeEachToken&&h.tool){let S=b.input||b.args||{},x=JSON.stringify(S),k=r.current.get(b.toolCallId);if(x!==k&&x!=="{}"){r.current.set(b.toolCallId,x);try{if(T==="requestInput")p.current(S,b.toolCallId);else {let v=(o.current.get(b.toolCallId)||0)+1;o.current.set(b.toolCallId,v),v>1&&h.tool({...S,toolCallNumber:v-1});}}catch{}}}});});},[e]);}function Mt(e){let{agentId:t,baseUrl:n="",tools:r={},uiComponents:o={},onStart:i,onFinish:p,onError:c,initialMessages:b=[],onMessagesChange:T,controlledChatId:h,onChatIdChange:S}=e,{baseUrl:x,setCurrentChatId:k}=re(),a=n&&n.length>0?n:x||"",[v,s]=tt.useState(""),[d,g]=tt.useState(()=>`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`),y=h??d,m=tt.useCallback(E=>{h===void 0&&g(E),S&&S(E);},[h,S]);tt.useEffect(()=>{try{k(y);}catch{}return ()=>{try{k(void 0);}catch{}}},[y,k]);let I=tt.useMemo(()=>Xt(a,t,y),[a,t,y]),C=tt.useCallback(E=>{console.log("Message finished:",E);let P=E?.message?.id;if(!P&&Array.isArray(E?.messages))for(let _=E.messages.length-1;_>=0;_--){let z=E.messages[_];if(z&&z.role==="assistant"&&z.id){P=z.id;break}}p?.({...E,chatId:y,assistantMessageId:P});},[p,y]),l=tt.useCallback(E=>{console.error("Chat error:",E),c?.(E);},[c]),u=tt.useMemo(()=>cn(),[]),w=tt.useMemo(()=>({...u,...r}),[u,r]),f=tt.useMemo(()=>gn(),[]),A=tt.useMemo(()=>({...f,...o}),[f,o]),B=tt.useRef(new Map),H=tt.useRef(new Map),K=tt.useCallback(()=>{try{B.current.forEach(E=>{try{E.remove();}catch{}}),B.current.clear(),H.current.clear();}catch{}},[]),R=tt.useCallback((E,P)=>{fn(E,P,B.current,H.current,_=>O.current.addToolResult(_));},[]),O=tt.useRef(null),F=tt.useRef(new Set),L=tt.useCallback((E,P,_)=>{console.error(`UI Error [${P}]:`,_),O.current&&F.current.has(E)&&(F.current.delete(E),O.current.addToolResult({tool:P,toolCallId:E,state:"output-error",errorText:_?.message||String(_)}));},[]),N=tt.useCallback((E,P)=>{O.current&&F.current.has(E)&&(F.current.delete(E),O.current.addToolResult({tool:P,toolCallId:E,output:{status:"ok",rendered:true,component:P,logs:[]}}));},[]),G=tt.useCallback(E=>{let P=w[E];return P?typeof P=="object"&&"tool"in P?P.tool:typeof P=="function"?P:null:null},[w]),D=react.useChat({transport:I,onFinish:C,onError:l,experimental_throttle:10,sendAutomaticallyWhen:ai.lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:E}){let P=G(E.toolName);if(E.toolName==="requestInput"){try{R(E.input,E.toolCallId);}catch(ee){console.error("requestInput render error",ee);}return}let _=E.toolName==="ui";E?.input;let Q=A&&E.toolName in A;if(_||Q){F.current.add(E.toolCallId);return}if(P)try{let ee=await P(E.input);D.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,output:ee});}catch(ee){D.addToolResult({tool:E.toolName,toolCallId:E.toolCallId,state:"output-error",errorText:ee?.message||String(ee)});}}}),{messages:Y,sendMessage:pe,status:ue,stop:we,error:J}=D;O.current=D,yn(Y,w,R),tt.useEffect(()=>{try{let E=new Set,P=[];if(Y.forEach(_=>{_.role==="assistant"&&(_.parts||[]).forEach(z=>{if((z?.toolName||(typeof z?.type=="string"&&z.type.startsWith("tool-")?String(z.type.replace(/^tool-/,"")):void 0))!=="requestInput")return;let ee=z?.toolCallId||"";if(!ee)return;E.add(ee);let q=z?.output;if(q&&(q.submitted||q.skipped||q.values)){let Ie={submitted:!!q.submitted,skipped:!!q.skipped,values:q.values||void 0};H.current.set(ee,Ie);}let xe=z?.input||z?.args||{};P.push({input:xe,toolCallId:ee});});}),B.current.forEach((_,z)=>{if(!E.has(z)){let Q=B.current.get(z);try{Q?.remove();}catch{}B.current.delete(z),H.current.delete(z);}}),P.length>0){let _=requestAnimationFrame(()=>{P.forEach(({input:z,toolCallId:Q})=>{try{R(z,Q);}catch{}});});return ()=>cancelAnimationFrame(_)}}catch{}},[Y,R]),tt.useEffect(()=>{b&&b.length>0&&Y.length===0&&console.log("Initial messages:",b);},[b,Y.length]);let me=ue==="submitted"||ue==="streaming",$e=tt.useCallback(()=>{T&&T(Y,y);},[T,Y,y]),Te=tt.useCallback(async E=>{let P=E?.text!==void 0?E.text:v,_=E?.files||[],z=P.trim();if(!(!z&&_.length===0)&&!me){E?.text===void 0&&s("");try{if(i){let Q={role:"user",content:z,createdAt:Date.now(),chatId:y};i(Q);}await pe({text:z,files:_});}catch(Q){throw console.error("Failed to send message:",Q),Q}}},[v,me,pe,i,y]),Lt=tt.useCallback(()=>{if(me)return;K(),s("");try{D?.setMessages?.([]);}catch{}let E=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;m(E);},[me,D,K,m]),mt=tt.useCallback(E=>{try{D?.setMessages?.(E);}catch{}},[D]);return {input:v,setInput:s,messages:Y,isLoading:me,status:ue,error:J,sendMessage:Te,stop:we,newChat:Lt,setMessages:mt,notifyMessagesChange:$e,chatApi:D,chatId:y,setChatId:m,tools:w,uiComponents:A,formHostRef:B,formStateRef:H,cleanupForms:K,onUISuccess:N,onUIError:L}}function rt(e){let t=`hsafaChat_${e}`,n=`${t}.chats`,r=y=>`${t}.chat.${y}`,o=`${t}.currentChatId`,i=`${t}.showChat`,p=()=>{try{let y=localStorage.getItem(n);return y?JSON.parse(y):[]}catch{return []}},c=y=>{try{localStorage.setItem(n,JSON.stringify(y));}catch{}},b=y=>{try{let m=localStorage.getItem(r(y));return m?JSON.parse(m):null}catch{return null}},T=y=>{try{localStorage.setItem(r(y.id),JSON.stringify(y));}catch{}},h=y=>{let m=p(),I=m.findIndex(C=>C.id===y.id);I>=0?m[I]=y:m.unshift(y),c(m);},S=y=>{let I=p().filter(C=>C.id!==y);c(I);},x=y=>{try{localStorage.removeItem(r(y));}catch{}};return {loadChatsIndex:p,saveChatsIndex:c,loadChat:b,saveChat:T,upsertChatMeta:h,deleteChatMeta:S,deleteChatData:x,deleteChat:y=>{x(y),S(y);},loadShowChatPreference:y=>{try{let m=localStorage.getItem(i);return m!==null?m==="true":y}catch{return y}},saveShowChatPreference:y=>{try{localStorage.setItem(i,String(y));}catch{}},loadCurrentChatId:()=>{try{return localStorage.getItem(o)}catch{return null}},saveCurrentChatId:y=>{try{localStorage.setItem(o,y);}catch{}},removeCurrentChatId:()=>{try{localStorage.removeItem(o);}catch{}}}}function Et(e){let{agentId:t,chatId:n,messages:r,isLoading:o=false,autoSave:i=true,autoRestore:p=true}=e,c=tt.useMemo(()=>rt(t),[t]),[b,T]=tt.useState([]),[h,S]=tt.useState(null),x=tt.useRef(false),k=tt.useRef(false),a=tt.useCallback(()=>{try{let C=c.loadChatsIndex();T(C);let l=C.find(u=>u.id===n);S(l||null);}catch(C){console.error("Failed to refresh chat list:",C);}},[c,n]);tt.useEffect(()=>{a();},[a]),tt.useEffect(()=>{if(!(!p||k.current)){try{c.loadCurrentChatId()&&(x.current=!0);}catch(C){console.error("Failed to restore chat:",C);}k.current=true;}},[c,p]),tt.useEffect(()=>{if(!(!i||r.length===0))if(x.current){if(!o){let C=Date.now();try{c.saveChat({id:n,messages:r,agentId:t});let u=c.loadChatsIndex().find(w=>w.id===n);u&&(c.upsertChatMeta({...u,updatedAt:C}),a());}catch(l){console.error("Failed to save chat:",l);}}}else {let C=r.find(l=>l.role==="user");if(C){let l="";if(Array.isArray(C.parts)){let f=C.parts.find(A=>A&&A.type==="text");l=f&&typeof f.text=="string"?f.text:"";}let u=(l||"New chat").slice(0,80),w=Date.now();try{c.upsertChatMeta({id:n,title:u,createdAt:w,updatedAt:w}),c.saveChat({id:n,messages:r,agentId:t}),c.saveCurrentChatId(n),x.current=!0,a();}catch(f){console.error("Failed to create chat:",f);}}}},[r,t,n,c,o,i,a]);let v=tt.useRef(false);tt.useEffect(()=>{if(o){v.current=true;return}if(v.current&&i){v.current=false;try{let C=Date.now();c.saveChat({id:n,messages:r,agentId:t});let u=c.loadChatsIndex().find(w=>w.id===n);u&&(c.upsertChatMeta({...u,updatedAt:C}),a());}catch(C){console.error("Failed to save chat on completion:",C);}}},[o,r,n,t,c,i,a]);let s=tt.useCallback(C=>{try{let l=c.loadChat(C);return l?{id:l.id,messages:l.messages,agentId:l.agentId||t}:null}catch(l){return console.error("Failed to load chat:",l),null}},[c,t]),d=tt.useCallback(()=>{if(r.length!==0)try{let C=Date.now();c.saveChat({id:n,messages:r,agentId:t});let u=c.loadChatsIndex().find(w=>w.id===n);u&&(c.upsertChatMeta({...u,updatedAt:C}),a());}catch(C){console.error("Failed to save chat:",C);}},[c,n,r,t,a]),g=tt.useCallback(C=>{try{c.deleteChat(C),a();}catch(l){console.error("Failed to delete chat:",l);}},[c,a]),y=tt.useCallback((C,l)=>{if(C!==n)try{x.current=!0,c.saveCurrentChatId(C);let u=c.loadChat(C),w=u&&Array.isArray(u.messages)?u.messages:[];l(w),a();}catch(u){console.error("Failed to switch chat:",u);}},[c,n,a]),m=tt.useCallback(C=>{x.current=false,C();},[]),I=tt.useCallback(C=>{if(!C.trim())return b;let l=C.toLowerCase();return b.filter(u=>u.title.toLowerCase().includes(l))},[b]);return {chatList:b,currentChatMeta:h,refreshChatList:a,loadChat:s,saveCurrentChat:d,deleteChat:g,switchToChat:y,createNewChat:m,searchChats:I,storage:c}}function _o(e){let{messages:t,isLoading:n,sendMessage:r,setMessages:o,baseUrl:i}=e,{baseUrl:p}=re(),c=i||p||"",[b,T]=tt.useState(null),[h,S]=tt.useState(""),[x,k]=tt.useState([]),[a,v]=tt.useState(false),s=tt.useCallback((C,l,u=[])=>{T(C),S(l),k(u);},[]),d=tt.useCallback(()=>{T(null),S(""),k([]);},[]),g=tt.useCallback(async C=>{if(!n)try{let l=t.findIndex(w=>w.id===C);if(l===-1)return;let u=t.slice(0,l);o(u),await r({text:h.trim(),files:x.map(w=>({type:"file",url:w.url,mediaType:w.mimeType||"application/octet-stream",...w.name?{name:w.name}:{},...w.size?{size:w.size}:{}}))}),d();}catch(l){throw console.error("Failed to save edit:",l),l}},[n,t,r,h,x,o,d]),y=tt.useCallback(C=>b===C,[b]),m=tt.useCallback(async C=>{if(!c){console.warn("baseUrl not provided, cannot upload attachments");return}v(true);try{let l=Array.from(C).map(async w=>{if(w.size>26214400)throw new Error(`${w.name} is too large (max 25MB)`);let f=new FormData;f.append("file",w);let A=await fetch(`${c}/api/upload`,{method:"POST",body:f});if(!A.ok)throw new Error(`Upload failed: ${A.statusText}`);let B=await A.json();return {id:B.url||`${Date.now()}-${Math.random()}`,name:w.name,url:B.url,mimeType:w.type,size:w.size}}),u=await Promise.all(l);k(w=>[...w,...u]);}catch(l){throw console.error("Failed to upload files:",l),l}finally{v(false);}},[c]),I=tt.useCallback(C=>{k(l=>l.filter(u=>u.id!==C));},[]);return {editingMessageId:b,editingText:h,setEditingText:S,editAttachments:x,setEditAttachments:k,editUploading:a,startEdit:s,cancelEdit:d,saveEdit:g,isEditing:y,addEditAttachments:m,removeEditAttachment:I}}function X({IconComponent:e,...t}){return tt__default.default.createElement(e,t)}function At({icon:e,onClick:t,ariaLabel:n,resolvedColors:r,disabled:o=false,title:i}){return jsxRuntime.jsx("button",{"aria-label":n,title:i,disabled:o,style:{backgroundColor:"transparent",color:r.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:o?"not-allowed":"pointer",opacity:o?.5:1,transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:p=>{o||(p.currentTarget.style.backgroundColor=r.hoverBackground,p.currentTarget.style.color=r.textColor);},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="transparent",p.currentTarget.style.color=r.mutedTextColor;},onClick:t,children:e})}function Cn({title:e,alwaysOpen:t,streaming:n,dir:r,resolvedColors:o,onNew:i,onToggleHistory:p,onClose:c,historyBtnRef:b,t:T}){return jsxRuntime.jsxs("div",{style:{marginBottom:"24px",display:"flex",alignItems:"center",justifyContent:"space-between",direction:r==="rtl"?"rtl":"ltr"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0"},children:jsxRuntime.jsx("h1",{title:e,style:{color:o.textColor,fontSize:"18px",fontWeight:"600",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",margin:"0"},children:e})}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",position:"relative",color:o.mutedTextColor},children:[jsxRuntime.jsx(At,{icon:jsxRuntime.jsx(X,{IconComponent:lucideReact.Plus,size:"20",strokeWidth:"2"}),onClick:()=>{n||i();},ariaLabel:T("header.new"),resolvedColors:o,disabled:n}),jsxRuntime.jsx("button",{ref:b,"aria-label":T("header.history"),style:{backgroundColor:"transparent",color:o.mutedTextColor,border:"none",borderRadius:"8px",padding:"8px",cursor:"pointer",transition:"all 0.2s ease-out",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor=o.hoverBackground,h.currentTarget.style.color=o.textColor;},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent",h.currentTarget.style.color=o.mutedTextColor;},onClick:p,children:jsxRuntime.jsx(X,{IconComponent:lucideReact.History,size:"20",strokeWidth:"2"})}),!t&&jsxRuntime.jsx(At,{icon:jsxRuntime.jsx(X,{IconComponent:lucideReact.ChevronRight,size:"20",strokeWidth:"2",style:{transform:r==="rtl"?"rotate(180deg)":"none"}}),onClick:c,ariaLabel:T("header.close"),resolvedColors:o})]})]})}var ct=class extends tt.Component{constructor(t){super(t),this.state={hasError:false,error:null,errorInfo:null};}static getDerivedStateFromError(t){return {hasError:true,error:t,errorInfo:null}}componentDidMount(){let{toolCallId:t,toolName:n,onSuccess:r}=this.props;t&&n&&r&&!this.state.hasError&&setTimeout(()=>{this.state.hasError||r(t,n);},0);}componentDidCatch(t,n){console.error(`UI Component Error (${this.props.componentName}):`,t,n),this.setState({error:t,errorInfo:n});let{toolCallId:r,toolName:o,onError:i}=this.props;r&&o&&i&&i(r,o,t);}render(){if(this.state.hasError&&this.state.error){let{resolvedColors:t,componentName:n}=this.props;return jsxRuntime.jsxs("div",{style:{padding:"16px",backgroundColor:"#fee2e2",border:"2px solid #ef4444",borderRadius:"12px",color:"#991b1b"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsxRuntime.jsx("span",{style:{fontSize:"20px"},children:"\u26A0\uFE0F"}),jsxRuntime.jsxs("strong",{style:{fontSize:"16px"},children:["Component Error: ",n]})]}),jsxRuntime.jsx("div",{style:{fontSize:"14px",marginBottom:"8px",fontFamily:"monospace"},children:this.state.error.message}),this.state.errorInfo&&jsxRuntime.jsxs("details",{style:{fontSize:"12px",marginTop:"8px"},children:[jsxRuntime.jsx("summary",{style:{cursor:"pointer",fontWeight:"bold"},children:"Stack Trace"}),jsxRuntime.jsx("pre",{style:{marginTop:"8px",padding:"8px",backgroundColor:"#fef2f2",borderRadius:"4px",overflow:"auto",maxHeight:"200px",fontSize:"11px"},children:this.state.errorInfo.componentStack})]})]})}return this.props.children}};var Jo=e=>{let t={"input-streaming":{color:"#eab308",text:"Inputting"},"input-available":{color:"#3b82f6",text:"Running"},error:{color:"#ef4444",text:"Error"},"output-available":{color:"#10b981",text:"Called"},finished:{color:"#10b981",text:"Called"}};return t[e||"output-available"]||t["output-available"]},Zo=e=>{let t=/^(.+?)_([a-f0-9]{6})_(.+)$/,n=e.match(t);if(n){let[,r,,o]=n;return {isMCP:true,mcpName:r.replace(/_/g," "),toolName:o.replace(/_/g," ")}}return {isMCP:false,toolName:e}},Qo=e=>e.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase());function vn({parts:e,messageId:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:i,onUIError:p,onUISuccess:c,addToolResult:b}){let T=[],h=[],S,x,k=false;for(let a of Array.isArray(e)?e:[]){if(!a)continue;if(a.type==="reasoning"&&typeof a.text=="string"){h.push(a.text),S||(S=a.startDate),x=a.endDate,a.state==="done"&&(k=true);continue}if(a.type==="text"&&typeof a.text=="string"){h.length&&(T.push({type:"reasoning",texts:h,startDate:S,endDate:x,isCompleted:k}),h=[],S=void 0,x=void 0,k=false),T.push({type:"text",text:a.text,startDate:a.startDate,endDate:a.endDate});continue}let v=a.type==="dynamic-tool",s=typeof a.type=="string"&&a.type.startsWith("tool-");if(v||s||a.type==="tool-call"){h.length&&(T.push({type:"reasoning",texts:h,startDate:S,endDate:x,isCompleted:k}),h=[],S=void 0,x=void 0,k=false);let d=String(v?a.toolName||"dynamic-tool":s?a.type?.slice(5)||"tool":a.toolName||"tool");d==="requestInput"?T.push({type:"tool",toolName:d,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId}):T.push({type:"tool",toolName:d,status:a.state||a.status,input:a.input,output:a.output,startDate:a.startDate,endDate:a.endDate,toolCallId:a.toolCallId});continue}}return h.length&&T.push({type:"reasoning",texts:h,startDate:S,endDate:x,isCompleted:k}),T.length?jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[T.map((a,v)=>{let s=`${t}-${v}`,d=n.has(s);if(a.type==="reasoning"){let l=a.isCompleted||typeof a.startDate=="number"&&typeof a.endDate=="number",u=a.texts&&a.texts.length>0&&a.texts.some(f=>f.trim().length>0),w=()=>{u&&r(s);};return l&&!u?null:jsxRuntime.jsx("div",{onClick:w,style:{cursor:u?"pointer":"default",padding:"0"},children:jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:d?"4px":"0px"},children:[jsxRuntime.jsxs("div",{style:{fontSize:"13px",color:o.mutedTextColor,fontWeight:500,display:"flex",alignItems:"center",gap:"6px",overflow:"hidden",maxWidth:"100%",minWidth:0,width:"100%"},children:[jsxRuntime.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px"},children:[!l&&jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsxRuntime.jsx("span",{style:{color:o.textColor,fontWeight:600,opacity:.9,background:l?"none":`linear-gradient(90deg, ${o.textColor}, ${o.mutedTextColor}, ${o.mutedTextColor})`,backgroundSize:l?"auto":"200% 100%",backgroundClip:l?"unset":"text",WebkitBackgroundClip:l?"unset":"text",WebkitTextFillColor:l?o.mutedTextColor:"transparent",animation:l?void 0:"shimmer 2s ease-in-out infinite"},children:l?"Finish Thinking":"Thinking"})]}),u&&jsxRuntime.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:d?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s ease-out"},children:jsxRuntime.jsx("polyline",{points:"9 18 15 12 9 6"})})]}),jsxRuntime.jsx("div",{style:{display:"grid",gridTemplateRows:d||!l?"1fr":"0fr",transition:"grid-template-rows 0.2s ease-out",overflow:"hidden"},children:jsxRuntime.jsx("div",{style:{minHeight:0},children:a.texts&&a.texts.length>0?jsxRuntime.jsx("div",{style:{fontSize:"13px",color:o.mutedTextColor,lineHeight:"1.6",maxWidth:"100%"},children:(!l&&d?a.texts:l?d?a.texts:[]:[a.texts[a.texts.length-1]]).map((f,A)=>jsxRuntime.jsx("div",{style:{marginBottom:"6px"},children:jsxRuntime.jsx(Oe,{content:f,theme:"dark"})},`rg-line-${v}-${A}`))}):jsxRuntime.jsxs("div",{style:{fontSize:"12px",color:o.mutedTextColor,opacity:.7,display:"flex",alignItems:"center",gap:"8px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"pulse 1.5s ease-in-out infinite"}}),jsxRuntime.jsx("span",{style:{letterSpacing:"2px",animation:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite"},children:"..."})]})})})]})},s)}if(a.type==="text")return jsxRuntime.jsx("div",{style:{fontSize:"15px",color:o.textColor,lineHeight:"1.6"},children:jsxRuntime.jsx(Oe,{content:a.text,theme:"dark"})},s);let{color:g,text:y}=Jo(a.status),m=a.status==="input-streaming"||a.status==="input-available";if(a.toolName==="requestInput")return jsxRuntime.jsx("div",{style:{display:"block",position:"relative"},children:jsxRuntime.jsx("div",{"data-get-from-user-host":a.toolCallId||s,style:{width:"100%"}})},s);let I=i?.[a.toolName||""];if(I)return jsxRuntime.jsx("div",{style:{display:"block",position:"relative"},children:jsxRuntime.jsx(ct,{componentName:a.toolName||"Unknown",resolvedColors:o,toolCallId:a.toolCallId,toolName:a.toolName||"unknown",onError:p,onSuccess:c,children:jsxRuntime.jsx(I,{toolName:a.toolName||"",toolCallId:a.toolCallId||"",input:a.input,output:a.output,status:a.status,addToolResult:b})})},s);let C=Zo(a.toolName||"tool");return jsxRuntime.jsx("div",{style:{display:"flex",gap:"12px",position:"relative"},children:jsxRuntime.jsx("div",{style:{flex:1,minWidth:0},children:jsxRuntime.jsxs("div",{style:{fontSize:"13px",color:o.mutedTextColor,display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[jsxRuntime.jsxs("span",{style:{fontWeight:600,color:g,display:"flex",alignItems:"center",gap:"6px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",height:"6px",width:"6px",borderRadius:"50%",backgroundColor:g,animation:m?"pulse 1.5s ease-in-out infinite":void 0}}),y]}),C.isMCP?jsxRuntime.jsxs("span",{style:{fontWeight:500,color:o.textColor},children:[jsxRuntime.jsx("span",{style:{fontWeight:600},children:C.toolName}),jsxRuntime.jsx("span",{style:{opacity:.7,margin:"0 4px"},children:"from"}),jsxRuntime.jsx("span",{style:{fontWeight:600,opacity:.85},children:C.mcpName})]}):jsxRuntime.jsx("span",{style:{fontWeight:500,color:o.textColor},children:Qo(C.toolName)})]})})},s)}),jsxRuntime.jsx("style",{children:`
|
|
19
19
|
@keyframes shimmer {
|
|
20
20
|
0% { background-position: -200% 0; }
|
|
21
21
|
100% { background-position: 200% 0; }
|
|
22
22
|
}
|
|
23
|
-
`})]}):null}function
|
|
23
|
+
`})]}):null}function kn(e){if(!e||Number.isNaN(e))return "0 B";let t=["B","KB","MB","GB","TB"],n=Math.min(t.length-1,Math.floor(Math.log(e)/Math.log(1024)));return `${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function wn({attachment:e,resolvedColors:t,mode:n,onRemove:r,maxWidth:o="200px"}){let i=e.mimeType?.startsWith("image/"),p=n==="editable"||n==="input",c=n==="viewable",b={display:"flex",alignItems:"center",gap:n==="input"?"8px":"6px",padding:n==="input"?"8px 12px":"6px 10px",backgroundColor:t.inputBackground,borderRadius:n==="input"?"10px":"8px",border:`1px solid ${t.borderColor}`,fontSize:n==="input"?"12px":"11px",color:t.textColor,transition:"all 0.2s ease-out",cursor:c?"pointer":"default",maxWidth:n==="input"?"140px":o,position:"relative"},T=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",backgroundColor:i?"transparent":t.accentColor,flexShrink:0},children:[i?jsxRuntime.jsx("img",{src:e.url,alt:e.name,style:{width:n==="input"?"20px":"16px",height:n==="input"?"20px":"16px",borderRadius:n==="input"?"4px":"3px",objectFit:"cover"},onError:h=>{h.target.style.display="none";let S=h.target.nextElementSibling;S&&(S.style.display="block");}}):null,jsxRuntime.jsx(X,{IconComponent:lucideReact.File,size:n==="input"?14:10,strokeWidth:"2",style:{display:i?"none":"block",color:t.mutedTextColor}})]}),jsxRuntime.jsxs("div",{style:{minWidth:"0",flex:"1",display:"flex",flexDirection:"column"},children:[jsxRuntime.jsx("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:"500"},children:e.name}),jsxRuntime.jsx("span",{style:{fontSize:n==="input"?"10px":"9px",color:t.mutedTextColor,marginTop:n==="input"?"2px":"1px"},children:kn(e.size)})]}),n==="input"&&i&&jsxRuntime.jsx("button",{onClick:h=>{h.stopPropagation(),window.open(e.url,"_blank");},style:{background:"none",border:"none",color:t.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",transition:"all 0.2s"},title:"Preview image",onMouseEnter:h=>{h.currentTarget.style.backgroundColor=t.hoverBackground,h.currentTarget.style.color=t.textColor;},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent",h.currentTarget.style.color=t.mutedTextColor;},children:jsxRuntime.jsx(X,{IconComponent:lucideReact.Eye,size:"12",strokeWidth:"2"})}),p&&r&&jsxRuntime.jsx("button",{onClick:h=>{h.stopPropagation(),r(e.id);},style:{display:"flex",alignItems:"center",justifyContent:"center",width:n==="input"?"auto":"16px",height:n==="input"?"auto":"16px",padding:n==="input"?"2px":"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",color:t.mutedTextColor,cursor:"pointer",transition:"all 0.2s",flexShrink:0},onMouseEnter:h=>{h.currentTarget.style.backgroundColor="#ef444420",h.currentTarget.style.color="#ef4444";},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent",h.currentTarget.style.color=t.mutedTextColor;},children:jsxRuntime.jsx(X,{IconComponent:lucideReact.X,size:"12",strokeWidth:"2"})}),c&&jsxRuntime.jsx(X,{IconComponent:lucideReact.Download,size:"10",strokeWidth:"2",style:{color:t.mutedTextColor,flexShrink:0}})]});return c?jsxRuntime.jsx("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{...b,textDecoration:"none"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor=t.hoverBackground,h.currentTarget.style.borderColor=t.primaryColor;},onMouseLeave:h=>{h.currentTarget.style.backgroundColor=t.inputBackground,h.currentTarget.style.borderColor=t.borderColor;},children:T}):jsxRuntime.jsx("div",{style:b,children:T})}function In({attachments:e,resolvedColors:t,onRemove:n}){if(!Array.isArray(e)||e.length===0)return null;let r=typeof n=="function"?"editable":"viewable";return jsxRuntime.jsx("div",{style:{marginTop:"12px",display:"flex",flexWrap:"wrap",gap:"8px"},children:e.map(o=>jsxRuntime.jsx(wn,{attachment:o,resolvedColors:t,mode:r,onRemove:n},o.id))})}function Mn({chatMessages:e,isLoading:t,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,t:i,onUserMessageClick:p,HsafaUI:c,onUIError:b,onUISuccess:T,addToolResult:h,editableMessageIcon:S}){return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("style",{children:`
|
|
24
24
|
@keyframes jumpingDots {
|
|
25
25
|
0%, 80%, 100% {
|
|
26
26
|
transform: translateY(0);
|
|
@@ -29,15 +29,15 @@
|
|
|
29
29
|
transform: translateY(-5px);
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
|
-
`}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[
|
|
33
|
-
`),s=a.filter(l=>l.type==="file"||l.type==="image").map(l=>{if(l.type==="image"){let m=typeof l.image=="string"?l.image:l.image?.toString?.()||"";return {id:m||`${y.id}-img-${Date.now()}`,name:l.name||"image",url:m,mimeType:l.mediaType||"image/jpeg",size:l.size||0}}else return {id:l.url||`${y.id}-file-${Date.now()}`,name:l.name||"file",url:l.url||"",mimeType:l.mediaType||"application/octet-stream",size:l.size||0}});return jsxRuntime.jsx("div",{style:{padding:"0 4px"},children:y.role==="user"?jsxRuntime.jsx("div",{children:jsxRuntime.jsx("div",{title:i("editor.clickToEdit"),onClick:()=>c(y,y.id,p,s),style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:r.accentColor,color:r.textColor,marginBottom:"16px",marginTop:"16px",position:"relative"},onMouseEnter:l=>l.currentTarget.style.backgroundColor=r.hoverBackground,onMouseLeave:l=>l.currentTarget.style.backgroundColor=r.accentColor,children:jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[jsxRuntime.jsxs("div",{style:{flex:1},children:[p,s.length>0&&jsxRuntime.jsx(Nn,{attachments:s,resolvedColors:r})]}),jsxRuntime.jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsxRuntime.jsx(Q,{IconComponent:T||lucideReact.Pencil,size:"14",strokeWidth:"2"})})]})})}):jsxRuntime.jsx(Hn,{parts:a,messageId:y.id,openReasoningIds:t,toggleReasoning:o,resolvedColors:r,HsafaUI:d,onUIError:u,onUISuccess:x,addToolResult:g})},y.id)}),e&&jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsxRuntime.jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsxRuntime.jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:r.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function Un({input:n,setInput:e,textareaRef:t,fileInputRef:o,isLoading:r,uploading:i,attachments:c,formatBytes:d,handleRemoveAttachment:u,onFileInputChange:x,onSend:g,onStop:T,status:y,t:C,resolvedColors:a}){let p=y==="streaming"||y==="submitted",s=c.length>0||n.trim().length>0;return jsxRuntime.jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsxRuntime.jsx("div",{style:{position:"relative",flex:1},children:jsxRuntime.jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground},children:[c.length>0&&jsxRuntime.jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:c.map(l=>{let m=l.mimeType.startsWith("image/");return jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:a.inputBackground,borderRadius:"10px",border:`1px solid ${a.borderColor}`,fontSize:"12px",color:a.textColor,position:"relative"},children:[jsxRuntime.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:m?"transparent":a.cardBackground},children:m?jsxRuntime.jsx("img",{src:l.url,alt:l.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"}}):jsxRuntime.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsxRuntime.jsx("rect",{x:"4",y:"4",width:"16",height:"20",rx:"2",ry:"2"})})}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,flex:1},children:[jsxRuntime.jsx("span",{title:l.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:l.name}),jsxRuntime.jsx("span",{style:{color:a.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:d(l.size)})]}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[m&&jsxRuntime.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",textDecoration:"none"},title:C("input.previewImage"),children:jsxRuntime.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),jsxRuntime.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),jsxRuntime.jsx("button",{onClick:()=>u(l.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:C("input.removeFile"),children:jsxRuntime.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsxRuntime.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]},l.id)})}),i&&jsxRuntime.jsxs("div",{style:{padding:"0px 16px 12px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:a.mutedTextColor},children:[jsxRuntime.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{animation:"spin 1s linear infinite"},children:jsxRuntime.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsxRuntime.jsx("span",{children:C("input.uploadingFiles")})]}),jsxRuntime.jsx("div",{style:{padding:"0 16px"},children:jsxRuntime.jsx("textarea",{ref:t,"aria-label":"Prompt",rows:1,placeholder:C("input.placeholder"),value:n,onChange:l=>e(l.target.value),onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),g());},disabled:r||i,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:a.textColor,fontFamily:"inherit",overflow:"auto"}})}),jsxRuntime.jsx("input",{ref:o,type:"file",multiple:true,onChange:x,style:{display:"none"},accept:"*/*"}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:a.mutedTextColor},children:jsxRuntime.jsx("button",{onClick:()=>o.current?.click(),disabled:r||i,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:r||i?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:r||i?.5:1},"aria-label":C("input.attachFiles"),children:jsxRuntime.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 1 1 5.66 5.66l-9.2 9.19a2 2 0 1 1-2.83-2.83l8.49-8.49"})})})}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:r?jsxRuntime.jsx("button",{onClick:T,disabled:!p,"aria-label":C("input.stop"),title:"Stop generation",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:"1px solid #ef4444",backgroundColor:"#ef444420",color:"#ef4444",opacity:p?1:.4,cursor:p?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:l=>{p&&(l.currentTarget.style.backgroundColor="#ef444430",l.currentTarget.style.transform="scale(1.02)");},onMouseLeave:l=>{l.currentTarget.style.backgroundColor="#ef444420",l.currentTarget.style.transform="scale(1)";},children:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsxRuntime.jsx("button",{onClick:g,disabled:!s||i,"aria-label":C("input.send"),title:"Send message",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground,color:!s||i?a.mutedTextColor:a.primaryColor,cursor:!s||i?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!s||i?.5:1},onMouseEnter:l=>{s&&!i&&(l.currentTarget.style.borderColor=a.primaryColor,l.currentTarget.style.transform="scale(1.02)");},onMouseLeave:l=>{l.currentTarget.style.borderColor=a.borderColor,l.currentTarget.style.transform="scale(1)";},children:jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("path",{d:"m5 12 7-7 7 7"}),jsxRuntime.jsx("path",{d:"M12 19V5"})]})})})]})})})}function Gn(n){let e=Date.now()-n,t=Math.max(1,Math.floor(e/1e3));if(t<60)return `${t}s`;let o=Math.floor(t/60);if(o<60)return `${o}m`;let r=Math.floor(o/60);if(r<24)return `${r}h`;let i=Math.floor(r/24);if(i<7)return `${i}d`;let c=Math.floor(i/7);if(c<4)return `${c}w`;let d=Math.floor(i/30);return d<12?`${d}mo`:`${Math.floor(d/12)}y`}function qn({historyOpen:n,historySearch:e,currentChatId:t,refreshKey:o,resolvedColors:r,onClose:i,onSearchChange:c,onChatSelect:d,onChatDelete:u,loadChatsIndex:x,historyPopupRef:g}){if(!n)return null;let T=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:i}),jsxRuntime.jsxs("div",{ref:g,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${r.borderColor}`,backgroundColor:`${r.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxRuntime.jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${r.borderColor}`,padding:"12px 16px"},children:jsxRuntime.jsx("div",{style:{flex:"1"},children:jsxRuntime.jsx("input",{autoFocus:true,value:e,onChange:y=>c(y.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:r.inputBackground,padding:"8px 12px",fontSize:"14px",color:r.textColor,border:`1px solid ${r.borderColor}`,outline:"none"},onFocus:y=>y.currentTarget.style.borderColor=r.primaryColor,onBlur:y=>y.currentTarget.style.borderColor=r.borderColor})})}),jsxRuntime.jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let y=e.toLowerCase().trim(),C=x();return y&&(C=C.filter(a=>(a.title||"").toLowerCase().includes(y))),!C||C.length===0?jsxRuntime.jsx("div",{style:{padding:"24px",color:r.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsxRuntime.jsx("div",{children:C.map((a,p)=>jsxRuntime.jsx("div",{style:{borderTop:p>0?`1px solid ${r.borderColor}`:"none"},children:jsxRuntime.jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:a.id===t?r.cardBackground:"transparent"},children:[jsxRuntime.jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:r.textColor},onMouseEnter:s=>s.currentTarget.style.backgroundColor=r.hoverBackground,onMouseLeave:s=>s.currentTarget.style.backgroundColor="transparent",onClick:()=>d(a.id),children:jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0",flex:"1"},children:jsxRuntime.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:r.textColor},children:a.title||"Untitled chat"})}),jsxRuntime.jsx("div",{style:{flexShrink:0,fontSize:"12px",color:r.mutedTextColor},children:Gn(a.updatedAt)})]})}),jsxRuntime.jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:r.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:s=>{s.currentTarget.style.color="#ef4444",s.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",s.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:s=>{s.currentTarget.style.color=r.mutedTextColor,s.currentTarget.style.backgroundColor="transparent",s.currentTarget.style.borderColor="transparent";},onClick:s=>{s.stopPropagation(),u(a.id);},children:jsxRuntime.jsx(Q,{IconComponent:lucideReact.Trash2,size:"16",strokeWidth:"2"})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?reactDom.createPortal(T,document.body):T}function Vn({isOpen:n,resolvedColors:e,onConfirm:t,onCancel:o,editProcessContent:r}){if(!n)return null;let i=r?.title||"Edit Message",c=r?.content||"This will remove this message and all messages after it, and place its content in the input field for editing. Do you want to continue?",d=r?.submit_button_label||"Edit",u=r?.cancel_button_label||"Cancel",x=r?.icon,g=typeof c=="function",T=g?c:null,y=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:o}),jsxRuntime.jsxs("div",{style:{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)",zIndex:1101,width:"420px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${e.borderColor}`,backgroundColor:e.backgroundColor,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxRuntime.jsxs("div",{style:{padding:"20px 24px",borderBottom:`1px solid ${e.borderColor}`,display:"flex",alignItems:"center",gap:"12px"},children:[x?jsxRuntime.jsx("div",{style:{flexShrink:0},children:jsxRuntime.jsx(Q,{IconComponent:x,size:"20",strokeWidth:"2"})}):jsxRuntime.jsx("div",{style:{flexShrink:0,color:e.mutedTextColor},children:jsxRuntime.jsx(Q,{IconComponent:lucideReact.Pencil,size:"20",strokeWidth:"2"})}),jsxRuntime.jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:e.textColor,flex:1},children:i})]}),jsxRuntime.jsx("div",{style:{padding:"24px",color:e.textColor,fontSize:"14px",lineHeight:"1.6"},children:g&&T?jsxRuntime.jsx(T,{}):jsxRuntime.jsx("p",{style:{margin:0},children:c})}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",padding:"16px 24px",borderTop:`1px solid ${e.borderColor}`,justifyContent:"flex-end"},children:[jsxRuntime.jsx("button",{onClick:o,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:`1px solid ${e.borderColor}`,backgroundColor:"transparent",color:e.textColor,cursor:"pointer",transition:"all 0.2s"},onMouseEnter:C=>{C.currentTarget.style.backgroundColor=e.hoverBackground;},onMouseLeave:C=>{C.currentTarget.style.backgroundColor="transparent";},children:u}),jsxRuntime.jsx("button",{onClick:t,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:"none",backgroundColor:e.primaryColor,color:e.backgroundColor,cursor:"pointer",transition:"all 0.2s",opacity:1},onMouseEnter:C=>{C.currentTarget.style.opacity="0.9";},onMouseLeave:C=>{C.currentTarget.style.opacity="1";},children:d})]})]})]});return typeof document<"u"&&document.body?reactDom.createPortal(y,document.body):y}function Ho({agentId:n,theme:e,primaryColor:t,primaryColorDark:o,primaryColorLight:r,backgroundColor:i,borderColor:c,textColor:d,accentColor:u,baseUrl:x="",initialMessages:g=[],onMessagesChange:T,defaultOpen:y=true,floatingButtonPosition:C={bottom:24,right:24},HsafaTools:a={},HsafaUI:p={},dynamicPageTypes:s=[],componentAboveInput:l,editProcessContent:m}){let{dir:f,theme:v,baseUrl:I,setStreamingState:k,setChatOpenState:b}=ne(),h=e||v||"dark",E=x&&x.length>0?x:I||"",S={primaryColor:h==="dark"?o||t||"#ffffff":r||t||"#000000",backgroundColor:i||(h==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:c||(h==="dark"?"#2A2C33":"#E5E7EB"),textColor:d||(h==="dark"?"#EDEEF0":"#111827"),accentColor:u||(h==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:h==="dark"?"#6f7276":"#6B7280",inputBackground:h==="dark"?"#17181C":"#F3F4F6",cardBackground:h==="dark"?"#121318":"#FFFFFF",hoverBackground:h==="dark"?"#1c1e25":"#F3F4F6"},A=j=>({"header.new":"New","header.history":"History","header.close":"Close chat","input.placeholder":"Ask your question...","input.attachFiles":"Attach files","input.insertLink":"Insert link","input.send":"Send","input.stop":"Stop","input.uploadingFiles":"Uploading files...","input.previewImage":"Preview image","input.removeFile":"Remove file","messages.empty":"Start by sending a message to the agent.","general.agent":"Agent","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit"})[j]||j,F=zt({agentId:n,baseUrl:E,tools:a,uiComponents:p,dynamicPageTypes:s,onFinish:st.useCallback(j=>{console.log("Message finished:",j);},[]),onError:st.useCallback(j=>{console.error("Chat error:",j);},[]),initialMessages:g,onMessagesChange:T}),{input:M,setInput:$,messages:D,isLoading:R,status:O,error:N,sendMessage:J,stop:V,setMessages:H,chatId:K,setChatId:ae,tools:Ne,uiComponents:kt,formHostRef:Xe,formStateRef:Ae,cleanupForms:ye,onUISuccess:wt,onUIError:Tt,chatApi:St}=F,{attachments:_,uploading:z,fileInputRef:U,formatBytes:G,handleRemoveAttachment:se,handleFileSelection:ee,clearAttachments:oe,setAttachments:Ye}=dn(E),[Ze,Re]=st.useState(null),[Qe,Xt]=st.useState(()=>{try{return pt(n).loadShowChatPreference(!!y)}catch{return !!y}}),[Yn,Et]=st.useState(false),[Zn,Qn]=st.useState(""),[er,tr]=st.useState(0),nr=st.useRef(null),rr=st.useRef(null),[or,ar]=st.useState(new Set),[sr,It]=st.useState(false),[We,Mt]=st.useState(null),Yt=st.useRef(null),ir=an(R),ie=Wt({agentId:n,chatId:K,messages:D,isLoading:R,autoSave:true,autoRestore:false}).storage,Zt=st.useRef(false);st.useEffect(()=>{if(!Zt.current){try{let j=ie.loadCurrentChatId();if(j){ae(j);let W=ie.loadChat(j),q=W&&Array.isArray(W.messages)?W.messages:[];try{H(q);}catch{}}}catch{}Zt.current=true;}},[]),st.useEffect(()=>{try{k(K,R);}catch{}return ()=>{try{k(K,!1);}catch{}}},[K,R,k]),st.useEffect(()=>{try{b(K,Qe);}catch{}return ()=>{try{b(K,!1);}catch{}}},[K,Qe,b]);let lr=st.useCallback(async()=>{let j=M.trim();if(!j&&_.length===0||R)return;let W=[..._];$(""),oe(),Re(null);try{await J({text:j,files:W.map(q=>({type:"file",url:q.url,mediaType:q.mimeType||"application/octet-stream",...q.name?{name:q.name}:{},...q.size?{size:q.size}:{}}))});}catch(q){console.error("Failed to send message:",q),Re("Failed to send message. Please try again.");}},[M,_,R,J,oe]),Qt=st.useCallback(()=>{if(R)return;ye(),$(""),oe(),Re(null);try{H([]);}catch{}let j=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;ae(j);try{ie.saveCurrentChatId(j);}catch{}},[R,oe,ie,H,ae,ye]),cr=st.useCallback(()=>{Et(j=>!j);},[]),dr=st.useCallback(()=>{Xt(false);try{ie.saveShowChatPreference(!1);}catch{}},[ie]),ur=st.useCallback(async j=>{let W=j.target.files;W&&await ee(W,Re),U.current&&(U.current.value="");},[ee,U]);st.useEffect(()=>{let j=Yt.current;if(!j)return;j.style.height="24px",j.offsetHeight,j.style.height="auto";let W=Math.min(j.scrollHeight,200);j.style.height=`${W}px`;},[M]);let pr=st.useCallback((j,W,q,fr)=>{Mt({id:W,text:q,attachments:fr||[]}),It(true);},[]),mr=st.useCallback(()=>{if(!(!We||R))try{let j=D.findIndex(q=>q.id===We.id);if(j===-1)return;let W=D.slice(0,j);try{H(W);}catch{}$(We.text),Ye(We.attachments),It(!1),Mt(null);}catch(j){console.error("Failed to edit message:",j),Re("Failed to edit message. Please try again.");}},[We,R,D,H,Ye]),gr=st.useCallback(()=>{It(false),Mt(null);},[]),en=jsxRuntime.jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:S.textColor,gap:"16px",zIndex:1e3,transform:Qe?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsxRuntime.jsx(Ln,{title:A("general.agent"),alwaysOpen:false,streaming:R,dir:f||"ltr",resolvedColors:S,onNew:Qt,onToggleHistory:cr,onClose:dr,historyBtnRef:nr,t:A}),jsxRuntime.jsx("div",{ref:ir,className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth","--hsafa-primary":S.primaryColor,"--hsafa-border":S.borderColor,"--hsafa-card":S.cardBackground,"--hsafa-text":S.textColor,"--hsafa-muted":S.mutedTextColor,"--hsafa-bg":S.backgroundColor,"--hsafa-hover":S.hoverBackground,"--hsafa-input-bg":S.inputBackground,"--hsafa-accent":S.accentColor},children:D.length===0?jsxRuntime.jsx("div",{style:{padding:"32px",textAlign:"center",color:S.mutedTextColor,fontSize:"14px"},children:A("messages.empty")}):jsxRuntime.jsx(Wn,{chatMessages:D,isLoading:R,openReasoningIds:or,toggleReasoning:j=>ar(W=>{let q=new Set(W);return q.has(j)?q.delete(j):q.add(j),q}),resolvedColors:S,t:A,onUserMessageClick:pr,HsafaUI:kt,onUIError:Tt,onUISuccess:wt,addToolResult:j=>St?.addToolResult?.(j),editableMessageIcon:m?.message_icon})}),jsxRuntime.jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[l&&st__default.default.createElement(l,{}),Ze&&jsxRuntime.jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxRuntime.jsx("span",{children:Ze}),jsxRuntime.jsx("button",{onClick:()=>Re(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),N&&jsxRuntime.jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxRuntime.jsxs("span",{children:["An error occurred: ",N.message||"Please try again."]}),jsxRuntime.jsx("button",{onClick:()=>window.location.reload(),style:{background:"none",border:"1px solid #fff",color:"#fff",cursor:"pointer",padding:"4px 8px",borderRadius:"4px",fontSize:"12px"},children:"Refresh"})]}),jsxRuntime.jsx(Un,{input:M,setInput:$,textareaRef:Yt,fileInputRef:U,isLoading:R,uploading:z,attachments:_,formatBytes:G,handleRemoveAttachment:se,onFileInputChange:ur,onSend:lr,onStop:()=>V(),status:O,t:A,resolvedColors:S})]}),jsxRuntime.jsx(qn,{historyOpen:Yn,historySearch:Zn,currentChatId:K,refreshKey:er,resolvedColors:S,onClose:()=>Et(false),onSearchChange:Qn,onChatSelect:j=>{if(Et(false),j&&j!==K){ye(),ae(j);try{ie.saveCurrentChatId(j);}catch{}try{let W=ie.loadChat(j),q=W&&Array.isArray(W.messages)?W.messages:[];try{H(q);}catch{}}catch{}}},onChatDelete:j=>{try{ie.deleteChat(j),tr(W=>W+1),j===K&&Qt();}catch{}},loadChatsIndex:()=>ie.loadChatsIndex(),historyPopupRef:rr}),jsxRuntime.jsx(Vn,{isOpen:sr,resolvedColors:S,onConfirm:mr,onCancel:gr,editProcessContent:m}),jsxRuntime.jsx("style",{children:`
|
|
32
|
+
`}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.map((x,k)=>{let a=Array.isArray(x.parts)?x.parts:[],v=a.filter(d=>d.type==="text").map(d=>d&&typeof d.text=="string"?d.text:"").join(`
|
|
33
|
+
`),s=a.filter(d=>d.type==="file"||d.type==="image").map(d=>{if(d.type==="image"){let g=typeof d.image=="string"?d.image:d.image?.toString?.()||"";return {id:g||`${x.id}-img-${Date.now()}`,name:d.name||"image",url:g,mimeType:d.mediaType||"image/jpeg",size:d.size||0}}else return {id:d.url||`${x.id}-file-${Date.now()}`,name:d.name||"file",url:d.url||"",mimeType:d.mediaType||"application/octet-stream",size:d.size||0}});return jsxRuntime.jsx("div",{style:{padding:"0 4px"},children:x.role==="user"?jsxRuntime.jsx("div",{children:jsxRuntime.jsx("div",{title:i("editor.clickToEdit"),onClick:()=>p(x,x.id,v,s),style:{maxWidth:"720px",borderRadius:"16px",padding:"16px",fontSize:"15px",lineHeight:"1.6",whiteSpace:"pre-wrap",cursor:"pointer",transition:"background-color 0.2s",backgroundColor:o.accentColor,color:o.textColor,marginBottom:"16px",marginTop:"16px",position:"relative"},onMouseEnter:d=>d.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:d=>d.currentTarget.style.backgroundColor=o.accentColor,children:jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[jsxRuntime.jsxs("div",{style:{flex:1},children:[v,s.length>0&&jsxRuntime.jsx(In,{attachments:s,resolvedColors:o})]}),jsxRuntime.jsx("div",{style:{flexShrink:0,opacity:.5,transition:"opacity 0.2s"},children:jsxRuntime.jsx(X,{IconComponent:S||lucideReact.Pencil,size:"14",strokeWidth:"2"})})]})})}):jsxRuntime.jsx(vn,{parts:a,messageId:x.id,openReasoningIds:n,toggleReasoning:r,resolvedColors:o,HsafaUI:c,onUIError:b,onUISuccess:T,addToolResult:h})},x.id)}),t&&jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"0 4px",height:"20px"},children:[jsxRuntime.jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0s"}}),jsxRuntime.jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.2s"}}),jsxRuntime.jsx("span",{style:{display:"inline-block",width:"4px",height:"4px",borderRadius:"50%",backgroundColor:o.mutedTextColor,animation:"jumpingDots 1s infinite ease-in-out",animationDelay:"0.4s"}})]})]})]})}function Sn({input:e,setInput:t,textareaRef:n,fileInputRef:r,isLoading:o,uploading:i,attachments:p,formatBytes:c,handleRemoveAttachment:b,onFileInputChange:T,onSend:h,onStop:S,status:x,t:k,resolvedColors:a}){let v=x==="streaming"||x==="submitted",s=p.length>0||e.trim().length>0;return jsxRuntime.jsx("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px",paddingTop:"4px"},children:jsxRuntime.jsx("div",{style:{position:"relative",flex:1},children:jsxRuntime.jsxs("div",{style:{position:"relative",width:"100%",borderRadius:"16px",paddingBottom:"48px",paddingTop:"16px",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground},children:[p.length>0&&jsxRuntime.jsx("div",{style:{padding:"0px 16px 12px 16px",display:"flex",flexWrap:"wrap",gap:"10px"},children:p.map(d=>{let g=d.mimeType.startsWith("image/");return jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:a.inputBackground,borderRadius:"10px",border:`1px solid ${a.borderColor}`,fontSize:"12px",color:a.textColor,position:"relative"},children:[jsxRuntime.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:"20px",height:"20px",borderRadius:"4px",backgroundColor:g?"transparent":a.cardBackground},children:g?jsxRuntime.jsx("img",{src:d.url,alt:d.name,style:{width:"20px",height:"20px",borderRadius:"4px",objectFit:"cover"}}):jsxRuntime.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsxRuntime.jsx("rect",{x:"4",y:"4",width:"16",height:"20",rx:"2",ry:"2"})})}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,flex:1},children:[jsxRuntime.jsx("span",{title:d.name,style:{maxWidth:"140px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:d.name}),jsxRuntime.jsx("span",{style:{color:a.mutedTextColor,fontSize:"10px",marginTop:"2px"},children:c(d.size)})]}),jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",marginLeft:"8px"},children:[g&&jsxRuntime.jsx("a",{href:d.url,target:"_blank",rel:"noopener noreferrer",style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px",textDecoration:"none"},title:k("input.previewImage"),children:jsxRuntime.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),jsxRuntime.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),jsxRuntime.jsx("button",{onClick:()=>b(d.id),style:{background:"none",border:"none",color:a.mutedTextColor,cursor:"pointer",padding:"2px",display:"flex",alignItems:"center",borderRadius:"4px"},title:k("input.removeFile"),children:jsxRuntime.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsxRuntime.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]},d.id)})}),i&&jsxRuntime.jsxs("div",{style:{padding:"0px 16px 12px 16px",display:"flex",alignItems:"center",gap:"8px",fontSize:"13px",color:a.mutedTextColor},children:[jsxRuntime.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{animation:"spin 1s linear infinite"},children:jsxRuntime.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),jsxRuntime.jsx("span",{children:k("input.uploadingFiles")})]}),jsxRuntime.jsx("div",{style:{padding:"0 16px"},children:jsxRuntime.jsx("textarea",{ref:n,"aria-label":"Prompt",rows:1,placeholder:k("input.placeholder"),value:e,onChange:d=>t(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),h());},disabled:o||i,style:{height:"24px",maxHeight:"200px",width:"100%",resize:"none",backgroundColor:"transparent",fontSize:"15px",lineHeight:"1.6",outline:"none",border:"none",color:a.textColor,fontFamily:"inherit",overflow:"auto"}})}),jsxRuntime.jsx("input",{ref:r,type:"file",multiple:true,onChange:T,style:{display:"none"},accept:"*/*"}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",left:"8px",display:"flex",alignItems:"center",gap:"4px",color:a.mutedTextColor},children:jsxRuntime.jsx("button",{onClick:()=>r.current?.click(),disabled:o||i,style:{borderRadius:"8px",padding:"8px",transition:"all 0.2s",backgroundColor:"transparent",border:"none",cursor:o||i?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"inherit",opacity:o||i?.5:1},"aria-label":k("input.attachFiles"),children:jsxRuntime.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 1 1 5.66 5.66l-9.2 9.19a2 2 0 1 1-2.83-2.83l8.49-8.49"})})})}),jsxRuntime.jsx("div",{style:{position:"absolute",bottom:"8px",right:"8px"},children:o?jsxRuntime.jsx("button",{onClick:S,disabled:!v,"aria-label":k("input.stop"),title:"Stop generation",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:"1px solid #ef4444",backgroundColor:"#ef444420",color:"#ef4444",opacity:v?1:.4,cursor:v?"pointer":"not-allowed",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:d=>{v&&(d.currentTarget.style.backgroundColor="#ef444430",d.currentTarget.style.transform="scale(1.02)");},onMouseLeave:d=>{d.currentTarget.style.backgroundColor="#ef444420",d.currentTarget.style.transform="scale(1)";},children:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsxRuntime.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"})})}):jsxRuntime.jsx("button",{onClick:h,disabled:!s||i,"aria-label":k("input.send"),title:"Send message",style:{borderRadius:"12px",padding:"12px",transition:"all 0.2s ease-out",border:`1px solid ${a.borderColor}`,backgroundColor:a.cardBackground,color:!s||i?a.mutedTextColor:a.primaryColor,cursor:!s||i?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:!s||i?.5:1},onMouseEnter:d=>{s&&!i&&(d.currentTarget.style.borderColor=a.primaryColor,d.currentTarget.style.transform="scale(1.02)");},onMouseLeave:d=>{d.currentTarget.style.borderColor=a.borderColor,d.currentTarget.style.transform="scale(1)";},children:jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntime.jsx("path",{d:"m5 12 7-7 7 7"}),jsxRuntime.jsx("path",{d:"M12 19V5"})]})})})]})})})}function En(e){let t=Date.now()-e,n=Math.max(1,Math.floor(t/1e3));if(n<60)return `${n}s`;let r=Math.floor(n/60);if(r<60)return `${r}m`;let o=Math.floor(r/60);if(o<24)return `${o}h`;let i=Math.floor(o/24);if(i<7)return `${i}d`;let p=Math.floor(i/7);if(p<4)return `${p}w`;let c=Math.floor(i/30);return c<12?`${c}mo`:`${Math.floor(c/12)}y`}function An({historyOpen:e,historySearch:t,currentChatId:n,refreshKey:r,resolvedColors:o,onClose:i,onSearchChange:p,onChatSelect:c,onChatDelete:b,loadChatsIndex:T,historyPopupRef:h}){if(!e)return null;let S=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:i}),jsxRuntime.jsxs("div",{ref:h,style:{position:"fixed",left:"50%",top:"64px",transform:"translateX(-50%)",zIndex:1101,width:"680px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${o.borderColor}`,backgroundColor:`${o.backgroundColor}f0`,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxRuntime.jsx("div",{style:{display:"flex",alignItems:"center",gap:"12px",borderBottom:`1px solid ${o.borderColor}`,padding:"12px 16px"},children:jsxRuntime.jsx("div",{style:{flex:"1"},children:jsxRuntime.jsx("input",{autoFocus:true,value:t,onChange:x=>p(x.target.value),placeholder:"Search",style:{width:"100%",borderRadius:"8px",backgroundColor:o.inputBackground,padding:"8px 12px",fontSize:"14px",color:o.textColor,border:`1px solid ${o.borderColor}`,outline:"none"},onFocus:x=>x.currentTarget.style.borderColor=o.primaryColor,onBlur:x=>x.currentTarget.style.borderColor=o.borderColor})})}),jsxRuntime.jsx("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:(()=>{let x=t.toLowerCase().trim(),k=T();return x&&(k=k.filter(a=>(a.title||"").toLowerCase().includes(x))),!k||k.length===0?jsxRuntime.jsx("div",{style:{padding:"24px",color:o.mutedTextColor,textAlign:"center"},children:"No chats found."}):jsxRuntime.jsx("div",{children:k.map((a,v)=>jsxRuntime.jsx("div",{style:{borderTop:v>0?`1px solid ${o.borderColor}`:"none"},children:jsxRuntime.jsxs("div",{style:{display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",gap:"12px",padding:"12px",backgroundColor:a.id===n?o.cardBackground:"transparent"},children:[jsxRuntime.jsx("button",{style:{flex:"1",textAlign:"left",transition:"background-color 0.2s",borderRadius:"8px",padding:"8px",border:"none",backgroundColor:"transparent",cursor:"pointer",color:o.textColor},onMouseEnter:s=>s.currentTarget.style.backgroundColor=o.hoverBackground,onMouseLeave:s=>s.currentTarget.style.backgroundColor="transparent",onClick:()=>c(a.id),children:jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"12px"},children:[jsxRuntime.jsx("div",{style:{minWidth:"0",flex:"1"},children:jsxRuntime.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"14px",color:o.textColor},children:a.title||"Untitled chat"})}),jsxRuntime.jsx("div",{style:{flexShrink:0,fontSize:"12px",color:o.mutedTextColor},children:En(a.updatedAt)})]})}),jsxRuntime.jsx("button",{style:{flexShrink:0,borderRadius:"6px",padding:"8px",color:o.mutedTextColor,border:"1px solid transparent",backgroundColor:"transparent",cursor:"pointer",transition:"all 0.2s"},title:"Delete chat",onMouseEnter:s=>{s.currentTarget.style.color="#ef4444",s.currentTarget.style.backgroundColor="rgba(239, 68, 68, 0.1)",s.currentTarget.style.borderColor="rgba(239, 68, 68, 0.3)";},onMouseLeave:s=>{s.currentTarget.style.color=o.mutedTextColor,s.currentTarget.style.backgroundColor="transparent",s.currentTarget.style.borderColor="transparent";},onClick:s=>{s.stopPropagation(),b(a.id);},children:jsxRuntime.jsx(X,{IconComponent:lucideReact.Trash2,size:"16",strokeWidth:"2"})})]})},a.id))})})()})]})]});return typeof document<"u"&&document.body?reactDom.createPortal(S,document.body):S}function Rn({isOpen:e,resolvedColors:t,onConfirm:n,onCancel:r,editProcessContent:o}){if(!e)return null;let i=o?.title||"Edit Message",p=o?.content||"This will remove this message and all messages after it, and place its content in the input field for editing. Do you want to continue?",c=o?.submit_button_label||"Edit",b=o?.cancel_button_label||"Cancel",T=o?.icon,h=typeof p=="function",S=h?p:null,x=jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{style:{position:"fixed",inset:"0",zIndex:1100,backgroundColor:"rgba(0, 0, 0, 0.4)",backdropFilter:"blur(4px)",WebkitBackdropFilter:"blur(4px)"},onClick:r}),jsxRuntime.jsxs("div",{style:{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)",zIndex:1101,width:"420px",maxWidth:"94vw",overflow:"hidden",borderRadius:"16px",border:`1px solid ${t.borderColor}`,backgroundColor:t.backgroundColor,boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)"},children:[jsxRuntime.jsxs("div",{style:{padding:"20px 24px",borderBottom:`1px solid ${t.borderColor}`,display:"flex",alignItems:"center",gap:"12px"},children:[T?jsxRuntime.jsx("div",{style:{flexShrink:0},children:jsxRuntime.jsx(X,{IconComponent:T,size:"20",strokeWidth:"2"})}):jsxRuntime.jsx("div",{style:{flexShrink:0,color:t.mutedTextColor},children:jsxRuntime.jsx(X,{IconComponent:lucideReact.Pencil,size:"20",strokeWidth:"2"})}),jsxRuntime.jsx("h3",{style:{margin:0,fontSize:"18px",fontWeight:"600",color:t.textColor,flex:1},children:i})]}),jsxRuntime.jsx("div",{style:{padding:"24px",color:t.textColor,fontSize:"14px",lineHeight:"1.6"},children:h&&S?jsxRuntime.jsx(S,{}):jsxRuntime.jsx("p",{style:{margin:0},children:p})}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",padding:"16px 24px",borderTop:`1px solid ${t.borderColor}`,justifyContent:"flex-end"},children:[jsxRuntime.jsx("button",{onClick:r,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:`1px solid ${t.borderColor}`,backgroundColor:"transparent",color:t.textColor,cursor:"pointer",transition:"all 0.2s"},onMouseEnter:k=>{k.currentTarget.style.backgroundColor=t.hoverBackground;},onMouseLeave:k=>{k.currentTarget.style.backgroundColor="transparent";},children:b}),jsxRuntime.jsx("button",{onClick:n,style:{padding:"8px 16px",borderRadius:"8px",fontSize:"14px",fontWeight:"500",border:"none",backgroundColor:t.primaryColor,color:t.backgroundColor,cursor:"pointer",transition:"all 0.2s",opacity:1},onMouseEnter:k=>{k.currentTarget.style.opacity="0.9";},onMouseLeave:k=>{k.currentTarget.style.opacity="1";},children:c})]})]})]});return typeof document<"u"&&document.body?reactDom.createPortal(x,document.body):x}function fr({agentId:e,theme:t,primaryColor:n,primaryColorDark:r,primaryColorLight:o,backgroundColor:i,borderColor:p,textColor:c,accentColor:b,baseUrl:T="",initialMessages:h=[],onMessagesChange:S,defaultOpen:x=true,floatingButtonPosition:k={bottom:24,right:24},HsafaTools:a={},HsafaUI:v={},componentAboveInput:s,editProcessContent:d,onStart:g,onFinish:y,currentChat:m,onChatChanged:I}){let{dir:C,theme:l,baseUrl:u,setStreamingState:w,setChatOpenState:f}=re(),A=t||l||"dark",B=T&&T.length>0?T:u||"",R={primaryColor:A==="dark"?r||n||"#ffffff":o||n||"#000000",backgroundColor:i||(A==="dark"?"#0B0B0F":"#FFFFFF"),borderColor:p||(A==="dark"?"#2A2C33":"#E5E7EB"),textColor:c||(A==="dark"?"#EDEEF0":"#111827"),accentColor:b||(A==="dark"?"#17181C":"#F9FAFB"),mutedTextColor:A==="dark"?"#6f7276":"#6B7280",inputBackground:A==="dark"?"#17181C":"#F3F4F6",cardBackground:A==="dark"?"#121318":"#FFFFFF",hoverBackground:A==="dark"?"#1c1e25":"#F3F4F6"},O=M=>({"header.new":"New","header.history":"History","header.close":"Close chat","input.placeholder":"Ask your question...","input.attachFiles":"Attach files","input.insertLink":"Insert link","input.send":"Send","input.stop":"Stop","input.uploadingFiles":"Uploading files...","input.previewImage":"Preview image","input.removeFile":"Remove file","messages.empty":"Start by sending a message to the agent.","general.agent":"Agent","editor.cancel":"Cancel","editor.saveAndRegenerate":"Save & Regenerate","editor.clickToEdit":"Click to edit"})[M]||M,F=Mt({agentId:e,baseUrl:B,tools:a,uiComponents:v,controlledChatId:m,onChatIdChange:m===void 0?M=>{I&&I(M);}:void 0,onStart:tt.useCallback(M=>{g&&g(M);},[g]),onFinish:tt.useCallback(M=>{y&&y(M);},[y]),onError:tt.useCallback(M=>{console.error("Chat error:",M);},[]),initialMessages:h,onMessagesChange:S}),{input:L,setInput:N,messages:G,isLoading:D,status:Y,error:pe,sendMessage:ue,stop:we,setMessages:J,notifyMessagesChange:me,chatId:$e,setChatId:Te,tools:Lt,uiComponents:mt,formHostRef:E,formStateRef:P,cleanupForms:_,onUISuccess:z,onUIError:Q,chatApi:ee}=F,q=m!==void 0?m:$e,xe=tt.useCallback(M=>{m===void 0&&Te(M),I&&I(M);},[m,Te,I]);tt.useEffect(()=>{m!==void 0&&m!==$e&&Te(m);},[m,$e,Te]);let{attachments:Ie,uploading:Ln,fileInputRef:qe,formatBytes:Hn,handleRemoveAttachment:$n,handleFileSelection:Ht,clearAttachments:Ve,setAttachments:$t}=Kt(B),[Bt,Me]=tt.useState(null),[Ke,Dt]=tt.useState(()=>{try{return rt(e).loadShowChatPreference(!!x)}catch{return !!x}}),[Bn,gt]=tt.useState(false),[Dn,Pn]=tt.useState(""),[Nn,zn]=tt.useState(0),Un=tt.useRef(null),Wn=tt.useRef(null),[On,Gn]=tt.useState(new Set),[_n,ft]=tt.useState(false),[Be,yt]=tt.useState(null),Pt=tt.useRef(null),jn=_t(D),ht=Et({agentId:e,chatId:q,messages:G,isLoading:D,autoSave:true,autoRestore:false}),V=ht.storage,De=tt.useRef(false),Pe=tt.useRef(null);tt.useEffect(()=>{if(!De.current){if(m!==void 0){try{let M=V.loadChat(m),U=M&&Array.isArray(M.messages)?M.messages:[];if(U.length>0)try{J(U);}catch{}Pe.current=m;}catch{}try{V.saveCurrentChatId(m);}catch{}De.current=true;return}try{let M=V.loadCurrentChatId();if(M){xe(M);let U=V.loadChat(M),j=U&&Array.isArray(U.messages)?U.messages:[];try{J(j);}catch{}Pe.current=M;}}catch{}De.current=true;}},[m]),tt.useEffect(()=>{if(De.current&&m!==void 0&&m!==Pe.current)try{let M=V.loadChat(m),U=M&&Array.isArray(M.messages)?M.messages:[];try{J(U);}catch{}Pe.current=m;try{V.saveCurrentChatId(m);}catch{}}catch{}},[m,V,J]),tt.useEffect(()=>{if(De.current)try{V.saveCurrentChatId(q);}catch{}},[q,V]),tt.useEffect(()=>{try{w(q,D);}catch{}return ()=>{try{w(q,!1);}catch{}}},[q,D,w]),tt.useEffect(()=>{try{f(q,Ke);}catch{}return ()=>{try{f(q,!1);}catch{}}},[q,Ke,f]);let qn=tt.useCallback(async()=>{let M=L.trim();if(!M&&Ie.length===0||D)return;let U=[...Ie];N(""),Ve(),Me(null);try{await ue({text:M,files:U.map(j=>({type:"file",url:j.url,mediaType:j.mimeType||"application/octet-stream",...j.name?{name:j.name}:{},...j.size?{size:j.size}:{}}))});}catch(j){console.error("Failed to send message:",j),Me("Failed to send message. Please try again.");}},[L,Ie,D,ue,Ve]),Nt=tt.useCallback(()=>{if(D)return;_(),N(""),Ve(),Me(null);try{J([]);}catch{}let M=`chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;Pe.current=M;try{ht.createNewChat(()=>{xe(M);try{V.saveCurrentChatId(M);}catch{}});}catch{xe(M);try{V.saveCurrentChatId(M);}catch{}}},[D,Ve,V,J,xe,_,ht]),Vn=tt.useCallback(()=>{gt(M=>!M);},[]),Kn=tt.useCallback(()=>{Dt(false);try{V.saveShowChatPreference(!1);}catch{}},[V]),Xn=tt.useCallback(async M=>{let U=M.target.files;U&&await Ht(U,Me),qe.current&&(qe.current.value="");},[Ht,qe]);tt.useEffect(()=>{let M=Pt.current;if(!M)return;M.style.height="24px",M.offsetHeight,M.style.height="auto";let U=Math.min(M.scrollHeight,200);M.style.height=`${U}px`;},[L]);let Yn=tt.useCallback((M,U,j,Qn)=>{yt({id:U,text:j,attachments:Qn||[]}),ft(true);},[]),Jn=tt.useCallback(()=>{if(!(!Be||D))try{let M=G.findIndex(j=>j.id===Be.id);if(M===-1)return;let U=G.slice(0,M);try{J(U);}catch{}N(Be.text),$t(Be.attachments),ft(!1),yt(null),me();}catch(M){console.error("Failed to edit message:",M),Me("Failed to edit message. Please try again.");}},[Be,D,G,J,$t,me]),Zn=tt.useCallback(()=>{ft(false),yt(null);},[]),zt=jsxRuntime.jsxs("div",{style:{position:"fixed",right:0,top:0,bottom:0,width:"420px",display:"flex",flexDirection:"column",padding:"24px 16px",color:R.textColor,gap:"16px",zIndex:1e3,transform:Ke?"translateX(0)":"translateX(100%)",transition:"transform 0.25s ease-out, width 0.2s ease-out"},children:[jsxRuntime.jsx(Cn,{title:O("general.agent"),alwaysOpen:false,streaming:D,dir:C||"ltr",resolvedColors:R,onNew:Nt,onToggleHistory:Vn,onClose:Kn,historyBtnRef:Un,t:O}),jsxRuntime.jsx("div",{ref:jn,className:"chat-scroll-container",style:{flex:"1",overflowY:"auto",overflowX:"hidden",padding:"16px 4px 16px 4px",display:"flex",flexDirection:"column",gap:"16px",scrollBehavior:"smooth","--hsafa-primary":R.primaryColor,"--hsafa-border":R.borderColor,"--hsafa-card":R.cardBackground,"--hsafa-text":R.textColor,"--hsafa-muted":R.mutedTextColor,"--hsafa-bg":R.backgroundColor,"--hsafa-hover":R.hoverBackground,"--hsafa-input-bg":R.inputBackground,"--hsafa-accent":R.accentColor},children:G.length===0?jsxRuntime.jsx("div",{style:{padding:"32px",textAlign:"center",color:R.mutedTextColor,fontSize:"14px"},children:O("messages.empty")}):jsxRuntime.jsx(Mn,{chatMessages:G,isLoading:D,openReasoningIds:On,toggleReasoning:M=>Gn(U=>{let j=new Set(U);return j.has(M)?j.delete(M):j.add(M),j}),resolvedColors:R,t:O,onUserMessageClick:Yn,HsafaUI:mt,onUIError:Q,onUISuccess:z,addToolResult:M=>ee?.addToolResult?.(M),editableMessageIcon:d?.message_icon})}),jsxRuntime.jsxs("div",{style:{position:"sticky",bottom:"0",marginTop:"auto",paddingBottom:"8px"},children:[s&&tt__default.default.createElement(s,{}),Bt&&jsxRuntime.jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxRuntime.jsx("span",{children:Bt}),jsxRuntime.jsx("button",{onClick:()=>Me(null),style:{background:"none",border:"none",color:"#fff",cursor:"pointer",padding:"2px"},children:"\xD7"})]}),pe&&jsxRuntime.jsxs("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:"#ef4444",color:"#fff",borderRadius:"8px",fontSize:"13px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsxRuntime.jsxs("span",{children:["An error occurred: ",pe.message||"Please try again."]}),jsxRuntime.jsx("button",{onClick:()=>window.location.reload(),style:{background:"none",border:"1px solid #fff",color:"#fff",cursor:"pointer",padding:"4px 8px",borderRadius:"4px",fontSize:"12px"},children:"Refresh"})]}),jsxRuntime.jsx(Sn,{input:L,setInput:N,textareaRef:Pt,fileInputRef:qe,isLoading:D,uploading:Ln,attachments:Ie,formatBytes:Hn,handleRemoveAttachment:$n,onFileInputChange:Xn,onSend:qn,onStop:()=>we(),status:Y,t:O,resolvedColors:R})]}),jsxRuntime.jsx(An,{historyOpen:Bn,historySearch:Dn,currentChatId:q,refreshKey:Nn,resolvedColors:R,onClose:()=>gt(false),onSearchChange:Pn,onChatSelect:M=>{if(gt(false),M&&M!==q&&(_(),xe(M),m===void 0)){try{V.saveCurrentChatId(M);}catch{}try{let U=V.loadChat(M),j=U&&Array.isArray(U.messages)?U.messages:[];try{J(j);}catch{}}catch{}}},onChatDelete:M=>{try{V.deleteChat(M),zn(U=>U+1),M===q&&Nt();}catch{}},loadChatsIndex:()=>V.loadChatsIndex(),historyPopupRef:Wn}),jsxRuntime.jsx(Rn,{isOpen:_n,resolvedColors:R,onConfirm:Jn,onCancel:Zn,editProcessContent:d}),jsxRuntime.jsx("style",{children:`
|
|
34
34
|
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
|
|
35
35
|
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
|
|
36
|
-
`})]});return typeof document<"u"&&document.body?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(
|
|
37
|
-
@keyframes ${
|
|
36
|
+
`})]});return typeof document<"u"&&document.body?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Qe,{}),reactDom.createPortal(zt,document.body),jsxRuntime.jsx(Wt,{show:!Ke,onClick:()=>{Dt(true);try{V.saveShowChatPreference(!0);}catch{}},resolvedColors:R,floatingButtonPosition:k})]}):zt}var Fn={dark:{primaryColor:"#4D78FF",backgroundColor:"#0B0B0F",borderColor:"#2A2C33",textColor:"#EDEEF0",accentColor:"#17181C",mutedTextColor:"#9AA0A6",inputBackground:"#17181C",cardBackground:"#121318",hoverBackground:"#1c1e25"},light:{primaryColor:"#2563EB",backgroundColor:"#FFFFFF",borderColor:"#E5E7EB",textColor:"#111827",accentColor:"#F9FAFB",mutedTextColor:"#6B7280",inputBackground:"#F9FAFB",cardBackground:"#F3F4F6",hoverBackground:"#F3F4F6"}};function Cr({children:e,theme:t="dark",primaryColor:n,backgroundColor:r,borderColor:o,textColor:i,mutedTextColor:p,enableBorderAnimation:c=true,borderRadius:b=16,enableContentBorder:T=true,className:h="",enableMargin:S=true,chatWidth:x=420,dir:k="ltr"}){let{isAnyStreaming:a,isAnyChatOpen:v,dir:s,theme:d}=re(),g=(k??s)||"ltr",y=(t??d)||"dark",m=tt.useRef(`content-container-${Date.now()}-${Math.random().toString(36).slice(2,8)}`),[I,C]=tt.useState(false);tt.useEffect(()=>{let H=setTimeout(()=>C(true),50);return ()=>clearTimeout(H)},[]);let l=Fn[y],u={primaryColor:n||l.primaryColor,backgroundColor:r||l.backgroundColor,borderColor:o||l.borderColor,textColor:i||l.textColor,accentColor:l.accentColor,mutedTextColor:p||l.mutedTextColor,inputBackground:l.inputBackground,cardBackground:l.cardBackground,hoverBackground:l.hoverBackground},w=typeof b=="number"?`${b}px`:b,f=typeof x=="number"?`${x}px`:x,A=S&&v?g==="rtl"?{marginLeft:f}:{marginRight:f}:{},B=S&&v?`calc(100% - ${f})`:"100%";return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:h,style:{width:B,height:"100%",transition:I?"all 0.2s ease-out":"none",padding:v&&T?"16px":"0",...A},children:jsxRuntime.jsx("div",{style:{position:"relative",width:"100%",height:"100%",transition:I?"all 0.2s ease-out":"none",borderRadius:v?w:"0",border:v&&a&&c?"none":v?`1px solid ${u.borderColor}`:"none",padding:v&&a&&c?"1.5px":"0",background:v&&a&&c?`linear-gradient(120deg, ${u.primaryColor}dd 0%, ${u.primaryColor}88 25%, ${u.primaryColor}00 50%, ${u.primaryColor}88 75%, ${u.primaryColor}dd 100%)`:"transparent",backgroundSize:v&&a&&c?"300% 300%":"auto",animation:v&&a&&c?`${m.current}-border-flow 3s ease-in-out infinite`:"none",filter:v&&a&&c?`drop-shadow(0 0 10px ${u.primaryColor}40)`:"none"},children:jsxRuntime.jsx("div",{className:"hsafa-content-container",style:{width:"100%",height:"100%",borderRadius:v&&T?w:"0",backgroundColor:v&&T?u.backgroundColor:"transparent",overflow:"auto",position:"relative",isolation:"isolate",contain:"layout style paint",transform:"translateZ(0)",scrollbarWidth:"thin",scrollbarColor:`${u.mutedTextColor}40 transparent`},children:e})})}),jsxRuntime.jsx("style",{children:`
|
|
37
|
+
@keyframes ${m.current}-border-flow {
|
|
38
38
|
0% { background-position: 0% 50%; }
|
|
39
39
|
50% { background-position: 100% 50%; }
|
|
40
40
|
100% { background-position: 0% 50%; }
|
|
41
41
|
}
|
|
42
|
-
`})," "]})}var
|
|
42
|
+
`})," "]})}var Ft=class{constructor(){this.components=new Map;}register(t,n){this.components.set(t,n);}unregister(t){this.components.delete(t);}get(t){return this.components.get(t)}has(t){return this.components.has(t)}clear(){this.components.clear();}getRegisteredNames(){return Array.from(this.components.keys())}},wr=new Ft;exports.Button=Mr;exports.ContentContainer=Cr;exports.CursorController=Qe;exports.FillActiveInput=Ue;exports.FloatingChatButton=Wt;exports.HsafaChat=fr;exports.HsafaProvider=ro;exports.componentRegistry=wr;exports.controlCursor=Ce;exports.getDomComponents=ze;exports.guideCursor=Ce;exports.useAutoScroll=_t;exports.useChatStorage=Et;exports.useFileUpload=Kt;exports.useHsafa=re;exports.useHsafaAgent=Mt;exports.useMessageEditor=_o;//# sourceMappingURL=index.cjs.map
|
|
43
43
|
//# sourceMappingURL=index.cjs.map
|