claudius-chat-widget 1.13.0 → 1.14.0
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/claudius.iife.js +1 -1
- package/package.json +1 -1
package/dist/claudius.iife.js
CHANGED
|
@@ -43,4 +43,4 @@ Error generating stack: `+o.message+`
|
|
|
43
43
|
`))v.startsWith("event:")?d=v.slice(6).trim():v.startsWith("data:")&&u.push(v.slice(5).trimStart());if(u.length===0)return null;try{const v=JSON.parse(u.join(`
|
|
44
44
|
`));return typeof v!="object"||v===null?null:{event:d,data:v}}catch{return null}}function qi(a){return typeof a=="string"?{content:a}:a}function Kl(a,d,u){console.error(`[claudius] plugin "${a.name}" failed in ${d}:`,u)}async function pc(a,d,u){let v=d;for(const y of a){if(!y.onBeforeSend)continue;let w=null;const R={...u,respondWith(L){w={type:"respond",message:v,reply:qi(L)}},abort(L){w={type:"abort",reason:L}}};try{const L=await y.onBeforeSend(v,R);if(w)return w;L&&(v=L)}catch(L){Kl(y,"onBeforeSend",L)}}return{type:"send",message:v}}async function hc(a,d,u){let v=d;for(const y of a)if(y.onAfterReceive)try{const w=await y.onAfterReceive(v,u);w&&(v=w)}catch(w){Kl(y,"onAfterReceive",w)}return v}async function mc(a,d,u){for(const v of a){if(!v.onError)continue;let y=null;const w={...u,respondWith(R){y=qi(R)}};try{if(await v.onError(d,w),y)return y}catch(R){Kl(v,"onError",R)}}return null}const vc=200,gc="claudius:messages";function yc(a,d){let u;try{u=new URL(d).host}catch{u=d}return`${a}:${u}`}function Gl(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function wc(a){const d=Gl();if(!d)return[];try{const u=d.getItem(a);if(!u)return[];const v=JSON.parse(u);return Array.isArray(v)?v:[]}catch{return[]}}function xc({apiUrl:a,persistMessages:d=!0,storageKeyPrefix:u=gc,timeoutMs:v,translations:y,plugins:w,streaming:R=!0}){const L=O.useMemo(()=>new fc(a,{debounceMs:0,timeoutMs:v}),[a,v]),N=yc(u,a),P=d?wc(N):[],[B,V]=O.useState(P),[ee,oe]=O.useState(!1),[ie,U]=O.useState(!1),[W,fe]=O.useState(null),[ye,ne]=O.useState(null),[$,ue]=O.useState(!1),he=O.useRef(P.length),me=O.useRef(!1),q=O.useRef(P),He=O.useRef(null),Ce=O.useRef(w??[]);Ce.current=w??[];const _e=O.useCallback(E=>{if(!d)return;const p=Gl();if(p)try{const x=E.slice(-vc);p.setItem(N,JSON.stringify(x))}catch{}},[d,N]),b=()=>(he.current+=1,`msg-${he.current}`),ke=O.useCallback((E,p)=>{if(!y)return p??"Something went wrong. Please try again.";switch(E){case"TIMEOUT":return y.errorTimeout;case"NETWORK_ERROR":return y.errorConnection;case"RATE_LIMITED":return p!=null&&p.includes("minute")?y.errorRateLimitMinute:y.errorRateLimitHour;case"VALIDATION_ERROR":case"CONFIG_ERROR":case"SERVICE_ERROR":case"UNKNOWN_ERROR":default:return p??y.errorGeneric}},[y]),Be=O.useCallback(E=>!(E instanceof tt)||E.code==="TIMEOUT"||E.code==="NETWORK_ERROR"||E.code==="RATE_LIMITED"||E.code==="SERVICE_ERROR"||E.code==="UNKNOWN_ERROR"||E.status>=500||E.status===0,[]),Ae=O.useCallback(async E=>{oe(!0),me.current=!0,ne(null),ue(!1);const p=R&&typeof L.streamMessage=="function";let x=null;const X=D=>{if(x===null){x=b(),fe(x);const G=[...q.current,{id:x,role:"assistant",content:"",...D}];q.current=G,V(G)}else{const G=x,Z=q.current.map(te=>te.id===G?{...te,...D}:te);q.current=Z,V(Z)}},Y=()=>{if(x===null)return;const D=x,G=q.current.filter(Z=>Z.id!==D);q.current=G,V(G)};try{let D,G,Z,te=!1;if(p){const Ve=new AbortController;He.current=Ve,U(!0);const St=await L.streamMessage(E,{signal:Ve.signal,onChunk:(It,ze)=>X({content:ze}),onToolUse:(It,ze)=>X({toolUses:[...ze]})});D=St.reply,G=St.sources,Z=St.toolUses,te=St.aborted??!1}else{const Ve=await L.sendMessage(E);D=Ve.reply,G=Ve.sources,Z=Ve.toolUses}if(te&&!D){Y();return}let le={id:x??b(),role:"assistant",content:D,sources:G,toolUses:Z};Ce.current.length>0&&!te&&(le=await hc(Ce.current,le,{messages:E,apiUrl:a}));const Le=x!==null?q.current.map(Ve=>Ve.id===le.id?le:Ve):[...E,le];q.current=Le,V(Le),_e(Le)}catch(D){if(D instanceof Ql)return;if(x!==null){_e(q.current),D instanceof tt?ne(ke(D.code,D.message)):ne((y==null?void 0:y.errorConnection)??"Failed to connect. Please try again."),ue(!1);return}if(Ce.current.length>0){const G=D instanceof Error?D:new Error(String(D)),Z=await mc(Ce.current,G,{messages:E,apiUrl:a});if(Z){const te={id:b(),role:"assistant",content:Z.content,sources:Z.sources},le=[...E,te];q.current=le,V(le),_e(le),ne(null),ue(!1);return}}D instanceof tt?ne(ke(D.code,D.message)):ne((y==null?void 0:y.errorConnection)??"Failed to connect. Please try again."),ue(Be(D))}finally{oe(!1),me.current=!1,U(!1),fe(null),He.current=null}},[a,L,ke,Be,_e,R,y]),je=O.useCallback(()=>{var E;(E=He.current)==null||E.abort()},[]),de=O.useCallback(async E=>{const p=E.trim();if(!p||me.current)return;const x={id:b(),role:"user",content:p};let X=x;if(Ce.current.length>0){const D=await pc(Ce.current,x,{messages:q.current,apiUrl:a});if(D.type==="abort")return;if(D.type==="respond"){const G={id:b(),role:"assistant",content:D.reply.content,sources:D.reply.sources},Z=[...q.current,D.message,G];q.current=Z,V(Z),_e(Z),ne(null),ue(!1);return}X=D.message}const Y=[...q.current,X];q.current=Y,V(Y),_e(Y),await Ae(Y)},[a,_e,Ae]),M=O.useCallback(async()=>{if(me.current)return;const E=q.current[q.current.length-1];!E||E.role!=="user"||await Ae(q.current)},[Ae]),H=O.useCallback(()=>{if(q.current=[],V([]),ne(null),ue(!1),d){const E=Gl();if(!E)return;try{E.removeItem(N)}catch{}}},[d,N]);return{messages:B,isLoading:ee,isStreaming:ie,streamingMessageId:W,error:ye,canRetry:$,sendMessage:de,stop:je,retry:M,clearMessages:H}}function Sc(a){const[d,u]=O.useState(()=>typeof window>"u"?!1:window.matchMedia(a).matches);return O.useEffect(()=>{const v=window.matchMedia(a);u(v.matches);const y=w=>u(w.matches);return v.addEventListener("change",y),()=>v.removeEventListener("change",y)},[a]),d}function Mr(a,d){return a instanceof RegExp?a.test(d):d.toLowerCase().includes(a.toLowerCase())}function kc(){const a=document.documentElement,d=document.body,u=a.scrollTop||d.scrollTop||0,v=Math.max(a.scrollHeight,d.scrollHeight),y=a.clientHeight||window.innerHeight,w=v-y;return w<=0?100:u/w*100}function Ec({triggers:a,enabled:d,onOpen:u,onGreeting:v}){O.useEffect(()=>{if(!d||!a||a.length===0)return;const y=new Set,w=[],R=typeof window<"u"?window.location.href:"",L=(N,P)=>{y.has(N)||(y.add(N),P==="open"?u():v(P.greeting))};return a.forEach((N,P)=>{switch(N.on){case"url":{Mr(N.pattern,R)&&L(P,N.action);break}case"time":{if(N.matchUrl&&!Mr(N.matchUrl,R))return;const B=window.setTimeout(()=>L(P,N.action),Math.max(0,N.seconds*1e3));w.push(()=>window.clearTimeout(B));break}case"scroll":{if(N.matchUrl&&!Mr(N.matchUrl,R))return;const B=()=>{kc()>=N.percent&&L(P,N.action)};B(),window.addEventListener("scroll",B,{passive:!0}),w.push(()=>window.removeEventListener("scroll",B));break}case"exit-intent":{if(N.matchUrl&&!Mr(N.matchUrl,R))return;const B=V=>{V.clientY<=0&&L(P,N.action)};document.addEventListener("mouseleave",B),w.push(()=>document.removeEventListener("mouseleave",B));break}}}),()=>{w.forEach(N=>N())}},[a,d,u,v])}const Cc={"bottom-right":"bottom-6 right-6","bottom-left":"bottom-6 left-6","top-right":"top-6 right-6","top-left":"top-6 left-6"},_c=O.forwardRef(function({isOpen:d,onClick:u,position:v="bottom-right",translations:y},w){const R=d?(y==null?void 0:y.closeChat)??"Close chat":(y==null?void 0:y.openChat)??"Open chat";return S.jsx("button",{ref:w,onClick:u,"aria-label":R,className:`fixed ${Cc[v]} z-50 flex h-14 w-14 items-center justify-center rounded-claudius-full bg-claudius-accent text-claudius-accent-text shadow-claudius-floating transition-transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-claudius-accent focus:ring-offset-2`,children:d?S.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[S.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),S.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}):S.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:S.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}),Rc=O.memo(function({count:d,isActive:u,onClick:v}){return S.jsxs("button",{onClick:v,"aria-label":"View sources",title:"View sources",className:`group relative flex h-7 w-7 items-center justify-center rounded-claudius-full transition-colors ${u?"bg-claudius-accent text-claudius-accent-text":"text-claudius-text-muted hover:bg-claudius-surface-muted hover:text-claudius-text"}`,children:[S.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[S.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),S.jsx("polyline",{points:"14 2 14 8 20 8"}),S.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),S.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]}),S.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 min-w-4 items-center justify-center rounded-claudius-full bg-claudius-accent px-1 text-[10px] font-bold text-claudius-accent-text",children:d})]})}),Nc=["http:","https:"];function bi(a){if(!a||typeof a!="string")return null;const d=a.trim();if(!d)return null;try{const u=new URL(d);return Nc.includes(u.protocol)?d:null}catch{return null}}function Tc(a){const d=a.lastIndexOf(`
|
|
45
45
|
`),u=d===-1?"":a.slice(0,d+1);let v=d===-1?a:a.slice(d+1);return v=Pc(v),v=jc(v),u+v}function Lc(a){const d=[];for(let u=0;u<a.length-1;u++)a[u]==="*"&&a[u+1]==="*"&&(d.push(u),u++);return d}function Mc(a){const d=[];for(let u=0;u<a.length;u++)if(a[u]==="*"){if(a[u+1]==="*"){u++;continue}d.push(u)}return d}function Pc(a){const d=Lc(a);if(d.length%2===0)return a;const u=d[d.length-1],v=a.slice(u+2);return v.trim()===""?a.slice(0,u)+v:a+"**"}function jc(a){const d=Mc(a);if(d.length%2===0)return a;const u=d[d.length-1],v=a.slice(u+1);return v.trim()===""?a.slice(0,u)+v:a+"*"}function zc({toolUse:a,usedLabel:d,detailsLabel:u}){const[v,y]=O.useState(!1),w=a.input!==void 0||a.result!==void 0;return S.jsxs("div",{className:"text-xs text-claudius-text-muted",children:[S.jsxs("button",{type:"button",disabled:!w,onClick:()=>y(R=>!R),"aria-expanded":w?v:void 0,className:"flex items-center gap-1.5 rounded-claudius-full border border-claudius-border bg-claudius-surface px-2 py-0.5 hover:opacity-80 disabled:cursor-default disabled:hover:opacity-100",children:[S.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:S.jsx("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),S.jsxs("span",{children:[d," ",S.jsx("span",{className:"font-mono text-claudius-text",children:a.name}),a.isError&&S.jsx("span",{className:"text-claudius-error",children:" ✕"})]}),w&&S.jsxs(S.Fragment,{children:[S.jsx("span",{className:"sr-only",children:u}),S.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:v?"rotate-180":void 0,children:S.jsx("polyline",{points:"6 9 12 15 18 9"})})]})]}),v&&w&&S.jsxs("div",{className:"mt-1 overflow-x-auto rounded-claudius-sm border border-claudius-border bg-claudius-field p-2 font-mono",children:[a.input!==void 0&&S.jsx("pre",{className:"whitespace-pre-wrap break-all",children:JSON.stringify(a.input,null,2)}),a.result!==void 0&&S.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-all border-t border-claudius-border pt-1",children:a.result})]})]})}const eu=/(https?:\/\/[^\s)]+)/,tu=/(\*\*[^*]+\*\*)/,nu=/(\*[^*]+\*)/;function Oc(a,d){const u=a.match(/[.,;:!?'"]+$/),v=u?a.slice(0,-u[0].length):a,y=u?u[0]:"",w=bi(v);return w?S.jsxs(S.Fragment,{children:[S.jsxs("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:"underline font-medium hover:opacity-80 text-claudius-link",children:[w.replace(/^https?:\/\//,""),S.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]},d),y]}):a}function Dc(a,d){const u=a.split(tu),v=[];return u.forEach((y,w)=>{if(tu.test(y)){const R=y.slice(2,-2);v.push(S.jsx("strong",{children:R},`${d}-b${w}`))}else y.split(nu).forEach((L,N)=>{if(nu.test(L)){const P=L.slice(1,-1);v.push(S.jsx("em",{children:P},`${d}-b${w}-i${N}`))}else L.split(eu).forEach((B,V)=>{eu.test(B)?v.push(Oc(B,`${d}-b${w}-i${N}-u${V}`)):B&&v.push(B)})})}),v}function Ic(a){const d=a.split(`
|
|
46
|
-
`);return d.map((u,v)=>S.jsxs("span",{children:[Dc(u,`l${v}`),v<d.length-1&&S.jsx("br",{})]},v))}const Ac=O.memo(function({role:d,content:u,isStreaming:v=!1,sources:y,toolUses:w,toolUsedLabel:R="Used tool:",toolDetailsLabel:L="Tool details",onSourceClick:N,isSourceActive:P}){const B=d==="user",V=v?Tc(u):u,ee=B||u!==""||!(w!=null&&w.length);return S.jsxs("div",{className:`${B?"ml-auto":"mr-auto"} max-w-[85%]`,children:[ee&&S.jsx("div",{className:`rounded-claudius-bubble px-4 py-2.5 text-sm leading-relaxed font-body ${B?"bg-claudius-user-bubble text-claudius-user-bubble-text rounded-br-claudius-tail":"bg-claudius-assistant-bubble text-claudius-assistant-bubble-text rounded-bl-claudius-tail"}`,children:Ic(V)}),!B&&w&&w.length>0&&S.jsx("div",{className:"mt-1 space-y-1",children:w.map((oe,ie)=>S.jsx(zc,{toolUse:oe,usedLabel:R,detailsLabel:L},`${oe.name}-${ie}`))}),!B&&y&&y.length>0&&N&&S.jsx("div",{className:"mt-1",children:S.jsx(Rc,{count:y.length,isActive:P??!1,onClick:N})})]})}),Yl=2e3,Fc=1800;function Uc({onSend:a,isLoading:d,isStreaming:u=!1,onStop:v,placeholder:y,translations:w}){const[R,L]=O.useState(""),N=O.useRef(null),P=R.length,B=P>=Fc,V=P>=Yl,ee=y??(w==null?void 0:w.placeholder)??"Type your message...",oe=(w==null?void 0:w.sendMessage)??"Send message",ie=(w==null?void 0:w.stopGenerating)??"Stop generating",U=(w==null?void 0:w.typeYourMessage)??"Type your message",W=u&&!!v;O.useEffect(()=>{var ne;d||(ne=N.current)==null||ne.focus()},[d]);const fe=ne=>{ne.preventDefault();const $=R.trim();!$||V||(a($),L(""))},ye=ne=>{const $=ne.target.value;$.length<=Yl&&L($)};return S.jsxs("form",{onSubmit:fe,className:"border-t border-claudius-border bg-claudius-surface p-3",children:[S.jsxs("div",{className:"flex gap-2",children:[S.jsx("input",{ref:N,type:"text",value:R,onChange:ye,placeholder:ee,disabled:d,"aria-label":U,"aria-describedby":B?"char-count":void 0,className:"flex-1 rounded-claudius-sm border border-claudius-border bg-claudius-field px-3 py-2 text-sm font-body text-claudius-text placeholder:text-claudius-text-muted focus:border-claudius-accent focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50"}),W?S.jsx("button",{type:"button",onClick:v,"aria-label":ie,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm bg-claudius-accent text-claudius-accent-text transition-colors hover:opacity-90",children:S.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:S.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})}):S.jsx("button",{type:"submit",disabled:d||V,"aria-label":oe,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm bg-claudius-accent text-claudius-accent-text transition-colors hover:opacity-90 disabled:opacity-50",children:S.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[S.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),S.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),B&&S.jsxs("div",{id:"char-count",className:`mt-1 text-xs text-right ${V?"text-claudius-error":"text-claudius-text-muted"}`,"aria-live":"polite",children:[P,"/",Yl]})]})}const Hc=["blog","page","external"],Bc={blog:"Blog",page:"Page",external:"External"};function Vc(a){try{return new URL(a).hostname}catch{return a}}const Wc=O.memo(function({sources:d,onClose:u}){const v=Hc.map(w=>({type:w,label:Bc[w],items:d.filter(R=>R.type===w)})).filter(w=>w.items.length>0),y=d.length===1?"1 source found":`${d.length} sources found`;return S.jsxs("div",{className:"absolute inset-y-0 left-0 z-10 flex w-[280px] flex-col border-r-2 border-claudius-border bg-claudius-surface rounded-r-claudius-lg transition-transform duration-200 ease-out",children:[S.jsxs("div",{className:"flex items-center justify-between border-b border-claudius-border px-4 py-3",children:[S.jsxs("div",{children:[S.jsx("h3",{className:"text-sm font-heading font-semibold text-claudius-text",children:"Sources"}),S.jsx("p",{className:"text-xs text-claudius-text-muted",children:y})]}),S.jsx("button",{onClick:u,"aria-label":"Close sources",className:"flex h-7 w-7 items-center justify-center rounded-claudius-full text-claudius-text-muted transition-colors hover:bg-claudius-surface-muted hover:text-claudius-text",children:S.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[S.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),S.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),S.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-4",children:v.map(w=>S.jsxs("div",{children:[S.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-claudius-text-muted",children:w.label}),S.jsx("div",{className:"space-y-2",children:w.items.map(R=>{const L=bi(R.url);return L?S.jsxs("a",{href:L,target:"_blank",rel:"noopener noreferrer",className:"block rounded-claudius-md border-2 border-claudius-border bg-claudius-surface-muted p-3 transition-colors hover:bg-claudius-border",children:[S.jsx("p",{className:"truncate text-sm font-medium text-claudius-text",children:R.title}),S.jsx("p",{className:"mt-0.5 text-xs text-claudius-text-muted",children:Vc(L)})]},L):null})})]},w.type))})]})});function $c({title:a,subtitle:d,titleId:u,closeLabel:v,onClose:y}){return S.jsxs("div",{className:"flex items-center gap-3 bg-claudius-accent px-5 py-4",children:[S.jsx("div",{"aria-hidden":"true",className:"flex h-8 w-8 items-center justify-center rounded-claudius-full bg-claudius-accent-soft text-sm font-bold text-claudius-accent-text",children:a.charAt(0).toUpperCase()}),S.jsxs("div",{className:"flex-1",children:[S.jsx("h2",{id:u,className:"text-sm font-heading font-semibold text-claudius-accent-text",children:a}),S.jsx("p",{className:"text-xs text-claudius-accent-text",children:d})]}),S.jsx("button",{onClick:y,"aria-label":v,className:"flex h-10 w-10 items-center justify-center rounded-claudius-full text-claudius-accent-text-muted transition-colors hover:bg-claudius-accent-soft hover:text-claudius-accent-text",children:S.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[S.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),S.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}function Qc({message:a,retryLabel:d,onRetry:u}){return S.jsxs("div",{role:"alert",className:"mx-auto flex max-w-[90%] flex-col items-center gap-2 rounded-claudius-sm bg-claudius-error-surface px-3 py-2 text-center text-xs text-claudius-error",children:[S.jsx("span",{children:a}),u&&S.jsx("button",{type:"button",onClick:u,className:"rounded-claudius-md bg-claudius-error px-3 py-1 text-xs font-semibold text-claudius-error-text transition-opacity hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-claudius-error focus-visible:ring-offset-1",children:d})]})}function Kc({label:a}){return S.jsx("div",{role:"status","aria-live":"polite","aria-label":a,className:"mr-auto flex max-w-[85%]",children:S.jsxs("div",{className:"flex gap-1 rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-3",children:[S.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:0ms]"}),S.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:150ms]"}),S.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:300ms]"})]})})}function Gc(a,d,u){const[v,y]=O.useState(0),w=O.useRef(0),R=O.useRef(0),L=O.useRef(0),N=O.useRef(!1);return O.useEffect(()=>{const P=a.current;if(!u||!P)return;const B=oe=>{if(P.scrollTop>0){N.current=!1;return}N.current=!0,R.current=oe.touches[0].clientY,L.current=Date.now()},V=oe=>{if(!N.current)return;let ie=oe.touches[0].clientY-R.current;ie<0&&(ie=ie*.3),w.current=ie,y(ie)},ee=()=>{if(!N.current)return;N.current=!1;const oe=w.current,ie=(Date.now()-L.current)/1e3,U=P.getBoundingClientRect().height,W=ie>.05&&oe>0&&oe/ie>500,fe=oe>U*.3;W||fe?d():(w.current=0,y(0))};return P.addEventListener("touchstart",B,{passive:!0}),P.addEventListener("touchmove",V,{passive:!0}),P.addEventListener("touchend",ee),()=>{P.removeEventListener("touchstart",B),P.removeEventListener("touchmove",V),P.removeEventListener("touchend",ee)}},[a,d,u]),{offsetY:v}}const Yc='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Xc(a,d){O.useEffect(()=>{const u=a.current;if(!u)return;const v=y=>{if(y.key!=="Tab")return;const w=Array.from(u.querySelectorAll(Yc)).filter(P=>!P.hasAttribute("aria-hidden"));if(w.length===0)return;const R=w[0],L=w[w.length-1],N=document.activeElement;y.shiftKey&&N===R?(y.preventDefault(),L.focus()):!y.shiftKey&&N===L&&(y.preventDefault(),R.focus())};return u.addEventListener("keydown",v),()=>u.removeEventListener("keydown",v)},[a,d])}const Zc=/\*\*([^*]+)\*\*/g,Jc=/\*([^*]+)\*/g,qc=/https?:\/\/[^\s)]+/g;function bc(a){return a.replace(Zc,"$1").replace(Jc,"$1").replace(qc,d=>{try{return new URL(d).hostname}catch{return d}})}const ef={"bottom-right":"bottom-24 right-3 sm:right-6","bottom-left":"bottom-24 left-3 sm:left-6","top-right":"top-24 right-3 sm:right-6","top-left":"top-24 left-3 sm:left-6"};function tf({messages:a,isLoading:d,isStreaming:u=!1,streamingMessageId:v=null,error:y,canRetry:w=!1,onSend:R,onStop:L,onRetry:N,onClose:P,title:B="Chat",subtitle:V="Ask me anything",welcomeMessage:ee="Hi! How can I help you today?",placeholder:oe,position:ie="bottom-right",translations:U,isMobile:W=!1}){const fe=O.useId(),ye=O.useRef(null),ne=O.useRef(null),[$,ue]=O.useState(null);Xc(ye,!0);const{offsetY:he}=Gc(ne,P,W),me=he!==0,q=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1;O.useEffect(()=>{const b=ne.current;b&&(b.scrollTop=b.scrollHeight)},[a,d]),O.useEffect(()=>{const b=ke=>{ke.key==="Escape"&&!ke.isComposing&&P()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[P]);const He=(U==null?void 0:U.closeChat)??"Close chat",Ce=(U==null?void 0:U.chatMessages)??"Chat messages",_e=[...a].reverse().find(b=>b.role==="assistant");return S.jsxs("div",{ref:ye,role:"dialog","aria-modal":W?"true":void 0,"aria-labelledby":fe,className:W?"claudius-bottom-sheet fixed inset-x-0 bottom-0 z-50 flex h-[90vh] w-full flex-col overflow-hidden rounded-t-claudius-lg bg-claudius-surface shadow-claudius-elevated font-body":`fixed ${ef[ie]} z-50 flex h-[min(500px,calc(100vh-7rem))] w-[calc(100vw-1.5rem)] max-w-[380px] sm:max-w-[400px] md:max-w-[440px] flex-col overflow-hidden rounded-claudius-lg bg-claudius-surface shadow-claudius-elevated font-body`,style:W&&!q?{transform:`translateY(${Math.max(0,he)}px)`}:void 0,"data-dragging":me||void 0,children:[W&&S.jsx("div",{className:"flex justify-center py-2","aria-hidden":"true",children:S.jsx("div",{className:"h-1 w-8 rounded-claudius-full bg-claudius-border"})}),S.jsx($c,{title:B,subtitle:V,titleId:fe,closeLabel:He,onClose:P}),S.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[$&&S.jsx(Wc,{sources:$.sources,onClose:()=>ue(null)}),S.jsxs("div",{ref:ne,role:"log","aria-label":Ce,className:"h-full space-y-3 overflow-y-auto px-4 py-4",children:[a.length===0&&!y&&S.jsx("div",{className:"mr-auto flex max-w-[85%]",children:S.jsx("div",{className:"rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-2.5 text-sm leading-relaxed text-claudius-assistant-bubble-text",children:ee})}),a.map(b=>S.jsx(Ac,{role:b.role,content:b.content,isStreaming:b.id===v,sources:b.sources,toolUses:b.toolUses,toolUsedLabel:U==null?void 0:U.toolUsed,toolDetailsLabel:U==null?void 0:U.toolDetails,isSourceActive:($==null?void 0:$.messageId)===b.id,onSourceClick:()=>{($==null?void 0:$.messageId)===b.id?ue(null):b.sources&&b.sources.length>0&&ue({messageId:b.id,sources:b.sources})}},b.id)),d&&!(v!==null&&a.some(b=>b.id===v&&b.content.length>0))&&S.jsx(Kc,{label:(U==null?void 0:U.typingIndicator)??"Assistant is typing"}),y&&S.jsx(Qc,{message:y,retryLabel:(U==null?void 0:U.errorRetry)??"Retry",onRetry:w&&N&&!d?N:void 0})]})]}),S.jsx("div",{"data-claudius-live":"assistant","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:_e&&_e.id!==v?bc(_e.content):""}),S.jsx(Uc,{onSend:R,isLoading:d,isStreaming:u,onStop:L,placeholder:oe,translations:U})]})}function nf({message:a,position:d,onOpen:u,onDismiss:v,dismissLabel:y}){const w=d.startsWith("bottom"),R=d.endsWith("right"),L=["claudius-greeting-bubble","fixed z-40 max-w-xs",w?"bottom-20":"top-20",R?"right-4":"left-4"].join(" ");return S.jsxs("div",{className:L,role:"status","aria-live":"polite",children:[S.jsx("button",{type:"button",onClick:u,className:"block w-full rounded-claudius-lg bg-claudius-surface p-4 pr-8 text-left text-sm font-body text-claudius-text shadow-claudius-floating ring-1 ring-claudius-border transition hover:shadow-claudius-floating-hover focus:outline-none focus:ring-2 focus:ring-claudius-accent",children:a}),S.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),v()},"aria-label":y,className:"absolute right-1 top-1 flex h-6 w-6 items-center justify-center rounded-claudius-full text-claudius-text-muted hover:bg-claudius-surface-muted focus:outline-none focus:ring-2 focus:ring-claudius-accent",children:S.jsx("span",{"aria-hidden":"true",children:"×"})})]})}const ru={en:{title:"Chat",subtitle:"Ask me anything",welcomeMessage:"Hi! How can I help you today?",closeChat:"Close chat",chatMessages:"Chat messages",typingIndicator:"Assistant is typing",placeholder:"Type your message...",sendMessage:"Send message",stopGenerating:"Stop generating",toolUsed:"Used tool:",toolDetails:"Tool details",typeYourMessage:"Type your message",openChat:"Open chat",dismissGreeting:"Dismiss greeting",errorGeneric:"Something went wrong. Please try again.",errorConnection:"Failed to connect. Please try again.",errorTimeout:"Request timed out. Please try again.",errorRateLimitMinute:"Too many requests. Please wait a minute.",errorRateLimitHour:"Hourly limit reached. Please try again later.",errorRetry:"Retry"},es:{title:"Chat",subtitle:"Pregúntame lo que quieras",welcomeMessage:"¡Hola! ¿En qué puedo ayudarte hoy?",closeChat:"Cerrar chat",chatMessages:"Mensajes del chat",typingIndicator:"El asistente está escribiendo",placeholder:"Escribe tu mensaje...",sendMessage:"Enviar mensaje",stopGenerating:"Detener la respuesta",toolUsed:"Herramienta usada:",toolDetails:"Detalles de la herramienta",typeYourMessage:"Escribe tu mensaje",openChat:"Abrir chat",dismissGreeting:"Descartar saludo",errorGeneric:"Algo salió mal. Inténtalo de nuevo.",errorConnection:"No se pudo conectar. Inténtalo de nuevo.",errorTimeout:"La solicitud tardó demasiado. Inténtalo de nuevo.",errorRateLimitMinute:"Demasiadas solicitudes. Espera un minuto.",errorRateLimitHour:"Has alcanzado el límite por hora. Inténtalo más tarde.",errorRetry:"Reintentar"},fr:{title:"Chat",subtitle:"Posez-moi vos questions",welcomeMessage:"Bonjour ! Comment puis-je vous aider aujourd'hui ?",closeChat:"Fermer le chat",chatMessages:"Messages du chat",typingIndicator:"L'assistant écrit",placeholder:"Saisissez votre message...",sendMessage:"Envoyer le message",stopGenerating:"Arrêter la génération",toolUsed:"Outil utilisé :",toolDetails:"Détails de l'outil",typeYourMessage:"Saisissez votre message",openChat:"Ouvrir le chat",dismissGreeting:"Ignorer le message d'accueil",errorGeneric:"Une erreur s'est produite. Veuillez réessayer.",errorConnection:"Échec de la connexion. Veuillez réessayer.",errorTimeout:"La requête a expiré. Veuillez réessayer.",errorRateLimitMinute:"Trop de requêtes. Veuillez patienter une minute.",errorRateLimitHour:"Limite horaire atteinte. Veuillez réessayer plus tard.",errorRetry:"Réessayer"},de:{title:"Chat",subtitle:"Fragen Sie mich alles",welcomeMessage:"Hallo! Wie kann ich Ihnen heute helfen?",closeChat:"Chat schließen",chatMessages:"Chat-Nachrichten",typingIndicator:"Der Assistent schreibt",placeholder:"Geben Sie Ihre Nachricht ein...",sendMessage:"Nachricht senden",stopGenerating:"Generierung stoppen",toolUsed:"Verwendetes Tool:",toolDetails:"Tool-Details",typeYourMessage:"Geben Sie Ihre Nachricht ein",openChat:"Chat öffnen",dismissGreeting:"Begrüßung schließen",errorGeneric:"Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.",errorConnection:"Verbindung fehlgeschlagen. Bitte versuchen Sie es erneut.",errorTimeout:"Zeitüberschreitung der Anfrage. Bitte versuchen Sie es erneut.",errorRateLimitMinute:"Zu viele Anfragen. Bitte warten Sie eine Minute.",errorRateLimitHour:"Stündliches Limit erreicht. Bitte versuchen Sie es später erneut.",errorRetry:"Erneut versuchen"}};function lu(a){if(!a)return;const d=a.toLowerCase().split("-")[0];return Object.prototype.hasOwnProperty.call(ru,d)?d:void 0}function rf(){const a=typeof document<"u"?lu(document.documentElement.lang):void 0;if(a)return a;const d=typeof navigator<"u"?lu(navigator.language):void 0;return d||"en"}function lf(a={}){const{locale:d,translations:u}=a,v=ru[d??rf()];return u?{...v,...u}:{...v}}const ou=["accent","accentText","accentSoft","accentTextMuted","surface","surfaceMuted","text","textMuted","border","userBubble","userBubbleText","assistantBubble","assistantBubbleText","field","error","errorSurface","errorText","link","scrim"],of=["sm","md","lg","full","tail"],uf=["elevated","floating","floatingHover"],sf=["heading","body"],iu={default:{name:"default"},minimal:{name:"minimal",colors:{accent:"#171717",accentText:"#ffffff",surface:"#ffffff",surfaceMuted:"#f5f5f5",text:"#171717",textMuted:"#737373",border:"#e5e5e5",link:"#171717"},colorsDark:{accent:"#fafafa",accentText:"#171717",surface:"#0a0a0a",surfaceMuted:"#1c1c1c",text:"#fafafa",textMuted:"#a3a3a3",border:"#2e2e2e",field:"#1c1c1c",link:"#fafafa"},radii:{sm:"4px",md:"6px",lg:"10px"},shadows:{elevated:"0 4px 16px rgb(0 0 0 / 0.12)",floating:"0 2px 8px rgb(0 0 0 / 0.12)",floatingHover:"0 4px 12px rgb(0 0 0 / 0.16)"}},playful:{name:"playful",colors:{accent:"#8b5cf6",surfaceMuted:"#f5f3ff",assistantBubbleText:"#4c1d95",link:"#7c3aed"},colorsDark:{accent:"#a78bfa",surfaceMuted:"#2e1065",assistantBubbleText:"#ede9fe",link:"#c4b5fd"},radii:{sm:"12px",md:"16px",lg:"24px",tail:"8px"},shadows:{elevated:"0 24px 48px -12px rgb(139 92 246 / 0.35)",floating:"0 10px 20px -5px rgb(139 92 246 / 0.4)",floatingHover:"0 16px 28px -6px rgb(139 92 246 / 0.5)"},fonts:{heading:"ui-rounded, 'Hiragino Maru Gothic ProN', system-ui",body:"ui-rounded, 'Hiragino Maru Gothic ProN', system-ui"}},corporate:{name:"corporate",colors:{accent:"#1e3a5f",surfaceMuted:"#f3f4f6",text:"#1f2937",textMuted:"#6b7280",border:"#d1d5db",link:"#1d4ed8"},colorsDark:{accent:"#2c5282",link:"#93c5fd"},radii:{sm:"4px",md:"6px",lg:"8px",tail:"2px"},shadows:{elevated:"0 8px 24px rgb(15 23 42 / 0.16)",floating:"0 4px 12px rgb(15 23 42 / 0.18)",floatingHover:"0 6px 16px rgb(15 23 42 / 0.24)"},fonts:{heading:"'Segoe UI', 'Helvetica Neue', Arial, system-ui",body:"'Segoe UI', 'Helvetica Neue', Arial, system-ui"}}};function af(a){return Object.prototype.hasOwnProperty.call(iu,a)}const cf=new Set(["light","dark","auto"]);function ff(a){if(a===void 0)return{mode:"light"};if(typeof a=="string"){if(cf.has(a))return{mode:a};if(af(a)){const d=iu[a];return{mode:d.colorScheme??"light",theme:d}}return{mode:"light",url:a}}return{mode:a.colorScheme??"light",theme:a}}function df(a){return a.replace(/[A-Z]/g,d=>`-${d.toLowerCase()}`)}function pf(a,d){console.warn(`[Claudius] Ignoring unknown theme token "${d}" in "${a}"`)}function Vn(a,d,u,v,y,w=""){if(y)for(const[R,L]of Object.entries(y)){if(!v.includes(R)){pf(d,R);continue}typeof L=="string"&&(a[`${u}${df(R)}${w}`]=L)}}function hf(a){const d={};Vn(d,"colors","--cl-color-",ou,a.colors);for(const[u,v]of Object.entries({...d}))d[`${u}-dark`]=v;return Vn(d,"colorsDark","--cl-color-",ou,a.colorsDark,"-dark"),Vn(d,"radii","--cl-radius-",of,a.radii),Vn(d,"shadows","--cl-shadow-",uf,a.shadows),Vn(d,"fonts","--cl-font-",sf,a.fonts),d}function mf(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}function vf(a){const d=O.useMemo(()=>ff(a),[a]),[u,v]=O.useState(null),y=d.url;O.useEffect(()=>{if(v(null),!y)return;const N=new AbortController;return fetch(y,{signal:N.signal}).then(P=>{if(!P.ok)throw new Error(`HTTP ${P.status}`);return P.json()}).then(P=>{if(!mf(P))throw new Error("theme JSON must be an object");v(P)}).catch(P=>{N.signal.aborted||console.error(`[Claudius] Failed to load theme from ${y}:`,P)}),()=>N.abort()},[y]);const w=d.theme??u??null,R=(u==null?void 0:u.colorScheme)??d.mode,L=O.useMemo(()=>w?hf(w):{},[w]);return{mode:R,cssVars:L}}const uu="claudius:triggers:dismissed";function gf(){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(uu)==="1"}catch{return!1}}function yf(){if(!(typeof window>"u"))try{window.sessionStorage.setItem(uu,"1")}catch{}}function su({apiUrl:a,title:d,subtitle:u,welcomeMessage:v,placeholder:y,persistMessages:w,storageKeyPrefix:R,requestTimeoutMs:L,theme:N="light",accentColor:P,position:B="bottom-right",locale:V,translations:ee,triggers:oe,plugins:ie,streaming:U=!0}){const[W,fe]=O.useState(!1),[ye,ne]=O.useState(null),[$,ue]=O.useState(gf),he=O.useRef(!1),me=Sc("(max-width: 639px)"),q=O.useMemo(()=>lf({locale:V,translations:ee}),[V,ee]),{messages:He,isLoading:Ce,isStreaming:_e,streamingMessageId:b,error:ke,canRetry:Be,sendMessage:Ae,stop:je,retry:de}=xc({apiUrl:a,persistMessages:w,storageKeyPrefix:R,timeoutMs:L,translations:q,plugins:ie,streaming:U}),M=O.useRef(null),H=O.useRef(W),{mode:E,cssVars:p}=vf(N),[x,X]=O.useState(!1);O.useEffect(()=>{if(E!=="auto")return;const ze=window.matchMedia("(prefers-color-scheme: dark)");X(ze.matches);const Wn=Pr=>X(Pr.matches);return ze.addEventListener("change",Wn),()=>ze.removeEventListener("change",Wn)},[E]),O.useEffect(()=>{var ze;H.current&&!W&&((ze=M.current)==null||ze.focus()),H.current=W},[W]);const Y=O.useCallback(()=>{ue(!0),yf()},[]),D=O.useCallback(()=>{fe(!1),he.current&&(he.current=!1,Y())},[Y]),G=O.useCallback(()=>{fe(ze=>!ze)},[]),Z=O.useCallback(()=>{he.current=!0,ne(null),fe(!0)},[]),te=O.useCallback(ze=>{ne(ze)},[]),le=O.useCallback(()=>{ne(null),Z()},[Z]),Le=O.useCallback(()=>{ne(null),Y()},[Y]);Ec({triggers:oe,enabled:!$&&!W,onOpen:Z,onGreeting:te});const Ve=E==="dark"||E==="auto"&&x,St={...p,...P?{"--cl-color-accent":P,"--cl-color-accent-dark":P}:{}},It=Object.keys(St).length>0?St:void 0;return S.jsx("div",{className:"claudius-root",style:It,children:S.jsxs("div",{"data-claudius-dark":Ve?"true":"false",children:[W&&me&&S.jsx("div",{className:"claudius-scrim fixed inset-0 z-40 bg-claudius-scrim",onClick:D,"aria-hidden":"true"}),W&&S.jsx(tf,{messages:He,isLoading:Ce,isStreaming:_e,streamingMessageId:b,error:ke,canRetry:Be,onSend:Ae,onStop:je,onRetry:de,onClose:D,title:d??q.title,subtitle:u??q.subtitle,welcomeMessage:v??q.welcomeMessage,placeholder:y??q.placeholder,position:B,translations:q,isMobile:me}),!(W&&me)&&S.jsx(_c,{ref:M,isOpen:W,onClick:G,position:B,translations:q}),!W&&ye&&S.jsx(nf,{message:ye,position:B,onOpen:le,onDismiss:Le,dismissLabel:q.dismissGreeting})]})})}const wf="1.13.0";typeof window<"u"&&(window.ClaudiusWidgetVersion=wf);function au(){const a=window.ClaudiusConfig;if(!(a!=null&&a.apiUrl)){console.error("[Claudius] Missing ClaudiusConfig.apiUrl");return}const d=document.createElement("div");d.id="claudius-chat-widget",document.body.appendChild(d),Ji.createRoot(d).render(S.jsx(su,{apiUrl:a.apiUrl,title:a.title,subtitle:a.subtitle,welcomeMessage:a.welcomeMessage,placeholder:a.placeholder,persistMessages:a.persistMessages,storageKeyPrefix:a.storageKeyPrefix,requestTimeoutMs:a.requestTimeoutMs,theme:a.theme,accentColor:a.accentColor,position:a.position,locale:a.locale,translations:a.translations,triggers:a.triggers}))}class cu extends HTMLElement{constructor(){super(...arguments);nn(this,"root",null);nn(this,"container",null)}static get observedAttributes(){return["api-url","title","subtitle","welcome-message","placeholder","persist-messages","storage-key-prefix","request-timeout-ms","theme","accent-color","position"]}connectedCallback(){this.container=document.createElement("div"),this.appendChild(this.container),this.root=Ji.createRoot(this.container),this.render()}disconnectedCallback(){this.root&&(this.root.unmount(),this.root=null),this.container&&(this.container.remove(),this.container=null)}attributeChangedCallback(){this.render()}render(){if(!this.root)return;const u=this.getAttribute("api-url");if(!u){console.error("[Claudius] Missing api-url attribute on <claudius-chat>");return}const v=this.getAttribute("persist-messages"),y=v===null?void 0:v!=="false",w=this.getAttribute("request-timeout-ms"),R=w===null?void 0:Number(w);this.root.render(S.jsx(su,{apiUrl:u,title:this.getAttribute("title")??void 0,subtitle:this.getAttribute("subtitle")??void 0,welcomeMessage:this.getAttribute("welcome-message")??void 0,placeholder:this.getAttribute("placeholder")??void 0,persistMessages:y,storageKeyPrefix:this.getAttribute("storage-key-prefix")??void 0,requestTimeoutMs:R!==void 0&&Number.isFinite(R)?R:void 0,theme:this.getAttribute("theme")??void 0,accentColor:this.getAttribute("accent-color")??void 0,position:this.getAttribute("position")??void 0}))}}return typeof customElements<"u"&&!customElements.get("claudius-chat")&&customElements.define("claudius-chat",cu),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",au):au(),Nt.ClaudiusChat=cu,Object.defineProperty(Nt,Symbol.toStringTag,{value:"Module"}),Nt})({});
|
|
46
|
+
`);return d.map((u,v)=>S.jsxs("span",{children:[Dc(u,`l${v}`),v<d.length-1&&S.jsx("br",{})]},v))}const Ac=O.memo(function({role:d,content:u,isStreaming:v=!1,sources:y,toolUses:w,toolUsedLabel:R="Used tool:",toolDetailsLabel:L="Tool details",onSourceClick:N,isSourceActive:P}){const B=d==="user",V=v?Tc(u):u,ee=B||u!==""||!(w!=null&&w.length);return S.jsxs("div",{className:`${B?"ml-auto":"mr-auto"} max-w-[85%]`,children:[ee&&S.jsx("div",{className:`rounded-claudius-bubble px-4 py-2.5 text-sm leading-relaxed font-body ${B?"bg-claudius-user-bubble text-claudius-user-bubble-text rounded-br-claudius-tail":"bg-claudius-assistant-bubble text-claudius-assistant-bubble-text rounded-bl-claudius-tail"}`,children:Ic(V)}),!B&&w&&w.length>0&&S.jsx("div",{className:"mt-1 space-y-1",children:w.map((oe,ie)=>S.jsx(zc,{toolUse:oe,usedLabel:R,detailsLabel:L},`${oe.name}-${ie}`))}),!B&&y&&y.length>0&&N&&S.jsx("div",{className:"mt-1",children:S.jsx(Rc,{count:y.length,isActive:P??!1,onClick:N})})]})}),Yl=2e3,Fc=1800;function Uc({onSend:a,isLoading:d,isStreaming:u=!1,onStop:v,placeholder:y,translations:w}){const[R,L]=O.useState(""),N=O.useRef(null),P=R.length,B=P>=Fc,V=P>=Yl,ee=y??(w==null?void 0:w.placeholder)??"Type your message...",oe=(w==null?void 0:w.sendMessage)??"Send message",ie=(w==null?void 0:w.stopGenerating)??"Stop generating",U=(w==null?void 0:w.typeYourMessage)??"Type your message",W=u&&!!v;O.useEffect(()=>{var ne;d||(ne=N.current)==null||ne.focus()},[d]);const fe=ne=>{ne.preventDefault();const $=R.trim();!$||V||(a($),L(""))},ye=ne=>{const $=ne.target.value;$.length<=Yl&&L($)};return S.jsxs("form",{onSubmit:fe,className:"border-t border-claudius-border bg-claudius-surface p-3",children:[S.jsxs("div",{className:"flex gap-2",children:[S.jsx("input",{ref:N,type:"text",value:R,onChange:ye,placeholder:ee,disabled:d,"aria-label":U,"aria-describedby":B?"char-count":void 0,className:"flex-1 rounded-claudius-sm border border-claudius-border bg-claudius-field px-3 py-2 text-sm font-body text-claudius-text placeholder:text-claudius-text-muted focus:border-claudius-accent focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50"}),W?S.jsx("button",{type:"button",onClick:v,"aria-label":ie,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm bg-claudius-accent text-claudius-accent-text transition-colors hover:opacity-90",children:S.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:S.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})}):S.jsx("button",{type:"submit",disabled:d||V,"aria-label":oe,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm bg-claudius-accent text-claudius-accent-text transition-colors hover:opacity-90 disabled:opacity-50",children:S.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[S.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),S.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),B&&S.jsxs("div",{id:"char-count",className:`mt-1 text-xs text-right ${V?"text-claudius-error":"text-claudius-text-muted"}`,"aria-live":"polite",children:[P,"/",Yl]})]})}const Hc=["blog","page","external"],Bc={blog:"Blog",page:"Page",external:"External"};function Vc(a){try{return new URL(a).hostname}catch{return a}}const Wc=O.memo(function({sources:d,onClose:u}){const v=Hc.map(w=>({type:w,label:Bc[w],items:d.filter(R=>R.type===w)})).filter(w=>w.items.length>0),y=d.length===1?"1 source found":`${d.length} sources found`;return S.jsxs("div",{className:"absolute inset-y-0 left-0 z-10 flex w-[280px] flex-col border-r-2 border-claudius-border bg-claudius-surface rounded-r-claudius-lg transition-transform duration-200 ease-out",children:[S.jsxs("div",{className:"flex items-center justify-between border-b border-claudius-border px-4 py-3",children:[S.jsxs("div",{children:[S.jsx("h3",{className:"text-sm font-heading font-semibold text-claudius-text",children:"Sources"}),S.jsx("p",{className:"text-xs text-claudius-text-muted",children:y})]}),S.jsx("button",{onClick:u,"aria-label":"Close sources",className:"flex h-7 w-7 items-center justify-center rounded-claudius-full text-claudius-text-muted transition-colors hover:bg-claudius-surface-muted hover:text-claudius-text",children:S.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[S.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),S.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),S.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-4",children:v.map(w=>S.jsxs("div",{children:[S.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-claudius-text-muted",children:w.label}),S.jsx("div",{className:"space-y-2",children:w.items.map(R=>{const L=bi(R.url);return L?S.jsxs("a",{href:L,target:"_blank",rel:"noopener noreferrer",className:"block rounded-claudius-md border-2 border-claudius-border bg-claudius-surface-muted p-3 transition-colors hover:bg-claudius-border",children:[S.jsx("p",{className:"truncate text-sm font-medium text-claudius-text",children:R.title}),S.jsx("p",{className:"mt-0.5 text-xs text-claudius-text-muted",children:Vc(L)})]},L):null})})]},w.type))})]})});function $c({title:a,subtitle:d,titleId:u,closeLabel:v,onClose:y}){return S.jsxs("div",{className:"flex items-center gap-3 bg-claudius-accent px-5 py-4",children:[S.jsx("div",{"aria-hidden":"true",className:"flex h-8 w-8 items-center justify-center rounded-claudius-full bg-claudius-accent-soft text-sm font-bold text-claudius-accent-text",children:a.charAt(0).toUpperCase()}),S.jsxs("div",{className:"flex-1",children:[S.jsx("h2",{id:u,className:"text-sm font-heading font-semibold text-claudius-accent-text",children:a}),S.jsx("p",{className:"text-xs text-claudius-accent-text",children:d})]}),S.jsx("button",{onClick:y,"aria-label":v,className:"flex h-10 w-10 items-center justify-center rounded-claudius-full text-claudius-accent-text-muted transition-colors hover:bg-claudius-accent-soft hover:text-claudius-accent-text",children:S.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[S.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),S.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}function Qc({message:a,retryLabel:d,onRetry:u}){return S.jsxs("div",{role:"alert",className:"mx-auto flex max-w-[90%] flex-col items-center gap-2 rounded-claudius-sm bg-claudius-error-surface px-3 py-2 text-center text-xs text-claudius-error",children:[S.jsx("span",{children:a}),u&&S.jsx("button",{type:"button",onClick:u,className:"rounded-claudius-md bg-claudius-error px-3 py-1 text-xs font-semibold text-claudius-error-text transition-opacity hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-claudius-error focus-visible:ring-offset-1",children:d})]})}function Kc({label:a}){return S.jsx("div",{role:"status","aria-live":"polite","aria-label":a,className:"mr-auto flex max-w-[85%]",children:S.jsxs("div",{className:"flex gap-1 rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-3",children:[S.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:0ms]"}),S.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:150ms]"}),S.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:300ms]"})]})})}function Gc(a,d,u){const[v,y]=O.useState(0),w=O.useRef(0),R=O.useRef(0),L=O.useRef(0),N=O.useRef(!1);return O.useEffect(()=>{const P=a.current;if(!u||!P)return;const B=oe=>{if(P.scrollTop>0){N.current=!1;return}N.current=!0,R.current=oe.touches[0].clientY,L.current=Date.now()},V=oe=>{if(!N.current)return;let ie=oe.touches[0].clientY-R.current;ie<0&&(ie=ie*.3),w.current=ie,y(ie)},ee=()=>{if(!N.current)return;N.current=!1;const oe=w.current,ie=(Date.now()-L.current)/1e3,U=P.getBoundingClientRect().height,W=ie>.05&&oe>0&&oe/ie>500,fe=oe>U*.3;W||fe?d():(w.current=0,y(0))};return P.addEventListener("touchstart",B,{passive:!0}),P.addEventListener("touchmove",V,{passive:!0}),P.addEventListener("touchend",ee),()=>{P.removeEventListener("touchstart",B),P.removeEventListener("touchmove",V),P.removeEventListener("touchend",ee)}},[a,d,u]),{offsetY:v}}const Yc='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Xc(a,d){O.useEffect(()=>{const u=a.current;if(!u)return;const v=y=>{if(y.key!=="Tab")return;const w=Array.from(u.querySelectorAll(Yc)).filter(P=>!P.hasAttribute("aria-hidden"));if(w.length===0)return;const R=w[0],L=w[w.length-1],N=document.activeElement;y.shiftKey&&N===R?(y.preventDefault(),L.focus()):!y.shiftKey&&N===L&&(y.preventDefault(),R.focus())};return u.addEventListener("keydown",v),()=>u.removeEventListener("keydown",v)},[a,d])}const Zc=/\*\*([^*]+)\*\*/g,Jc=/\*([^*]+)\*/g,qc=/https?:\/\/[^\s)]+/g;function bc(a){return a.replace(Zc,"$1").replace(Jc,"$1").replace(qc,d=>{try{return new URL(d).hostname}catch{return d}})}const ef={"bottom-right":"bottom-24 right-3 sm:right-6","bottom-left":"bottom-24 left-3 sm:left-6","top-right":"top-24 right-3 sm:right-6","top-left":"top-24 left-3 sm:left-6"};function tf({messages:a,isLoading:d,isStreaming:u=!1,streamingMessageId:v=null,error:y,canRetry:w=!1,onSend:R,onStop:L,onRetry:N,onClose:P,title:B="Chat",subtitle:V="Ask me anything",welcomeMessage:ee="Hi! How can I help you today?",placeholder:oe,position:ie="bottom-right",translations:U,isMobile:W=!1}){const fe=O.useId(),ye=O.useRef(null),ne=O.useRef(null),[$,ue]=O.useState(null);Xc(ye,!0);const{offsetY:he}=Gc(ne,P,W),me=he!==0,q=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1;O.useEffect(()=>{const b=ne.current;b&&(b.scrollTop=b.scrollHeight)},[a,d]),O.useEffect(()=>{const b=ke=>{ke.key==="Escape"&&!ke.isComposing&&P()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[P]);const He=(U==null?void 0:U.closeChat)??"Close chat",Ce=(U==null?void 0:U.chatMessages)??"Chat messages",_e=[...a].reverse().find(b=>b.role==="assistant");return S.jsxs("div",{ref:ye,role:"dialog","aria-modal":W?"true":void 0,"aria-labelledby":fe,className:W?"claudius-bottom-sheet fixed inset-x-0 bottom-0 z-50 flex h-[90vh] w-full flex-col overflow-hidden rounded-t-claudius-lg bg-claudius-surface shadow-claudius-elevated font-body":`fixed ${ef[ie]} z-50 flex h-[min(500px,calc(100vh-7rem))] w-[calc(100vw-1.5rem)] max-w-[380px] sm:max-w-[400px] md:max-w-[440px] flex-col overflow-hidden rounded-claudius-lg bg-claudius-surface shadow-claudius-elevated font-body`,style:W&&!q?{transform:`translateY(${Math.max(0,he)}px)`}:void 0,"data-dragging":me||void 0,children:[W&&S.jsx("div",{className:"flex justify-center py-2","aria-hidden":"true",children:S.jsx("div",{className:"h-1 w-8 rounded-claudius-full bg-claudius-border"})}),S.jsx($c,{title:B,subtitle:V,titleId:fe,closeLabel:He,onClose:P}),S.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[$&&S.jsx(Wc,{sources:$.sources,onClose:()=>ue(null)}),S.jsxs("div",{ref:ne,role:"log","aria-label":Ce,className:"h-full space-y-3 overflow-y-auto px-4 py-4",children:[a.length===0&&!y&&S.jsx("div",{className:"mr-auto flex max-w-[85%]",children:S.jsx("div",{className:"rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-2.5 text-sm leading-relaxed text-claudius-assistant-bubble-text",children:ee})}),a.map(b=>S.jsx(Ac,{role:b.role,content:b.content,isStreaming:b.id===v,sources:b.sources,toolUses:b.toolUses,toolUsedLabel:U==null?void 0:U.toolUsed,toolDetailsLabel:U==null?void 0:U.toolDetails,isSourceActive:($==null?void 0:$.messageId)===b.id,onSourceClick:()=>{($==null?void 0:$.messageId)===b.id?ue(null):b.sources&&b.sources.length>0&&ue({messageId:b.id,sources:b.sources})}},b.id)),d&&!(v!==null&&a.some(b=>b.id===v&&b.content.length>0))&&S.jsx(Kc,{label:(U==null?void 0:U.typingIndicator)??"Assistant is typing"}),y&&S.jsx(Qc,{message:y,retryLabel:(U==null?void 0:U.errorRetry)??"Retry",onRetry:w&&N&&!d?N:void 0})]})]}),S.jsx("div",{"data-claudius-live":"assistant","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:_e&&_e.id!==v?bc(_e.content):""}),S.jsx(Uc,{onSend:R,isLoading:d,isStreaming:u,onStop:L,placeholder:oe,translations:U})]})}function nf({message:a,position:d,onOpen:u,onDismiss:v,dismissLabel:y}){const w=d.startsWith("bottom"),R=d.endsWith("right"),L=["claudius-greeting-bubble","fixed z-40 max-w-xs",w?"bottom-20":"top-20",R?"right-4":"left-4"].join(" ");return S.jsxs("div",{className:L,role:"status","aria-live":"polite",children:[S.jsx("button",{type:"button",onClick:u,className:"block w-full rounded-claudius-lg bg-claudius-surface p-4 pr-8 text-left text-sm font-body text-claudius-text shadow-claudius-floating ring-1 ring-claudius-border transition hover:shadow-claudius-floating-hover focus:outline-none focus:ring-2 focus:ring-claudius-accent",children:a}),S.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),v()},"aria-label":y,className:"absolute right-1 top-1 flex h-6 w-6 items-center justify-center rounded-claudius-full text-claudius-text-muted hover:bg-claudius-surface-muted focus:outline-none focus:ring-2 focus:ring-claudius-accent",children:S.jsx("span",{"aria-hidden":"true",children:"×"})})]})}const ru={en:{title:"Chat",subtitle:"Ask me anything",welcomeMessage:"Hi! How can I help you today?",closeChat:"Close chat",chatMessages:"Chat messages",typingIndicator:"Assistant is typing",placeholder:"Type your message...",sendMessage:"Send message",stopGenerating:"Stop generating",toolUsed:"Used tool:",toolDetails:"Tool details",typeYourMessage:"Type your message",openChat:"Open chat",dismissGreeting:"Dismiss greeting",errorGeneric:"Something went wrong. Please try again.",errorConnection:"Failed to connect. Please try again.",errorTimeout:"Request timed out. Please try again.",errorRateLimitMinute:"Too many requests. Please wait a minute.",errorRateLimitHour:"Hourly limit reached. Please try again later.",errorRetry:"Retry"},es:{title:"Chat",subtitle:"Pregúntame lo que quieras",welcomeMessage:"¡Hola! ¿En qué puedo ayudarte hoy?",closeChat:"Cerrar chat",chatMessages:"Mensajes del chat",typingIndicator:"El asistente está escribiendo",placeholder:"Escribe tu mensaje...",sendMessage:"Enviar mensaje",stopGenerating:"Detener la respuesta",toolUsed:"Herramienta usada:",toolDetails:"Detalles de la herramienta",typeYourMessage:"Escribe tu mensaje",openChat:"Abrir chat",dismissGreeting:"Descartar saludo",errorGeneric:"Algo salió mal. Inténtalo de nuevo.",errorConnection:"No se pudo conectar. Inténtalo de nuevo.",errorTimeout:"La solicitud tardó demasiado. Inténtalo de nuevo.",errorRateLimitMinute:"Demasiadas solicitudes. Espera un minuto.",errorRateLimitHour:"Has alcanzado el límite por hora. Inténtalo más tarde.",errorRetry:"Reintentar"},fr:{title:"Chat",subtitle:"Posez-moi vos questions",welcomeMessage:"Bonjour ! Comment puis-je vous aider aujourd'hui ?",closeChat:"Fermer le chat",chatMessages:"Messages du chat",typingIndicator:"L'assistant écrit",placeholder:"Saisissez votre message...",sendMessage:"Envoyer le message",stopGenerating:"Arrêter la génération",toolUsed:"Outil utilisé :",toolDetails:"Détails de l'outil",typeYourMessage:"Saisissez votre message",openChat:"Ouvrir le chat",dismissGreeting:"Ignorer le message d'accueil",errorGeneric:"Une erreur s'est produite. Veuillez réessayer.",errorConnection:"Échec de la connexion. Veuillez réessayer.",errorTimeout:"La requête a expiré. Veuillez réessayer.",errorRateLimitMinute:"Trop de requêtes. Veuillez patienter une minute.",errorRateLimitHour:"Limite horaire atteinte. Veuillez réessayer plus tard.",errorRetry:"Réessayer"},de:{title:"Chat",subtitle:"Fragen Sie mich alles",welcomeMessage:"Hallo! Wie kann ich Ihnen heute helfen?",closeChat:"Chat schließen",chatMessages:"Chat-Nachrichten",typingIndicator:"Der Assistent schreibt",placeholder:"Geben Sie Ihre Nachricht ein...",sendMessage:"Nachricht senden",stopGenerating:"Generierung stoppen",toolUsed:"Verwendetes Tool:",toolDetails:"Tool-Details",typeYourMessage:"Geben Sie Ihre Nachricht ein",openChat:"Chat öffnen",dismissGreeting:"Begrüßung schließen",errorGeneric:"Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.",errorConnection:"Verbindung fehlgeschlagen. Bitte versuchen Sie es erneut.",errorTimeout:"Zeitüberschreitung der Anfrage. Bitte versuchen Sie es erneut.",errorRateLimitMinute:"Zu viele Anfragen. Bitte warten Sie eine Minute.",errorRateLimitHour:"Stündliches Limit erreicht. Bitte versuchen Sie es später erneut.",errorRetry:"Erneut versuchen"}};function lu(a){if(!a)return;const d=a.toLowerCase().split("-")[0];return Object.prototype.hasOwnProperty.call(ru,d)?d:void 0}function rf(){const a=typeof document<"u"?lu(document.documentElement.lang):void 0;if(a)return a;const d=typeof navigator<"u"?lu(navigator.language):void 0;return d||"en"}function lf(a={}){const{locale:d,translations:u}=a,v=ru[d??rf()];return u?{...v,...u}:{...v}}const ou=["accent","accentText","accentSoft","accentTextMuted","surface","surfaceMuted","text","textMuted","border","userBubble","userBubbleText","assistantBubble","assistantBubbleText","field","error","errorSurface","errorText","link","scrim"],of=["sm","md","lg","full","tail"],uf=["elevated","floating","floatingHover"],sf=["heading","body"],iu={default:{name:"default"},minimal:{name:"minimal",colors:{accent:"#171717",accentText:"#ffffff",surface:"#ffffff",surfaceMuted:"#f5f5f5",text:"#171717",textMuted:"#737373",border:"#e5e5e5",link:"#171717"},colorsDark:{accent:"#fafafa",accentText:"#171717",surface:"#0a0a0a",surfaceMuted:"#1c1c1c",text:"#fafafa",textMuted:"#a3a3a3",border:"#2e2e2e",field:"#1c1c1c",link:"#fafafa"},radii:{sm:"4px",md:"6px",lg:"10px"},shadows:{elevated:"0 4px 16px rgb(0 0 0 / 0.12)",floating:"0 2px 8px rgb(0 0 0 / 0.12)",floatingHover:"0 4px 12px rgb(0 0 0 / 0.16)"}},playful:{name:"playful",colors:{accent:"#8b5cf6",surfaceMuted:"#f5f3ff",assistantBubbleText:"#4c1d95",link:"#7c3aed"},colorsDark:{accent:"#a78bfa",surfaceMuted:"#2e1065",assistantBubbleText:"#ede9fe",link:"#c4b5fd"},radii:{sm:"12px",md:"16px",lg:"24px",tail:"8px"},shadows:{elevated:"0 24px 48px -12px rgb(139 92 246 / 0.35)",floating:"0 10px 20px -5px rgb(139 92 246 / 0.4)",floatingHover:"0 16px 28px -6px rgb(139 92 246 / 0.5)"},fonts:{heading:"ui-rounded, 'Hiragino Maru Gothic ProN', system-ui",body:"ui-rounded, 'Hiragino Maru Gothic ProN', system-ui"}},corporate:{name:"corporate",colors:{accent:"#1e3a5f",surfaceMuted:"#f3f4f6",text:"#1f2937",textMuted:"#6b7280",border:"#d1d5db",link:"#1d4ed8"},colorsDark:{accent:"#2c5282",link:"#93c5fd"},radii:{sm:"4px",md:"6px",lg:"8px",tail:"2px"},shadows:{elevated:"0 8px 24px rgb(15 23 42 / 0.16)",floating:"0 4px 12px rgb(15 23 42 / 0.18)",floatingHover:"0 6px 16px rgb(15 23 42 / 0.24)"},fonts:{heading:"'Segoe UI', 'Helvetica Neue', Arial, system-ui",body:"'Segoe UI', 'Helvetica Neue', Arial, system-ui"}}};function af(a){return Object.prototype.hasOwnProperty.call(iu,a)}const cf=new Set(["light","dark","auto"]);function ff(a){if(a===void 0)return{mode:"light"};if(typeof a=="string"){if(cf.has(a))return{mode:a};if(af(a)){const d=iu[a];return{mode:d.colorScheme??"light",theme:d}}return{mode:"light",url:a}}return{mode:a.colorScheme??"light",theme:a}}function df(a){return a.replace(/[A-Z]/g,d=>`-${d.toLowerCase()}`)}function pf(a,d){console.warn(`[Claudius] Ignoring unknown theme token "${d}" in "${a}"`)}function Vn(a,d,u,v,y,w=""){if(y)for(const[R,L]of Object.entries(y)){if(!v.includes(R)){pf(d,R);continue}typeof L=="string"&&(a[`${u}${df(R)}${w}`]=L)}}function hf(a){const d={};Vn(d,"colors","--cl-color-",ou,a.colors);for(const[u,v]of Object.entries({...d}))d[`${u}-dark`]=v;return Vn(d,"colorsDark","--cl-color-",ou,a.colorsDark,"-dark"),Vn(d,"radii","--cl-radius-",of,a.radii),Vn(d,"shadows","--cl-shadow-",uf,a.shadows),Vn(d,"fonts","--cl-font-",sf,a.fonts),d}function mf(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}function vf(a){const d=O.useMemo(()=>ff(a),[a]),[u,v]=O.useState(null),y=d.url;O.useEffect(()=>{if(v(null),!y)return;const N=new AbortController;return fetch(y,{signal:N.signal}).then(P=>{if(!P.ok)throw new Error(`HTTP ${P.status}`);return P.json()}).then(P=>{if(!mf(P))throw new Error("theme JSON must be an object");v(P)}).catch(P=>{N.signal.aborted||console.error(`[Claudius] Failed to load theme from ${y}:`,P)}),()=>N.abort()},[y]);const w=d.theme??u??null,R=(u==null?void 0:u.colorScheme)??d.mode,L=O.useMemo(()=>w?hf(w):{},[w]);return{mode:R,cssVars:L}}const uu="claudius:triggers:dismissed";function gf(){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(uu)==="1"}catch{return!1}}function yf(){if(!(typeof window>"u"))try{window.sessionStorage.setItem(uu,"1")}catch{}}function su({apiUrl:a,title:d,subtitle:u,welcomeMessage:v,placeholder:y,persistMessages:w,storageKeyPrefix:R,requestTimeoutMs:L,theme:N="light",accentColor:P,position:B="bottom-right",locale:V,translations:ee,triggers:oe,plugins:ie,streaming:U=!0}){const[W,fe]=O.useState(!1),[ye,ne]=O.useState(null),[$,ue]=O.useState(gf),he=O.useRef(!1),me=Sc("(max-width: 639px)"),q=O.useMemo(()=>lf({locale:V,translations:ee}),[V,ee]),{messages:He,isLoading:Ce,isStreaming:_e,streamingMessageId:b,error:ke,canRetry:Be,sendMessage:Ae,stop:je,retry:de}=xc({apiUrl:a,persistMessages:w,storageKeyPrefix:R,timeoutMs:L,translations:q,plugins:ie,streaming:U}),M=O.useRef(null),H=O.useRef(W),{mode:E,cssVars:p}=vf(N),[x,X]=O.useState(!1);O.useEffect(()=>{if(E!=="auto")return;const ze=window.matchMedia("(prefers-color-scheme: dark)");X(ze.matches);const Wn=Pr=>X(Pr.matches);return ze.addEventListener("change",Wn),()=>ze.removeEventListener("change",Wn)},[E]),O.useEffect(()=>{var ze;H.current&&!W&&((ze=M.current)==null||ze.focus()),H.current=W},[W]);const Y=O.useCallback(()=>{ue(!0),yf()},[]),D=O.useCallback(()=>{fe(!1),he.current&&(he.current=!1,Y())},[Y]),G=O.useCallback(()=>{fe(ze=>!ze)},[]),Z=O.useCallback(()=>{he.current=!0,ne(null),fe(!0)},[]),te=O.useCallback(ze=>{ne(ze)},[]),le=O.useCallback(()=>{ne(null),Z()},[Z]),Le=O.useCallback(()=>{ne(null),Y()},[Y]);Ec({triggers:oe,enabled:!$&&!W,onOpen:Z,onGreeting:te});const Ve=E==="dark"||E==="auto"&&x,St={...p,...P?{"--cl-color-accent":P,"--cl-color-accent-dark":P}:{}},It=Object.keys(St).length>0?St:void 0;return S.jsx("div",{className:"claudius-root",style:It,children:S.jsxs("div",{"data-claudius-dark":Ve?"true":"false",children:[W&&me&&S.jsx("div",{className:"claudius-scrim fixed inset-0 z-40 bg-claudius-scrim",onClick:D,"aria-hidden":"true"}),W&&S.jsx(tf,{messages:He,isLoading:Ce,isStreaming:_e,streamingMessageId:b,error:ke,canRetry:Be,onSend:Ae,onStop:je,onRetry:de,onClose:D,title:d??q.title,subtitle:u??q.subtitle,welcomeMessage:v??q.welcomeMessage,placeholder:y??q.placeholder,position:B,translations:q,isMobile:me}),!(W&&me)&&S.jsx(_c,{ref:M,isOpen:W,onClick:G,position:B,translations:q}),!W&&ye&&S.jsx(nf,{message:ye,position:B,onOpen:le,onDismiss:Le,dismissLabel:q.dismissGreeting})]})})}const wf="1.14.0";typeof window<"u"&&(window.ClaudiusWidgetVersion=wf);function au(){const a=window.ClaudiusConfig;if(!(a!=null&&a.apiUrl)){console.error("[Claudius] Missing ClaudiusConfig.apiUrl");return}const d=document.createElement("div");d.id="claudius-chat-widget",document.body.appendChild(d),Ji.createRoot(d).render(S.jsx(su,{apiUrl:a.apiUrl,title:a.title,subtitle:a.subtitle,welcomeMessage:a.welcomeMessage,placeholder:a.placeholder,persistMessages:a.persistMessages,storageKeyPrefix:a.storageKeyPrefix,requestTimeoutMs:a.requestTimeoutMs,theme:a.theme,accentColor:a.accentColor,position:a.position,locale:a.locale,translations:a.translations,triggers:a.triggers}))}class cu extends HTMLElement{constructor(){super(...arguments);nn(this,"root",null);nn(this,"container",null)}static get observedAttributes(){return["api-url","title","subtitle","welcome-message","placeholder","persist-messages","storage-key-prefix","request-timeout-ms","theme","accent-color","position"]}connectedCallback(){this.container=document.createElement("div"),this.appendChild(this.container),this.root=Ji.createRoot(this.container),this.render()}disconnectedCallback(){this.root&&(this.root.unmount(),this.root=null),this.container&&(this.container.remove(),this.container=null)}attributeChangedCallback(){this.render()}render(){if(!this.root)return;const u=this.getAttribute("api-url");if(!u){console.error("[Claudius] Missing api-url attribute on <claudius-chat>");return}const v=this.getAttribute("persist-messages"),y=v===null?void 0:v!=="false",w=this.getAttribute("request-timeout-ms"),R=w===null?void 0:Number(w);this.root.render(S.jsx(su,{apiUrl:u,title:this.getAttribute("title")??void 0,subtitle:this.getAttribute("subtitle")??void 0,welcomeMessage:this.getAttribute("welcome-message")??void 0,placeholder:this.getAttribute("placeholder")??void 0,persistMessages:y,storageKeyPrefix:this.getAttribute("storage-key-prefix")??void 0,requestTimeoutMs:R!==void 0&&Number.isFinite(R)?R:void 0,theme:this.getAttribute("theme")??void 0,accentColor:this.getAttribute("accent-color")??void 0,position:this.getAttribute("position")??void 0}))}}return typeof customElements<"u"&&!customElements.get("claudius-chat")&&customElements.define("claudius-chat",cu),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",au):au(),Nt.ClaudiusChat=cu,Object.defineProperty(Nt,Symbol.toStringTag,{value:"Module"}),Nt})({});
|
package/package.json
CHANGED