@holaboss/client 0.2.0-beta.11 → 0.2.0-beta.13

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 CHANGED
@@ -1,8 +1,8 @@
1
1
  'use client'
2
- var X=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Ue=Object.prototype.hasOwnProperty;var Fe=(e,t)=>{for(var o in t)X(e,o,{get:t[o],enumerable:!0})},Le=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of _e(t))!Ue.call(e,s)&&s!==o&&X(e,s,{get:()=>t[s],enumerable:!(r=Oe(t,s))||r.enumerable});return e};var Ne=e=>Le(X({},"__esModule",{value:!0}),e);var dt={};Fe(dt,{Chat:()=>Re,GRID_COLS:()=>Q,GRID_MAX_COLS:()=>Z,GRID_MAX_ROWS:()=>ee,HolaProvider:()=>Te,PortalConflict:()=>W,bandOfKind:()=>j,bandOfType:()=>te,cellValue:()=>me,createApiTransport:()=>xe,createHolaClient:()=>De,createPortalData:()=>Ae,createWidgetTransport:()=>G,deliverableCellText:()=>de,deliverableStatus:()=>ae,deriveFields:()=>K,footprintOf:()=>ne,footprintWith:()=>B,formatDeliverableDate:()=>fe,groupDeliverableVersions:()=>J,inferSpec:()=>Y,isDeliverableChecked:()=>pe,mergeMessage:()=>ye,normalizeDeliverableColType:()=>q,normalizeDeliverableItem:()=>z,parseDashboardSpec:()=>se,parseDeliverableItems:()=>ie,parseDeliverableTable:()=>ue,parseTableResponses:()=>ce,placeWidgets:()=>re,publishedVersionOf:()=>le,renderModel:()=>oe,setResponse:()=>ge,textDeltaOf:()=>A,thinkingDeltaOf:()=>E,toolEventOf:()=>$,useArtifactUrl:()=>U,useChat:()=>N,useHolaClient:()=>L,useThread:()=>$e});module.exports=Ne(dt);var be=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="message_update"?t.assistantMessageEvent??null:null},A=e=>{let t=be(e);return t?.type==="text_delta"&&typeof t.delta=="string"?t.delta:null},E=e=>{let t=be(e);return t?.type==="thinking_delta"&&typeof t.delta=="string"?t.delta:null},$=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="tool_execution_start"&&t.toolCallId?{phase:"start",id:t.toolCallId,name:t.toolName}:t.type==="tool_execution_end"&&t.toolCallId?{phase:"end",id:t.toolCallId,isError:t.isError}:null};var Ve=/^ /,D=e=>{if(e&&typeof e=="object"){let t=e,o=typeof t.error=="string"?t.error:"request_failed";return typeof t.retryable=="boolean"?{error:o,retryable:t.retryable}:{error:o}}return{error:"request_failed"}},Ge=e=>{let t="message",o=[];for(let r of e.split(`
3
- `))r.startsWith(":")||(r.startsWith("event:")?t=r.slice(6).trim():r.startsWith("data:")&&o.push(r.slice(5).replace(Ve,"")));return o.length>0?{event:t,data:o.join(`
4
- `)}:null},je=(e,t,o)=>{let r;try{r=JSON.parse(e.data)}catch{return}if(e.event==="session"){let s=r.sessionId;s&&(o(s),t.onSession?.(s));return}if(e.event==="turn_event"){t.onEvent?.(r);let s=A(r);s&&t.onText?.(s);let a=E(r);a&&t.onThinking?.(a);let n=$(r);n&&t.onTool?.(n);return}if(e.event==="chat_completed"){let s=r;o(s.sessionId),t.onComplete?.(s);return}e.event==="chat_error"&&t.onError?.(D(r))},w=async(e,t)=>{let o=await fetch(e,{headers:t});if(!o.ok)throw new Error(`hola: request failed (${o.status})`);return await o.json()},he=async e=>{let t=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body});if(!t.ok)throw new Error(`hola: message failed (${t.status})`);return await t.json()},we=async(e,t,o,r)=>{let s=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body,signal:r});if(!(s.ok&&s.body)){t.onError?.({error:`stream_failed_${s.status}`});return}let a=s.body.getReader(),n=new TextDecoder,i="",l=()=>{let d=i.indexOf(`
2
+ var K=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var Ue=Object.prototype.hasOwnProperty;var Fe=(e,t)=>{for(var o in t)K(e,o,{get:t[o],enumerable:!0})},Ne=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Le(t))!Ue.call(e,s)&&s!==o&&K(e,s,{get:()=>t[s],enumerable:!(r=_e(t,s))||r.enumerable});return e};var Ve=e=>Ne(K({},"__esModule",{value:!0}),e);var pt={};Fe(pt,{Chat:()=>De,GRID_COLS:()=>Z,GRID_MAX_COLS:()=>ee,GRID_MAX_ROWS:()=>te,HolaProvider:()=>ke,PortalConflict:()=>A,bandOfKind:()=>H,bandOfType:()=>ne,cellValue:()=>me,createApiTransport:()=>ve,createHolaClient:()=>Ce,createPortalData:()=>Ee,createWidgetTransport:()=>j,deliverableCellText:()=>pe,deliverableStatus:()=>le,deriveFields:()=>Y,footprintOf:()=>re,footprintWith:()=>B,formatDeliverableDate:()=>ye,groupDeliverableVersions:()=>q,inferSpec:()=>Q,isDeliverableChecked:()=>ce,mergeMessage:()=>be,normalizeDeliverableColType:()=>X,normalizeDeliverableItem:()=>J,parseDashboardSpec:()=>ie,parseDeliverableItems:()=>ae,parseDeliverableTable:()=>de,parseTableResponses:()=>ge,placeWidgets:()=>z,publishedVersionOf:()=>ue,renderModel:()=>se,setResponse:()=>fe,splitLayout:()=>oe,textDeltaOf:()=>E,thinkingDeltaOf:()=>$,toolEventOf:()=>O,useArtifactUrl:()=>U,useChat:()=>V,useHolaClient:()=>N,useThread:()=>Oe});module.exports=Ve(pt);var he=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="message_update"?t.assistantMessageEvent??null:null},E=e=>{let t=he(e);return t?.type==="text_delta"&&typeof t.delta=="string"?t.delta:null},$=e=>{let t=he(e);return t?.type==="thinking_delta"&&typeof t.delta=="string"?t.delta:null},O=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="tool_execution_start"&&t.toolCallId?{phase:"start",id:t.toolCallId,name:t.toolName}:t.type==="tool_execution_end"&&t.toolCallId?{phase:"end",id:t.toolCallId,isError:t.isError}:null};var Ge=/^ /,D=e=>{if(e&&typeof e=="object"){let t=e,o=typeof t.error=="string"?t.error:"request_failed";return typeof t.retryable=="boolean"?{error:o,retryable:t.retryable}:{error:o}}return{error:"request_failed"}},je=e=>{let t="message",o=[];for(let r of e.split(`
3
+ `))r.startsWith(":")||(r.startsWith("event:")?t=r.slice(6).trim():r.startsWith("data:")&&o.push(r.slice(5).replace(Ge,"")));return o.length>0?{event:t,data:o.join(`
4
+ `)}:null},Be=(e,t,o)=>{let r;try{r=JSON.parse(e.data)}catch{return}if(e.event==="session"){let s=r.sessionId;s&&(o(s),t.onSession?.(s));return}if(e.event==="turn_event"){t.onEvent?.(r);let s=E(r);s&&t.onText?.(s);let a=$(r);a&&t.onThinking?.(a);let n=O(r);n&&t.onTool?.(n);return}if(e.event==="chat_completed"){let s=r;o(s.sessionId),t.onComplete?.(s);return}e.event==="chat_error"&&t.onError?.(D(r))},x=async(e,t)=>{let o=await fetch(e,{headers:t});if(!o.ok)throw new Error(`hola: request failed (${o.status})`);return await o.json()},xe=async e=>{let t=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body});if(!t.ok)throw new Error(`hola: message failed (${t.status})`);return await t.json()},we=async(e,t,o,r)=>{let s=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body,signal:r});if(!(s.ok&&s.body)){t.onError?.({error:`stream_failed_${s.status}`});return}let a=s.body.getReader(),n=new TextDecoder,i="",l=()=>{let d=i.indexOf(`
5
5
 
6
- `);for(;d!==-1;){let g=i.slice(0,d);i=i.slice(d+2);let p=Ge(g);p&&je(p,t,o),d=i.indexOf(`
6
+ `);for(;d!==-1;){let m=i.slice(0,d);i=i.slice(d+2);let p=je(m);p&&Be(p,t,o),d=i.indexOf(`
7
7
 
8
- `)}},u=async()=>{let d=await a.read();if(!d.done)return i+=n.decode(d.value,{stream:!0}),l(),u()};await u()};var Be=/\/+$/,O="/api/v1/end-user",xe=e=>{let t=e.baseUrl.replace(Be,""),o=()=>typeof e.token=="function"?e.token():e.token,r=n=>e.project?`${n}project=${encodeURIComponent(e.project)}`:"",s=async()=>({"content-type":"application/json",authorization:`Bearer ${await o()}`}),a=async n=>{let i=await fetch(`${t}${O}/chat${r("?")}`,{method:"POST",headers:await s(),body:JSON.stringify({message:n})});if(!i.ok)throw new Error(`hola: message failed (${i.status})`);return{reply:(await i.json()).reply??"",sessionId:"",artifacts:[]}};return{sessionId:()=>"",getInfo:async()=>w(`${t}${O}/chat/info${r("?")}`,await s()),sendMessage:a,streamMessage:async(n,i)=>{try{let l=await a(n);i.onText?.(l.reply),i.onComplete?.(l)}catch(l){i.onError?.(D(l))}},subscribe:(n,i)=>{let l=i?.since??"0",u=!1,d,g=i?.intervalMs??3e3,p=typeof document<"u",m=()=>p&&document.visibilityState==="hidden",y=!1,b=()=>{if(!u){if(m()){y=!0;return}d=setTimeout(c,g)}},c=async()=>{try{let P=await w(`${t}${O}/chat/thread?since=${encodeURIComponent(l)}${r("&")}`,await s());for(let I of P.messages)n.onMessage(I);l=P.cursor,n.onHealthy?.()}catch(P){n.onError?.(D(P))}b()},f=()=>{u||!y||m()||(y=!1,d&&clearTimeout(d),d=setTimeout(c,0))};p&&document.addEventListener("visibilitychange",f);let x=()=>{u=!0,d&&clearTimeout(d),p&&document.removeEventListener("visibilitychange",f)};return i?.signal?.addEventListener("abort",x),d=setTimeout(c,0),x},requestHuman:async()=>{await fetch(`${t}${O}/chat/request-human${r("?")}`,{method:"POST",headers:await s(),body:"{}"})}}};var _=require("react"),U=(e,t)=>{let[o,r]=(0,_.useState)("");return(0,_.useEffect)(()=>{if(!e){r("");return}let s=Uint8Array.from(atob(e),n=>n.charCodeAt(0)),a=URL.createObjectURL(new Blob([s],{type:t}));return r(a),()=>URL.revokeObjectURL(a)},[e,t]),o};var V=require("react");var F=require("react"),ke=require("react/jsx-runtime"),ve=(0,F.createContext)(null),Te=({client:e,children:t})=>(0,ke.jsx)(ve.Provider,{value:e,children:t}),L=()=>{let e=(0,F.useContext)(ve);if(!e)throw new Error("useHolaClient must be used within <HolaProvider>");return e};var v=require("react"),N=e=>{let[t,o]=(0,v.useState)([]),[r,s]=(0,v.useState)(""),[a,n]=(0,v.useState)(!1),[i,l]=(0,v.useState)(null),u=(0,v.useRef)(0),d=(0,v.useCallback)(()=>{let p=u.current;return u.current+=1,p},[]);(0,v.useEffect)(()=>{let p=!0;return e.getInfo().then(m=>{p&&m.greeting&&o([{id:d(),role:"assistant",text:m.greeting}])}).catch(()=>{}),()=>{p=!1}},[e,d]);let g=(0,v.useCallback)(()=>{let p=r.trim();if(!p||a)return;s(""),l(null),n(!0);let m=d(),y=d();o(c=>[...c,{id:m,role:"user",text:p},{id:y,role:"assistant",text:"",streaming:!0}]);let b=c=>{o(f=>f.map(x=>x.id===y?c(x):x))};e.streamMessage(p,{onText:c=>b(f=>({...f,text:f.text+c})),onComplete:c=>{b(f=>({...f,text:c.reply||f.text,artifacts:c.artifacts,streaming:!1})),n(!1)},onError:c=>{b(f=>({...f,streaming:!1})),l(c.error),n(!1)}}).catch(c=>{b(f=>({...f,streaming:!1})),l(c instanceof Error?c.message:"stream_failed"),n(!1)})},[r,a,e,d]);return{messages:t,input:r,setInput:s,send:g,sending:a,error:i}};var h=require("react/jsx-runtime"),k={root:{display:"flex",flexDirection:"column",height:"100%",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:14,color:"#111827"},log:{flex:1,overflowY:"auto",padding:12,display:"flex",flexDirection:"column",gap:8},user:{alignSelf:"flex-end",background:"#111827",color:"#ffffff",borderRadius:12,padding:"8px 12px",maxWidth:"80%",whiteSpace:"pre-wrap"},assistant:{alignSelf:"flex-start",background:"#f1f1f4",color:"#111827",borderRadius:12,padding:"8px 12px",maxWidth:"80%",whiteSpace:"pre-wrap"},artifacts:{display:"flex",flexDirection:"column",gap:6,marginTop:6},image:{maxHeight:220,borderRadius:8,border:"1px solid #e5e7eb"},link:{color:"#2563eb",textDecoration:"underline",wordBreak:"break-all"},error:{color:"#b91c1c",padding:"4px 12px",fontSize:13},form:{display:"flex",gap:8,borderTop:"1px solid #e5e7eb",padding:8},input:{flex:1,border:"1px solid #d1d5db",borderRadius:8,padding:"8px 10px",fontSize:14,outline:"none"},button:{border:"none",background:"#111827",color:"#ffffff",borderRadius:8,padding:"8px 14px",fontSize:14,cursor:"pointer"}},ze=({artifact:e})=>{let t=U(e.dataBase64??"",e.mimeType),o=e.url??t;return o?e.mimeType.startsWith("image/")?(0,h.jsx)("a",{href:o,rel:"noopener noreferrer",target:"_blank",children:(0,h.jsx)("img",{alt:e.filename,src:o,style:k.image})}):(0,h.jsx)("a",{download:e.filename,href:o,style:k.link,children:e.filename}):null},Re=()=>{let e=L(),{messages:t,input:o,setInput:r,send:s,sending:a,error:n}=N(e),i=(0,V.useRef)(null);(0,V.useEffect)(()=>{let u=i.current;u&&(u.scrollTop=u.scrollHeight)},[t]);let l=u=>{u.preventDefault(),s()};return(0,h.jsxs)("div",{style:k.root,children:[(0,h.jsx)("div",{ref:i,style:k.log,children:t.map(u=>(0,h.jsxs)("div",{style:u.role==="user"?k.user:k.assistant,children:[u.text||(u.streaming?"\u2026":""),u.artifacts&&u.artifacts.length>0?(0,h.jsx)("div",{style:k.artifacts,children:u.artifacts.map(d=>(0,h.jsx)(ze,{artifact:d},d.filename))}):null]},u.id))}),n?(0,h.jsx)("div",{style:k.error,children:n}):null,(0,h.jsxs)("form",{onSubmit:l,style:k.form,children:[(0,h.jsx)("input",{"aria-label":"Message",onChange:u=>r(u.target.value),placeholder:"Type a message\u2026",style:k.input,value:o}),(0,h.jsx)("button",{disabled:a||o.trim().length===0,style:k.button,type:"submit",children:"Send"})]})]})};var Je=/\/+$/,G=e=>{let t=e.sessionId,o=e.baseUrl.replace(Je,""),r=n=>`${o}/endpoint/${encodeURIComponent(e.token)}${n}`,s={"content-type":"application/json"},a=(n,i)=>({url:r(n),headers:s,body:JSON.stringify({message:i,...t?{sessionId:t}:{},...e.identity?{externalUserId:e.identity.externalUserId,userHmac:e.identity.userHmac}:{}})});return{sessionId:()=>t,getInfo:()=>w(r("/config"),{}),sendMessage:async n=>{let i=await he(a("/message",n));return t=i.sessionId,i},streamMessage:(n,i,l)=>we(a("/message/stream",n),i,u=>{t=u},l),subscribe:(n,i)=>{let l=i?.since??"0",u=!1,d,g=i?.intervalMs??3e3,p=async()=>{let y=t;if(y)try{let b=await w(r(`/messages?session=${encodeURIComponent(y)}&since=${encodeURIComponent(l)}`),{});for(let c of b.messages)n.onMessage(c);l=b.cursor,n.onHealthy?.()}catch(b){n.onError?.(D(b))}u||(d=setTimeout(p,g))},m=()=>{u=!0,d&&clearTimeout(d)};return i?.signal?.addEventListener("abort",m),d=setTimeout(p,0),m},requestHuman:async()=>{t&&await fetch(r("/request-human"),{method:"POST",headers:s,body:JSON.stringify({sessionId:t})})}}};var De=e=>"transport"in e?e.transport:G(e);var qe=/^https?:\/\//i,Xe=/^\d{4}-\d{2}-\d{2}(?:[T ]|$)/,Ke=e=>e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase());function Ye(e){if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean";if(typeof e=="string"){if(qe.test(e))return"url";if(Xe.test(e))return"date"}return"text"}function K(e){let t=[],o=new Map;for(let r of e)for(let[s,a]of Object.entries(r.data??{})){if(a==null)continue;let n=o.get(s);n||(n=new Map,o.set(s,n),t.push(s));let i=Ye(a);n.set(i,(n.get(i)??0)+1)}return t.map(r=>{let s=o.get(r)??new Map,a="text",n=-1;for(let[i,l]of s)l>n&&(n=l,a=i);return{key:r,label:Ke(r),type:a}})}var Qe=e=>typeof e=="number"?e:Number(e)||0,Ce=e=>/rate|position|rank|score|percent|avg/i.test(e),Ze=/posted|published|sent|completed|shipped|launched|_at|date/i,et=new Set(["service","order","end_user_id"]);function Y(e,t){let o=e.filter(l=>!et.has(l.key)),r=o.filter(l=>l.type==="number").slice(0,3),s=o.find(l=>l.key==="status")??o.find(l=>l.type==="select"),a=o.find(l=>l.type==="date"&&Ze.test(l.key))??o.find(l=>l.type==="date"),n=o.filter(l=>l.type==="number"&&!Ce(l.key)).map(l=>({field:l,total:t.reduce((u,d)=>u+Qe(d.data[l.key]),0)})).sort((l,u)=>u.total-l.total).find(l=>l.total>0)?.field??null,i=[{type:"stat",label:"Items",agg:"count"}];for(let l of r){let u=Ce(l.key);i.push({type:"stat",metric:l.key,agg:u?"avg":"sum",label:u?`Avg ${l.label.toLowerCase()}`:l.label})}return a&&i.push({type:"line",x:a.key,y:n?.key,agg:"sum",title:n?`${n.label} by day`:"Items by day"}),s&&i.push({type:"donut",groupBy:s.key,title:s.label}),i.push({type:"table",columns:o.map(l=>l.key)}),{version:1,widgets:i}}var Q=6,Z=6,ee=4,Se={stat:{w:1,h:1},chart:{w:2,h:2},block:{w:6,h:4}},tt=e=>Math.max(1,Math.min(6,Math.round(e))),nt=e=>Math.max(1,Math.min(4,Math.round(e)));function j(e){return e==="stat"?"stat":e==="series"||e==="donut"?"chart":"block"}function te(e){return e==="stat"?"stat":e==="line"||e==="bar"||e==="donut"?"chart":"block"}function ne(e){return Se[e]}function B(e,t,o){let r=Se[e];return{w:t===void 0?r.w:tt(t),h:o===void 0?r.h:nt(o)}}function re(e){let t=[],o=[],r=(n,i,l,u)=>{if(n<0||n+l>6)return!1;for(let d=0;d<u;d+=1){let g=o[i+d];if(g){for(let p=0;p<l;p+=1)if(g[n+p])return!1}}return!0},s=(n,i,l,u)=>{for(let d=0;d<u;d+=1){let g=o[i+d]??[];for(let p=0;p<l;p+=1)g[n+p]=!0;o[i+d]=g}},a=(n,i)=>{for(let l=0;;l+=1)for(let u=0;u+n<=6;u+=1)if(r(u,l,n,i))return{gx:u,gy:l}};for(let n of e){let i=B(j(n.kind),n.w,n.h),u=n.gx!==void 0&&n.gy!==void 0&&r(n.gx,n.gy,i.w,i.h)&&n.gx!==void 0&&n.gy!==void 0?{gx:n.gx,gy:n.gy}:a(i.w,i.h);s(u.gx,u.gy,i.w,i.h),t.push({widget:n,gx:u.gx,gy:u.gy,w:i.w,h:i.h})}return t}var Pe=new Set(["service","order","end_user_id"]),Ie=e=>typeof e=="number"?e:Number(e)||0,He=e=>e==null?"":String(e);function Me(e,t){if(e==="count")return t.length;if(t.length===0)return 0;if(e==="last")return t[t.length-1]??0;if(e==="min")return Math.min(...t);if(e==="max")return Math.max(...t);let o=t.reduce((r,s)=>r+s,0);return e==="avg"?Math.round(o/t.length):o}function rt(e,t,o,r){let s=new Map;for(let a of e){let n=new Date(He(a.data[t]));if(Number.isNaN(n.getTime()))continue;let i=n.toISOString().slice(0,10),l=s.get(i)??[];l.push(o?Ie(a.data[o]):1),s.set(i,l)}return[...s.entries()].sort((a,n)=>a[0]<n[0]?-1:1).map(([a,n])=>({label:new Date(`${a}T00:00:00`).toLocaleDateString(void 0,{month:"short",day:"numeric"}),value:o?Me(r,n):n.length}))}function ot(e,t){let o=new Map;for(let r of e){let s=He(r.data[t]).trim();s&&o.set(s,(o.get(s)??0)+1)}return[...o.entries()].sort((r,s)=>s[1]-r[1]).map(([r,s])=>({label:r,value:s}))}function st(e,t,o,r){switch(e.type){case"stat":{let s=e.metric?t.get(e.metric):void 0;if(e.metric&&!s)return null;if(!s)return{kind:"stat",label:e.label??"Items",value:r.length};let a=r.map(n=>Ie(n.data[s.key]));return{kind:"stat",label:e.label??s.label,value:Me(e.agg??"sum",a)}}case"line":case"bar":{if(!t.has(e.x)||e.y&&!t.has(e.y))return null;let s=rt(r,e.x,e.y,e.agg??"sum");return s.length<2?null:{kind:"series",draw:e.type,title:e.title??"By day",points:s}}case"donut":{if(!t.has(e.groupBy))return null;let s=ot(r,e.groupBy);return s.length===0?null:{kind:"donut",title:e.title??t.get(e.groupBy)?.label??"Breakdown",points:s}}case"table":{let s=e.columns?e.columns.map(a=>t.get(a)).filter(a=>a!==void 0&&!Pe.has(a.key)):o;return s.length===0?null:{kind:"table",title:e.title,columns:s,rows:r}}case"text":return{kind:"text",title:e.title,body:e.body};default:return null}}function oe(e,t,o){let r=t.filter(n=>!Pe.has(n.key)),s=new Map(t.map(n=>[n.key,n])),a=[];for(let n of e.widgets){let i=st(n,s,r,o);i&&a.push({...i,w:n.w,h:n.h,gx:n.gx,gy:n.gy})}return a}var it=new Set(["sum","avg","count","min","max","last"]),We=e=>typeof e=="string"&&it.has(e)?e:void 0,R=e=>typeof e=="string"&&e!==""?e:void 0,H=e=>typeof e=="number"&&e>=1?Math.min(6,Math.round(e)):void 0,M=e=>typeof e=="number"&&e>=1?Math.min(4,Math.round(e)):void 0,C=e=>typeof e=="number"&&e>=0?Math.round(e):void 0;function at(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"stat":return{type:"stat",label:R(t.label),metric:R(t.metric),agg:We(t.agg),w:H(t.w),h:M(t.h),gx:C(t.gx),gy:C(t.gy)};case"line":case"bar":{let o=R(t.x);return o?{type:t.type,title:R(t.title),x:o,y:R(t.y),agg:We(t.agg),w:H(t.w),h:M(t.h),gx:C(t.gx),gy:C(t.gy)}:null}case"donut":{let o=R(t.groupBy);return o?{type:"donut",title:R(t.title),groupBy:o,w:H(t.w),h:M(t.h),gx:C(t.gx),gy:C(t.gy)}:null}case"table":{let o=Array.isArray(t.columns)?t.columns.filter(r=>typeof r=="string"):void 0;return{type:"table",title:R(t.title),columns:o,w:H(t.w),h:M(t.h),gx:C(t.gx),gy:C(t.gy)}}case"text":{let o=R(t.body);return o?{type:"text",title:R(t.title),body:o,w:H(t.w),h:M(t.h),gx:C(t.gx),gy:C(t.gy)}:null}default:return null}}function se(e){let t=e;if(typeof e=="string"){if(e.trim()==="")return null;try{t=JSON.parse(e)}catch{return null}}if(typeof t!="object"||t===null)return null;let o=t.widgets;if(!Array.isArray(o))return null;let r=o.map(at).filter(a=>a!==null);if(r.length===0)return null;let s=t.version;return{version:typeof s=="number"?s:1,title:R(t.title),widgets:r}}function z(e){if(typeof e=="string")return e?{kind:"file",value:e}:null;if(e&&typeof e=="object"){let t=e,o=typeof t.value=="string"?t.value:"",r=t.kind==="link"||t.kind==="text"||t.kind==="table"?t.kind:"file",s=typeof t.v=="number"&&t.v>=1?Math.floor(t.v):void 0;return o?{kind:r,value:o,...s?{v:s}:{}}:null}return null}function J(e){let t=new Map;for(let o of e){let r=o.v??1,s=t.get(r)??[];s.push(o),t.set(r,s)}return[...t.entries()].sort(([o],[r])=>o-r).map(([o,r])=>({v:o,items:r}))}function ie(e){let t=e.files;if(typeof t=="string"&&t.trim()!=="")try{let r=JSON.parse(t);if(Array.isArray(r))return r.map(z).filter(s=>s!==null)}catch{}let o=String(e.file??"");return o?[{kind:"file",value:o}]:[]}function ae(e,t,o){let s=(J(e).find(n=>n.v===t)?.items??[]).filter(n=>n.kind==="file").map(n=>n.value),a=s.map(n=>o.get(n)??"");return s.length===0||a.some(n=>n==="")?"awaiting":a.some(n=>n==="revise")?"revise":"accepted"}function le(e){return Number(e.published_version)||0}function q(e){return e==="number"||e==="date"||e==="boolean"||e==="select"||e==="url"?e:e==="link"?"url":e==="checkbox"?"boolean":"text"}function ue(e){try{let t=JSON.parse(e);if(Array.isArray(t.columns)&&Array.isArray(t.rows)&&t.columns.length){let o=t.columns.map((a,n)=>({key:typeof a.key=="string"&&a.key?a.key:typeof a.id=="string"&&a.id?a.id:`column_${n+1}`,label:typeof a.label=="string"?a.label:"",type:q(a.type),...a.clientEditable===!0?{clientEditable:!0}:{}})),r=t.rows.map((a,n)=>({id:typeof a.id=="string"&&a.id?a.id:`row_${n}`,cells:a.cells&&typeof a.cells=="object"?a.cells:{}})),s=typeof t.name=="string"?t.name:void 0;return{columns:o,rows:r,...s?{name:s}:{}}}}catch{}return null}function de(e){return e==null?"":String(e)}function pe(e){return e===!0||e==="true"||e==="1"||e==="yes"||e==="\u2713"}function ce(e){if(typeof e!="string"||e.trim()==="")return{};try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function me(e,t,o){if(e.clientEditable){let r=o[t.id];if(r&&e.key in r)return r[e.key]}return t.cells[e.key]}function ge(e,t,o,r){return{...e,[t]:{...e[t]??{},[o]:r}}}function fe(e){let t=new Date(`${e}T00:00:00`);return Number.isNaN(t.getTime())?e:t.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var lt=/\/+$/,S="/api/v1/end-user",W=class extends Error{constructor(t){super(t),this.name="PortalConflict"}};function ut(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}var Ae=e=>{let t=e.baseUrl.replace(lt,""),o=()=>typeof e.token=="function"?e.token():e.token,r=async()=>({"content-type":"application/json",authorization:`Bearer ${await o()}`}),s=async(n,i)=>{try{let l=await fetch(`${t}${S}${n}`,{method:i.method,headers:await r(),...i.body===void 0?{}:{body:JSON.stringify(i.body)}});if(l.status===409){let u=await l.json().catch(()=>({}));throw new W(u.message??"Someone else saved this first.")}if(!l.ok){let u=await l.text().catch(()=>""),d=`${i.method} ${n} \u2192 ${String(l.status)}`;try{let g=JSON.parse(u);g.message&&(d=g.message)}catch{d=u?`${d}: ${u}`:d}throw D(new Error(d))}return await l.json()}catch(l){throw D(l)}},a=n=>`/tables/${encodeURIComponent(n)}`;return{listTables:async()=>(await w(`${t}${S}/tables`,await r())).tables,listRows:async(n,i)=>await w(`${t}${S}${a(n)}/rows?limit=${String(i??100)}`,await r()),insertRow:async(n,i)=>{let{rowIds:l}=await s(`${a(n)}/rows`,{method:"POST",body:{rows:[i]}}),u=l[0];if(!u)throw D(new Error("The row was not created."));return u},patchRow:async(n,i,l)=>(await s(`${a(n)}/rows/${encodeURIComponent(i)}`,{method:"PATCH",body:l})).updated,deleteRow:async(n,i)=>(await s(`/${encodeURIComponent(n)}/${encodeURIComponent(i)}`,{method:"DELETE"})).deleted,listFiles:async()=>(await w(`${t}${S}/tables/files/rows?limit=200`,await r())).rows.map(i=>({id:i.rowId,filename:String(i.data.filename??""),source:String(i.data.source??"client"),campaign:String(i.data.campaign??""),size:typeof i.data.size=="number"?i.data.size:0,createdAt:i.createdAt})),uploadFile:async(n,i)=>{let l=new Uint8Array(await n.arrayBuffer());return await s("/files",{method:"POST",body:{filename:n.name,mime:n.type||"application/octet-stream",data:ut(l),...i===void 0?{}:{message:i}}})},fileLink:async n=>await w(`${t}${S}/files/${encodeURIComponent(n)}/url`,await r()),deleteFile:async n=>(await s(`/files/${encodeURIComponent(n)}`,{method:"DELETE"})).deleted,listDocuments:async()=>(await w(`${t}${S}/documents`,await r())).documents,readDocument:async n=>(await w(`${t}${S}/documents/${encodeURIComponent(n)}`,await r())).document,saveDocument:async(n,i)=>await s(`/documents/${encodeURIComponent(n)}`,{method:"PATCH",body:i})}};var T=require("react"),Ee="greeting";function ye(e,t){if(e.some(a=>a.id===t.id))return e;let o=e.filter(a=>a.id!==Ee),r=a=>a.author==="client"==(t.author==="client");return[...o.filter(a=>!(a.pending&&r(a)&&a.text===t.text)),t]}var $e=(e,t)=>{let[o,r]=(0,T.useState)([]),[s,a]=(0,T.useState)(""),[n,i]=(0,T.useState)(!1),[l,u]=(0,T.useState)(null),d=(0,T.useRef)(0),g=t?.pollMs??2e3;(0,T.useEffect)(()=>{let m=!0;return e.getInfo().then(y=>{m&&y.greeting&&r(b=>b.length===0?[{id:Ee,cursor:"",author:"agent",text:y.greeting}]:b)}).catch(()=>{}),()=>{m=!1}},[e]),(0,T.useEffect)(()=>e.subscribe?.({onMessage:m=>r(y=>ye(y,m)),onError:m=>u(m.error),onHealthy:()=>u(null)},{intervalMs:g}),[e,g]);let p=(0,T.useCallback)(()=>{let m=s.trim();if(!m||n)return;a(""),u(null),i(!0),d.current+=1;let y=`pending-${d.current}`,b={id:y,cursor:"",author:"client",text:m,pending:!0};r(c=>[...c,b]),e.sendMessage(m).then(c=>{i(!1),c.reply.trim()&&r(x=>x.some(I=>!I.pending&&I.author!=="client"&&I.text===c.reply)?x:(d.current+=1,[...x,{id:`pending-agent-${d.current}`,cursor:"",author:"agent",text:c.reply,pending:!0}]))}).catch(c=>{u(c instanceof Error?c.message:"send_failed"),i(!1),r(f=>f.filter(x=>x.id!==y)),a(f=>f||m)})},[s,n,e]);return{messages:o,input:s,setInput:a,send:p,sending:n,error:l}};0&&(module.exports={Chat,GRID_COLS,GRID_MAX_COLS,GRID_MAX_ROWS,HolaProvider,PortalConflict,bandOfKind,bandOfType,cellValue,createApiTransport,createHolaClient,createPortalData,createWidgetTransport,deliverableCellText,deliverableStatus,deriveFields,footprintOf,footprintWith,formatDeliverableDate,groupDeliverableVersions,inferSpec,isDeliverableChecked,mergeMessage,normalizeDeliverableColType,normalizeDeliverableItem,parseDashboardSpec,parseDeliverableItems,parseDeliverableTable,parseTableResponses,placeWidgets,publishedVersionOf,renderModel,setResponse,textDeltaOf,thinkingDeltaOf,toolEventOf,useArtifactUrl,useChat,useHolaClient,useThread});
8
+ `)}},u=async()=>{let d=await a.read();if(!d.done)return i+=n.decode(d.value,{stream:!0}),l(),u()};await u()};var ze=/\/+$/,_="/api/v1/end-user",ve=e=>{let t=e.baseUrl.replace(ze,""),o=()=>typeof e.token=="function"?e.token():e.token,r=n=>e.project?`${n}project=${encodeURIComponent(e.project)}`:"",s=async()=>({"content-type":"application/json",authorization:`Bearer ${await o()}`}),a=async n=>{let i=await fetch(`${t}${_}/chat${r("?")}`,{method:"POST",headers:await s(),body:JSON.stringify({message:n})});if(!i.ok)throw new Error(`hola: message failed (${i.status})`);return{reply:(await i.json()).reply??"",sessionId:"",artifacts:[]}};return{sessionId:()=>"",getInfo:async()=>x(`${t}${_}/chat/info${r("?")}`,await s()),sendMessage:a,streamMessage:async(n,i)=>{try{let l=await a(n);i.onText?.(l.reply),i.onComplete?.(l)}catch(l){i.onError?.(D(l))}},subscribe:(n,i)=>{let l=i?.since??"0",u=!1,d,m=i?.intervalMs??3e3,p=typeof document<"u",g=()=>p&&document.visibilityState==="hidden",y=!1,b=()=>{if(!u){if(g()){y=!0;return}d=setTimeout(c,m)}},c=async()=>{try{let P=await x(`${t}${_}/chat/thread?since=${encodeURIComponent(l)}${r("&")}`,await s());for(let I of P.messages)n.onMessage(I);l=P.cursor,n.onHealthy?.()}catch(P){n.onError?.(D(P))}b()},f=()=>{u||!y||g()||(y=!1,d&&clearTimeout(d),d=setTimeout(c,0))};p&&document.addEventListener("visibilitychange",f);let w=()=>{u=!0,d&&clearTimeout(d),p&&document.removeEventListener("visibilitychange",f)};return i?.signal?.addEventListener("abort",w),d=setTimeout(c,0),w},requestHuman:async()=>{await fetch(`${t}${_}/chat/request-human${r("?")}`,{method:"POST",headers:await s(),body:"{}"})}}};var L=require("react"),U=(e,t)=>{let[o,r]=(0,L.useState)("");return(0,L.useEffect)(()=>{if(!e){r("");return}let s=Uint8Array.from(atob(e),n=>n.charCodeAt(0)),a=URL.createObjectURL(new Blob([s],{type:t}));return r(a),()=>URL.revokeObjectURL(a)},[e,t]),o};var G=require("react");var F=require("react"),Re=require("react/jsx-runtime"),Te=(0,F.createContext)(null),ke=({client:e,children:t})=>(0,Re.jsx)(Te.Provider,{value:e,children:t}),N=()=>{let e=(0,F.useContext)(Te);if(!e)throw new Error("useHolaClient must be used within <HolaProvider>");return e};var v=require("react"),V=e=>{let[t,o]=(0,v.useState)([]),[r,s]=(0,v.useState)(""),[a,n]=(0,v.useState)(!1),[i,l]=(0,v.useState)(null),u=(0,v.useRef)(0),d=(0,v.useCallback)(()=>{let p=u.current;return u.current+=1,p},[]);(0,v.useEffect)(()=>{let p=!0;return e.getInfo().then(g=>{p&&g.greeting&&o([{id:d(),role:"assistant",text:g.greeting}])}).catch(()=>{}),()=>{p=!1}},[e,d]);let m=(0,v.useCallback)(()=>{let p=r.trim();if(!p||a)return;s(""),l(null),n(!0);let g=d(),y=d();o(c=>[...c,{id:g,role:"user",text:p},{id:y,role:"assistant",text:"",streaming:!0}]);let b=c=>{o(f=>f.map(w=>w.id===y?c(w):w))};e.streamMessage(p,{onText:c=>b(f=>({...f,text:f.text+c})),onComplete:c=>{b(f=>({...f,text:c.reply||f.text,artifacts:c.artifacts,streaming:!1})),n(!1)},onError:c=>{b(f=>({...f,streaming:!1})),l(c.error),n(!1)}}).catch(c=>{b(f=>({...f,streaming:!1})),l(c instanceof Error?c.message:"stream_failed"),n(!1)})},[r,a,e,d]);return{messages:t,input:r,setInput:s,send:m,sending:a,error:i}};var h=require("react/jsx-runtime"),k={root:{display:"flex",flexDirection:"column",height:"100%",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:14,color:"#111827"},log:{flex:1,overflowY:"auto",padding:12,display:"flex",flexDirection:"column",gap:8},user:{alignSelf:"flex-end",background:"#111827",color:"#ffffff",borderRadius:12,padding:"8px 12px",maxWidth:"80%",whiteSpace:"pre-wrap"},assistant:{alignSelf:"flex-start",background:"#f1f1f4",color:"#111827",borderRadius:12,padding:"8px 12px",maxWidth:"80%",whiteSpace:"pre-wrap"},artifacts:{display:"flex",flexDirection:"column",gap:6,marginTop:6},image:{maxHeight:220,borderRadius:8,border:"1px solid #e5e7eb"},link:{color:"#2563eb",textDecoration:"underline",wordBreak:"break-all"},error:{color:"#b91c1c",padding:"4px 12px",fontSize:13},form:{display:"flex",gap:8,borderTop:"1px solid #e5e7eb",padding:8},input:{flex:1,border:"1px solid #d1d5db",borderRadius:8,padding:"8px 10px",fontSize:14,outline:"none"},button:{border:"none",background:"#111827",color:"#ffffff",borderRadius:8,padding:"8px 14px",fontSize:14,cursor:"pointer"}},Je=({artifact:e})=>{let t=U(e.dataBase64??"",e.mimeType),o=e.url??t;return o?e.mimeType.startsWith("image/")?(0,h.jsx)("a",{href:o,rel:"noopener noreferrer",target:"_blank",children:(0,h.jsx)("img",{alt:e.filename,src:o,style:k.image})}):(0,h.jsx)("a",{download:e.filename,href:o,style:k.link,children:e.filename}):null},De=()=>{let e=N(),{messages:t,input:o,setInput:r,send:s,sending:a,error:n}=V(e),i=(0,G.useRef)(null);(0,G.useEffect)(()=>{let u=i.current;u&&(u.scrollTop=u.scrollHeight)},[t]);let l=u=>{u.preventDefault(),s()};return(0,h.jsxs)("div",{style:k.root,children:[(0,h.jsx)("div",{ref:i,style:k.log,children:t.map(u=>(0,h.jsxs)("div",{style:u.role==="user"?k.user:k.assistant,children:[u.text||(u.streaming?"\u2026":""),u.artifacts&&u.artifacts.length>0?(0,h.jsx)("div",{style:k.artifacts,children:u.artifacts.map(d=>(0,h.jsx)(Je,{artifact:d},d.filename))}):null]},u.id))}),n?(0,h.jsx)("div",{style:k.error,children:n}):null,(0,h.jsxs)("form",{onSubmit:l,style:k.form,children:[(0,h.jsx)("input",{"aria-label":"Message",onChange:u=>r(u.target.value),placeholder:"Type a message\u2026",style:k.input,value:o}),(0,h.jsx)("button",{disabled:a||o.trim().length===0,style:k.button,type:"submit",children:"Send"})]})]})};var qe=/\/+$/,j=e=>{let t=e.sessionId,o=e.baseUrl.replace(qe,""),r=n=>`${o}/endpoint/${encodeURIComponent(e.token)}${n}`,s={"content-type":"application/json"},a=(n,i)=>({url:r(n),headers:s,body:JSON.stringify({message:i,...t?{sessionId:t}:{},...e.identity?{externalUserId:e.identity.externalUserId,userHmac:e.identity.userHmac}:{}})});return{sessionId:()=>t,getInfo:()=>x(r("/config"),{}),sendMessage:async n=>{let i=await xe(a("/message",n));return t=i.sessionId,i},streamMessage:(n,i,l)=>we(a("/message/stream",n),i,u=>{t=u},l),subscribe:(n,i)=>{let l=i?.since??"0",u=!1,d,m=i?.intervalMs??3e3,p=async()=>{let y=t;if(y)try{let b=await x(r(`/messages?session=${encodeURIComponent(y)}&since=${encodeURIComponent(l)}`),{});for(let c of b.messages)n.onMessage(c);l=b.cursor,n.onHealthy?.()}catch(b){n.onError?.(D(b))}u||(d=setTimeout(p,m))},g=()=>{u=!0,d&&clearTimeout(d)};return i?.signal?.addEventListener("abort",g),d=setTimeout(p,0),g},requestHuman:async()=>{t&&await fetch(r("/request-human"),{method:"POST",headers:s,body:JSON.stringify({sessionId:t})})}}};var Ce=e=>"transport"in e?e.transport:j(e);var Xe=/^https?:\/\//i,Ke=/^\d{4}-\d{2}-\d{2}(?:[T ]|$)/,Ye=e=>e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase());function Qe(e){if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean";if(typeof e=="string"){if(Xe.test(e))return"url";if(Ke.test(e))return"date"}return"text"}function Y(e){let t=[],o=new Map;for(let r of e)for(let[s,a]of Object.entries(r.data??{})){if(a==null)continue;let n=o.get(s);n||(n=new Map,o.set(s,n),t.push(s));let i=Qe(a);n.set(i,(n.get(i)??0)+1)}return t.map(r=>{let s=o.get(r)??new Map,a="text",n=-1;for(let[i,l]of s)l>n&&(n=l,a=i);return{key:r,label:Ye(r),type:a}})}var Ze=e=>typeof e=="number"?e:Number(e)||0,Se=e=>/rate|position|rank|score|percent|avg/i.test(e),et=/posted|published|sent|completed|shipped|launched|_at|date/i,tt=new Set(["service","order","end_user_id"]);function Q(e,t){let o=e.filter(l=>!tt.has(l.key)),r=o.filter(l=>l.type==="number").slice(0,3),s=o.find(l=>l.key==="status")??o.find(l=>l.type==="select"),a=o.find(l=>l.type==="date"&&et.test(l.key))??o.find(l=>l.type==="date"),n=o.filter(l=>l.type==="number"&&!Se(l.key)).map(l=>({field:l,total:t.reduce((u,d)=>u+Ze(d.data[l.key]),0)})).sort((l,u)=>u.total-l.total).find(l=>l.total>0)?.field??null,i=[{type:"stat",label:"Items",agg:"count"}];for(let l of r){let u=Se(l.key);i.push({type:"stat",metric:l.key,agg:u?"avg":"sum",label:u?`Avg ${l.label.toLowerCase()}`:l.label})}return a&&i.push({type:"line",x:a.key,y:n?.key,agg:"sum",title:n?`${n.label} by day`:"Items by day"}),s&&i.push({type:"donut",groupBy:s.key,title:s.label}),i.push({type:"table",columns:o.map(l=>l.key)}),{version:1,widgets:i}}var Z=6,ee=6,te=4,Pe={stat:{w:1,h:1},chart:{w:2,h:2},block:{w:6,h:2}},nt=e=>Math.max(1,Math.min(6,Math.round(e))),rt=e=>Math.max(1,Math.min(4,Math.round(e)));function H(e){return e==="stat"?"stat":e==="series"||e==="donut"?"chart":"block"}function ne(e){return e==="stat"?"stat":e==="line"||e==="bar"||e==="donut"?"chart":"block"}function re(e){return Pe[e]}function B(e,t,o){let r=Pe[e];return{w:t===void 0?r.w:nt(t),h:o===void 0?r.h:rt(o)}}function z(e){let t=[],o=[],r=(n,i,l,u)=>{if(n<0||n+l>6)return!1;for(let d=0;d<u;d+=1){let m=o[i+d];if(m){for(let p=0;p<l;p+=1)if(m[n+p])return!1}}return!0},s=(n,i,l,u)=>{for(let d=0;d<u;d+=1){let m=o[i+d]??[];for(let p=0;p<l;p+=1)m[n+p]=!0;o[i+d]=m}},a=(n,i)=>{for(let l=0;;l+=1)for(let u=0;u+n<=6;u+=1)if(r(u,l,n,i))return{gx:u,gy:l}};for(let n of e){let i=B(H(n.kind),n.w,n.h),u=n.gx!==void 0&&n.gy!==void 0&&r(n.gx,n.gy,i.w,i.h)&&n.gx!==void 0&&n.gy!==void 0?{gx:n.gx,gy:n.gy}:a(i.w,i.h);s(u.gx,u.gy,i.w,i.h),t.push({widget:n,gx:u.gx,gy:u.gy,w:i.w,h:i.h})}return t}function oe(e){let t=[],o=[];for(let r of e)H(r.kind)==="block"?o.push(r):t.push(r);return{tiles:z(t),blocks:o}}var Ie=new Set(["service","order","end_user_id"]),He=e=>typeof e=="number"?e:Number(e)||0,We=e=>e==null?"":String(e);function Me(e,t){if(e==="count")return t.length;if(t.length===0)return 0;if(e==="last")return t[t.length-1]??0;if(e==="min")return Math.min(...t);if(e==="max")return Math.max(...t);let o=t.reduce((r,s)=>r+s,0);return e==="avg"?Math.round(o/t.length):o}function ot(e,t,o,r){let s=new Map;for(let a of e){let n=new Date(We(a.data[t]));if(Number.isNaN(n.getTime()))continue;let i=n.toISOString().slice(0,10),l=s.get(i)??[];l.push(o?He(a.data[o]):1),s.set(i,l)}return[...s.entries()].sort((a,n)=>a[0]<n[0]?-1:1).map(([a,n])=>({label:new Date(`${a}T00:00:00`).toLocaleDateString(void 0,{month:"short",day:"numeric"}),value:o?Me(r,n):n.length}))}function st(e,t){let o=new Map;for(let r of e){let s=We(r.data[t]).trim();s&&o.set(s,(o.get(s)??0)+1)}return[...o.entries()].sort((r,s)=>s[1]-r[1]).map(([r,s])=>({label:r,value:s}))}function it(e,t,o,r){switch(e.type){case"stat":{let s=e.metric?t.get(e.metric):void 0;if(e.metric&&!s)return null;if(!s)return{kind:"stat",label:e.label??"Items",value:r.length};let a=r.map(n=>He(n.data[s.key]));return{kind:"stat",label:e.label??s.label,value:Me(e.agg??"sum",a)}}case"line":case"bar":{if(!t.has(e.x)||e.y&&!t.has(e.y))return null;let s=ot(r,e.x,e.y,e.agg??"sum");return s.length<2?null:{kind:"series",draw:e.type,title:e.title??"By day",points:s}}case"donut":{if(!t.has(e.groupBy))return null;let s=st(r,e.groupBy);return s.length===0?null:{kind:"donut",title:e.title??t.get(e.groupBy)?.label??"Breakdown",points:s}}case"table":{let s=e.columns?e.columns.map(a=>t.get(a)).filter(a=>a!==void 0&&!Ie.has(a.key)):o;return s.length===0?null:{kind:"table",title:e.title,columns:s,rows:r}}case"text":return{kind:"text",title:e.title,body:e.body};default:return null}}function se(e,t,o){let r=t.filter(n=>!Ie.has(n.key)),s=new Map(t.map(n=>[n.key,n])),a=[];for(let n of e.widgets){let i=it(n,s,r,o);i&&a.push({...i,w:n.w,h:n.h,gx:n.gx,gy:n.gy})}return a}var at=new Set(["sum","avg","count","min","max","last"]),Ae=e=>typeof e=="string"&&at.has(e)?e:void 0,R=e=>typeof e=="string"&&e!==""?e:void 0,W=e=>typeof e=="number"&&e>=1?Math.min(6,Math.round(e)):void 0,M=e=>typeof e=="number"&&e>=1?Math.min(4,Math.round(e)):void 0,C=e=>typeof e=="number"&&e>=0?Math.round(e):void 0;function lt(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"stat":return{type:"stat",label:R(t.label),metric:R(t.metric),agg:Ae(t.agg),w:W(t.w),h:M(t.h),gx:C(t.gx),gy:C(t.gy)};case"line":case"bar":{let o=R(t.x);return o?{type:t.type,title:R(t.title),x:o,y:R(t.y),agg:Ae(t.agg),w:W(t.w),h:M(t.h),gx:C(t.gx),gy:C(t.gy)}:null}case"donut":{let o=R(t.groupBy);return o?{type:"donut",title:R(t.title),groupBy:o,w:W(t.w),h:M(t.h),gx:C(t.gx),gy:C(t.gy)}:null}case"table":{let o=Array.isArray(t.columns)?t.columns.filter(r=>typeof r=="string"):void 0;return{type:"table",title:R(t.title),columns:o,w:W(t.w),h:M(t.h),gx:C(t.gx),gy:C(t.gy)}}case"text":{let o=R(t.body);return o?{type:"text",title:R(t.title),body:o,w:W(t.w),h:M(t.h),gx:C(t.gx),gy:C(t.gy)}:null}default:return null}}function ie(e){let t=e;if(typeof e=="string"){if(e.trim()==="")return null;try{t=JSON.parse(e)}catch{return null}}if(typeof t!="object"||t===null)return null;let o=t.widgets;if(!Array.isArray(o))return null;let r=o.map(lt).filter(a=>a!==null);if(r.length===0)return null;let s=t.version;return{version:typeof s=="number"?s:1,title:R(t.title),widgets:r}}function J(e){if(typeof e=="string")return e?{kind:"file",value:e}:null;if(e&&typeof e=="object"){let t=e,o=typeof t.value=="string"?t.value:"",r=t.kind==="link"||t.kind==="text"||t.kind==="table"?t.kind:"file",s=typeof t.v=="number"&&t.v>=1?Math.floor(t.v):void 0;return o?{kind:r,value:o,...s?{v:s}:{}}:null}return null}function q(e){let t=new Map;for(let o of e){let r=o.v??1,s=t.get(r)??[];s.push(o),t.set(r,s)}return[...t.entries()].sort(([o],[r])=>o-r).map(([o,r])=>({v:o,items:r}))}function ae(e){let t=e.files;if(typeof t=="string"&&t.trim()!=="")try{let r=JSON.parse(t);if(Array.isArray(r))return r.map(J).filter(s=>s!==null)}catch{}let o=String(e.file??"");return o?[{kind:"file",value:o}]:[]}function le(e,t,o){let s=(q(e).find(n=>n.v===t)?.items??[]).filter(n=>n.kind==="file").map(n=>n.value),a=s.map(n=>o.get(n)??"");return s.length===0||a.some(n=>n==="")?"awaiting":a.some(n=>n==="revise")?"revise":"accepted"}function ue(e){return Number(e.published_version)||0}function X(e){return e==="number"||e==="date"||e==="boolean"||e==="select"||e==="url"?e:e==="link"?"url":e==="checkbox"?"boolean":"text"}function de(e){try{let t=JSON.parse(e);if(Array.isArray(t.columns)&&Array.isArray(t.rows)&&t.columns.length){let o=t.columns.map((a,n)=>({key:typeof a.key=="string"&&a.key?a.key:typeof a.id=="string"&&a.id?a.id:`column_${n+1}`,label:typeof a.label=="string"?a.label:"",type:X(a.type),...a.clientEditable===!0?{clientEditable:!0}:{}})),r=t.rows.map((a,n)=>({id:typeof a.id=="string"&&a.id?a.id:`row_${n}`,cells:a.cells&&typeof a.cells=="object"?a.cells:{}})),s=typeof t.name=="string"?t.name:void 0;return{columns:o,rows:r,...s?{name:s}:{}}}}catch{}return null}function pe(e){return e==null?"":String(e)}function ce(e){return e===!0||e==="true"||e==="1"||e==="yes"||e==="\u2713"}function ge(e){if(typeof e!="string"||e.trim()==="")return{};try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function me(e,t,o){if(e.clientEditable){let r=o[t.id];if(r&&e.key in r)return r[e.key]}return t.cells[e.key]}function fe(e,t,o,r){return{...e,[t]:{...e[t]??{},[o]:r}}}function ye(e){let t=new Date(`${e}T00:00:00`);return Number.isNaN(t.getTime())?e:t.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var ut=/\/+$/,S="/api/v1/end-user",A=class extends Error{constructor(t){super(t),this.name="PortalConflict"}};function dt(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}var Ee=e=>{let t=e.baseUrl.replace(ut,""),o=()=>typeof e.token=="function"?e.token():e.token,r=async()=>({"content-type":"application/json",authorization:`Bearer ${await o()}`}),s=async(n,i)=>{try{let l=await fetch(`${t}${S}${n}`,{method:i.method,headers:await r(),...i.body===void 0?{}:{body:JSON.stringify(i.body)}});if(l.status===409){let u=await l.json().catch(()=>({}));throw new A(u.message??"Someone else saved this first.")}if(!l.ok){let u=await l.text().catch(()=>""),d=`${i.method} ${n} \u2192 ${String(l.status)}`;try{let m=JSON.parse(u);m.message&&(d=m.message)}catch{d=u?`${d}: ${u}`:d}throw D(new Error(d))}return await l.json()}catch(l){throw D(l)}},a=n=>`/tables/${encodeURIComponent(n)}`;return{listTables:async()=>(await x(`${t}${S}/tables`,await r())).tables,listRows:async(n,i)=>await x(`${t}${S}${a(n)}/rows?limit=${String(i??100)}`,await r()),insertRow:async(n,i)=>{let{rowIds:l}=await s(`${a(n)}/rows`,{method:"POST",body:{rows:[i]}}),u=l[0];if(!u)throw D(new Error("The row was not created."));return u},patchRow:async(n,i,l)=>(await s(`${a(n)}/rows/${encodeURIComponent(i)}`,{method:"PATCH",body:l})).updated,deleteRow:async(n,i)=>(await s(`/${encodeURIComponent(n)}/${encodeURIComponent(i)}`,{method:"DELETE"})).deleted,listFiles:async()=>(await x(`${t}${S}/tables/files/rows?limit=200`,await r())).rows.map(i=>({id:i.rowId,filename:String(i.data.filename??""),source:String(i.data.source??"client"),campaign:String(i.data.campaign??""),size:typeof i.data.size=="number"?i.data.size:0,createdAt:i.createdAt})),uploadFile:async(n,i)=>{let l=new Uint8Array(await n.arrayBuffer());return await s("/files",{method:"POST",body:{filename:n.name,mime:n.type||"application/octet-stream",data:dt(l),...i===void 0?{}:{message:i}}})},fileLink:async n=>await x(`${t}${S}/files/${encodeURIComponent(n)}/url`,await r()),deleteFile:async n=>(await s(`/files/${encodeURIComponent(n)}`,{method:"DELETE"})).deleted,listDocuments:async()=>(await x(`${t}${S}/documents`,await r())).documents,readDocument:async n=>(await x(`${t}${S}/documents/${encodeURIComponent(n)}`,await r())).document,saveDocument:async(n,i)=>await s(`/documents/${encodeURIComponent(n)}`,{method:"PATCH",body:i})}};var T=require("react"),$e="greeting";function be(e,t){if(e.some(a=>a.id===t.id))return e;let o=e.filter(a=>a.id!==$e),r=a=>a.author==="client"==(t.author==="client");return[...o.filter(a=>!(a.pending&&r(a)&&a.text===t.text)),t]}var Oe=(e,t)=>{let[o,r]=(0,T.useState)([]),[s,a]=(0,T.useState)(""),[n,i]=(0,T.useState)(!1),[l,u]=(0,T.useState)(null),d=(0,T.useRef)(0),m=t?.pollMs??2e3;(0,T.useEffect)(()=>{let g=!0;return e.getInfo().then(y=>{g&&y.greeting&&r(b=>b.length===0?[{id:$e,cursor:"",author:"agent",text:y.greeting}]:b)}).catch(()=>{}),()=>{g=!1}},[e]),(0,T.useEffect)(()=>e.subscribe?.({onMessage:g=>r(y=>be(y,g)),onError:g=>u(g.error),onHealthy:()=>u(null)},{intervalMs:m}),[e,m]);let p=(0,T.useCallback)(()=>{let g=s.trim();if(!g||n)return;a(""),u(null),i(!0),d.current+=1;let y=`pending-${d.current}`,b={id:y,cursor:"",author:"client",text:g,pending:!0};r(c=>[...c,b]),e.sendMessage(g).then(c=>{i(!1),c.reply.trim()&&r(w=>w.some(I=>!I.pending&&I.author!=="client"&&I.text===c.reply)?w:(d.current+=1,[...w,{id:`pending-agent-${d.current}`,cursor:"",author:"agent",text:c.reply,pending:!0}]))}).catch(c=>{u(c instanceof Error?c.message:"send_failed"),i(!1),r(f=>f.filter(w=>w.id!==y)),a(f=>f||g)})},[s,n,e]);return{messages:o,input:s,setInput:a,send:p,sending:n,error:l}};0&&(module.exports={Chat,GRID_COLS,GRID_MAX_COLS,GRID_MAX_ROWS,HolaProvider,PortalConflict,bandOfKind,bandOfType,cellValue,createApiTransport,createHolaClient,createPortalData,createWidgetTransport,deliverableCellText,deliverableStatus,deriveFields,footprintOf,footprintWith,formatDeliverableDate,groupDeliverableVersions,inferSpec,isDeliverableChecked,mergeMessage,normalizeDeliverableColType,normalizeDeliverableItem,parseDashboardSpec,parseDeliverableItems,parseDeliverableTable,parseTableResponses,placeWidgets,publishedVersionOf,renderModel,setResponse,splitLayout,textDeltaOf,thinkingDeltaOf,toolEventOf,useArtifactUrl,useChat,useHolaClient,useThread});
package/dist/index.d.cts CHANGED
@@ -460,6 +460,19 @@ interface PlacedWidget {
460
460
  * so a legacy spec (no positions) and a positioned one both render stably, and a stale position that
461
461
  * now overlaps (e.g. after a neighbour grew) falls back to a free slot instead of stacking. */
462
462
  declare function placeWidgets(resolved: ResolvedWidget[]): PlacedWidget[];
463
+ /** A dashboard split into the two things that lay out differently: square TILES (stats + charts) that
464
+ * pack into the fixed grid, and full-width BLOCKS (tables + notes) that stack UNDER the grid at their
465
+ * content height. A table's height depends on its rows, not the column width, so it can't share the
466
+ * square-cell grid without leaving slack — it flows below instead, exactly as tall as its content. */
467
+ interface DashboardLayout {
468
+ /** Stats + charts, placed on the fixed grid. */
469
+ tiles: PlacedWidget[];
470
+ /** Tables + notes, full-width and content-height, in spec order (top to bottom). */
471
+ blocks: ResolvedWidget[];
472
+ }
473
+ /** Split resolved widgets into grid tiles and stacked full-width blocks (see {@link DashboardLayout}).
474
+ * Every surface (portal, console) renders these the same way, so a dashboard reads identically. */
475
+ declare function splitLayout(resolved: ResolvedWidget[]): DashboardLayout;
463
476
 
464
477
  type DeliverableItemKind = "file" | "link" | "text" | "table";
465
478
  type DeliverableItem = {
@@ -583,4 +596,4 @@ declare const useThread: (client: HolaClient, options?: {
583
596
  pollMs?: number;
584
597
  }) => UseThread;
585
598
 
586
- export { type Agg, type ApiTransportConfig, type Band, type ChartView, Chat, type ChatMessage, type CreateHolaClientOptions, type DashboardSpec, type DeliverableColType, type DeliverableColumn, type DeliverableItem, type DeliverableItemKind, type DeliverableReviewState, type DeliverableRow, type DeliverableTable, type DeliverableVersion, type DonutWidget, GRID_COLS, GRID_MAX_COLS, GRID_MAX_ROWS, type HolaArtifact, type HolaAuthor, type HolaClient, type HolaCompletion, type HolaEmployeeInfo, type HolaError, type HolaIdentity, type HolaMessage, HolaProvider, type HolaStreamHandlers, type HolaSubscribeHandlers, type HolaSubscribeOptions, type HolaToolEvent, type HolaTransport, type PlacedWidget, type Point, PortalConflict, type PortalData, type PortalDocument, type PortalDocumentSummary, type PortalField, type PortalFile, type PortalRow, type PortalRowPage, type PortalTable, type ResolvedWidget, type SeriesWidget, type StatView, type StatWidget, type TableResponses, type TableWidget, type TextWidget, type ThreadMessage, type UseChat, type UseThread, type Widget, type WidgetTransportConfig, type WidgetType, bandOfKind, bandOfType, cellValue, createApiTransport, createHolaClient, createPortalData, createWidgetTransport, deliverableCellText, deliverableStatus, deriveFields, footprintOf, footprintWith, formatDeliverableDate, groupDeliverableVersions, inferSpec, isDeliverableChecked, mergeMessage, normalizeDeliverableColType, normalizeDeliverableItem, parseDashboardSpec, parseDeliverableItems, parseDeliverableTable, parseTableResponses, placeWidgets, publishedVersionOf, renderModel, setResponse, textDeltaOf, thinkingDeltaOf, toolEventOf, useArtifactUrl, useChat, useHolaClient, useThread };
599
+ export { type Agg, type ApiTransportConfig, type Band, type ChartView, Chat, type ChatMessage, type CreateHolaClientOptions, type DashboardLayout, type DashboardSpec, type DeliverableColType, type DeliverableColumn, type DeliverableItem, type DeliverableItemKind, type DeliverableReviewState, type DeliverableRow, type DeliverableTable, type DeliverableVersion, type DonutWidget, GRID_COLS, GRID_MAX_COLS, GRID_MAX_ROWS, type HolaArtifact, type HolaAuthor, type HolaClient, type HolaCompletion, type HolaEmployeeInfo, type HolaError, type HolaIdentity, type HolaMessage, HolaProvider, type HolaStreamHandlers, type HolaSubscribeHandlers, type HolaSubscribeOptions, type HolaToolEvent, type HolaTransport, type PlacedWidget, type Point, PortalConflict, type PortalData, type PortalDocument, type PortalDocumentSummary, type PortalField, type PortalFile, type PortalRow, type PortalRowPage, type PortalTable, type ResolvedWidget, type SeriesWidget, type StatView, type StatWidget, type TableResponses, type TableWidget, type TextWidget, type ThreadMessage, type UseChat, type UseThread, type Widget, type WidgetTransportConfig, type WidgetType, bandOfKind, bandOfType, cellValue, createApiTransport, createHolaClient, createPortalData, createWidgetTransport, deliverableCellText, deliverableStatus, deriveFields, footprintOf, footprintWith, formatDeliverableDate, groupDeliverableVersions, inferSpec, isDeliverableChecked, mergeMessage, normalizeDeliverableColType, normalizeDeliverableItem, parseDashboardSpec, parseDeliverableItems, parseDeliverableTable, parseTableResponses, placeWidgets, publishedVersionOf, renderModel, setResponse, splitLayout, textDeltaOf, thinkingDeltaOf, toolEventOf, useArtifactUrl, useChat, useHolaClient, useThread };
package/dist/index.d.ts CHANGED
@@ -460,6 +460,19 @@ interface PlacedWidget {
460
460
  * so a legacy spec (no positions) and a positioned one both render stably, and a stale position that
461
461
  * now overlaps (e.g. after a neighbour grew) falls back to a free slot instead of stacking. */
462
462
  declare function placeWidgets(resolved: ResolvedWidget[]): PlacedWidget[];
463
+ /** A dashboard split into the two things that lay out differently: square TILES (stats + charts) that
464
+ * pack into the fixed grid, and full-width BLOCKS (tables + notes) that stack UNDER the grid at their
465
+ * content height. A table's height depends on its rows, not the column width, so it can't share the
466
+ * square-cell grid without leaving slack — it flows below instead, exactly as tall as its content. */
467
+ interface DashboardLayout {
468
+ /** Stats + charts, placed on the fixed grid. */
469
+ tiles: PlacedWidget[];
470
+ /** Tables + notes, full-width and content-height, in spec order (top to bottom). */
471
+ blocks: ResolvedWidget[];
472
+ }
473
+ /** Split resolved widgets into grid tiles and stacked full-width blocks (see {@link DashboardLayout}).
474
+ * Every surface (portal, console) renders these the same way, so a dashboard reads identically. */
475
+ declare function splitLayout(resolved: ResolvedWidget[]): DashboardLayout;
463
476
 
464
477
  type DeliverableItemKind = "file" | "link" | "text" | "table";
465
478
  type DeliverableItem = {
@@ -583,4 +596,4 @@ declare const useThread: (client: HolaClient, options?: {
583
596
  pollMs?: number;
584
597
  }) => UseThread;
585
598
 
586
- export { type Agg, type ApiTransportConfig, type Band, type ChartView, Chat, type ChatMessage, type CreateHolaClientOptions, type DashboardSpec, type DeliverableColType, type DeliverableColumn, type DeliverableItem, type DeliverableItemKind, type DeliverableReviewState, type DeliverableRow, type DeliverableTable, type DeliverableVersion, type DonutWidget, GRID_COLS, GRID_MAX_COLS, GRID_MAX_ROWS, type HolaArtifact, type HolaAuthor, type HolaClient, type HolaCompletion, type HolaEmployeeInfo, type HolaError, type HolaIdentity, type HolaMessage, HolaProvider, type HolaStreamHandlers, type HolaSubscribeHandlers, type HolaSubscribeOptions, type HolaToolEvent, type HolaTransport, type PlacedWidget, type Point, PortalConflict, type PortalData, type PortalDocument, type PortalDocumentSummary, type PortalField, type PortalFile, type PortalRow, type PortalRowPage, type PortalTable, type ResolvedWidget, type SeriesWidget, type StatView, type StatWidget, type TableResponses, type TableWidget, type TextWidget, type ThreadMessage, type UseChat, type UseThread, type Widget, type WidgetTransportConfig, type WidgetType, bandOfKind, bandOfType, cellValue, createApiTransport, createHolaClient, createPortalData, createWidgetTransport, deliverableCellText, deliverableStatus, deriveFields, footprintOf, footprintWith, formatDeliverableDate, groupDeliverableVersions, inferSpec, isDeliverableChecked, mergeMessage, normalizeDeliverableColType, normalizeDeliverableItem, parseDashboardSpec, parseDeliverableItems, parseDeliverableTable, parseTableResponses, placeWidgets, publishedVersionOf, renderModel, setResponse, textDeltaOf, thinkingDeltaOf, toolEventOf, useArtifactUrl, useChat, useHolaClient, useThread };
599
+ export { type Agg, type ApiTransportConfig, type Band, type ChartView, Chat, type ChatMessage, type CreateHolaClientOptions, type DashboardLayout, type DashboardSpec, type DeliverableColType, type DeliverableColumn, type DeliverableItem, type DeliverableItemKind, type DeliverableReviewState, type DeliverableRow, type DeliverableTable, type DeliverableVersion, type DonutWidget, GRID_COLS, GRID_MAX_COLS, GRID_MAX_ROWS, type HolaArtifact, type HolaAuthor, type HolaClient, type HolaCompletion, type HolaEmployeeInfo, type HolaError, type HolaIdentity, type HolaMessage, HolaProvider, type HolaStreamHandlers, type HolaSubscribeHandlers, type HolaSubscribeOptions, type HolaToolEvent, type HolaTransport, type PlacedWidget, type Point, PortalConflict, type PortalData, type PortalDocument, type PortalDocumentSummary, type PortalField, type PortalFile, type PortalRow, type PortalRowPage, type PortalTable, type ResolvedWidget, type SeriesWidget, type StatView, type StatWidget, type TableResponses, type TableWidget, type TextWidget, type ThreadMessage, type UseChat, type UseThread, type Widget, type WidgetTransportConfig, type WidgetType, bandOfKind, bandOfType, cellValue, createApiTransport, createHolaClient, createPortalData, createWidgetTransport, deliverableCellText, deliverableStatus, deriveFields, footprintOf, footprintWith, formatDeliverableDate, groupDeliverableVersions, inferSpec, isDeliverableChecked, mergeMessage, normalizeDeliverableColType, normalizeDeliverableItem, parseDashboardSpec, parseDeliverableItems, parseDeliverableTable, parseTableResponses, placeWidgets, publishedVersionOf, renderModel, setResponse, splitLayout, textDeltaOf, thinkingDeltaOf, toolEventOf, useArtifactUrl, useChat, useHolaClient, useThread };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  'use client'
2
- var J=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="message_update"?t.assistantMessageEvent??null:null},E=e=>{let t=J(e);return t?.type==="text_delta"&&typeof t.delta=="string"?t.delta:null},$=e=>{let t=J(e);return t?.type==="thinking_delta"&&typeof t.delta=="string"?t.delta:null},O=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="tool_execution_start"&&t.toolCallId?{phase:"start",id:t.toolCallId,name:t.toolName}:t.type==="tool_execution_end"&&t.toolCallId?{phase:"end",id:t.toolCallId,isError:t.isError}:null};var Pe=/^ /,T=e=>{if(e&&typeof e=="object"){let t=e,o=typeof t.error=="string"?t.error:"request_failed";return typeof t.retryable=="boolean"?{error:o,retryable:t.retryable}:{error:o}}return{error:"request_failed"}},Ie=e=>{let t="message",o=[];for(let r of e.split(`
3
- `))r.startsWith(":")||(r.startsWith("event:")?t=r.slice(6).trim():r.startsWith("data:")&&o.push(r.slice(5).replace(Pe,"")));return o.length>0?{event:t,data:o.join(`
4
- `)}:null},He=(e,t,o)=>{let r;try{r=JSON.parse(e.data)}catch{return}if(e.event==="session"){let s=r.sessionId;s&&(o(s),t.onSession?.(s));return}if(e.event==="turn_event"){t.onEvent?.(r);let s=E(r);s&&t.onText?.(s);let a=$(r);a&&t.onThinking?.(a);let n=O(r);n&&t.onTool?.(n);return}if(e.event==="chat_completed"){let s=r;o(s.sessionId),t.onComplete?.(s);return}e.event==="chat_error"&&t.onError?.(T(r))},h=async(e,t)=>{let o=await fetch(e,{headers:t});if(!o.ok)throw new Error(`hola: request failed (${o.status})`);return await o.json()},q=async e=>{let t=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body});if(!t.ok)throw new Error(`hola: message failed (${t.status})`);return await t.json()},X=async(e,t,o,r)=>{let s=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body,signal:r});if(!(s.ok&&s.body)){t.onError?.({error:`stream_failed_${s.status}`});return}let a=s.body.getReader(),n=new TextDecoder,i="",l=()=>{let d=i.indexOf(`
2
+ var q=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="message_update"?t.assistantMessageEvent??null:null},$=e=>{let t=q(e);return t?.type==="text_delta"&&typeof t.delta=="string"?t.delta:null},O=e=>{let t=q(e);return t?.type==="thinking_delta"&&typeof t.delta=="string"?t.delta:null},_=e=>{if(!e||typeof e!="object")return null;let t=e;return t.type==="tool_execution_start"&&t.toolCallId?{phase:"start",id:t.toolCallId,name:t.toolName}:t.type==="tool_execution_end"&&t.toolCallId?{phase:"end",id:t.toolCallId,isError:t.isError}:null};var Ie=/^ /,T=e=>{if(e&&typeof e=="object"){let t=e,o=typeof t.error=="string"?t.error:"request_failed";return typeof t.retryable=="boolean"?{error:o,retryable:t.retryable}:{error:o}}return{error:"request_failed"}},He=e=>{let t="message",o=[];for(let r of e.split(`
3
+ `))r.startsWith(":")||(r.startsWith("event:")?t=r.slice(6).trim():r.startsWith("data:")&&o.push(r.slice(5).replace(Ie,"")));return o.length>0?{event:t,data:o.join(`
4
+ `)}:null},We=(e,t,o)=>{let r;try{r=JSON.parse(e.data)}catch{return}if(e.event==="session"){let s=r.sessionId;s&&(o(s),t.onSession?.(s));return}if(e.event==="turn_event"){t.onEvent?.(r);let s=$(r);s&&t.onText?.(s);let a=O(r);a&&t.onThinking?.(a);let n=_(r);n&&t.onTool?.(n);return}if(e.event==="chat_completed"){let s=r;o(s.sessionId),t.onComplete?.(s);return}e.event==="chat_error"&&t.onError?.(T(r))},h=async(e,t)=>{let o=await fetch(e,{headers:t});if(!o.ok)throw new Error(`hola: request failed (${o.status})`);return await o.json()},X=async e=>{let t=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body});if(!t.ok)throw new Error(`hola: message failed (${t.status})`);return await t.json()},K=async(e,t,o,r)=>{let s=await fetch(e.url,{method:"POST",headers:e.headers,body:e.body,signal:r});if(!(s.ok&&s.body)){t.onError?.({error:`stream_failed_${s.status}`});return}let a=s.body.getReader(),n=new TextDecoder,i="",l=()=>{let d=i.indexOf(`
5
5
 
6
- `);for(;d!==-1;){let g=i.slice(0,d);i=i.slice(d+2);let p=Ie(g);p&&He(p,t,o),d=i.indexOf(`
6
+ `);for(;d!==-1;){let m=i.slice(0,d);i=i.slice(d+2);let p=He(m);p&&We(p,t,o),d=i.indexOf(`
7
7
 
8
- `)}},u=async()=>{let d=await a.read();if(!d.done)return i+=n.decode(d.value,{stream:!0}),l(),u()};await u()};var Me=/\/+$/,H="/api/v1/end-user",We=e=>{let t=e.baseUrl.replace(Me,""),o=()=>typeof e.token=="function"?e.token():e.token,r=n=>e.project?`${n}project=${encodeURIComponent(e.project)}`:"",s=async()=>({"content-type":"application/json",authorization:`Bearer ${await o()}`}),a=async n=>{let i=await fetch(`${t}${H}/chat${r("?")}`,{method:"POST",headers:await s(),body:JSON.stringify({message:n})});if(!i.ok)throw new Error(`hola: message failed (${i.status})`);return{reply:(await i.json()).reply??"",sessionId:"",artifacts:[]}};return{sessionId:()=>"",getInfo:async()=>h(`${t}${H}/chat/info${r("?")}`,await s()),sendMessage:a,streamMessage:async(n,i)=>{try{let l=await a(n);i.onText?.(l.reply),i.onComplete?.(l)}catch(l){i.onError?.(T(l))}},subscribe:(n,i)=>{let l=i?.since??"0",u=!1,d,g=i?.intervalMs??3e3,p=typeof document<"u",m=()=>p&&document.visibilityState==="hidden",y=!1,b=()=>{if(!u){if(m()){y=!0;return}d=setTimeout(c,g)}},c=async()=>{try{let C=await h(`${t}${H}/chat/thread?since=${encodeURIComponent(l)}${r("&")}`,await s());for(let S of C.messages)n.onMessage(S);l=C.cursor,n.onHealthy?.()}catch(C){n.onError?.(T(C))}b()},f=()=>{u||!y||m()||(y=!1,d&&clearTimeout(d),d=setTimeout(c,0))};p&&document.addEventListener("visibilitychange",f);let w=()=>{u=!0,d&&clearTimeout(d),p&&document.removeEventListener("visibilitychange",f)};return i?.signal?.addEventListener("abort",w),d=setTimeout(c,0),w},requestHuman:async()=>{await fetch(`${t}${H}/chat/request-human${r("?")}`,{method:"POST",headers:await s(),body:"{}"})}}};import{useEffect as Ae,useState as Ee}from"react";var _=(e,t)=>{let[o,r]=Ee("");return Ae(()=>{if(!e){r("");return}let s=Uint8Array.from(atob(e),n=>n.charCodeAt(0)),a=URL.createObjectURL(new Blob([s],{type:t}));return r(a),()=>URL.revokeObjectURL(a)},[e,t]),o};import{useEffect as Ne,useRef as Ve}from"react";import{createContext as $e,useContext as Oe}from"react";import{jsx as Ue}from"react/jsx-runtime";var K=$e(null),_e=({client:e,children:t})=>Ue(K.Provider,{value:e,children:t}),U=()=>{let e=Oe(K);if(!e)throw new Error("useHolaClient must be used within <HolaProvider>");return e};import{useCallback as Y,useEffect as Fe,useRef as Le,useState as M}from"react";var F=e=>{let[t,o]=M([]),[r,s]=M(""),[a,n]=M(!1),[i,l]=M(null),u=Le(0),d=Y(()=>{let p=u.current;return u.current+=1,p},[]);Fe(()=>{let p=!0;return e.getInfo().then(m=>{p&&m.greeting&&o([{id:d(),role:"assistant",text:m.greeting}])}).catch(()=>{}),()=>{p=!1}},[e,d]);let g=Y(()=>{let p=r.trim();if(!p||a)return;s(""),l(null),n(!0);let m=d(),y=d();o(c=>[...c,{id:m,role:"user",text:p},{id:y,role:"assistant",text:"",streaming:!0}]);let b=c=>{o(f=>f.map(w=>w.id===y?c(w):w))};e.streamMessage(p,{onText:c=>b(f=>({...f,text:f.text+c})),onComplete:c=>{b(f=>({...f,text:c.reply||f.text,artifacts:c.artifacts,streaming:!1})),n(!1)},onError:c=>{b(f=>({...f,streaming:!1})),l(c.error),n(!1)}}).catch(c=>{b(f=>({...f,streaming:!1})),l(c instanceof Error?c.message:"stream_failed"),n(!1)})},[r,a,e,d]);return{messages:t,input:r,setInput:s,send:g,sending:a,error:i}};import{jsx as R,jsxs as L}from"react/jsx-runtime";var x={root:{display:"flex",flexDirection:"column",height:"100%",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:14,color:"#111827"},log:{flex:1,overflowY:"auto",padding:12,display:"flex",flexDirection:"column",gap:8},user:{alignSelf:"flex-end",background:"#111827",color:"#ffffff",borderRadius:12,padding:"8px 12px",maxWidth:"80%",whiteSpace:"pre-wrap"},assistant:{alignSelf:"flex-start",background:"#f1f1f4",color:"#111827",borderRadius:12,padding:"8px 12px",maxWidth:"80%",whiteSpace:"pre-wrap"},artifacts:{display:"flex",flexDirection:"column",gap:6,marginTop:6},image:{maxHeight:220,borderRadius:8,border:"1px solid #e5e7eb"},link:{color:"#2563eb",textDecoration:"underline",wordBreak:"break-all"},error:{color:"#b91c1c",padding:"4px 12px",fontSize:13},form:{display:"flex",gap:8,borderTop:"1px solid #e5e7eb",padding:8},input:{flex:1,border:"1px solid #d1d5db",borderRadius:8,padding:"8px 10px",fontSize:14,outline:"none"},button:{border:"none",background:"#111827",color:"#ffffff",borderRadius:8,padding:"8px 14px",fontSize:14,cursor:"pointer"}},Ge=({artifact:e})=>{let t=_(e.dataBase64??"",e.mimeType),o=e.url??t;return o?e.mimeType.startsWith("image/")?R("a",{href:o,rel:"noopener noreferrer",target:"_blank",children:R("img",{alt:e.filename,src:o,style:x.image})}):R("a",{download:e.filename,href:o,style:x.link,children:e.filename}):null},je=()=>{let e=U(),{messages:t,input:o,setInput:r,send:s,sending:a,error:n}=F(e),i=Ve(null);Ne(()=>{let u=i.current;u&&(u.scrollTop=u.scrollHeight)},[t]);let l=u=>{u.preventDefault(),s()};return L("div",{style:x.root,children:[R("div",{ref:i,style:x.log,children:t.map(u=>L("div",{style:u.role==="user"?x.user:x.assistant,children:[u.text||(u.streaming?"\u2026":""),u.artifacts&&u.artifacts.length>0?R("div",{style:x.artifacts,children:u.artifacts.map(d=>R(Ge,{artifact:d},d.filename))}):null]},u.id))}),n?R("div",{style:x.error,children:n}):null,L("form",{onSubmit:l,style:x.form,children:[R("input",{"aria-label":"Message",onChange:u=>r(u.target.value),placeholder:"Type a message\u2026",style:x.input,value:o}),R("button",{disabled:a||o.trim().length===0,style:x.button,type:"submit",children:"Send"})]})]})};var Be=/\/+$/,N=e=>{let t=e.sessionId,o=e.baseUrl.replace(Be,""),r=n=>`${o}/endpoint/${encodeURIComponent(e.token)}${n}`,s={"content-type":"application/json"},a=(n,i)=>({url:r(n),headers:s,body:JSON.stringify({message:i,...t?{sessionId:t}:{},...e.identity?{externalUserId:e.identity.externalUserId,userHmac:e.identity.userHmac}:{}})});return{sessionId:()=>t,getInfo:()=>h(r("/config"),{}),sendMessage:async n=>{let i=await q(a("/message",n));return t=i.sessionId,i},streamMessage:(n,i,l)=>X(a("/message/stream",n),i,u=>{t=u},l),subscribe:(n,i)=>{let l=i?.since??"0",u=!1,d,g=i?.intervalMs??3e3,p=async()=>{let y=t;if(y)try{let b=await h(r(`/messages?session=${encodeURIComponent(y)}&since=${encodeURIComponent(l)}`),{});for(let c of b.messages)n.onMessage(c);l=b.cursor,n.onHealthy?.()}catch(b){n.onError?.(T(b))}u||(d=setTimeout(p,g))},m=()=>{u=!0,d&&clearTimeout(d)};return i?.signal?.addEventListener("abort",m),d=setTimeout(p,0),m},requestHuman:async()=>{t&&await fetch(r("/request-human"),{method:"POST",headers:s,body:JSON.stringify({sessionId:t})})}}};var ze=e=>"transport"in e?e.transport:N(e);var Je=/^https?:\/\//i,qe=/^\d{4}-\d{2}-\d{2}(?:[T ]|$)/,Xe=e=>e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase());function Ke(e){if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean";if(typeof e=="string"){if(Je.test(e))return"url";if(qe.test(e))return"date"}return"text"}function Q(e){let t=[],o=new Map;for(let r of e)for(let[s,a]of Object.entries(r.data??{})){if(a==null)continue;let n=o.get(s);n||(n=new Map,o.set(s,n),t.push(s));let i=Ke(a);n.set(i,(n.get(i)??0)+1)}return t.map(r=>{let s=o.get(r)??new Map,a="text",n=-1;for(let[i,l]of s)l>n&&(n=l,a=i);return{key:r,label:Xe(r),type:a}})}var Ye=e=>typeof e=="number"?e:Number(e)||0,Z=e=>/rate|position|rank|score|percent|avg/i.test(e),Qe=/posted|published|sent|completed|shipped|launched|_at|date/i,Ze=new Set(["service","order","end_user_id"]);function ee(e,t){let o=e.filter(l=>!Ze.has(l.key)),r=o.filter(l=>l.type==="number").slice(0,3),s=o.find(l=>l.key==="status")??o.find(l=>l.type==="select"),a=o.find(l=>l.type==="date"&&Qe.test(l.key))??o.find(l=>l.type==="date"),n=o.filter(l=>l.type==="number"&&!Z(l.key)).map(l=>({field:l,total:t.reduce((u,d)=>u+Ye(d.data[l.key]),0)})).sort((l,u)=>u.total-l.total).find(l=>l.total>0)?.field??null,i=[{type:"stat",label:"Items",agg:"count"}];for(let l of r){let u=Z(l.key);i.push({type:"stat",metric:l.key,agg:u?"avg":"sum",label:u?`Avg ${l.label.toLowerCase()}`:l.label})}return a&&i.push({type:"line",x:a.key,y:n?.key,agg:"sum",title:n?`${n.label} by day`:"Items by day"}),s&&i.push({type:"donut",groupBy:s.key,title:s.label}),i.push({type:"table",columns:o.map(l=>l.key)}),{version:1,widgets:i}}var te=6,ne=6,re=4,oe={stat:{w:1,h:1},chart:{w:2,h:2},block:{w:6,h:4}},et=e=>Math.max(1,Math.min(6,Math.round(e))),tt=e=>Math.max(1,Math.min(4,Math.round(e)));function V(e){return e==="stat"?"stat":e==="series"||e==="donut"?"chart":"block"}function se(e){return e==="stat"?"stat":e==="line"||e==="bar"||e==="donut"?"chart":"block"}function ie(e){return oe[e]}function G(e,t,o){let r=oe[e];return{w:t===void 0?r.w:et(t),h:o===void 0?r.h:tt(o)}}function ae(e){let t=[],o=[],r=(n,i,l,u)=>{if(n<0||n+l>6)return!1;for(let d=0;d<u;d+=1){let g=o[i+d];if(g){for(let p=0;p<l;p+=1)if(g[n+p])return!1}}return!0},s=(n,i,l,u)=>{for(let d=0;d<u;d+=1){let g=o[i+d]??[];for(let p=0;p<l;p+=1)g[n+p]=!0;o[i+d]=g}},a=(n,i)=>{for(let l=0;;l+=1)for(let u=0;u+n<=6;u+=1)if(r(u,l,n,i))return{gx:u,gy:l}};for(let n of e){let i=G(V(n.kind),n.w,n.h),u=n.gx!==void 0&&n.gy!==void 0&&r(n.gx,n.gy,i.w,i.h)&&n.gx!==void 0&&n.gy!==void 0?{gx:n.gx,gy:n.gy}:a(i.w,i.h);s(u.gx,u.gy,i.w,i.h),t.push({widget:n,gx:u.gx,gy:u.gy,w:i.w,h:i.h})}return t}var le=new Set(["service","order","end_user_id"]),ue=e=>typeof e=="number"?e:Number(e)||0,de=e=>e==null?"":String(e);function pe(e,t){if(e==="count")return t.length;if(t.length===0)return 0;if(e==="last")return t[t.length-1]??0;if(e==="min")return Math.min(...t);if(e==="max")return Math.max(...t);let o=t.reduce((r,s)=>r+s,0);return e==="avg"?Math.round(o/t.length):o}function nt(e,t,o,r){let s=new Map;for(let a of e){let n=new Date(de(a.data[t]));if(Number.isNaN(n.getTime()))continue;let i=n.toISOString().slice(0,10),l=s.get(i)??[];l.push(o?ue(a.data[o]):1),s.set(i,l)}return[...s.entries()].sort((a,n)=>a[0]<n[0]?-1:1).map(([a,n])=>({label:new Date(`${a}T00:00:00`).toLocaleDateString(void 0,{month:"short",day:"numeric"}),value:o?pe(r,n):n.length}))}function rt(e,t){let o=new Map;for(let r of e){let s=de(r.data[t]).trim();s&&o.set(s,(o.get(s)??0)+1)}return[...o.entries()].sort((r,s)=>s[1]-r[1]).map(([r,s])=>({label:r,value:s}))}function ot(e,t,o,r){switch(e.type){case"stat":{let s=e.metric?t.get(e.metric):void 0;if(e.metric&&!s)return null;if(!s)return{kind:"stat",label:e.label??"Items",value:r.length};let a=r.map(n=>ue(n.data[s.key]));return{kind:"stat",label:e.label??s.label,value:pe(e.agg??"sum",a)}}case"line":case"bar":{if(!t.has(e.x)||e.y&&!t.has(e.y))return null;let s=nt(r,e.x,e.y,e.agg??"sum");return s.length<2?null:{kind:"series",draw:e.type,title:e.title??"By day",points:s}}case"donut":{if(!t.has(e.groupBy))return null;let s=rt(r,e.groupBy);return s.length===0?null:{kind:"donut",title:e.title??t.get(e.groupBy)?.label??"Breakdown",points:s}}case"table":{let s=e.columns?e.columns.map(a=>t.get(a)).filter(a=>a!==void 0&&!le.has(a.key)):o;return s.length===0?null:{kind:"table",title:e.title,columns:s,rows:r}}case"text":return{kind:"text",title:e.title,body:e.body};default:return null}}function ce(e,t,o){let r=t.filter(n=>!le.has(n.key)),s=new Map(t.map(n=>[n.key,n])),a=[];for(let n of e.widgets){let i=ot(n,s,r,o);i&&a.push({...i,w:n.w,h:n.h,gx:n.gx,gy:n.gy})}return a}var st=new Set(["sum","avg","count","min","max","last"]),me=e=>typeof e=="string"&&st.has(e)?e:void 0,v=e=>typeof e=="string"&&e!==""?e:void 0,P=e=>typeof e=="number"&&e>=1?Math.min(6,Math.round(e)):void 0,I=e=>typeof e=="number"&&e>=1?Math.min(4,Math.round(e)):void 0,k=e=>typeof e=="number"&&e>=0?Math.round(e):void 0;function it(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"stat":return{type:"stat",label:v(t.label),metric:v(t.metric),agg:me(t.agg),w:P(t.w),h:I(t.h),gx:k(t.gx),gy:k(t.gy)};case"line":case"bar":{let o=v(t.x);return o?{type:t.type,title:v(t.title),x:o,y:v(t.y),agg:me(t.agg),w:P(t.w),h:I(t.h),gx:k(t.gx),gy:k(t.gy)}:null}case"donut":{let o=v(t.groupBy);return o?{type:"donut",title:v(t.title),groupBy:o,w:P(t.w),h:I(t.h),gx:k(t.gx),gy:k(t.gy)}:null}case"table":{let o=Array.isArray(t.columns)?t.columns.filter(r=>typeof r=="string"):void 0;return{type:"table",title:v(t.title),columns:o,w:P(t.w),h:I(t.h),gx:k(t.gx),gy:k(t.gy)}}case"text":{let o=v(t.body);return o?{type:"text",title:v(t.title),body:o,w:P(t.w),h:I(t.h),gx:k(t.gx),gy:k(t.gy)}:null}default:return null}}function ge(e){let t=e;if(typeof e=="string"){if(e.trim()==="")return null;try{t=JSON.parse(e)}catch{return null}}if(typeof t!="object"||t===null)return null;let o=t.widgets;if(!Array.isArray(o))return null;let r=o.map(it).filter(a=>a!==null);if(r.length===0)return null;let s=t.version;return{version:typeof s=="number"?s:1,title:v(t.title),widgets:r}}function j(e){if(typeof e=="string")return e?{kind:"file",value:e}:null;if(e&&typeof e=="object"){let t=e,o=typeof t.value=="string"?t.value:"",r=t.kind==="link"||t.kind==="text"||t.kind==="table"?t.kind:"file",s=typeof t.v=="number"&&t.v>=1?Math.floor(t.v):void 0;return o?{kind:r,value:o,...s?{v:s}:{}}:null}return null}function B(e){let t=new Map;for(let o of e){let r=o.v??1,s=t.get(r)??[];s.push(o),t.set(r,s)}return[...t.entries()].sort(([o],[r])=>o-r).map(([o,r])=>({v:o,items:r}))}function fe(e){let t=e.files;if(typeof t=="string"&&t.trim()!=="")try{let r=JSON.parse(t);if(Array.isArray(r))return r.map(j).filter(s=>s!==null)}catch{}let o=String(e.file??"");return o?[{kind:"file",value:o}]:[]}function ye(e,t,o){let s=(B(e).find(n=>n.v===t)?.items??[]).filter(n=>n.kind==="file").map(n=>n.value),a=s.map(n=>o.get(n)??"");return s.length===0||a.some(n=>n==="")?"awaiting":a.some(n=>n==="revise")?"revise":"accepted"}function be(e){return Number(e.published_version)||0}function z(e){return e==="number"||e==="date"||e==="boolean"||e==="select"||e==="url"?e:e==="link"?"url":e==="checkbox"?"boolean":"text"}function he(e){try{let t=JSON.parse(e);if(Array.isArray(t.columns)&&Array.isArray(t.rows)&&t.columns.length){let o=t.columns.map((a,n)=>({key:typeof a.key=="string"&&a.key?a.key:typeof a.id=="string"&&a.id?a.id:`column_${n+1}`,label:typeof a.label=="string"?a.label:"",type:z(a.type),...a.clientEditable===!0?{clientEditable:!0}:{}})),r=t.rows.map((a,n)=>({id:typeof a.id=="string"&&a.id?a.id:`row_${n}`,cells:a.cells&&typeof a.cells=="object"?a.cells:{}})),s=typeof t.name=="string"?t.name:void 0;return{columns:o,rows:r,...s?{name:s}:{}}}}catch{}return null}function we(e){return e==null?"":String(e)}function xe(e){return e===!0||e==="true"||e==="1"||e==="yes"||e==="\u2713"}function ve(e){if(typeof e!="string"||e.trim()==="")return{};try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function Te(e,t,o){if(e.clientEditable){let r=o[t.id];if(r&&e.key in r)return r[e.key]}return t.cells[e.key]}function ke(e,t,o,r){return{...e,[t]:{...e[t]??{},[o]:r}}}function Re(e){let t=new Date(`${e}T00:00:00`);return Number.isNaN(t.getTime())?e:t.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var at=/\/+$/,D="/api/v1/end-user",W=class extends Error{constructor(t){super(t),this.name="PortalConflict"}};function lt(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}var ut=e=>{let t=e.baseUrl.replace(at,""),o=()=>typeof e.token=="function"?e.token():e.token,r=async()=>({"content-type":"application/json",authorization:`Bearer ${await o()}`}),s=async(n,i)=>{try{let l=await fetch(`${t}${D}${n}`,{method:i.method,headers:await r(),...i.body===void 0?{}:{body:JSON.stringify(i.body)}});if(l.status===409){let u=await l.json().catch(()=>({}));throw new W(u.message??"Someone else saved this first.")}if(!l.ok){let u=await l.text().catch(()=>""),d=`${i.method} ${n} \u2192 ${String(l.status)}`;try{let g=JSON.parse(u);g.message&&(d=g.message)}catch{d=u?`${d}: ${u}`:d}throw T(new Error(d))}return await l.json()}catch(l){throw T(l)}},a=n=>`/tables/${encodeURIComponent(n)}`;return{listTables:async()=>(await h(`${t}${D}/tables`,await r())).tables,listRows:async(n,i)=>await h(`${t}${D}${a(n)}/rows?limit=${String(i??100)}`,await r()),insertRow:async(n,i)=>{let{rowIds:l}=await s(`${a(n)}/rows`,{method:"POST",body:{rows:[i]}}),u=l[0];if(!u)throw T(new Error("The row was not created."));return u},patchRow:async(n,i,l)=>(await s(`${a(n)}/rows/${encodeURIComponent(i)}`,{method:"PATCH",body:l})).updated,deleteRow:async(n,i)=>(await s(`/${encodeURIComponent(n)}/${encodeURIComponent(i)}`,{method:"DELETE"})).deleted,listFiles:async()=>(await h(`${t}${D}/tables/files/rows?limit=200`,await r())).rows.map(i=>({id:i.rowId,filename:String(i.data.filename??""),source:String(i.data.source??"client"),campaign:String(i.data.campaign??""),size:typeof i.data.size=="number"?i.data.size:0,createdAt:i.createdAt})),uploadFile:async(n,i)=>{let l=new Uint8Array(await n.arrayBuffer());return await s("/files",{method:"POST",body:{filename:n.name,mime:n.type||"application/octet-stream",data:lt(l),...i===void 0?{}:{message:i}}})},fileLink:async n=>await h(`${t}${D}/files/${encodeURIComponent(n)}/url`,await r()),deleteFile:async n=>(await s(`/files/${encodeURIComponent(n)}`,{method:"DELETE"})).deleted,listDocuments:async()=>(await h(`${t}${D}/documents`,await r())).documents,readDocument:async n=>(await h(`${t}${D}/documents/${encodeURIComponent(n)}`,await r())).document,saveDocument:async(n,i)=>await s(`/documents/${encodeURIComponent(n)}`,{method:"PATCH",body:i})}};import{useCallback as dt,useEffect as De,useRef as pt,useState as A}from"react";var Ce="greeting";function Se(e,t){if(e.some(a=>a.id===t.id))return e;let o=e.filter(a=>a.id!==Ce),r=a=>a.author==="client"==(t.author==="client");return[...o.filter(a=>!(a.pending&&r(a)&&a.text===t.text)),t]}var ct=(e,t)=>{let[o,r]=A([]),[s,a]=A(""),[n,i]=A(!1),[l,u]=A(null),d=pt(0),g=t?.pollMs??2e3;De(()=>{let m=!0;return e.getInfo().then(y=>{m&&y.greeting&&r(b=>b.length===0?[{id:Ce,cursor:"",author:"agent",text:y.greeting}]:b)}).catch(()=>{}),()=>{m=!1}},[e]),De(()=>e.subscribe?.({onMessage:m=>r(y=>Se(y,m)),onError:m=>u(m.error),onHealthy:()=>u(null)},{intervalMs:g}),[e,g]);let p=dt(()=>{let m=s.trim();if(!m||n)return;a(""),u(null),i(!0),d.current+=1;let y=`pending-${d.current}`,b={id:y,cursor:"",author:"client",text:m,pending:!0};r(c=>[...c,b]),e.sendMessage(m).then(c=>{i(!1),c.reply.trim()&&r(w=>w.some(S=>!S.pending&&S.author!=="client"&&S.text===c.reply)?w:(d.current+=1,[...w,{id:`pending-agent-${d.current}`,cursor:"",author:"agent",text:c.reply,pending:!0}]))}).catch(c=>{u(c instanceof Error?c.message:"send_failed"),i(!1),r(f=>f.filter(w=>w.id!==y)),a(f=>f||m)})},[s,n,e]);return{messages:o,input:s,setInput:a,send:p,sending:n,error:l}};export{je as Chat,te as GRID_COLS,ne as GRID_MAX_COLS,re as GRID_MAX_ROWS,_e as HolaProvider,W as PortalConflict,V as bandOfKind,se as bandOfType,Te as cellValue,We as createApiTransport,ze as createHolaClient,ut as createPortalData,N as createWidgetTransport,we as deliverableCellText,ye as deliverableStatus,Q as deriveFields,ie as footprintOf,G as footprintWith,Re as formatDeliverableDate,B as groupDeliverableVersions,ee as inferSpec,xe as isDeliverableChecked,Se as mergeMessage,z as normalizeDeliverableColType,j as normalizeDeliverableItem,ge as parseDashboardSpec,fe as parseDeliverableItems,he as parseDeliverableTable,ve as parseTableResponses,ae as placeWidgets,be as publishedVersionOf,ce as renderModel,ke as setResponse,E as textDeltaOf,$ as thinkingDeltaOf,O as toolEventOf,_ as useArtifactUrl,F as useChat,U as useHolaClient,ct as useThread};
8
+ `)}},u=async()=>{let d=await a.read();if(!d.done)return i+=n.decode(d.value,{stream:!0}),l(),u()};await u()};var Me=/\/+$/,H="/api/v1/end-user",Ae=e=>{let t=e.baseUrl.replace(Me,""),o=()=>typeof e.token=="function"?e.token():e.token,r=n=>e.project?`${n}project=${encodeURIComponent(e.project)}`:"",s=async()=>({"content-type":"application/json",authorization:`Bearer ${await o()}`}),a=async n=>{let i=await fetch(`${t}${H}/chat${r("?")}`,{method:"POST",headers:await s(),body:JSON.stringify({message:n})});if(!i.ok)throw new Error(`hola: message failed (${i.status})`);return{reply:(await i.json()).reply??"",sessionId:"",artifacts:[]}};return{sessionId:()=>"",getInfo:async()=>h(`${t}${H}/chat/info${r("?")}`,await s()),sendMessage:a,streamMessage:async(n,i)=>{try{let l=await a(n);i.onText?.(l.reply),i.onComplete?.(l)}catch(l){i.onError?.(T(l))}},subscribe:(n,i)=>{let l=i?.since??"0",u=!1,d,m=i?.intervalMs??3e3,p=typeof document<"u",g=()=>p&&document.visibilityState==="hidden",y=!1,b=()=>{if(!u){if(g()){y=!0;return}d=setTimeout(c,m)}},c=async()=>{try{let C=await h(`${t}${H}/chat/thread?since=${encodeURIComponent(l)}${r("&")}`,await s());for(let S of C.messages)n.onMessage(S);l=C.cursor,n.onHealthy?.()}catch(C){n.onError?.(T(C))}b()},f=()=>{u||!y||g()||(y=!1,d&&clearTimeout(d),d=setTimeout(c,0))};p&&document.addEventListener("visibilitychange",f);let x=()=>{u=!0,d&&clearTimeout(d),p&&document.removeEventListener("visibilitychange",f)};return i?.signal?.addEventListener("abort",x),d=setTimeout(c,0),x},requestHuman:async()=>{await fetch(`${t}${H}/chat/request-human${r("?")}`,{method:"POST",headers:await s(),body:"{}"})}}};import{useEffect as Ee,useState as $e}from"react";var L=(e,t)=>{let[o,r]=$e("");return Ee(()=>{if(!e){r("");return}let s=Uint8Array.from(atob(e),n=>n.charCodeAt(0)),a=URL.createObjectURL(new Blob([s],{type:t}));return r(a),()=>URL.revokeObjectURL(a)},[e,t]),o};import{useEffect as Ve,useRef as Ge}from"react";import{createContext as Oe,useContext as _e}from"react";import{jsx as Ue}from"react/jsx-runtime";var Y=Oe(null),Le=({client:e,children:t})=>Ue(Y.Provider,{value:e,children:t}),U=()=>{let e=_e(Y);if(!e)throw new Error("useHolaClient must be used within <HolaProvider>");return e};import{useCallback as Q,useEffect as Fe,useRef as Ne,useState as W}from"react";var F=e=>{let[t,o]=W([]),[r,s]=W(""),[a,n]=W(!1),[i,l]=W(null),u=Ne(0),d=Q(()=>{let p=u.current;return u.current+=1,p},[]);Fe(()=>{let p=!0;return e.getInfo().then(g=>{p&&g.greeting&&o([{id:d(),role:"assistant",text:g.greeting}])}).catch(()=>{}),()=>{p=!1}},[e,d]);let m=Q(()=>{let p=r.trim();if(!p||a)return;s(""),l(null),n(!0);let g=d(),y=d();o(c=>[...c,{id:g,role:"user",text:p},{id:y,role:"assistant",text:"",streaming:!0}]);let b=c=>{o(f=>f.map(x=>x.id===y?c(x):x))};e.streamMessage(p,{onText:c=>b(f=>({...f,text:f.text+c})),onComplete:c=>{b(f=>({...f,text:c.reply||f.text,artifacts:c.artifacts,streaming:!1})),n(!1)},onError:c=>{b(f=>({...f,streaming:!1})),l(c.error),n(!1)}}).catch(c=>{b(f=>({...f,streaming:!1})),l(c instanceof Error?c.message:"stream_failed"),n(!1)})},[r,a,e,d]);return{messages:t,input:r,setInput:s,send:m,sending:a,error:i}};import{jsx as R,jsxs as N}from"react/jsx-runtime";var w={root:{display:"flex",flexDirection:"column",height:"100%",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:14,color:"#111827"},log:{flex:1,overflowY:"auto",padding:12,display:"flex",flexDirection:"column",gap:8},user:{alignSelf:"flex-end",background:"#111827",color:"#ffffff",borderRadius:12,padding:"8px 12px",maxWidth:"80%",whiteSpace:"pre-wrap"},assistant:{alignSelf:"flex-start",background:"#f1f1f4",color:"#111827",borderRadius:12,padding:"8px 12px",maxWidth:"80%",whiteSpace:"pre-wrap"},artifacts:{display:"flex",flexDirection:"column",gap:6,marginTop:6},image:{maxHeight:220,borderRadius:8,border:"1px solid #e5e7eb"},link:{color:"#2563eb",textDecoration:"underline",wordBreak:"break-all"},error:{color:"#b91c1c",padding:"4px 12px",fontSize:13},form:{display:"flex",gap:8,borderTop:"1px solid #e5e7eb",padding:8},input:{flex:1,border:"1px solid #d1d5db",borderRadius:8,padding:"8px 10px",fontSize:14,outline:"none"},button:{border:"none",background:"#111827",color:"#ffffff",borderRadius:8,padding:"8px 14px",fontSize:14,cursor:"pointer"}},je=({artifact:e})=>{let t=L(e.dataBase64??"",e.mimeType),o=e.url??t;return o?e.mimeType.startsWith("image/")?R("a",{href:o,rel:"noopener noreferrer",target:"_blank",children:R("img",{alt:e.filename,src:o,style:w.image})}):R("a",{download:e.filename,href:o,style:w.link,children:e.filename}):null},Be=()=>{let e=U(),{messages:t,input:o,setInput:r,send:s,sending:a,error:n}=F(e),i=Ge(null);Ve(()=>{let u=i.current;u&&(u.scrollTop=u.scrollHeight)},[t]);let l=u=>{u.preventDefault(),s()};return N("div",{style:w.root,children:[R("div",{ref:i,style:w.log,children:t.map(u=>N("div",{style:u.role==="user"?w.user:w.assistant,children:[u.text||(u.streaming?"\u2026":""),u.artifacts&&u.artifacts.length>0?R("div",{style:w.artifacts,children:u.artifacts.map(d=>R(je,{artifact:d},d.filename))}):null]},u.id))}),n?R("div",{style:w.error,children:n}):null,N("form",{onSubmit:l,style:w.form,children:[R("input",{"aria-label":"Message",onChange:u=>r(u.target.value),placeholder:"Type a message\u2026",style:w.input,value:o}),R("button",{disabled:a||o.trim().length===0,style:w.button,type:"submit",children:"Send"})]})]})};var ze=/\/+$/,V=e=>{let t=e.sessionId,o=e.baseUrl.replace(ze,""),r=n=>`${o}/endpoint/${encodeURIComponent(e.token)}${n}`,s={"content-type":"application/json"},a=(n,i)=>({url:r(n),headers:s,body:JSON.stringify({message:i,...t?{sessionId:t}:{},...e.identity?{externalUserId:e.identity.externalUserId,userHmac:e.identity.userHmac}:{}})});return{sessionId:()=>t,getInfo:()=>h(r("/config"),{}),sendMessage:async n=>{let i=await X(a("/message",n));return t=i.sessionId,i},streamMessage:(n,i,l)=>K(a("/message/stream",n),i,u=>{t=u},l),subscribe:(n,i)=>{let l=i?.since??"0",u=!1,d,m=i?.intervalMs??3e3,p=async()=>{let y=t;if(y)try{let b=await h(r(`/messages?session=${encodeURIComponent(y)}&since=${encodeURIComponent(l)}`),{});for(let c of b.messages)n.onMessage(c);l=b.cursor,n.onHealthy?.()}catch(b){n.onError?.(T(b))}u||(d=setTimeout(p,m))},g=()=>{u=!0,d&&clearTimeout(d)};return i?.signal?.addEventListener("abort",g),d=setTimeout(p,0),g},requestHuman:async()=>{t&&await fetch(r("/request-human"),{method:"POST",headers:s,body:JSON.stringify({sessionId:t})})}}};var Je=e=>"transport"in e?e.transport:V(e);var qe=/^https?:\/\//i,Xe=/^\d{4}-\d{2}-\d{2}(?:[T ]|$)/,Ke=e=>e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase());function Ye(e){if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean";if(typeof e=="string"){if(qe.test(e))return"url";if(Xe.test(e))return"date"}return"text"}function Z(e){let t=[],o=new Map;for(let r of e)for(let[s,a]of Object.entries(r.data??{})){if(a==null)continue;let n=o.get(s);n||(n=new Map,o.set(s,n),t.push(s));let i=Ye(a);n.set(i,(n.get(i)??0)+1)}return t.map(r=>{let s=o.get(r)??new Map,a="text",n=-1;for(let[i,l]of s)l>n&&(n=l,a=i);return{key:r,label:Ke(r),type:a}})}var Qe=e=>typeof e=="number"?e:Number(e)||0,ee=e=>/rate|position|rank|score|percent|avg/i.test(e),Ze=/posted|published|sent|completed|shipped|launched|_at|date/i,et=new Set(["service","order","end_user_id"]);function te(e,t){let o=e.filter(l=>!et.has(l.key)),r=o.filter(l=>l.type==="number").slice(0,3),s=o.find(l=>l.key==="status")??o.find(l=>l.type==="select"),a=o.find(l=>l.type==="date"&&Ze.test(l.key))??o.find(l=>l.type==="date"),n=o.filter(l=>l.type==="number"&&!ee(l.key)).map(l=>({field:l,total:t.reduce((u,d)=>u+Qe(d.data[l.key]),0)})).sort((l,u)=>u.total-l.total).find(l=>l.total>0)?.field??null,i=[{type:"stat",label:"Items",agg:"count"}];for(let l of r){let u=ee(l.key);i.push({type:"stat",metric:l.key,agg:u?"avg":"sum",label:u?`Avg ${l.label.toLowerCase()}`:l.label})}return a&&i.push({type:"line",x:a.key,y:n?.key,agg:"sum",title:n?`${n.label} by day`:"Items by day"}),s&&i.push({type:"donut",groupBy:s.key,title:s.label}),i.push({type:"table",columns:o.map(l=>l.key)}),{version:1,widgets:i}}var ne=6,re=6,oe=4,se={stat:{w:1,h:1},chart:{w:2,h:2},block:{w:6,h:2}},tt=e=>Math.max(1,Math.min(6,Math.round(e))),nt=e=>Math.max(1,Math.min(4,Math.round(e)));function M(e){return e==="stat"?"stat":e==="series"||e==="donut"?"chart":"block"}function ie(e){return e==="stat"?"stat":e==="line"||e==="bar"||e==="donut"?"chart":"block"}function ae(e){return se[e]}function G(e,t,o){let r=se[e];return{w:t===void 0?r.w:tt(t),h:o===void 0?r.h:nt(o)}}function j(e){let t=[],o=[],r=(n,i,l,u)=>{if(n<0||n+l>6)return!1;for(let d=0;d<u;d+=1){let m=o[i+d];if(m){for(let p=0;p<l;p+=1)if(m[n+p])return!1}}return!0},s=(n,i,l,u)=>{for(let d=0;d<u;d+=1){let m=o[i+d]??[];for(let p=0;p<l;p+=1)m[n+p]=!0;o[i+d]=m}},a=(n,i)=>{for(let l=0;;l+=1)for(let u=0;u+n<=6;u+=1)if(r(u,l,n,i))return{gx:u,gy:l}};for(let n of e){let i=G(M(n.kind),n.w,n.h),u=n.gx!==void 0&&n.gy!==void 0&&r(n.gx,n.gy,i.w,i.h)&&n.gx!==void 0&&n.gy!==void 0?{gx:n.gx,gy:n.gy}:a(i.w,i.h);s(u.gx,u.gy,i.w,i.h),t.push({widget:n,gx:u.gx,gy:u.gy,w:i.w,h:i.h})}return t}function le(e){let t=[],o=[];for(let r of e)M(r.kind)==="block"?o.push(r):t.push(r);return{tiles:j(t),blocks:o}}var ue=new Set(["service","order","end_user_id"]),de=e=>typeof e=="number"?e:Number(e)||0,pe=e=>e==null?"":String(e);function ce(e,t){if(e==="count")return t.length;if(t.length===0)return 0;if(e==="last")return t[t.length-1]??0;if(e==="min")return Math.min(...t);if(e==="max")return Math.max(...t);let o=t.reduce((r,s)=>r+s,0);return e==="avg"?Math.round(o/t.length):o}function rt(e,t,o,r){let s=new Map;for(let a of e){let n=new Date(pe(a.data[t]));if(Number.isNaN(n.getTime()))continue;let i=n.toISOString().slice(0,10),l=s.get(i)??[];l.push(o?de(a.data[o]):1),s.set(i,l)}return[...s.entries()].sort((a,n)=>a[0]<n[0]?-1:1).map(([a,n])=>({label:new Date(`${a}T00:00:00`).toLocaleDateString(void 0,{month:"short",day:"numeric"}),value:o?ce(r,n):n.length}))}function ot(e,t){let o=new Map;for(let r of e){let s=pe(r.data[t]).trim();s&&o.set(s,(o.get(s)??0)+1)}return[...o.entries()].sort((r,s)=>s[1]-r[1]).map(([r,s])=>({label:r,value:s}))}function st(e,t,o,r){switch(e.type){case"stat":{let s=e.metric?t.get(e.metric):void 0;if(e.metric&&!s)return null;if(!s)return{kind:"stat",label:e.label??"Items",value:r.length};let a=r.map(n=>de(n.data[s.key]));return{kind:"stat",label:e.label??s.label,value:ce(e.agg??"sum",a)}}case"line":case"bar":{if(!t.has(e.x)||e.y&&!t.has(e.y))return null;let s=rt(r,e.x,e.y,e.agg??"sum");return s.length<2?null:{kind:"series",draw:e.type,title:e.title??"By day",points:s}}case"donut":{if(!t.has(e.groupBy))return null;let s=ot(r,e.groupBy);return s.length===0?null:{kind:"donut",title:e.title??t.get(e.groupBy)?.label??"Breakdown",points:s}}case"table":{let s=e.columns?e.columns.map(a=>t.get(a)).filter(a=>a!==void 0&&!ue.has(a.key)):o;return s.length===0?null:{kind:"table",title:e.title,columns:s,rows:r}}case"text":return{kind:"text",title:e.title,body:e.body};default:return null}}function ge(e,t,o){let r=t.filter(n=>!ue.has(n.key)),s=new Map(t.map(n=>[n.key,n])),a=[];for(let n of e.widgets){let i=st(n,s,r,o);i&&a.push({...i,w:n.w,h:n.h,gx:n.gx,gy:n.gy})}return a}var it=new Set(["sum","avg","count","min","max","last"]),me=e=>typeof e=="string"&&it.has(e)?e:void 0,v=e=>typeof e=="string"&&e!==""?e:void 0,P=e=>typeof e=="number"&&e>=1?Math.min(6,Math.round(e)):void 0,I=e=>typeof e=="number"&&e>=1?Math.min(4,Math.round(e)):void 0,k=e=>typeof e=="number"&&e>=0?Math.round(e):void 0;function at(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"stat":return{type:"stat",label:v(t.label),metric:v(t.metric),agg:me(t.agg),w:P(t.w),h:I(t.h),gx:k(t.gx),gy:k(t.gy)};case"line":case"bar":{let o=v(t.x);return o?{type:t.type,title:v(t.title),x:o,y:v(t.y),agg:me(t.agg),w:P(t.w),h:I(t.h),gx:k(t.gx),gy:k(t.gy)}:null}case"donut":{let o=v(t.groupBy);return o?{type:"donut",title:v(t.title),groupBy:o,w:P(t.w),h:I(t.h),gx:k(t.gx),gy:k(t.gy)}:null}case"table":{let o=Array.isArray(t.columns)?t.columns.filter(r=>typeof r=="string"):void 0;return{type:"table",title:v(t.title),columns:o,w:P(t.w),h:I(t.h),gx:k(t.gx),gy:k(t.gy)}}case"text":{let o=v(t.body);return o?{type:"text",title:v(t.title),body:o,w:P(t.w),h:I(t.h),gx:k(t.gx),gy:k(t.gy)}:null}default:return null}}function fe(e){let t=e;if(typeof e=="string"){if(e.trim()==="")return null;try{t=JSON.parse(e)}catch{return null}}if(typeof t!="object"||t===null)return null;let o=t.widgets;if(!Array.isArray(o))return null;let r=o.map(at).filter(a=>a!==null);if(r.length===0)return null;let s=t.version;return{version:typeof s=="number"?s:1,title:v(t.title),widgets:r}}function B(e){if(typeof e=="string")return e?{kind:"file",value:e}:null;if(e&&typeof e=="object"){let t=e,o=typeof t.value=="string"?t.value:"",r=t.kind==="link"||t.kind==="text"||t.kind==="table"?t.kind:"file",s=typeof t.v=="number"&&t.v>=1?Math.floor(t.v):void 0;return o?{kind:r,value:o,...s?{v:s}:{}}:null}return null}function z(e){let t=new Map;for(let o of e){let r=o.v??1,s=t.get(r)??[];s.push(o),t.set(r,s)}return[...t.entries()].sort(([o],[r])=>o-r).map(([o,r])=>({v:o,items:r}))}function ye(e){let t=e.files;if(typeof t=="string"&&t.trim()!=="")try{let r=JSON.parse(t);if(Array.isArray(r))return r.map(B).filter(s=>s!==null)}catch{}let o=String(e.file??"");return o?[{kind:"file",value:o}]:[]}function be(e,t,o){let s=(z(e).find(n=>n.v===t)?.items??[]).filter(n=>n.kind==="file").map(n=>n.value),a=s.map(n=>o.get(n)??"");return s.length===0||a.some(n=>n==="")?"awaiting":a.some(n=>n==="revise")?"revise":"accepted"}function he(e){return Number(e.published_version)||0}function J(e){return e==="number"||e==="date"||e==="boolean"||e==="select"||e==="url"?e:e==="link"?"url":e==="checkbox"?"boolean":"text"}function xe(e){try{let t=JSON.parse(e);if(Array.isArray(t.columns)&&Array.isArray(t.rows)&&t.columns.length){let o=t.columns.map((a,n)=>({key:typeof a.key=="string"&&a.key?a.key:typeof a.id=="string"&&a.id?a.id:`column_${n+1}`,label:typeof a.label=="string"?a.label:"",type:J(a.type),...a.clientEditable===!0?{clientEditable:!0}:{}})),r=t.rows.map((a,n)=>({id:typeof a.id=="string"&&a.id?a.id:`row_${n}`,cells:a.cells&&typeof a.cells=="object"?a.cells:{}})),s=typeof t.name=="string"?t.name:void 0;return{columns:o,rows:r,...s?{name:s}:{}}}}catch{}return null}function we(e){return e==null?"":String(e)}function ve(e){return e===!0||e==="true"||e==="1"||e==="yes"||e==="\u2713"}function Te(e){if(typeof e!="string"||e.trim()==="")return{};try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function ke(e,t,o){if(e.clientEditable){let r=o[t.id];if(r&&e.key in r)return r[e.key]}return t.cells[e.key]}function Re(e,t,o,r){return{...e,[t]:{...e[t]??{},[o]:r}}}function De(e){let t=new Date(`${e}T00:00:00`);return Number.isNaN(t.getTime())?e:t.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var lt=/\/+$/,D="/api/v1/end-user",A=class extends Error{constructor(t){super(t),this.name="PortalConflict"}};function ut(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}var dt=e=>{let t=e.baseUrl.replace(lt,""),o=()=>typeof e.token=="function"?e.token():e.token,r=async()=>({"content-type":"application/json",authorization:`Bearer ${await o()}`}),s=async(n,i)=>{try{let l=await fetch(`${t}${D}${n}`,{method:i.method,headers:await r(),...i.body===void 0?{}:{body:JSON.stringify(i.body)}});if(l.status===409){let u=await l.json().catch(()=>({}));throw new A(u.message??"Someone else saved this first.")}if(!l.ok){let u=await l.text().catch(()=>""),d=`${i.method} ${n} \u2192 ${String(l.status)}`;try{let m=JSON.parse(u);m.message&&(d=m.message)}catch{d=u?`${d}: ${u}`:d}throw T(new Error(d))}return await l.json()}catch(l){throw T(l)}},a=n=>`/tables/${encodeURIComponent(n)}`;return{listTables:async()=>(await h(`${t}${D}/tables`,await r())).tables,listRows:async(n,i)=>await h(`${t}${D}${a(n)}/rows?limit=${String(i??100)}`,await r()),insertRow:async(n,i)=>{let{rowIds:l}=await s(`${a(n)}/rows`,{method:"POST",body:{rows:[i]}}),u=l[0];if(!u)throw T(new Error("The row was not created."));return u},patchRow:async(n,i,l)=>(await s(`${a(n)}/rows/${encodeURIComponent(i)}`,{method:"PATCH",body:l})).updated,deleteRow:async(n,i)=>(await s(`/${encodeURIComponent(n)}/${encodeURIComponent(i)}`,{method:"DELETE"})).deleted,listFiles:async()=>(await h(`${t}${D}/tables/files/rows?limit=200`,await r())).rows.map(i=>({id:i.rowId,filename:String(i.data.filename??""),source:String(i.data.source??"client"),campaign:String(i.data.campaign??""),size:typeof i.data.size=="number"?i.data.size:0,createdAt:i.createdAt})),uploadFile:async(n,i)=>{let l=new Uint8Array(await n.arrayBuffer());return await s("/files",{method:"POST",body:{filename:n.name,mime:n.type||"application/octet-stream",data:ut(l),...i===void 0?{}:{message:i}}})},fileLink:async n=>await h(`${t}${D}/files/${encodeURIComponent(n)}/url`,await r()),deleteFile:async n=>(await s(`/files/${encodeURIComponent(n)}`,{method:"DELETE"})).deleted,listDocuments:async()=>(await h(`${t}${D}/documents`,await r())).documents,readDocument:async n=>(await h(`${t}${D}/documents/${encodeURIComponent(n)}`,await r())).document,saveDocument:async(n,i)=>await s(`/documents/${encodeURIComponent(n)}`,{method:"PATCH",body:i})}};import{useCallback as pt,useEffect as Ce,useRef as ct,useState as E}from"react";var Se="greeting";function Pe(e,t){if(e.some(a=>a.id===t.id))return e;let o=e.filter(a=>a.id!==Se),r=a=>a.author==="client"==(t.author==="client");return[...o.filter(a=>!(a.pending&&r(a)&&a.text===t.text)),t]}var gt=(e,t)=>{let[o,r]=E([]),[s,a]=E(""),[n,i]=E(!1),[l,u]=E(null),d=ct(0),m=t?.pollMs??2e3;Ce(()=>{let g=!0;return e.getInfo().then(y=>{g&&y.greeting&&r(b=>b.length===0?[{id:Se,cursor:"",author:"agent",text:y.greeting}]:b)}).catch(()=>{}),()=>{g=!1}},[e]),Ce(()=>e.subscribe?.({onMessage:g=>r(y=>Pe(y,g)),onError:g=>u(g.error),onHealthy:()=>u(null)},{intervalMs:m}),[e,m]);let p=pt(()=>{let g=s.trim();if(!g||n)return;a(""),u(null),i(!0),d.current+=1;let y=`pending-${d.current}`,b={id:y,cursor:"",author:"client",text:g,pending:!0};r(c=>[...c,b]),e.sendMessage(g).then(c=>{i(!1),c.reply.trim()&&r(x=>x.some(S=>!S.pending&&S.author!=="client"&&S.text===c.reply)?x:(d.current+=1,[...x,{id:`pending-agent-${d.current}`,cursor:"",author:"agent",text:c.reply,pending:!0}]))}).catch(c=>{u(c instanceof Error?c.message:"send_failed"),i(!1),r(f=>f.filter(x=>x.id!==y)),a(f=>f||g)})},[s,n,e]);return{messages:o,input:s,setInput:a,send:p,sending:n,error:l}};export{Be as Chat,ne as GRID_COLS,re as GRID_MAX_COLS,oe as GRID_MAX_ROWS,Le as HolaProvider,A as PortalConflict,M as bandOfKind,ie as bandOfType,ke as cellValue,Ae as createApiTransport,Je as createHolaClient,dt as createPortalData,V as createWidgetTransport,we as deliverableCellText,be as deliverableStatus,Z as deriveFields,ae as footprintOf,G as footprintWith,De as formatDeliverableDate,z as groupDeliverableVersions,te as inferSpec,ve as isDeliverableChecked,Pe as mergeMessage,J as normalizeDeliverableColType,B as normalizeDeliverableItem,fe as parseDashboardSpec,ye as parseDeliverableItems,xe as parseDeliverableTable,Te as parseTableResponses,j as placeWidgets,he as publishedVersionOf,ge as renderModel,Re as setResponse,le as splitLayout,$ as textDeltaOf,O as thinkingDeltaOf,_ as toolEventOf,L as useArtifactUrl,F as useChat,U as useHolaClient,gt as useThread};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@holaboss/client",
3
- "version": "0.2.0-beta.11",
3
+ "version": "0.2.0-beta.13",
4
4
  "description": "Injectable client SDK for embedding a Holaboss AI employee (chat + configurable dashboards today; artifacts next) into your own web app.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",