claudius-chat-widget 1.17.0 → 1.17.1
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.cjs +2 -2
- package/dist/claudius.iife.js +2 -2
- package/dist/claudius.js +15 -4
- package/package.json +1 -1
package/dist/claudius.cjs
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
`));return typeof r!="object"||r===null?null:{event:t,data:r}}catch{return null}}function Ke(e){return typeof e=="string"?{content:e}:e}function Te(e,t,n){console.error(`[claudius] plugin "${e.name}" failed in ${t}:`,n)}async function dt(e,t,n){let r=t;for(const s of e){if(!s.onBeforeSend)continue;let o=null;const i={...n,respondWith(l){o={type:"respond",message:r,reply:Ke(l)}},abort(l){o={type:"abort",reason:l}}};try{const l=await s.onBeforeSend(r,i);if(o)return o;l&&(r=l)}catch(l){Te(s,"onBeforeSend",l)}}return{type:"send",message:r}}async function ft(e,t,n){let r=t;for(const s of e)if(s.onAfterReceive)try{const o=await s.onAfterReceive(r,n);o&&(r=o)}catch(o){Te(s,"onAfterReceive",o)}return r}async function ht(e,t,n){for(const r of e){if(!r.onError)continue;let s=null;const o={...n,respondWith(i){s=Ke(i)}};try{if(await r.onError(t,o),s)return s}catch(i){Te(r,"onError",i)}}return null}const ge={maxSizeBytes:5*1024*1024,maxCount:5,allowedTypes:["image/jpeg","image/png","image/gif","image/webp","application/pdf"]};function pt(e){return e?e===!0?ge:{maxSizeBytes:e.maxSizeBytes??ge.maxSizeBytes,maxCount:e.maxCount??ge.maxCount,allowedTypes:(e.allowedTypes??ge.allowedTypes).map(t=>t.trim().toLowerCase()).filter(Boolean)}:null}function je(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${e} B`;const t=e/1024;if(t<1024)return`${Math.round(t)} KB`;const n=t/1024;return`${Number.isInteger(n)?n:n.toFixed(1)} MB`}const mt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",pdf:"application/pdf"};function qe(e){var r;const t=(e.type||"").trim().toLowerCase();if(t)return t;const n=((r=e.name.split(".").pop())==null?void 0:r.toLowerCase())??"";return mt[n]??""}function gt(e){return e.startsWith("image/")}function xt(e){if(gt(e.mediaType)){if(e.url)try{const t=new URL(e.url);if(t.protocol==="http:"||t.protocol==="https:")return e.url}catch{}if(e.data)return`data:${e.mediaType};base64,${e.data}`}}function bt(e,t,n){const r=[],s=[];let o=Math.max(0,n.maxCount-t);for(const i of e){const l=qe(i);!l||!n.allowedTypes.includes(l)?s.push({file:i,reason:"type"}):i.size>n.maxSizeBytes||i.size===0?s.push({file:i,reason:"size"}):o<=0?s.push({file:i,reason:"count"}):(r.push(i),o-=1)}return{accepted:r,rejected:s}}function yt(e){return new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>n(r.error??new Error("Failed to read file")),r.onload=()=>{const s=String(r.result??""),o=s.indexOf(",");t(o>=0?s.slice(o+1):s)},r.readAsDataURL(e)})}let Me=0;function wt(){return Me+=1,`att-${Date.now().toString(36)}-${Me}`}async function vt(e){const t=await yt(e);return{id:wt(),name:e.name||"attachment",mediaType:qe(e),size:e.size,data:t}}function Ye(e){return e.map(t=>{var n;return(n=t.attachments)!=null&&n.some(r=>r.data)?{...t,attachments:t.attachments.map(r=>{if(!r.data)return r;const s={...r};return delete s.data,s})}:t})}function jt(e,t){if(!t||t.length===0)return e;const n=new Map(t.map(r=>[r.id,r]));return e.map(r=>{var s;return(s=r.attachments)!=null&&s.some(o=>n.has(o.id))?{...r,attachments:r.attachments.map(o=>{const i=n.get(o.id);if(!i)return o;const l={...o,key:i.key,url:i.url,expiresAt:i.expiresAt};return delete l.data,l})}:r})}const Rt=200,Et="claudius:messages",fe=()=>new Date().toISOString();function St(e,t){let n;try{n=new URL(t).host}catch{n=t}return`${e}:${n}`}function Se(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function Tt(e){const t=Se();if(!t)return[];try{const n=t.getItem(e);if(!n)return[];const r=JSON.parse(n);return Array.isArray(r)?r:[]}catch{return[]}}function kt({apiUrl:e,persistMessages:t=!0,storageKeyPrefix:n=Et,timeoutMs:r,translations:s,plugins:o,streaming:i=!0}){const l=c.useMemo(()=>new Ve(e,{debounceMs:0,timeoutMs:r}),[e,r]),u=St(n,e),d=t?Tt(u):[],[f,w]=c.useState(d),[S,x]=c.useState(!1),[h,p]=c.useState(!1),[j,b]=c.useState(null),[E,y]=c.useState(null),[v,k]=c.useState(!1),L=c.useRef(d.length),C=c.useRef(!1),R=c.useRef(d),P=c.useRef(null),N=c.useRef(o??[]);N.current=o??[];const $=c.useCallback(m=>{if(!t)return;const I=Se();if(I)try{const O=Ye(m.slice(-Rt));I.setItem(u,JSON.stringify(O))}catch{}},[t,u]),V=()=>(L.current+=1,`msg-${L.current}`),F=c.useCallback((m,I)=>{if(!s)return I??"Something went wrong. Please try again.";switch(m){case"TIMEOUT":return s.errorTimeout;case"NETWORK_ERROR":return s.errorConnection;case"RATE_LIMITED":return I!=null&&I.includes("minute")?s.errorRateLimitMinute:s.errorRateLimitHour;case"ATTACHMENT_QUOTA_EXCEEDED":return s.errorAttachmentQuota;case"ATTACHMENTS_DISABLED":case"ATTACHMENT_INVALID":case"ATTACHMENT_TOO_LARGE":return s.errorAttachmentRejected;case"VALIDATION_ERROR":case"CONFIG_ERROR":case"SERVICE_ERROR":case"UNKNOWN_ERROR":default:return I??s.errorGeneric}},[s]),K=c.useCallback(m=>!(m instanceof G)||m.code==="TIMEOUT"||m.code==="NETWORK_ERROR"||m.code==="RATE_LIMITED"||m.code==="SERVICE_ERROR"||m.code==="UNKNOWN_ERROR"||m.status>=500||m.status===0,[]),U=c.useCallback(async m=>{var Q,_,B;x(!0),C.current=!0,y(null),k(!1);const I=i&&typeof l.streamMessage=="function";let O=null;const Z=T=>{if(O===null){O=V(),b(O);const A=[...R.current,{id:O,role:"assistant",content:"",createdAt:fe(),...T}];R.current=A,w(A)}else{const A=O,M=R.current.map(z=>z.id===A?{...z,...T}:z);R.current=M,w(M)}},J=()=>{if(O===null)return;const T=O,A=R.current.filter(M=>M.id!==T);R.current=A,w(A)};try{let T,A,M,z,q=!1;if(I){const H=new AbortController;P.current=H,p(!0);const ee=await l.streamMessage(m,{signal:H.signal,onChunk:(ie,ae)=>Z({content:ae}),onToolUse:(ie,ae)=>Z({toolUses:[...ae]})});T=ee.reply,A=ee.sources,M=ee.toolUses,z=ee.attachments,q=ee.aborted??!1}else{const H=await l.sendMessage(m);T=H.reply,A=H.sources,M=H.toolUses,z=H.attachments}if(q&&!T){J();return}const se=((Q=R.current.find(H=>H.id===O))==null?void 0:Q.createdAt)??fe();let W={id:O??V(),role:"assistant",content:T,createdAt:se,sources:A,toolUses:M};N.current.length>0&&!q&&(W=await ft(N.current,W,{messages:m,apiUrl:e}),W.createdAt||(W={...W,createdAt:se}));const de=O!==null?R.current.map(H=>H.id===W.id?W:H):[...m,W],oe=jt(de,z);R.current=oe,w(oe),$(oe)}catch(T){if(T instanceof ve)return;if(T instanceof G&&((_=T.code)!=null&&_.startsWith("ATTACHMENT"))&&m.length>0){const A=m[m.length-1];if(A.role==="user"&&((B=A.attachments)!=null&&B.length)){const M=m.slice(0,-1);R.current=M,w(M),$(M)}}if(O!==null){$(R.current),T instanceof G?y(F(T.code,T.message)):y((s==null?void 0:s.errorConnection)??"Failed to connect. Please try again."),k(!1);return}if(N.current.length>0){const A=T instanceof Error?T:new Error(String(T)),M=await ht(N.current,A,{messages:m,apiUrl:e});if(M){const z={id:V(),role:"assistant",content:M.content,createdAt:fe(),sources:M.sources},q=[...m,z];R.current=q,w(q),$(q),y(null),k(!1);return}}T instanceof G?y(F(T.code,T.message)):y((s==null?void 0:s.errorConnection)??"Failed to connect. Please try again."),k(K(T))}finally{x(!1),C.current=!1,p(!1),b(null),P.current=null}},[e,l,F,K,$,i,s]),te=c.useCallback(()=>{var m;(m=P.current)==null||m.abort()},[]),ne=c.useCallback(async(m,I)=>{const O=m.trim(),Z=(I==null?void 0:I.filter(B=>B&&B.id))??[];if(!O&&Z.length===0||C.current)return;const J={id:V(),role:"user",content:O,createdAt:fe(),...Z.length>0?{attachments:Z}:{}};let Q=J;if(N.current.length>0){const B=await dt(N.current,J,{messages:R.current,apiUrl:e});if(B.type==="abort")return;const T=A=>A.createdAt?A:{...A,createdAt:J.createdAt};if(B.type==="respond"){const A={id:V(),role:"assistant",content:B.reply.content,createdAt:fe(),sources:B.reply.sources},M=[...R.current,T(B.message),A];R.current=M,w(M),$(M),y(null),k(!1);return}Q=T(B.message)}const _=[...R.current,Q];R.current=_,w(_),$(_),await U(_)},[e,$,U]),re=c.useCallback(async()=>{if(C.current)return;const m=R.current[R.current.length-1];!m||m.role!=="user"||await U(R.current)},[U]),X=c.useCallback(()=>{if(R.current=[],w([]),y(null),k(!1),t){const m=Se();if(!m)return;try{m.removeItem(u)}catch{}}},[t,u]);return{messages:f,isLoading:S,isStreaming:h,streamingMessageId:j,error:E,canRetry:v,sendMessage:ne,stop:te,retry:re,clearMessages:X}}function At(e){const[t,n]=c.useState(()=>typeof window>"u"?!1:window.matchMedia(e).matches);return c.useEffect(()=>{const r=window.matchMedia(e);n(r.matches);const s=o=>n(o.matches);return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[e]),t}function be(e,t){return e instanceof RegExp?e.test(t):t.toLowerCase().includes(e.toLowerCase())}function Ct(){const e=document.documentElement,t=document.body,n=e.scrollTop||t.scrollTop||0,r=Math.max(e.scrollHeight,t.scrollHeight),s=e.clientHeight||window.innerHeight,o=r-s;return o<=0?100:n/o*100}function Mt({triggers:e,enabled:t,onOpen:n,onGreeting:r}){c.useEffect(()=>{if(!t||!e||e.length===0)return;const s=new Set,o=[],i=typeof window<"u"?window.location.href:"",l=(u,d)=>{s.has(u)||(s.add(u),d==="open"?n():r(d.greeting))};return e.forEach((u,d)=>{switch(u.on){case"url":{be(u.pattern,i)&&l(d,u.action);break}case"time":{if(u.matchUrl&&!be(u.matchUrl,i))return;const f=window.setTimeout(()=>l(d,u.action),Math.max(0,u.seconds*1e3));o.push(()=>window.clearTimeout(f));break}case"scroll":{if(u.matchUrl&&!be(u.matchUrl,i))return;const f=()=>{Ct()>=u.percent&&l(d,u.action)};f(),window.addEventListener("scroll",f,{passive:!0}),o.push(()=>window.removeEventListener("scroll",f));break}case"exit-intent":{if(u.matchUrl&&!be(u.matchUrl,i))return;const f=w=>{w.clientY<=0&&l(d,u.action)};document.addEventListener("mouseleave",f),o.push(()=>document.removeEventListener("mouseleave",f));break}}}),()=>{o.forEach(u=>u())}},[e,t,n,r])}const Nt={"bottom-right":"bottom-6 right-6","bottom-left":"bottom-6 left-6","top-right":"top-6 right-6","top-left":"top-6 left-6"},Dt=c.forwardRef(function({isOpen:t,onClick:n,position:r="bottom-right",translations:s},o){const i=t?(s==null?void 0:s.closeChat)??"Close chat":(s==null?void 0:s.openChat)??"Open chat";return a.jsx("button",{ref:o,onClick:n,"aria-label":i,className:`fixed ${Nt[r]} 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:t?a.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:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}):a.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:a.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"})})})}),Lt=c.memo(function({count:t,isActive:n,onClick:r}){return a.jsxs("button",{onClick:r,"aria-label":"View sources",title:"View sources",className:`group relative flex h-7 w-7 items-center justify-center rounded-claudius-full transition-colors ${n?"bg-claudius-accent text-claudius-accent-text":"text-claudius-text-muted hover:bg-claudius-surface-muted hover:text-claudius-text"}`,children:[a.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:[a.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a.jsx("polyline",{points:"14 2 14 8 20 8"}),a.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),a.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]}),a.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:t})]})}),It=["http:","https:"];function Re(e){if(!e||typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t);return It.includes(n.protocol)?t:null}catch{return null}}function Ot(){return a.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:[a.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function Ne({label:e,onClick:t}){return a.jsx("button",{type:"button",onClick:t,"aria-label":e,className:"absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-claudius-full bg-claudius-text text-claudius-surface shadow-claudius-floating hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-claudius-accent",children:a.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round","aria-hidden":"true",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})}const Ze=c.memo(function({attachment:t,variant:n,onRemove:r,removeLabel:s}){const o=xt(t),i=n==="composer",l=`${t.name} (${je(t.size)})`,u=t.url?Re(t.url):null;if(o){const f=a.jsx("img",{src:o,alt:t.name,title:l,loading:"lazy",className:i?"h-12 w-12 rounded-claudius-sm border border-claudius-border object-cover":"max-h-48 max-w-full rounded-claudius-sm object-contain"});return a.jsxs("div",{className:"relative inline-block",children:[!i&&u?a.jsxs("a",{href:u,target:"_blank",rel:"noopener noreferrer",children:[f,a.jsxs("span",{className:"sr-only",children:[l," (opens in a new tab)"]})]}):f,r&&s&&a.jsx(Ne,{label:s,onClick:r})]})}const d=a.jsxs("span",{title:l,className:`inline-flex max-w-[220px] items-center gap-1.5 rounded-claudius-sm border px-2 py-1 text-xs ${i?"border-claudius-border bg-claudius-field text-claudius-text":"border-current/30 bg-transparent"}`,children:[a.jsx(Ot,{}),a.jsx("span",{className:"truncate",children:t.name}),a.jsx("span",{className:"shrink-0 opacity-70",children:je(t.size)})]});return a.jsxs("div",{className:"relative inline-block",children:[!i&&u?a.jsxs("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:"underline-offset-2 hover:underline",children:[d,a.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]}):d,r&&s&&a.jsx(Ne,{label:s,onClick:r})]})}),De=c.forwardRef(function({label:t,onClick:n,children:r},s){return a.jsx("button",{ref:s,type:"button",onClick:n,"aria-label":t,title:t,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:a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:r})})});function Pt({state:e,labels:t,onPlay:n,onPause:r,onResume:s,onStop:o}){var f;const i=c.useRef(null),l=c.useRef(null),u=!!((f=i.current)!=null&&f.contains(document.activeElement));c.useEffect(()=>{var w,S;e==="idle"&&u&&!((w=i.current)!=null&&w.contains(document.activeElement))&&((S=l.current)==null||S.focus())},[e,u]);const d=e==="idle"?{label:t.play,onClick:n}:e==="paused"?{label:t.resume,onClick:s}:{label:t.pause,onClick:r};return a.jsxs("div",{ref:i,className:"flex items-center gap-1",children:[a.jsx(De,{ref:l,...d,children:e==="idle"?a.jsxs(a.Fragment,{children:[a.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),a.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07",fill:"none"}),a.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14",fill:"none"})]}):e==="paused"?a.jsx("polygon",{points:"6 3 20 12 6 21 6 3"}):a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1"}),a.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1"})]})}),e!=="idle"&&a.jsx(De,{label:t.stop,onClick:o,children:a.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})]})}function $t(e){const t=e.lastIndexOf(`
|
|
6
6
|
`),n=t===-1?"":e.slice(0,t+1);let r=t===-1?e:e.slice(t+1);return r=_t(r),r=Ft(r),n+r}function Ut(e){const t=[];for(let n=0;n<e.length-1;n++)e[n]==="*"&&e[n+1]==="*"&&(t.push(n),n++);return t}function Bt(e){const t=[];for(let n=0;n<e.length;n++)if(e[n]==="*"){if(e[n+1]==="*"){n++;continue}t.push(n)}return t}function _t(e){const t=Ut(e);if(t.length%2===0)return e;const n=t[t.length-1],r=e.slice(n+2);return r.trim()===""?e.slice(0,n)+r:e+"**"}function Ft(e){const t=Bt(e);if(t.length%2===0)return e;const n=t[t.length-1],r=e.slice(n+1);return r.trim()===""?e.slice(0,n)+r:e+"*"}function zt({toolUse:e,usedLabel:t,detailsLabel:n}){const[r,s]=c.useState(!1),o=e.input!==void 0||e.result!==void 0;return a.jsxs("div",{className:"text-xs text-claudius-text-muted",children:[a.jsxs("button",{type:"button",disabled:!o,onClick:()=>s(i=>!i),"aria-expanded":o?r: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:[a.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:a.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"})}),a.jsxs("span",{children:[t," ",a.jsx("span",{className:"font-mono text-claudius-text",children:e.name}),e.isError&&a.jsx("span",{className:"text-claudius-error",children:" ✕"})]}),o&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"sr-only",children:n}),a.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:r?"rotate-180":void 0,children:a.jsx("polyline",{points:"6 9 12 15 18 9"})})]})]}),r&&o&&a.jsxs("div",{className:"mt-1 overflow-x-auto rounded-claudius-sm border border-claudius-border bg-claudius-field p-2 font-mono",children:[e.input!==void 0&&a.jsx("pre",{className:"whitespace-pre-wrap break-all",children:JSON.stringify(e.input,null,2)}),e.result!==void 0&&a.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-all border-t border-claudius-border pt-1",children:e.result})]})]})}const Le=/(https?:\/\/[^\s)]+)/,Ie=/(\*\*[^*]+\*\*)/,Oe=/(\*[^*]+\*)/;function Ht(e,t){const n=e.match(/[.,;:!?'"]+$/),r=n?e.slice(0,-n[0].length):e,s=n?n[0]:"",o=Re(r);return o?a.jsxs(a.Fragment,{children:[a.jsxs("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"underline font-medium hover:opacity-80 text-claudius-link",children:[o.replace(/^https?:\/\//,""),a.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]},t),s]}):e}function Wt(e,t){const n=e.split(Ie),r=[];return n.forEach((s,o)=>{if(Ie.test(s)){const i=s.slice(2,-2);r.push(a.jsx("strong",{children:i},`${t}-b${o}`))}else s.split(Oe).forEach((l,u)=>{if(Oe.test(l)){const d=l.slice(1,-1);r.push(a.jsx("em",{children:d},`${t}-b${o}-i${u}`))}else l.split(Le).forEach((f,w)=>{Le.test(f)?r.push(Ht(f,`${t}-b${o}-i${u}-u${w}`)):f&&r.push(f)})})}),r}function Gt(e){const t=e.split(`
|
|
7
7
|
`);return t.map((n,r)=>a.jsxs("span",{children:[Wt(n,`l${r}`),r<t.length-1&&a.jsx("br",{})]},r))}const Vt=c.memo(function({role:t,content:n,isStreaming:r=!1,sources:s,attachments:o,toolUses:i,toolUsedLabel:l="Used tool:",toolDetailsLabel:u="Tool details",onSourceClick:d,isSourceActive:f,speech:w}){const S=t==="user",x=!!o&&o.length>0,h=r?$t(n):n,p=S||n!==""||!(i!=null&&i.length);return a.jsxs("div",{className:`${S?"ml-auto":"mr-auto"} max-w-[85%]`,children:[p&&a.jsxs("div",{className:`rounded-claudius-bubble px-4 py-2.5 text-sm leading-relaxed font-body ${S?"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:[x&&a.jsx("ul",{className:`flex flex-wrap gap-2 ${n?"mb-2":""}`,"aria-label":"Attachments",children:o.map(j=>a.jsx("li",{children:a.jsx(Ze,{attachment:j,variant:"message"})},j.id))}),(n!==""||!x)&&Gt(h)]}),!S&&i&&i.length>0&&a.jsx("div",{className:"mt-1 space-y-1",children:i.map((j,b)=>a.jsx(zt,{toolUse:j,usedLabel:l,detailsLabel:u},`${j.name}-${b}`))}),!S&&s&&s.length>0&&d&&a.jsx("div",{className:"mt-1",children:a.jsx(Lt,{count:s.length,isActive:f??!1,onClick:d})}),!S&&w&&a.jsx("div",{className:"mt-1",children:a.jsx(Pt,{...w})})]})}),Je={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",attachFile:"Attach a file",removeAttachment:"Remove attachment",attachmentsLabel:"Attachments",dropFilesHint:"Drop files to attach",attachmentTooLarge:"{name} is too large. The maximum size is {max}.",attachmentTypeNotAllowed:"{name} is not a supported file type.",attachmentTooMany:"You can attach up to {max} files per message.",voiceInput:"Voice input",voiceInputHold:"Hold to talk",voiceListening:"Listening...",voicePermissionDenied:"Microphone access is blocked. Allow it in your browser settings to use voice input.",voiceNoSpeech:"No speech was detected. Please try again.",voiceNoMicrophone:"No microphone was found.",voiceUnavailable:"Voice input is not available right now.",readAloud:"Read aloud",pauseReading:"Pause reading",resumeReading:"Resume reading",stopReading:"Stop reading",moreOptions:"More options",copyAsMarkdown:"Copy as Markdown",downloadAsMarkdown:"Download as Markdown",downloadAsJson:"Download as JSON",copiedToClipboard:"Copied to clipboard",copyFailed:"Could not copy. Try downloading instead.",transcriptTitle:"Chat transcript",transcriptExported:"Exported {date}",transcriptUser:"User",transcriptAssistant:"Assistant",transcriptAttachments:"Attachments:",transcriptSources:"Sources:",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.",errorAttachmentRejected:"An attachment was rejected. Please remove it and try again.",errorAttachmentQuota:"Upload limit reached. Please try again later.",errorRetry:"Retry"},Ee=Je;function Kt(e){return{...Ee,...e}}function Pe(e){return e.key===" "||e.key==="Enter"}function qt({mode:e,isListening:t,disabled:n=!1,onStart:r,onStop:s,label:o}){const i=e==="hold",l=c.useRef(!1),u=()=>{n||l.current||(l.current=!0,r({held:!0}))},d=()=>{l.current&&(l.current=!1,s())},f=h=>{i&&h.detail!==0||(t?s():r({held:!1}))},w=h=>{var p,j;!i||h.button!==0||((j=(p=h.currentTarget).setPointerCapture)==null||j.call(p,h.pointerId),u())},S=h=>{!i||!Pe(h)||(h.preventDefault(),h.repeat||u())},x=h=>{!i||!Pe(h)||(h.preventDefault(),d())};return a.jsx("button",{type:"button",disabled:n,"aria-label":o,"aria-pressed":t,title:o,onClick:f,onPointerDown:w,onPointerUp:d,onPointerCancel:d,onLostPointerCapture:d,onKeyDown:S,onKeyUp:x,onBlur:d,onContextMenu:i?h=>h.preventDefault():void 0,style:i?{WebkitTouchCallout:"none"}:void 0,className:`flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm border transition-colors focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50 ${t?"border-claudius-accent bg-claudius-accent text-claudius-accent-text focus:ring-2 focus:ring-offset-2 focus:ring-offset-claudius-surface":"border-claudius-border bg-claudius-field text-claudius-text-muted hover:text-claudius-text focus:border-claudius-accent"} ${i?"touch-none select-none":""}`,children:t&&!i?a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:a.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})}):a.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:[a.jsx("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),a.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),a.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]})})}function Yt({active:e}){return a.jsxs("span",{"aria-hidden":"true","data-claudius-voice-level":e?"active":"idle",className:"claudius-voice-level pointer-events-none absolute right-3 top-1/2 flex h-4 -translate-y-1/2 items-center gap-0.5 text-claudius-accent",children:[a.jsx("span",{}),a.jsx("span",{}),a.jsx("span",{}),a.jsx("span",{})]})}function ye(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>r in t?String(t[r]):n)}const Zt={en:"en-US",es:"es-ES",fr:"fr-FR",de:"de-DE"},Jt=["toggle","hold"];function $e(e,t){if(!(!e||!e.includes("-")))return e.toLowerCase().split("-")[0]===t?e:void 0}function Qe(e,t){const n=t==null?void 0:t.trim();if(n)return n;const r=typeof document<"u"?$e(document.documentElement.lang,e):void 0;if(r)return r;const s=typeof navigator<"u"?$e(navigator.language,e):void 0;return s||Zt[e]}function Qt(e,t){const n=typeof e=="object"&&e!==null&&!Array.isArray(e);if(e!==!0&&!n)return null;const r=e===!0?{}:e,s={input:r.input??!0,output:r.output??!0,mode:Jt.includes(r.mode)?r.mode:"toggle",autoSubmit:r.autoSubmit??!1,lang:Qe(t,r.lang)};return s.input||s.output?s:null}function Xt(e,t,n){const r=t.trim();if(!r)return e;const s=e.trimEnd();return(s?`${s} ${r}`:r).slice(0,n)}function en(e){const t=[];let n=0;for(let r=0;r<e.length;r++){const s=e[r];(s===`
|
|
8
|
-
`||s==="。"||s==="!"||s==="?"||(s==="."||s==="!"||s==="?")&&(r+1===e.length||/\s/.test(e[r+1])))&&(t.push(e.slice(n,r+1)),n=r+1)}return n<e.length&&t.push(e.slice(n)),t}function tn(e,t=150){const n=[];let r="";const s=()=>{const o=r.trim();o&&n.push(o),r=""};for(const o of en(e)){if((r+o).trim().length<=t){r+=o;continue}if(s(),o.trim().length<=t){r=o;continue}for(let i of o.trim().split(/\s+/)){for(r&&`${r} ${i}`.length>t&&s();i.length>t;)n.push(i.slice(0,t)),i=i.slice(t);r=r?`${r} ${i}`:i}}return s(),n}function Ue(){if(typeof window>"u")return;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition}function nn(e){switch(e){case"not-allowed":case"service-not-allowed":return"permission";case"no-speech":return"no-speech";case"audio-capture":return"no-microphone";default:return"unavailable"}}function rn(e){const[t]=c.useState(()=>Ue()!==void 0),[n,r]=c.useState(!1),[s,o]=c.useState(!1),i=c.useRef(null),l=c.useRef(!1),u=c.useRef(e);c.useEffect(()=>{u.current=e});const d=c.useCallback(x=>{x.onstart=null,x.onend=null,x.onerror=null,x.onresult=null,x.onspeechstart=null,x.onspeechend=null,i.current===x&&(i.current=null),r(!1),o(!1)},[]),f=c.useCallback(()=>{const x=i.current;x&&(d(x),x.abort())},[d]),w=c.useCallback(()=>{const x=i.current;return x?(l.current?x.stop():f(),!0):!1},[f]),S=c.useCallback(()=>{var b,E;const x=Ue();if(!x||i.current)return!1;const h=new x;h.lang=u.current.lang,h.interimResults=!0,h.continuous=!1;let p="";const j=()=>{l.current=!0};h.onstart=j,h.onspeechstart=()=>{j(),o(!0)},h.onspeechend=()=>o(!1),h.onresult=y=>{var L,C;let v="",k="";for(let R=0;R<y.results.length;R++){const P=y.results[R];P.isFinal?v+=P[0].transcript:k+=P[0].transcript}p=v,j(),o(!0),(C=(L=u.current).onTranscript)==null||C.call(L,v+k)},h.onerror=y=>{var v,k;y.error!=="aborted"&&((k=(v=u.current).onError)==null||k.call(v,nn(y.error))),d(h),h.abort()},h.onend=()=>{var y,v;d(h),(v=(y=u.current).onEnd)==null||v.call(y,p)},i.current=h,l.current=!1,r(!0);try{h.start()}catch{return d(h),(E=(b=u.current).onError)==null||E.call(b,"unavailable"),!1}return!0},[d]);return c.useEffect(()=>f,[f]),{isSupported:t,isListening:n,isSpeechDetected:s,start:S,stop:w,abort:f}}const he=2e3,sn=1800;function Be(e){var n;const t=(n=e.dataTransfer)==null?void 0:n.types;return!!t&&Array.from(t).includes("Files")}function on({onSend:e,isLoading:t,isStreaming:n=!1,onStop:r,placeholder:s,translations:o,attachments:i=null,voice:l=null,onVoiceStart:u,isReadingAloud:d=!1}){const f=o??Ee,[w,S]=c.useState(""),[x,h]=c.useState([]),[p,j]=c.useState(null),[b,E]=c.useState(!1),[y,v]=c.useState(null),k=c.useRef(null),L=c.useRef(null),C=c.useRef([]),R=c.useRef(0),P=c.useRef(""),N=c.useRef(""),$=c.useRef(!1),V=c.useRef(!1),F=c.useRef(!1),K=g=>{P.current=g,S(g)},U=w.length,te=U>=sn,ne=U>=he,re=s??f.placeholder,X=!!i&&x.length<i.maxCount,m=n&&!!r;c.useEffect(()=>{var g;t||(g=k.current)==null||g.focus()},[t]);const I=c.useCallback((g,D)=>{if(!i)return"";switch(D){case"size":return ye(f.attachmentTooLarge,{name:g,max:je(i.maxSizeBytes)});case"type":return ye(f.attachmentTypeNotAllowed,{name:g});case"count":return ye(f.attachmentTooMany,{max:i.maxCount})}},[i,f]),O=c.useCallback(async g=>{if(!i||g.length===0)return;const{accepted:D,rejected:ce}=bt(g,C.current.length,i);if(j(ce.length>0?I(ce[0].file.name,ce[0].reason):null),D.length===0)return;const ot=await Promise.all(D.map(vt));C.current=[...C.current,...ot],h(C.current)},[i,I]),Z=c.useCallback(g=>{C.current=C.current.filter(D=>D.id!==g),h(C.current),j(null)},[]),J=()=>{const g=P.current.trim(),D=C.current;!g&&D.length===0||P.current.length>=he||(D.length>0?e(g,D):e(g),K(""),C.current=[],h([]),j(null),v(null))},Q=g=>{switch(g){case"permission":return f.voicePermissionDenied;case"no-speech":return f.voiceNoSpeech;case"no-microphone":return f.voiceNoMicrophone;case"unavailable":return f.voiceUnavailable}},_=rn({lang:(l==null?void 0:l.lang)??"en-US",onTranscript:g=>K(Xt(N.current,g,he)),onEnd:g=>{const D=g.trim()!=="";if(D&&(V.current=!0),!$.current){A();return}D&&M()},onError:g=>{g==="no-speech"&&V.current||(F.current=!0,v(Q(g)))}}),B=!!(l!=null&&l.input)&&_.isSupported,T=_.isListening;c.useEffect(()=>{const g=k.current;T&&g&&(g.scrollLeft=g.scrollWidth)},[T,w]);const A=()=>{l!=null&&l.autoSubmit&&V.current&&!F.current&&J()},M=()=>{const g=P.current;_.start()&&(N.current=g)},z=({held:g})=>{v(null),$.current=g,V.current=!1,F.current=!1,u==null||u(),M()},q=()=>{const g=$.current;$.current=!1,!_.stop()&&g&&A()},se=()=>{$.current=!1,_.abort()},{abort:W}=_;c.useEffect(()=>{!t&&!d||($.current=!1,W())},[t,d,W]);const de=g=>{g.preventDefault(),se(),J()},oe=g=>{const D=g.target.value;D.length<=he&&(se(),v(null),K(D))},H=g=>{const D=Array.from(g.target.files??[]);g.target.value="",O(D)},ee=g=>{var ce;if(!i)return;const D=Array.from(((ce=g.clipboardData)==null?void 0:ce.files)??[]);D.length!==0&&(g.preventDefault(),O(D))},ie=g=>{!i||!Be(g)||(g.preventDefault(),R.current+=1,E(!0))},ae=g=>{!i||!Be(g)||g.preventDefault()},Y=()=>{i&&(R.current=Math.max(0,R.current-1),R.current===0&&E(!1))},xe=g=>{var D;i&&(g.preventDefault(),R.current=0,E(!1),O(Array.from(((D=g.dataTransfer)==null?void 0:D.files)??[])))};return a.jsxs("form",{onSubmit:de,onDragEnter:ie,onDragOver:ae,onDragLeave:Y,onDrop:xe,"data-drag-over":b||void 0,className:`relative border-t border-claudius-border bg-claudius-surface p-3 ${b?"ring-2 ring-inset ring-claudius-accent":""}`,children:[b&&a.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-claudius-surface text-sm font-medium text-claudius-accent",children:f.dropFilesHint}),i&&x.length>0&&a.jsx("ul",{"aria-label":f.attachmentsLabel,className:"mb-2 flex flex-wrap gap-3 pt-1",children:x.map(g=>a.jsx("li",{children:a.jsx(Ze,{attachment:g,variant:"composer",onRemove:()=>Z(g.id),removeLabel:`${f.removeAttachment}: ${g.name}`})},g.id))}),a.jsxs("div",{className:"flex gap-2",children:[i&&a.jsxs(a.Fragment,{children:[a.jsx("input",{ref:L,type:"file",multiple:!0,hidden:!0,tabIndex:-1,accept:i.allowedTypes.join(","),onChange:H,"aria-label":f.attachFile}),a.jsx("button",{type:"button",onClick:()=>{var g;return(g=L.current)==null?void 0:g.click()},disabled:t||!X,"aria-label":f.attachFile,title:f.attachFile,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm border border-claudius-border bg-claudius-field text-claudius-text-muted transition-colors hover:text-claudius-text focus:border-claudius-accent focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})})})]}),a.jsxs("div",{className:"relative min-w-0 flex-1",children:[a.jsx("input",{ref:k,type:"text",value:w,onChange:oe,onPaste:ee,placeholder:T?f.voiceListening:re,disabled:t,"aria-label":f.typeYourMessage,"aria-describedby":te?"char-count":void 0,className:`h-full w-full rounded-claudius-sm border border-claudius-border bg-claudius-field py-2 pl-3 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 ${T?"pr-10":"pr-3"}`}),T&&a.jsx(Yt,{active:_.isSpeechDetected})]}),B&&l&&a.jsx(qt,{mode:l.mode,isListening:T,disabled:t,onStart:z,onStop:q,label:l.mode==="hold"?f.voiceInputHold:f.voiceInput}),m?a.jsx("button",{type:"button",onClick:r,"aria-label":f.stopGenerating,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:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:a.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})}):a.jsx("button",{type:"submit",disabled:t||ne,"aria-label":f.sendMessage,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:a.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:[a.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),a.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),(p??y)&&a.jsx("div",{role:"alert",className:"mt-1 text-xs text-claudius-error",children:p??y}),te&&a.jsxs("div",{id:"char-count",className:`mt-1 text-xs text-right ${ne?"text-claudius-error":"text-claudius-text-muted"}`,"aria-live":"polite",children:[U,"/",he]})]})}const an=["blog","page","external"],cn={blog:"Blog",page:"Page",external:"External"};function ln(e){try{return new URL(e).hostname}catch{return e}}const un=c.memo(function({sources:t,onClose:n}){const r=an.map(o=>({type:o,label:cn[o],items:t.filter(i=>i.type===o)})).filter(o=>o.items.length>0),s=t.length===1?"1 source found":`${t.length} sources found`;return a.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:[a.jsxs("div",{className:"flex items-center justify-between border-b border-claudius-border px-4 py-3",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-heading font-semibold text-claudius-text",children:"Sources"}),a.jsx("p",{className:"text-xs text-claudius-text-muted",children:s})]}),a.jsx("button",{onClick:n,"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:a.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:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),a.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-4",children:r.map(o=>a.jsxs("div",{children:[a.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-claudius-text-muted",children:o.label}),a.jsx("div",{className:"space-y-2",children:o.items.map(i=>{const l=Re(i.url);return l?a.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:[a.jsx("p",{className:"truncate text-sm font-medium text-claudius-text",children:i.title}),a.jsx("p",{className:"mt-0.5 text-xs text-claudius-text-muted",children:ln(l)})]},l):null})})]},o.type))})]})});function dn({title:e,subtitle:t,titleId:n,closeLabel:r,onClose:s,actions:o}){return a.jsxs("div",{className:"flex items-center gap-3 bg-claudius-accent px-5 py-4",children:[a.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:e.charAt(0).toUpperCase()}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h2",{id:n,className:"text-sm font-heading font-semibold text-claudius-accent-text",children:e}),a.jsx("p",{className:"text-xs text-claudius-accent-text",children:t})]}),o,a.jsx("button",{onClick:s,"aria-label":r,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:a.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:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}function fn({message:e,retryLabel:t,onRetry:n}){return a.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:[a.jsx("span",{children:e}),n&&a.jsx("button",{type:"button",onClick:n,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:t})]})}function hn({label:e}){return a.jsx("div",{role:"status","aria-live":"polite","aria-label":e,className:"mr-auto flex max-w-[85%]",children:a.jsxs("div",{className:"flex gap-1 rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-3",children:[a.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:0ms]"}),a.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:150ms]"}),a.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:300ms]"})]})})}function pn({label:e,items:t,onOpen:n}){const[r,s]=c.useState(!1),o=c.useId(),i=c.useId(),l=c.useRef(null),u=c.useRef(null),d=c.useRef([]),f=c.useRef(null),w=b=>{f.current=b,s(!0),n==null||n()},S=b=>{var E;s(!1),(E=u.current)==null||E.focus()};c.useEffect(()=>{var E;if(!r)return;f.current!==null&&((E=d.current[f.current])==null||E.focus(),f.current=null);const b=y=>{var v;(v=l.current)!=null&&v.contains(y.target)||s(!1)};return document.addEventListener("pointerdown",b),()=>document.removeEventListener("pointerdown",b)},[r]);const x=b=>{var y;const E=t.length;(y=d.current[(b+E)%E])==null||y.focus()},h=b=>{b.key==="ArrowDown"?(b.preventDefault(),w(0)):b.key==="ArrowUp"&&(b.preventDefault(),w(t.length-1))},p=b=>{const E=d.current.findIndex(y=>y===document.activeElement);switch(b.key){case"ArrowDown":b.preventDefault(),x(E+1);break;case"ArrowUp":b.preventDefault(),x(E===-1?t.length-1:E-1);break;case"Home":b.preventDefault(),x(0);break;case"End":b.preventDefault(),x(t.length-1);break;case"Escape":b.preventDefault(),b.stopPropagation(),S();break;case"Tab":b.shiftKey&&(b.preventDefault(),S());break}},j=b=>{var y;const E=b.relatedTarget;E&&((y=l.current)!=null&&y.contains(E)||s(!1))};return a.jsxs("div",{ref:l,className:"relative",children:[a.jsx("button",{ref:u,id:o,type:"button","aria-label":e,"aria-haspopup":"menu","aria-expanded":r,"aria-controls":r?i:void 0,onClick:()=>r?S():w(0),onKeyDown:h,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:a.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"5",r:"1.75"}),a.jsx("circle",{cx:"12",cy:"12",r:"1.75"}),a.jsx("circle",{cx:"12",cy:"19",r:"1.75"})]})}),r&&a.jsx("div",{id:i,role:"menu","aria-labelledby":o,tabIndex:-1,onKeyDown:p,onBlur:j,className:"absolute right-0 top-full z-20 mt-1 min-w-[12rem] rounded-claudius-md border border-claudius-border bg-claudius-surface py-1 shadow-claudius-elevated",children:t.map((b,E)=>a.jsx("button",{ref:y=>{d.current[E]=y},type:"button",role:"menuitem",tabIndex:-1,"aria-disabled":b.disabled||void 0,onClick:()=>{b.disabled||(S(),b.onSelect())},className:"flex min-h-[40px] w-full items-center whitespace-nowrap px-4 text-left text-sm text-claudius-text hover:bg-claudius-surface-muted focus:bg-claudius-surface-muted aria-disabled:cursor-default aria-disabled:opacity-50 aria-disabled:hover:bg-transparent",children:b.label},b.id))})]})}function mn(e,t,n){const[r,s]=c.useState(0),o=c.useRef(0),i=c.useRef(0),l=c.useRef(0),u=c.useRef(!1);return c.useEffect(()=>{const d=e.current;if(!n||!d)return;const f=x=>{if(d.scrollTop>0){u.current=!1;return}u.current=!0,i.current=x.touches[0].clientY,l.current=Date.now()},w=x=>{if(!u.current)return;let h=x.touches[0].clientY-i.current;h<0&&(h=h*.3),o.current=h,s(h)},S=()=>{if(!u.current)return;u.current=!1;const x=o.current,h=(Date.now()-l.current)/1e3,p=d.getBoundingClientRect().height,j=h>.05&&x>0&&x/h>500,b=x>p*.3;j||b?t():(o.current=0,s(0))};return d.addEventListener("touchstart",f,{passive:!0}),d.addEventListener("touchmove",w,{passive:!0}),d.addEventListener("touchend",S),()=>{d.removeEventListener("touchstart",f),d.removeEventListener("touchmove",w),d.removeEventListener("touchend",S)}},[e,t,n]),{offsetY:r}}const gn='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function xn(e,t){c.useEffect(()=>{const n=e.current;if(!n)return;const r=s=>{if(s.key!=="Tab")return;const o=Array.from(n.querySelectorAll(gn)).filter(d=>!d.hasAttribute("aria-hidden"));if(o.length===0)return;const i=o[0],l=o[o.length-1],u=document.activeElement;s.shiftKey&&u===i?(s.preventDefault(),l.focus()):!s.shiftKey&&u===l&&(s.preventDefault(),i.focus())};return n.addEventListener("keydown",r),()=>n.removeEventListener("keydown",r)},[e,t])}function pe(){if(!(typeof window>"u")&&!(typeof window.SpeechSynthesisUtterance>"u"))return window.speechSynthesis??void 0}function bn(e){const[t]=c.useState(()=>pe()!==void 0),[n,r]=c.useState(null),[s,o]=c.useState(!1),i=c.useRef(0),l=c.useRef(!1),u=c.useRef([]),d=c.useCallback(()=>{i.current+=1,l.current=!1,u.current=[],r(null),o(!1)},[]),f=c.useCallback(()=>{const h=u.current.length>0;d();const p=pe();!h||!p||(p.cancel(),p.paused&&p.resume())},[d]),w=c.useCallback((h,p)=>{const j=pe();if(!j)return;d(),(j.speaking||j.pending)&&j.cancel(),j.paused&&j.resume();const b=tn(p);if(b.length===0)return;const E=i.current,y=()=>i.current===E;u.current=b.map((v,k)=>{const L=new SpeechSynthesisUtterance(v);return L.lang=e,L.onerror=C=>{if(!y())return;(C.error==="interrupted"||C.error==="canceled")&&!l.current?d():f()},L.onpause=()=>{y()&&o(!0)},L.onresume=()=>{y()&&o(!1)},L.onend=()=>{y()&&(l.current&&!j.paused?f():k===b.length-1&&d())},L}),r(h);for(const v of u.current)j.speak(v)},[e,f,d]),S=c.useCallback(()=>{const h=pe();h&&(l.current=!0,h.pause(),h.paused&&o(!0))},[]),x=c.useCallback(()=>{const h=pe();h&&(l.current=!1,h.resume(),o(!1))},[]);return c.useEffect(()=>f,[f]),{isSupported:t,activeId:n,isPaused:s,speak:w,pause:S,resume:x,cancel:f}}const yn=/^([ \t]*)(`{3,}|~{3,})(.*)$/,wn=/^( {0,3})<(?![A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\s]*>|[^\s<>@]+@[^\s<>]+>)(?=[A-Za-z!?/])/,vn=/^(?: {4}|\t)/;function Xe(e){let t=0;for(const n of e)if(n===" ")t+=1;else if(n===" ")t+=4-t%4;else break;return t}function _e(e){let t=e.length;for(;t>0&&(e[t-1]===" "||e[t-1]===" ");)t-=1;return t===e.length?e:e.slice(0,t)}function jn(e){const t=yn.exec(e);if(!t)return null;const[,n,r,s]=t;return r[0]==="`"&&s.includes("`")?null:{indent:n,indentColumns:Xe(n),char:r[0],length:r.length}}function Rn(e,t){const n=e.trim();if(n.length<t.length)return!1;for(const r of n)if(r!==t.char)return!1;return Xe(e)<=t.indentColumns+3}function En(e){const t=e.replace(/\r\n?/g,`
|
|
8
|
+
`||s==="。"||s==="!"||s==="?"||(s==="."||s==="!"||s==="?")&&(r+1===e.length||/\s/.test(e[r+1])))&&(t.push(e.slice(n,r+1)),n=r+1)}return n<e.length&&t.push(e.slice(n)),t}function tn(e,t=150){const n=[];let r="";const s=()=>{const o=r.trim();o&&n.push(o),r=""};for(const o of en(e)){if((r+o).trim().length<=t){r+=o;continue}if(s(),o.trim().length<=t){r=o;continue}for(let i of o.trim().split(/\s+/)){for(r&&`${r} ${i}`.length>t&&s();i.length>t;)n.push(i.slice(0,t)),i=i.slice(t);r=r?`${r} ${i}`:i}}return s(),n}function Ue(){if(typeof window>"u")return;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition}function nn(e){switch(e){case"not-allowed":case"service-not-allowed":return"permission";case"no-speech":return"no-speech";case"audio-capture":return"no-microphone";default:return"unavailable"}}function rn(e){const[t]=c.useState(()=>Ue()!==void 0),[n,r]=c.useState(!1),[s,o]=c.useState(!1),i=c.useRef(null),l=c.useRef(!1),u=c.useRef(e);c.useEffect(()=>{u.current=e});const d=c.useCallback(x=>{x.onstart=null,x.onend=null,x.onerror=null,x.onresult=null,x.onspeechstart=null,x.onspeechend=null,i.current===x&&(i.current=null),r(!1),o(!1)},[]),f=c.useCallback(()=>{const x=i.current;x&&(d(x),x.abort())},[d]),w=c.useCallback(()=>{const x=i.current;return x?(l.current?x.stop():f(),!0):!1},[f]),S=c.useCallback(()=>{var b,E;const x=Ue();if(!x||i.current)return!1;const h=new x;h.lang=u.current.lang,h.interimResults=!0,h.continuous=!1;let p="";const j=()=>{l.current=!0};h.onstart=j,h.onspeechstart=()=>{j(),o(!0)},h.onspeechend=()=>o(!1),h.onresult=y=>{var L,C;let v="",k="";for(let R=0;R<y.results.length;R++){const P=y.results[R];P.isFinal?v+=P[0].transcript:k+=P[0].transcript}p=v,j(),o(!0),(C=(L=u.current).onTranscript)==null||C.call(L,v+k)},h.onerror=y=>{var v,k;y.error!=="aborted"&&((k=(v=u.current).onError)==null||k.call(v,nn(y.error))),d(h),h.abort()},h.onend=()=>{var y,v;d(h),(v=(y=u.current).onEnd)==null||v.call(y,p)},i.current=h,l.current=!1,r(!0);try{h.start()}catch{return d(h),(E=(b=u.current).onError)==null||E.call(b,"unavailable"),!1}return!0},[d]);return c.useEffect(()=>f,[f]),{isSupported:t,isListening:n,isSpeechDetected:s,start:S,stop:w,abort:f}}const he=2e3,sn=1800;function Be(e){var n;const t=(n=e.dataTransfer)==null?void 0:n.types;return!!t&&Array.from(t).includes("Files")}function on({onSend:e,isLoading:t,isStreaming:n=!1,onStop:r,placeholder:s,translations:o,attachments:i=null,voice:l=null,onVoiceStart:u,isReadingAloud:d=!1}){const f=o??Ee,[w,S]=c.useState(""),[x,h]=c.useState([]),[p,j]=c.useState(null),[b,E]=c.useState(!1),[y,v]=c.useState(null),k=c.useRef(null),L=c.useRef(null),C=c.useRef([]),R=c.useRef(0),P=c.useRef(""),N=c.useRef(""),$=c.useRef(!1),V=c.useRef(!1),F=c.useRef(!1),K=g=>{P.current=g,S(g)},U=w.length,te=U>=sn,ne=U>=he,re=s??f.placeholder,X=!!i&&x.length<i.maxCount,m=n&&!!r;c.useEffect(()=>{var g;t||(g=k.current)==null||g.focus()},[t]);const I=c.useCallback((g,D)=>{if(!i)return"";switch(D){case"size":return ye(f.attachmentTooLarge,{name:g,max:je(i.maxSizeBytes)});case"type":return ye(f.attachmentTypeNotAllowed,{name:g});case"count":return ye(f.attachmentTooMany,{max:i.maxCount})}},[i,f]),O=c.useCallback(async g=>{if(!i||g.length===0)return;const{accepted:D,rejected:ce}=bt(g,C.current.length,i);if(j(ce.length>0?I(ce[0].file.name,ce[0].reason):null),D.length===0)return;const ot=await Promise.all(D.map(vt));C.current=[...C.current,...ot],h(C.current)},[i,I]),Z=c.useCallback(g=>{C.current=C.current.filter(D=>D.id!==g),h(C.current),j(null)},[]),J=()=>{const g=P.current.trim(),D=C.current;!g&&D.length===0||P.current.length>=he||(D.length>0?e(g,D):e(g),K(""),C.current=[],h([]),j(null),v(null))},Q=g=>{switch(g){case"permission":return f.voicePermissionDenied;case"no-speech":return f.voiceNoSpeech;case"no-microphone":return f.voiceNoMicrophone;case"unavailable":return f.voiceUnavailable}},_=rn({lang:(l==null?void 0:l.lang)??"en-US",onTranscript:g=>K(Xt(N.current,g,he)),onEnd:g=>{const D=g.trim()!=="";if(D&&(V.current=!0),!$.current){A();return}D&&M()},onError:g=>{g==="no-speech"&&V.current||(F.current=!0,v(Q(g)))}}),B=!!(l!=null&&l.input)&&_.isSupported,T=_.isListening;c.useEffect(()=>{const g=k.current;T&&g&&(g.scrollLeft=g.scrollWidth)},[T,w]);const A=()=>{l!=null&&l.autoSubmit&&V.current&&!F.current&&J()},M=()=>{const g=P.current;_.start()&&(N.current=g)},z=({held:g})=>{v(null),$.current=g,V.current=!1,F.current=!1,u==null||u(),M()},q=()=>{const g=$.current;$.current=!1,!_.stop()&&g&&A()},se=()=>{$.current=!1,_.abort()},{abort:W}=_;c.useEffect(()=>{!t&&!d||($.current=!1,W())},[t,d,W]);const de=g=>{g.preventDefault(),se(),J()},oe=g=>{const D=g.target.value;D.length<=he&&(se(),v(null),K(D))},H=g=>{const D=Array.from(g.target.files??[]);g.target.value="",O(D)},ee=g=>{var ce;if(!i)return;const D=Array.from(((ce=g.clipboardData)==null?void 0:ce.files)??[]);D.length!==0&&(g.preventDefault(),O(D))},ie=g=>{!i||!Be(g)||(g.preventDefault(),R.current+=1,E(!0))},ae=g=>{!i||!Be(g)||g.preventDefault()},Y=()=>{i&&(R.current=Math.max(0,R.current-1),R.current===0&&E(!1))},xe=g=>{var D;i&&(g.preventDefault(),R.current=0,E(!1),O(Array.from(((D=g.dataTransfer)==null?void 0:D.files)??[])))};return a.jsxs("form",{onSubmit:de,onDragEnter:ie,onDragOver:ae,onDragLeave:Y,onDrop:xe,"data-drag-over":b||void 0,className:`relative border-t border-claudius-border bg-claudius-surface p-3 ${b?"ring-2 ring-inset ring-claudius-accent":""}`,children:[b&&a.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-claudius-surface text-sm font-medium text-claudius-accent",children:f.dropFilesHint}),i&&x.length>0&&a.jsx("ul",{"aria-label":f.attachmentsLabel,className:"mb-2 flex flex-wrap gap-3 pt-1",children:x.map(g=>a.jsx("li",{children:a.jsx(Ze,{attachment:g,variant:"composer",onRemove:()=>Z(g.id),removeLabel:`${f.removeAttachment}: ${g.name}`})},g.id))}),a.jsxs("div",{className:"flex gap-2",children:[i&&a.jsxs(a.Fragment,{children:[a.jsx("input",{ref:L,type:"file",multiple:!0,hidden:!0,tabIndex:-1,accept:i.allowedTypes.join(","),onChange:H,"aria-label":f.attachFile}),a.jsx("button",{type:"button",onClick:()=>{var g;return(g=L.current)==null?void 0:g.click()},disabled:t||!X,"aria-label":f.attachFile,title:f.attachFile,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm border border-claudius-border bg-claudius-field text-claudius-text-muted transition-colors hover:text-claudius-text focus:border-claudius-accent focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})})})]}),a.jsxs("div",{className:"relative min-w-0 flex-1",children:[a.jsx("input",{ref:k,type:"text",value:w,onChange:oe,onPaste:ee,placeholder:T?f.voiceListening:re,disabled:t,"aria-label":f.typeYourMessage,"aria-describedby":te?"char-count":void 0,className:`h-full w-full rounded-claudius-sm border border-claudius-border bg-claudius-field py-2 pl-3 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 ${T?"pr-10":"pr-3"}`}),T&&a.jsx(Yt,{active:_.isSpeechDetected})]}),B&&l&&a.jsx(qt,{mode:l.mode,isListening:T,disabled:t,onStart:z,onStop:q,label:l.mode==="hold"?f.voiceInputHold:f.voiceInput}),m?a.jsx("button",{type:"button",onClick:r,"aria-label":f.stopGenerating,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:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:a.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})}):a.jsx("button",{type:"submit",disabled:t||ne,"aria-label":f.sendMessage,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:a.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:[a.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),a.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),(p??y)&&a.jsx("div",{role:"alert",className:"mt-1 text-xs text-claudius-error",children:p??y}),te&&a.jsxs("div",{id:"char-count",className:`mt-1 text-xs text-right ${ne?"text-claudius-error":"text-claudius-text-muted"}`,"aria-live":"polite",children:[U,"/",he]})]})}const an=["blog","page","external"],cn={blog:"Blog",page:"Page",external:"External"};function ln(e){try{return new URL(e).hostname}catch{return e}}const un=c.memo(function({sources:t,onClose:n}){const r=an.map(o=>({type:o,label:cn[o],items:t.filter(i=>i.type===o)})).filter(o=>o.items.length>0),s=t.length===1?"1 source found":`${t.length} sources found`;return a.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:[a.jsxs("div",{className:"flex items-center justify-between border-b border-claudius-border px-4 py-3",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-heading font-semibold text-claudius-text",children:"Sources"}),a.jsx("p",{className:"text-xs text-claudius-text-muted",children:s})]}),a.jsx("button",{onClick:n,"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:a.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:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),a.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-4",children:r.map(o=>a.jsxs("div",{children:[a.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-claudius-text-muted",children:o.label}),a.jsx("div",{className:"space-y-2",children:o.items.map(i=>{const l=Re(i.url);return l?a.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:[a.jsx("p",{className:"truncate text-sm font-medium text-claudius-text",children:i.title}),a.jsx("p",{className:"mt-0.5 text-xs text-claudius-text-muted",children:ln(l)})]},l):null})})]},o.type))})]})});function dn({title:e,subtitle:t,titleId:n,closeLabel:r,onClose:s,actions:o}){return a.jsxs("div",{className:"flex items-center gap-3 bg-claudius-accent px-5 py-4",children:[a.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:e.charAt(0).toUpperCase()}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h2",{id:n,className:"text-sm font-heading font-semibold text-claudius-accent-text",children:e}),a.jsx("p",{className:"text-xs text-claudius-accent-text",children:t})]}),o,a.jsx("button",{onClick:s,"aria-label":r,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:a.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:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}function fn({message:e,retryLabel:t,onRetry:n}){return a.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:[a.jsx("span",{children:e}),n&&a.jsx("button",{type:"button",onClick:n,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:t})]})}function hn({label:e}){return a.jsx("div",{role:"status","aria-live":"polite","aria-label":e,className:"mr-auto flex max-w-[85%]",children:a.jsxs("div",{className:"flex gap-1 rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-3",children:[a.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:0ms]"}),a.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:150ms]"}),a.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:300ms]"})]})})}function pn({label:e,items:t,onOpen:n}){const[r,s]=c.useState(!1),o=c.useId(),i=c.useId(),l=c.useRef(null),u=c.useRef(null),d=c.useRef([]),f=c.useRef(null),w=b=>{f.current=b,s(!0),n==null||n()},S=b=>{var E;s(!1),(E=u.current)==null||E.focus()};c.useEffect(()=>{var E;if(!r)return;f.current!==null&&((E=d.current[f.current])==null||E.focus(),f.current=null);const b=y=>{var v;(v=l.current)!=null&&v.contains(y.target)||s(!1)};return document.addEventListener("pointerdown",b),()=>document.removeEventListener("pointerdown",b)},[r]);const x=b=>{var y;const E=t.length;(y=d.current[(b+E)%E])==null||y.focus()},h=b=>{b.key==="ArrowDown"?(b.preventDefault(),w(0)):b.key==="ArrowUp"&&(b.preventDefault(),w(t.length-1))},p=b=>{const E=d.current.findIndex(y=>y===document.activeElement);switch(b.key){case"ArrowDown":b.preventDefault(),x(E+1);break;case"ArrowUp":b.preventDefault(),x(E===-1?t.length-1:E-1);break;case"Home":b.preventDefault(),x(0);break;case"End":b.preventDefault(),x(t.length-1);break;case"Escape":b.preventDefault(),b.stopPropagation(),S();break;case"Tab":b.shiftKey&&(b.preventDefault(),S());break}},j=b=>{var y;const E=b.relatedTarget;E&&((y=l.current)!=null&&y.contains(E)||s(!1))};return a.jsxs("div",{ref:l,className:"relative",children:[a.jsx("button",{ref:u,id:o,type:"button","aria-label":e,"aria-haspopup":"menu","aria-expanded":r,"aria-controls":r?i:void 0,onClick:()=>r?S():w(0),onKeyDown:h,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:a.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"5",r:"1.75"}),a.jsx("circle",{cx:"12",cy:"12",r:"1.75"}),a.jsx("circle",{cx:"12",cy:"19",r:"1.75"})]})}),r&&a.jsx("div",{id:i,role:"menu","aria-labelledby":o,tabIndex:-1,onKeyDown:p,onBlur:j,className:"absolute right-0 top-full z-20 mt-1 min-w-[12rem] rounded-claudius-md border border-claudius-border bg-claudius-surface py-1 shadow-claudius-elevated",children:t.map((b,E)=>a.jsx("button",{ref:y=>{d.current[E]=y},type:"button",role:"menuitem",tabIndex:-1,"aria-disabled":b.disabled||void 0,onClick:()=>{b.disabled||(S(),b.onSelect())},className:"flex min-h-[40px] w-full items-center whitespace-nowrap px-4 text-left text-sm text-claudius-text hover:bg-claudius-surface-muted focus:bg-claudius-surface-muted aria-disabled:cursor-default aria-disabled:opacity-50 aria-disabled:hover:bg-transparent",children:b.label},b.id))})]})}function mn(e,t,n){const[r,s]=c.useState(0),o=c.useRef(0),i=c.useRef(0),l=c.useRef(0),u=c.useRef(!1);return c.useEffect(()=>{const d=e.current;if(!n||!d)return;const f=x=>{if(d.scrollTop>0){u.current=!1;return}u.current=!0,i.current=x.touches[0].clientY,l.current=Date.now()},w=x=>{if(!u.current)return;let h=x.touches[0].clientY-i.current;h<0&&(h=h*.3),o.current=h,s(h)},S=()=>{if(!u.current)return;u.current=!1;const x=o.current,h=(Date.now()-l.current)/1e3,p=d.getBoundingClientRect().height,j=h>.05&&x>0&&x/h>500,b=x>p*.3;j||b?t():(o.current=0,s(0))};return d.addEventListener("touchstart",f,{passive:!0}),d.addEventListener("touchmove",w,{passive:!0}),d.addEventListener("touchend",S),()=>{d.removeEventListener("touchstart",f),d.removeEventListener("touchmove",w),d.removeEventListener("touchend",S)}},[e,t,n]),{offsetY:r}}const gn='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function xn(e,t){c.useEffect(()=>{const n=e.current;if(!n)return;const r=s=>{if(s.key!=="Tab")return;const o=Array.from(n.querySelectorAll(gn)).filter(d=>!d.hasAttribute("aria-hidden"));if(o.length===0)return;const i=o[0],l=o[o.length-1],u=document.activeElement;s.shiftKey&&u===i?(s.preventDefault(),l.focus()):!s.shiftKey&&u===l&&(s.preventDefault(),i.focus())};return n.addEventListener("keydown",r),()=>n.removeEventListener("keydown",r)},[e,t])}function pe(){if(!(typeof window>"u")&&!(typeof window.SpeechSynthesisUtterance>"u"))return window.speechSynthesis??void 0}function bn(e){const[t]=c.useState(()=>pe()!==void 0),[n,r]=c.useState(null),[s,o]=c.useState(!1),i=c.useRef(0),l=c.useRef(!1),u=c.useRef([]),d=c.useCallback(()=>{i.current+=1,l.current=!1,u.current=[],r(null),o(!1)},[]),f=c.useCallback(()=>{const h=u.current.length>0;d();const p=pe();!h||!p||(p.cancel(),p.paused&&p.resume())},[d]),w=c.useCallback((h,p)=>{const j=pe();if(!j)return;d(),(j.speaking||j.pending)&&j.cancel(),j.paused&&j.resume();const b=tn(p);if(b.length===0)return;const E=i.current,y=()=>i.current===E;u.current=b.map((v,k)=>{const L=new SpeechSynthesisUtterance(v);return L.lang=e,L.onerror=C=>{if(!y())return;(C.error==="interrupted"||C.error==="canceled")&&!l.current?d():f()},L.onpause=()=>{y()&&o(!0)},L.onresume=()=>{y()&&o(!1)},L.onend=()=>{y()&&(l.current&&!j.paused?f():k===b.length-1&&d())},L}),r(h);for(const v of u.current)j.speak(v)},[e,f,d]),S=c.useCallback(()=>{const h=pe();h&&(l.current=!0,h.pause(),h.paused&&o(!0))},[]),x=c.useCallback(()=>{const h=pe();h&&(l.current=!1,h.resume(),o(!1))},[]);return c.useEffect(()=>f,[f]),{isSupported:t,activeId:n,isPaused:s,speak:w,pause:S,resume:x,cancel:f}}const yn=/^([ \t]*)(`{3,}|~{3,})(.*)$/,wn=/^( {0,3})<(?![A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\s]*>|[A-Za-z0-9][^\s<>@]*@[^\s<>]+>)(?=[A-Za-z!?/])/,vn=/^(?: {4}|\t)/;function Xe(e){let t=0;for(const n of e)if(n===" ")t+=1;else if(n===" ")t+=4-t%4;else break;return t}function _e(e){let t=e.length;for(;t>0&&(e[t-1]===" "||e[t-1]===" ");)t-=1;return t===e.length?e:e.slice(0,t)}function jn(e){const t=yn.exec(e);if(!t)return null;const[,n,r,s]=t;return r[0]==="`"&&s.includes("`")?null:{indent:n,indentColumns:Xe(n),char:r[0],length:r.length}}function Rn(e,t){const n=e.trim();if(n.length<t.length)return!1;for(const r of n)if(r!==t.char)return!1;return Xe(e)<=t.indentColumns+3}function En(e){const t=e.replace(/\r\n?/g,`
|
|
9
9
|
`).split(`
|
|
10
10
|
`),n=[];let r=null;for(let s=0;s<t.length;s++){const o=t[s];if(r){n.push(o),Rn(o,r)&&(r=null);continue}const i=jn(o);if(i){r=i,n.push(o);continue}let l=o.replace(wn,"$1\\<");const u=t[s+1];o.trim()!==""&&u!==void 0&&u.trim()!==""&&!vn.test(o)&&!o.endsWith("\\")&&(l=_e(l)+" "),n.push(l)}if(r)n[n.length-1]===""&&n.pop(),n.push(r.indent+r.char.repeat(r.length));else{for(;n.length>0&&n[n.length-1].trim()==="";)n.pop();n.length>0&&(n[n.length-1]=_e(n[n.length-1]))}return n.join(`
|
|
11
11
|
`)}const Sn=/[\u00a0\u202f]/g;function Tn(e){if(e.formatDate)return e.formatDate;const t=s=>new Intl.DateTimeFormat(s,{dateStyle:"medium",timeStyle:"short",timeZone:e.timeZone});let n=null;try{n=t(e.locale)}catch{try{n=t(void 0)}catch{n=null}}const r=n;return r?s=>r.format(s):s=>s.toISOString()}function kn(e){const t=Tn(e);return n=>t(n).replace(Sn," ")}function An(e,t){var n;try{return((n=new Intl.DateTimeFormat("en",{timeZone:t,timeZoneName:"longOffset"}).formatToParts(e).find(s=>s.type==="timeZoneName"))==null?void 0:n.value)??""}catch{return""}}function et(e){const t=e.replace(/\s+/g," ").trim();if(t==="")return"";const n=Math.max(0,...(t.match(/`+/g)??[]).map(o=>o.length)),r="`".repeat(n+1),s=t.startsWith("`")||t.endsWith("`")?" ":"";return`${r}${s}${t}${s}${r}`}const Cn={"(":"%28",")":"%29","<":"%3C",">":"%3E","\\":"%5C"};function Mn(e,t){const n=ue(e.title||e.url).replace(/\s+/g," ").trim().replace(/[\\[\]<]/g,"\\$&"),r=Re(ue(e.url));if(!r)return`${t+1}. ${n}`;const s=r.replace(/[()<>\\]/g,o=>Cn[o]).replace(/\s/g,"%20");return`${t+1}. [${n}](${s})`}function Nn(e){const t=et(ue(e.name)),n=je(Number(e.size));return`- ${t} (${ue(e.mediaType)}, ${n})`}function ue(e){return typeof e=="string"?e:String(e??"")}function we(e){return Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function Dn(e,t){const{labels:n}=t,r=kn(t),s=t.now??new Date,o=An(s,t.timeZone),i=r(s)+(o?` (${o})`:""),l=[`# ${n.title}`,ye(n.exported,{date:i})];for(const u of e){if(u===null||typeof u!="object")continue;const d=u.role==="user"?n.user:n.assistant,f=u.createdAt?new Date(u.createdAt):null,w=f&&!Number.isNaN(f.getTime())?` · ${r(f)}`:"";l.push(`## ${d}${w}`);const S=En(ue(u.content));S&&l.push(S);const x=we(u.attachments);x.length&&l.push(n.attachments,x.map(Nn).join(`
|
|
@@ -15,4 +15,4 @@
|
|
|
15
15
|
|
|
16
16
|
`)+`
|
|
17
17
|
`}function Ln(e){const t=e.filter(n=>n!==null&&typeof n=="object").map(n=>n.attachments===void 0?n:{...n,attachments:we(n.attachments)});return JSON.stringify(Ye(t),null,2)+`
|
|
18
|
-
`}function Fe(e,t={}){const n=t.now??new Date;let r;try{const s=new Intl.DateTimeFormat("en",{timeZone:t.timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(n),o=i=>{var l;return((l=s.find(u=>u.type===i))==null?void 0:l.value)??""};r=`${o("year")}-${o("month")}-${o("day")}`}catch{r=n.toISOString().slice(0,10)}return`chat-transcript-${r}.${e}`}function In(e){const t=document.activeElement;let n=null;try{return n=document.createElement("textarea"),n.value=e,n.setAttribute("readonly",""),n.setAttribute("aria-hidden","true"),n.style.position="fixed",n.style.top="0",n.style.left="0",n.style.opacity="0",document.body.appendChild(n),n.focus({preventScroll:!0}),n.select(),document.execCommand("copy")}catch{return!1}finally{n==null||n.remove(),t==null||t.focus()}}async function On(e){var t;try{if((t=navigator.clipboard)!=null&&t.writeText)return await navigator.clipboard.writeText(e),!0}catch{}return In(e)}const Pn=4e4;function ze(e,t,n){const r=URL.createObjectURL(new Blob([t],{type:n})),s=document.createElement("a");s.href=r,s.download=e,s.style.display="none",document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),Pn)}const $n=4e3;function Un({enabled:e,messages:t,busy:n,locale:r,translations:s}){const o=s??Ee,[i,l]=c.useState(null),u=c.useRef(null),d=c.useRef(!0);c.useEffect(()=>(d.current=!0,()=>{d.current=!1,u.current&&clearTimeout(u.current)}),[]);const f=c.useCallback(()=>{u.current&&clearTimeout(u.current),u.current=null,l(null)},[]),w=c.useCallback(x=>{d.current&&(u.current&&clearTimeout(u.current),l(x),u.current=setTimeout(()=>{u.current=null,l(null)},$n))},[]);return{items:c.useMemo(()=>{if(!e)return[];const x=n||t.length===0,h=()=>Dn(t,{locale:r,labels:{title:o.transcriptTitle,exported:o.transcriptExported,user:o.transcriptUser,assistant:o.transcriptAssistant,attachments:o.transcriptAttachments,sources:o.transcriptSources,toolUsed:o.toolUsed}});return[{id:"copy-markdown",label:o.copyAsMarkdown,disabled:x,onSelect:()=>{On(h()).then(p=>w(p?o.copiedToClipboard:o.copyFailed))}},{id:"download-markdown",label:o.downloadAsMarkdown,disabled:x,onSelect:()=>ze(Fe("md"),h(),"text/markdown;charset=utf-8")},{id:"download-json",label:o.downloadAsJson,disabled:x,onSelect:()=>ze(Fe("json"),Ln(t),"application/json")}]},[e,n,t,r,o,w]),status:i,clearStatus:f}}const Bn=/\*\*([^*]+)\*\*/g,_n=/\*([^*]+)\*/g,Fn=/https?:\/\/[^\s)]+/g;function He(e){return e.replace(Bn,"$1").replace(_n,"$1").replace(Fn,t=>{var s;const n=((s=t.match(/[.,;:!?'"]+$/))==null?void 0:s[0])??"",r=n?t.slice(0,-n.length):t;try{return new URL(r).hostname+n}catch{return t}})}const zn={"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 Hn({messages:e,isLoading:t,isStreaming:n=!1,streamingMessageId:r=null,error:s,canRetry:o=!1,onSend:i,onStop:l,onRetry:u,onClose:d,title:f="Chat",subtitle:w="Ask me anything",welcomeMessage:S="Hi! How can I help you today?",placeholder:x,position:h="bottom-right",translations:p,isMobile:j=!1,attachments:b=null,voice:E=null,conversationExport:y=!1,locale:v="en-US"}){const k=c.useId(),L=c.useRef(null),C=c.useRef(null),[R,P]=c.useState(null);xn(L,!0);const N=bn((E==null?void 0:E.lang)??"en-US"),$=!!(E!=null&&E.output)&&N.isSupported,V={play:(p==null?void 0:p.readAloud)??"Read aloud",pause:(p==null?void 0:p.pauseReading)??"Pause reading",resume:(p==null?void 0:p.resumeReading)??"Resume reading",stop:(p==null?void 0:p.stopReading)??"Stop reading"},F=Un({enabled:y,messages:e,busy:t,locale:v,translations:p}),{offsetY:K}=mn(C,d,j),U=K!==0,te=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1;c.useEffect(()=>{const m=C.current;m&&(m.scrollTop=m.scrollHeight)},[e,t]),c.useEffect(()=>{const m=I=>{I.key==="Escape"&&!I.isComposing&&!I.defaultPrevented&&d()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[d]);const ne=(p==null?void 0:p.closeChat)??"Close chat",re=(p==null?void 0:p.chatMessages)??"Chat messages",X=[...e].reverse().find(m=>m.role==="assistant");return a.jsxs("div",{ref:L,role:"dialog","aria-modal":j?"true":void 0,"aria-labelledby":k,className:j?"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 ${zn[h]} 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:j&&!te?{transform:`translateY(${Math.max(0,K)}px)`}:void 0,"data-dragging":U||void 0,children:[j&&a.jsx("div",{className:"flex justify-center py-2","aria-hidden":"true",children:a.jsx("div",{className:"h-1 w-8 rounded-claudius-full bg-claudius-border"})}),a.jsx(dn,{title:f,subtitle:w,titleId:k,closeLabel:ne,onClose:d,actions:y?a.jsx(pn,{label:(p==null?void 0:p.moreOptions)??"More options",items:F.items,onOpen:F.clearStatus}):void 0}),a.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[R&&a.jsx(un,{sources:R.sources,onClose:()=>P(null)}),y&&a.jsx("div",{role:"status",className:"pointer-events-none absolute inset-x-0 top-2 z-10 flex justify-center px-4",children:F.status&&a.jsx("span",{className:"rounded-claudius-full bg-claudius-text px-3 py-1 text-xs text-claudius-surface shadow-claudius-elevated",children:F.status})}),a.jsxs("div",{ref:C,role:"log","aria-label":re,className:"h-full space-y-3 overflow-y-auto px-4 py-4",children:[e.length===0&&!s&&a.jsx("div",{className:"mr-auto flex max-w-[85%]",children:a.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:S})}),e.map(m=>a.jsx(Vt,{role:m.role,content:m.content,isStreaming:m.id===r,sources:m.sources,attachments:m.attachments,toolUses:m.toolUses,toolUsedLabel:p==null?void 0:p.toolUsed,toolDetailsLabel:p==null?void 0:p.toolDetails,isSourceActive:(R==null?void 0:R.messageId)===m.id,onSourceClick:()=>{(R==null?void 0:R.messageId)===m.id?P(null):m.sources&&m.sources.length>0&&P({messageId:m.id,sources:m.sources})},speech:$&&m.role==="assistant"&&m.id!==r&&m.content.trim()!==""?{state:N.activeId!==m.id?"idle":N.isPaused?"paused":"speaking",labels:V,onPlay:()=>N.speak(m.id,He(m.content)),onPause:N.pause,onResume:N.resume,onStop:N.cancel}:void 0},m.id)),t&&!(r!==null&&e.some(m=>m.id===r&&m.content.length>0))&&a.jsx(hn,{label:(p==null?void 0:p.typingIndicator)??"Assistant is typing"}),s&&a.jsx(fn,{message:s,retryLabel:(p==null?void 0:p.errorRetry)??"Retry",onRetry:o&&u&&!t?u:void 0})]})]}),a.jsx("div",{"data-claudius-live":"assistant","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:X&&X.id!==r?He(X.content):""}),a.jsx(on,{onSend:i,isLoading:t,isStreaming:n,onStop:l,placeholder:x,translations:p,attachments:b,voice:E,onVoiceStart:N.cancel,isReadingAloud:N.activeId!==null})]})}function Wn({message:e,position:t,onOpen:n,onDismiss:r,dismissLabel:s}){const o=t.startsWith("bottom"),i=t.endsWith("right"),l=["claudius-greeting-bubble","fixed z-40 max-w-xs",o?"bottom-20":"top-20",i?"right-4":"left-4"].join(" ");return a.jsxs("div",{className:l,role:"status","aria-live":"polite",children:[a.jsx("button",{type:"button",onClick:n,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:e}),a.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),r()},"aria-label":s,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:a.jsx("span",{"aria-hidden":"true",children:"×"})})]})}const Gn={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",attachFile:"Adjuntar un archivo",removeAttachment:"Quitar adjunto",attachmentsLabel:"Adjuntos",dropFilesHint:"Suelta los archivos para adjuntarlos",attachmentTooLarge:"{name} es demasiado grande. El tamaño máximo es {max}.",attachmentTypeNotAllowed:"{name} no es un tipo de archivo compatible.",attachmentTooMany:"Puedes adjuntar hasta {max} archivos por mensaje.",voiceInput:"Entrada de voz",voiceInputHold:"Mantén pulsado para hablar",voiceListening:"Escuchando...",voicePermissionDenied:"El acceso al micrófono está bloqueado. Permítelo en la configuración de tu navegador para usar la entrada de voz.",voiceNoSpeech:"No se detectó ninguna voz. Inténtalo de nuevo.",voiceNoMicrophone:"No se encontró ningún micrófono.",voiceUnavailable:"La entrada de voz no está disponible en este momento.",readAloud:"Leer en voz alta",pauseReading:"Pausar la lectura",resumeReading:"Reanudar la lectura",stopReading:"Detener la lectura",moreOptions:"Más opciones",copyAsMarkdown:"Copiar como Markdown",downloadAsMarkdown:"Descargar como Markdown",downloadAsJson:"Descargar como JSON",copiedToClipboard:"Copiado al portapapeles",copyFailed:"No se pudo copiar. Prueba a descargarlo.",transcriptTitle:"Transcripción del chat",transcriptExported:"Exportado el {date}",transcriptUser:"Usuario",transcriptAssistant:"Asistente",transcriptAttachments:"Adjuntos:",transcriptSources:"Fuentes:",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.",errorAttachmentRejected:"Se rechazó un adjunto. Quítalo e inténtalo de nuevo.",errorAttachmentQuota:"Límite de subida alcanzado. Inténtalo más tarde.",errorRetry:"Reintentar"},Vn={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",attachFile:"Joindre un fichier",removeAttachment:"Retirer la pièce jointe",attachmentsLabel:"Pièces jointes",dropFilesHint:"Déposez les fichiers pour les joindre",attachmentTooLarge:"{name} est trop volumineux. La taille maximale est de {max}.",attachmentTypeNotAllowed:"{name} n'est pas un type de fichier pris en charge.",attachmentTooMany:"Vous pouvez joindre jusqu'à {max} fichiers par message.",voiceInput:"Saisie vocale",voiceInputHold:"Maintenez pour parler",voiceListening:"Écoute en cours...",voicePermissionDenied:"L'accès au microphone est bloqué. Autorisez-le dans les paramètres de votre navigateur pour utiliser la saisie vocale.",voiceNoSpeech:"Aucune voix n'a été détectée. Veuillez réessayer.",voiceNoMicrophone:"Aucun microphone n'a été trouvé.",voiceUnavailable:"La saisie vocale n'est pas disponible pour le moment.",readAloud:"Lire à voix haute",pauseReading:"Mettre la lecture en pause",resumeReading:"Reprendre la lecture",stopReading:"Arrêter la lecture",moreOptions:"Plus d'options",copyAsMarkdown:"Copier en Markdown",downloadAsMarkdown:"Télécharger en Markdown",downloadAsJson:"Télécharger en JSON",copiedToClipboard:"Copié dans le presse-papiers",copyFailed:"Impossible de copier. Essayez plutôt de télécharger.",transcriptTitle:"Transcription du chat",transcriptExported:"Exporté le {date}",transcriptUser:"Utilisateur",transcriptAssistant:"Assistant",transcriptAttachments:"Pièces jointes :",transcriptSources:"Sources :",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.",errorAttachmentRejected:"Une pièce jointe a été refusée. Retirez-la et réessayez.",errorAttachmentQuota:"Limite d'envoi atteinte. Veuillez réessayer plus tard.",errorRetry:"Réessayer"},Kn={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",attachFile:"Datei anhängen",removeAttachment:"Anhang entfernen",attachmentsLabel:"Anhänge",dropFilesHint:"Dateien hier ablegen, um sie anzuhängen",attachmentTooLarge:"{name} ist zu groß. Die maximale Größe beträgt {max}.",attachmentTypeNotAllowed:"{name} ist kein unterstützter Dateityp.",attachmentTooMany:"Sie können bis zu {max} Dateien pro Nachricht anhängen.",voiceInput:"Spracheingabe",voiceInputHold:"Zum Sprechen gedrückt halten",voiceListening:"Ich höre zu...",voicePermissionDenied:"Der Zugriff auf das Mikrofon ist blockiert. Erlauben Sie ihn in den Einstellungen Ihres Browsers, um die Spracheingabe zu nutzen.",voiceNoSpeech:"Es wurde keine Sprache erkannt. Bitte versuchen Sie es erneut.",voiceNoMicrophone:"Es wurde kein Mikrofon gefunden.",voiceUnavailable:"Die Spracheingabe ist momentan nicht verfügbar.",readAloud:"Vorlesen",pauseReading:"Vorlesen pausieren",resumeReading:"Vorlesen fortsetzen",stopReading:"Vorlesen beenden",moreOptions:"Weitere Optionen",copyAsMarkdown:"Als Markdown kopieren",downloadAsMarkdown:"Als Markdown herunterladen",downloadAsJson:"Als JSON herunterladen",copiedToClipboard:"In die Zwischenablage kopiert",copyFailed:"Kopieren nicht möglich. Bitte stattdessen herunterladen.",transcriptTitle:"Chat-Protokoll",transcriptExported:"Exportiert am {date}",transcriptUser:"Nutzer",transcriptAssistant:"Assistent",transcriptAttachments:"Anhänge:",transcriptSources:"Quellen:",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.",errorAttachmentRejected:"Ein Anhang wurde abgelehnt. Bitte entfernen Sie ihn und versuchen Sie es erneut.",errorAttachmentQuota:"Upload-Limit erreicht. Bitte versuchen Sie es später erneut.",errorRetry:"Erneut versuchen"},ke={en:Je,es:Gn,fr:Vn,de:Kn};function We(e){if(!e)return;const t=e.toLowerCase().split("-")[0];return Object.prototype.hasOwnProperty.call(ke,t)?t:void 0}function Ae(){const e=typeof document<"u"?We(document.documentElement.lang):void 0;if(e)return e;const t=typeof navigator<"u"?We(navigator.language):void 0;return t||"en"}function tt(e={}){const{locale:t,translations:n}=e,r=ke[t??Ae()];return n?{...r,...n}:{...r}}const Ge=["accent","accentText","accentSoft","accentTextMuted","surface","surfaceMuted","text","textMuted","border","userBubble","userBubbleText","assistantBubble","assistantBubbleText","field","error","errorSurface","errorText","link","scrim"],qn=["sm","md","lg","full","tail"],Yn=["elevated","floating","floatingHover"],Zn=["heading","body"],Ce={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 Jn(e){return Object.prototype.hasOwnProperty.call(Ce,e)}const Qn=new Set(["light","dark","auto"]);function Xn(e){if(e===void 0)return{mode:"light"};if(typeof e=="string"){if(Qn.has(e))return{mode:e};if(Jn(e)){const t=Ce[e];return{mode:t.colorScheme??"light",theme:t}}return{mode:"light",url:e}}return{mode:e.colorScheme??"light",theme:e}}function er(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function tr(e,t){console.warn(`[Claudius] Ignoring unknown theme token "${t}" in "${e}"`)}function me(e,t,n,r,s,o=""){if(s)for(const[i,l]of Object.entries(s)){if(!r.includes(i)){tr(t,i);continue}typeof l=="string"&&(e[`${n}${er(i)}${o}`]=l)}}function nr(e){const t={};me(t,"colors","--cl-color-",Ge,e.colors);for(const[n,r]of Object.entries({...t}))t[`${n}-dark`]=r;return me(t,"colorsDark","--cl-color-",Ge,e.colorsDark,"-dark"),me(t,"radii","--cl-radius-",qn,e.radii),me(t,"shadows","--cl-shadow-",Yn,e.shadows),me(t,"fonts","--cl-font-",Zn,e.fonts),t}function rr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sr(e){const t=c.useMemo(()=>Xn(e),[e]),[n,r]=c.useState(null),s=t.url;c.useEffect(()=>{if(r(null),!s)return;const u=new AbortController;return fetch(s,{signal:u.signal}).then(d=>{if(!d.ok)throw new Error(`HTTP ${d.status}`);return d.json()}).then(d=>{if(!rr(d))throw new Error("theme JSON must be an object");r(d)}).catch(d=>{u.signal.aborted||console.error(`[Claudius] Failed to load theme from ${s}:`,d)}),()=>u.abort()},[s]);const o=t.theme??n??null,i=(n==null?void 0:n.colorScheme)??t.mode,l=c.useMemo(()=>o?nr(o):{},[o]);return{mode:i,cssVars:l}}const nt="claudius:triggers:dismissed";function or(){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(nt)==="1"}catch{return!1}}function ar(){if(!(typeof window>"u"))try{window.sessionStorage.setItem(nt,"1")}catch{}}function ir({apiUrl:e,title:t,subtitle:n,welcomeMessage:r,placeholder:s,persistMessages:o,storageKeyPrefix:i,requestTimeoutMs:l,theme:u="light",accentColor:d,position:f="bottom-right",locale:w,translations:S,triggers:x,plugins:h,streaming:p=!0,attachments:j=!1,voice:b=!1,conversationExport:E=!1}){const[y,v]=c.useState(!1),k=c.useMemo(()=>pt(j),[j]),L=c.useMemo(()=>w??Ae(),[w]),C=c.useMemo(()=>Qt(b,L),[b,L]),R=c.useMemo(()=>Qe(L),[L]),[P,N]=c.useState(null),[$,V]=c.useState(or),F=c.useRef(!1),K=At("(max-width: 639px)"),U=c.useMemo(()=>tt({locale:w,translations:S}),[w,S]),{messages:te,isLoading:ne,isStreaming:re,streamingMessageId:X,error:m,canRetry:I,sendMessage:O,stop:Z,retry:J}=kt({apiUrl:e,persistMessages:o,storageKeyPrefix:i,timeoutMs:l,translations:U,plugins:h,streaming:p}),Q=c.useRef(null),_=c.useRef(y),{mode:B,cssVars:T}=sr(u),[A,M]=c.useState(!1);c.useEffect(()=>{if(B!=="auto")return;const Y=window.matchMedia("(prefers-color-scheme: dark)");M(Y.matches);const xe=g=>M(g.matches);return Y.addEventListener("change",xe),()=>Y.removeEventListener("change",xe)},[B]),c.useEffect(()=>{var Y;_.current&&!y&&((Y=Q.current)==null||Y.focus()),_.current=y},[y]);const z=c.useCallback(()=>{V(!0),ar()},[]),q=c.useCallback(()=>{v(!1),F.current&&(F.current=!1,z())},[z]),se=c.useCallback(()=>{v(Y=>!Y)},[]),W=c.useCallback(()=>{F.current=!0,N(null),v(!0)},[]),de=c.useCallback(Y=>{N(Y)},[]),oe=c.useCallback(()=>{N(null),W()},[W]),H=c.useCallback(()=>{N(null),z()},[z]);Mt({triggers:x,enabled:!$&&!y,onOpen:W,onGreeting:de});const ee=B==="dark"||B==="auto"&&A,ie={...T,...d?{"--cl-color-accent":d,"--cl-color-accent-dark":d}:{}},ae=Object.keys(ie).length>0?ie:void 0;return a.jsx("div",{className:"claudius-root",style:ae,children:a.jsxs("div",{"data-claudius-dark":ee?"true":"false",children:[y&&K&&a.jsx("div",{className:"claudius-scrim fixed inset-0 z-40 bg-claudius-scrim",onClick:q,"aria-hidden":"true"}),y&&a.jsx(Hn,{messages:te,isLoading:ne,isStreaming:re,streamingMessageId:X,error:m,canRetry:I,onSend:O,onStop:Z,onRetry:J,onClose:q,title:t??U.title,subtitle:n??U.subtitle,welcomeMessage:r??U.welcomeMessage,placeholder:s??U.placeholder,position:f,translations:U,isMobile:K,attachments:k,voice:C,conversationExport:E===!0,locale:R}),!(y&&K)&&a.jsx(Dt,{ref:Q,isOpen:y,onClick:se,position:f,translations:U}),!y&&P&&a.jsx(Wn,{message:P,position:f,onOpen:oe,onDismiss:H,dismissLabel:U.dismissGreeting})]})})}function cr(e){const{onEvent:t,includeContent:n=!0}=e,r=s=>n?s:"";return{name:"analytics",onBeforeSend(s){t({type:"message_sent",role:"user",content:r(s.content),chars:s.content.length})},onAfterReceive(s){t({type:"message_received",role:"assistant",content:r(s.content),chars:s.content.length})},onError(s){t({type:"chat_error",message:s.message,code:s.code})}}}const rt=[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,/\b\d{3}-\d{2}-\d{4}\b/g,/\b(?:\d[ -]?){13,16}\b/g,/\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g];function st(e,t,n){return t.reduce((r,s)=>(s.lastIndex=0,r.replace(s,n)),e)}function lr(e={}){const{patterns:t=rt,replacement:n="[redacted]",redactReplies:r=!1}=e,s=o=>{const i=st(o.content,t,n);if(i!==o.content)return{...o,content:i}};return{name:"redact-pii",onBeforeSend:s,onAfterReceive:r?s:void 0}}function ur(e,t,n){return typeof e=="function"?e(t):e instanceof RegExp?e.test(t):n?t.includes(e):t.toLowerCase().includes(e.toLowerCase())}function dr(e){const{rules:t,caseSensitive:n=!1}=e;return{name:"canned-responses",onBeforeSend(r,s){for(const o of t)if(ur(o.match,r.content,n)){s.respondWith(o.reply);return}}}}exports.ChatApiClient=Ve;exports.ChatApiError=G;exports.ChatWidget=ir;exports.DEFAULT_ATTACHMENT_OPTIONS=ge;exports.DEFAULT_PII_PATTERNS=rt;exports.DebounceError=ve;exports.builtinThemes=Ce;exports.createTranslations=Kt;exports.defaultTranslations=Ee;exports.detectLocale=Ae;exports.locales=ke;exports.pluginAnalytics=cr;exports.pluginCannedResponses=dr;exports.pluginRedactPII=lr;exports.redactText=st;exports.resolveTranslations=tt;
|
|
18
|
+
`}function Fe(e,t={}){const n=t.now??new Date;let r;try{const s=new Intl.DateTimeFormat("en",{timeZone:t.timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(n),o=i=>{var l;return((l=s.find(u=>u.type===i))==null?void 0:l.value)??""};r=`${o("year")}-${o("month")}-${o("day")}`}catch{r=n.toISOString().slice(0,10)}return`chat-transcript-${r}.${e}`}function In(e){const t=document.activeElement;let n=null;try{return n=document.createElement("textarea"),n.value=e,n.setAttribute("readonly",""),n.setAttribute("aria-hidden","true"),n.tabIndex=-1,n.style.position="fixed",n.style.top="0",n.style.left="0",n.style.opacity="0",document.body.appendChild(n),n.focus({preventScroll:!0}),n.select(),document.execCommand("copy")}catch{return!1}finally{try{n==null||n.remove()}catch{}try{t==null||t.focus()}catch{}}}async function On(e){var t;try{if((t=navigator.clipboard)!=null&&t.writeText)return await navigator.clipboard.writeText(e),!0}catch{}try{return In(e)}catch{return!1}}const Pn=4e4;function ze(e,t,n){const r=URL.createObjectURL(new Blob([t],{type:n})),s=document.createElement("a");s.href=r,s.download=e,s.style.display="none",document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),Pn)}const $n=4e3;function Un({enabled:e,messages:t,busy:n,locale:r,translations:s}){const o=s??Ee,[i,l]=c.useState(null),u=c.useRef(null),d=c.useRef(!0);c.useEffect(()=>(d.current=!0,()=>{d.current=!1,u.current&&clearTimeout(u.current)}),[]);const f=c.useCallback(()=>{u.current&&clearTimeout(u.current),u.current=null,l(null)},[]),w=c.useCallback(x=>{d.current&&(u.current&&clearTimeout(u.current),l(x),u.current=setTimeout(()=>{u.current=null,l(null)},$n))},[]);return{items:c.useMemo(()=>{if(!e)return[];const x=n||t.length===0,h=()=>Dn(t,{locale:r,labels:{title:o.transcriptTitle,exported:o.transcriptExported,user:o.transcriptUser,assistant:o.transcriptAssistant,attachments:o.transcriptAttachments,sources:o.transcriptSources,toolUsed:o.toolUsed}});return[{id:"copy-markdown",label:o.copyAsMarkdown,disabled:x,onSelect:()=>{On(h()).then(p=>w(p?o.copiedToClipboard:o.copyFailed))}},{id:"download-markdown",label:o.downloadAsMarkdown,disabled:x,onSelect:()=>ze(Fe("md"),h(),"text/markdown;charset=utf-8")},{id:"download-json",label:o.downloadAsJson,disabled:x,onSelect:()=>ze(Fe("json"),Ln(t),"application/json")}]},[e,n,t,r,o,w]),status:i,clearStatus:f}}const Bn=/\*\*([^*]+)\*\*/g,_n=/\*([^*]+)\*/g,Fn=/https?:\/\/[^\s)]+/g;function He(e){return e.replace(Bn,"$1").replace(_n,"$1").replace(Fn,t=>{var s;const n=((s=t.match(/[.,;:!?'"]+$/))==null?void 0:s[0])??"",r=n?t.slice(0,-n.length):t;try{return new URL(r).hostname+n}catch{return t}})}const zn={"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 Hn({messages:e,isLoading:t,isStreaming:n=!1,streamingMessageId:r=null,error:s,canRetry:o=!1,onSend:i,onStop:l,onRetry:u,onClose:d,title:f="Chat",subtitle:w="Ask me anything",welcomeMessage:S="Hi! How can I help you today?",placeholder:x,position:h="bottom-right",translations:p,isMobile:j=!1,attachments:b=null,voice:E=null,conversationExport:y=!1,locale:v="en-US"}){const k=c.useId(),L=c.useRef(null),C=c.useRef(null),[R,P]=c.useState(null);xn(L,!0);const N=bn((E==null?void 0:E.lang)??"en-US"),$=!!(E!=null&&E.output)&&N.isSupported,V={play:(p==null?void 0:p.readAloud)??"Read aloud",pause:(p==null?void 0:p.pauseReading)??"Pause reading",resume:(p==null?void 0:p.resumeReading)??"Resume reading",stop:(p==null?void 0:p.stopReading)??"Stop reading"},F=Un({enabled:y,messages:e,busy:t,locale:v,translations:p}),{offsetY:K}=mn(C,d,j),U=K!==0,te=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1;c.useEffect(()=>{const m=C.current;m&&(m.scrollTop=m.scrollHeight)},[e,t]),c.useEffect(()=>{const m=I=>{I.key==="Escape"&&!I.isComposing&&!I.defaultPrevented&&d()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[d]);const ne=(p==null?void 0:p.closeChat)??"Close chat",re=(p==null?void 0:p.chatMessages)??"Chat messages",X=[...e].reverse().find(m=>m.role==="assistant");return a.jsxs("div",{ref:L,role:"dialog","aria-modal":j?"true":void 0,"aria-labelledby":k,className:j?"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 ${zn[h]} 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:j&&!te?{transform:`translateY(${Math.max(0,K)}px)`}:void 0,"data-dragging":U||void 0,children:[j&&a.jsx("div",{className:"flex justify-center py-2","aria-hidden":"true",children:a.jsx("div",{className:"h-1 w-8 rounded-claudius-full bg-claudius-border"})}),a.jsx(dn,{title:f,subtitle:w,titleId:k,closeLabel:ne,onClose:d,actions:y?a.jsx(pn,{label:(p==null?void 0:p.moreOptions)??"More options",items:F.items,onOpen:F.clearStatus}):void 0}),a.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[R&&a.jsx(un,{sources:R.sources,onClose:()=>P(null)}),y&&a.jsx("div",{role:"status",className:"pointer-events-none absolute inset-x-0 top-2 z-10 flex justify-center px-4",children:F.status&&a.jsx("span",{className:"rounded-claudius-full bg-claudius-text px-3 py-1 text-xs text-claudius-surface shadow-claudius-elevated",children:F.status})}),a.jsxs("div",{ref:C,role:"log","aria-label":re,className:"h-full space-y-3 overflow-y-auto px-4 py-4",children:[e.length===0&&!s&&a.jsx("div",{className:"mr-auto flex max-w-[85%]",children:a.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:S})}),e.map(m=>a.jsx(Vt,{role:m.role,content:m.content,isStreaming:m.id===r,sources:m.sources,attachments:m.attachments,toolUses:m.toolUses,toolUsedLabel:p==null?void 0:p.toolUsed,toolDetailsLabel:p==null?void 0:p.toolDetails,isSourceActive:(R==null?void 0:R.messageId)===m.id,onSourceClick:()=>{(R==null?void 0:R.messageId)===m.id?P(null):m.sources&&m.sources.length>0&&P({messageId:m.id,sources:m.sources})},speech:$&&m.role==="assistant"&&m.id!==r&&m.content.trim()!==""?{state:N.activeId!==m.id?"idle":N.isPaused?"paused":"speaking",labels:V,onPlay:()=>N.speak(m.id,He(m.content)),onPause:N.pause,onResume:N.resume,onStop:N.cancel}:void 0},m.id)),t&&!(r!==null&&e.some(m=>m.id===r&&m.content.length>0))&&a.jsx(hn,{label:(p==null?void 0:p.typingIndicator)??"Assistant is typing"}),s&&a.jsx(fn,{message:s,retryLabel:(p==null?void 0:p.errorRetry)??"Retry",onRetry:o&&u&&!t?u:void 0})]})]}),a.jsx("div",{"data-claudius-live":"assistant","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:X&&X.id!==r?He(X.content):""}),a.jsx(on,{onSend:i,isLoading:t,isStreaming:n,onStop:l,placeholder:x,translations:p,attachments:b,voice:E,onVoiceStart:N.cancel,isReadingAloud:N.activeId!==null})]})}function Wn({message:e,position:t,onOpen:n,onDismiss:r,dismissLabel:s}){const o=t.startsWith("bottom"),i=t.endsWith("right"),l=["claudius-greeting-bubble","fixed z-40 max-w-xs",o?"bottom-20":"top-20",i?"right-4":"left-4"].join(" ");return a.jsxs("div",{className:l,role:"status","aria-live":"polite",children:[a.jsx("button",{type:"button",onClick:n,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:e}),a.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),r()},"aria-label":s,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:a.jsx("span",{"aria-hidden":"true",children:"×"})})]})}const Gn={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",attachFile:"Adjuntar un archivo",removeAttachment:"Quitar adjunto",attachmentsLabel:"Adjuntos",dropFilesHint:"Suelta los archivos para adjuntarlos",attachmentTooLarge:"{name} es demasiado grande. El tamaño máximo es {max}.",attachmentTypeNotAllowed:"{name} no es un tipo de archivo compatible.",attachmentTooMany:"Puedes adjuntar hasta {max} archivos por mensaje.",voiceInput:"Entrada de voz",voiceInputHold:"Mantén pulsado para hablar",voiceListening:"Escuchando...",voicePermissionDenied:"El acceso al micrófono está bloqueado. Permítelo en la configuración de tu navegador para usar la entrada de voz.",voiceNoSpeech:"No se detectó ninguna voz. Inténtalo de nuevo.",voiceNoMicrophone:"No se encontró ningún micrófono.",voiceUnavailable:"La entrada de voz no está disponible en este momento.",readAloud:"Leer en voz alta",pauseReading:"Pausar la lectura",resumeReading:"Reanudar la lectura",stopReading:"Detener la lectura",moreOptions:"Más opciones",copyAsMarkdown:"Copiar como Markdown",downloadAsMarkdown:"Descargar como Markdown",downloadAsJson:"Descargar como JSON",copiedToClipboard:"Copiado al portapapeles",copyFailed:"No se pudo copiar. Prueba a descargarlo.",transcriptTitle:"Transcripción del chat",transcriptExported:"Exportado el {date}",transcriptUser:"Usuario",transcriptAssistant:"Asistente",transcriptAttachments:"Adjuntos:",transcriptSources:"Fuentes:",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.",errorAttachmentRejected:"Se rechazó un adjunto. Quítalo e inténtalo de nuevo.",errorAttachmentQuota:"Límite de subida alcanzado. Inténtalo más tarde.",errorRetry:"Reintentar"},Vn={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",attachFile:"Joindre un fichier",removeAttachment:"Retirer la pièce jointe",attachmentsLabel:"Pièces jointes",dropFilesHint:"Déposez les fichiers pour les joindre",attachmentTooLarge:"{name} est trop volumineux. La taille maximale est de {max}.",attachmentTypeNotAllowed:"{name} n'est pas un type de fichier pris en charge.",attachmentTooMany:"Vous pouvez joindre jusqu'à {max} fichiers par message.",voiceInput:"Saisie vocale",voiceInputHold:"Maintenez pour parler",voiceListening:"Écoute en cours...",voicePermissionDenied:"L'accès au microphone est bloqué. Autorisez-le dans les paramètres de votre navigateur pour utiliser la saisie vocale.",voiceNoSpeech:"Aucune voix n'a été détectée. Veuillez réessayer.",voiceNoMicrophone:"Aucun microphone n'a été trouvé.",voiceUnavailable:"La saisie vocale n'est pas disponible pour le moment.",readAloud:"Lire à voix haute",pauseReading:"Mettre la lecture en pause",resumeReading:"Reprendre la lecture",stopReading:"Arrêter la lecture",moreOptions:"Plus d'options",copyAsMarkdown:"Copier en Markdown",downloadAsMarkdown:"Télécharger en Markdown",downloadAsJson:"Télécharger en JSON",copiedToClipboard:"Copié dans le presse-papiers",copyFailed:"Impossible de copier. Essayez plutôt de télécharger.",transcriptTitle:"Transcription du chat",transcriptExported:"Exporté le {date}",transcriptUser:"Utilisateur",transcriptAssistant:"Assistant",transcriptAttachments:"Pièces jointes :",transcriptSources:"Sources :",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.",errorAttachmentRejected:"Une pièce jointe a été refusée. Retirez-la et réessayez.",errorAttachmentQuota:"Limite d'envoi atteinte. Veuillez réessayer plus tard.",errorRetry:"Réessayer"},Kn={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",attachFile:"Datei anhängen",removeAttachment:"Anhang entfernen",attachmentsLabel:"Anhänge",dropFilesHint:"Dateien hier ablegen, um sie anzuhängen",attachmentTooLarge:"{name} ist zu groß. Die maximale Größe beträgt {max}.",attachmentTypeNotAllowed:"{name} ist kein unterstützter Dateityp.",attachmentTooMany:"Sie können bis zu {max} Dateien pro Nachricht anhängen.",voiceInput:"Spracheingabe",voiceInputHold:"Zum Sprechen gedrückt halten",voiceListening:"Ich höre zu...",voicePermissionDenied:"Der Zugriff auf das Mikrofon ist blockiert. Erlauben Sie ihn in den Einstellungen Ihres Browsers, um die Spracheingabe zu nutzen.",voiceNoSpeech:"Es wurde keine Sprache erkannt. Bitte versuchen Sie es erneut.",voiceNoMicrophone:"Es wurde kein Mikrofon gefunden.",voiceUnavailable:"Die Spracheingabe ist momentan nicht verfügbar.",readAloud:"Vorlesen",pauseReading:"Vorlesen pausieren",resumeReading:"Vorlesen fortsetzen",stopReading:"Vorlesen beenden",moreOptions:"Weitere Optionen",copyAsMarkdown:"Als Markdown kopieren",downloadAsMarkdown:"Als Markdown herunterladen",downloadAsJson:"Als JSON herunterladen",copiedToClipboard:"In die Zwischenablage kopiert",copyFailed:"Kopieren nicht möglich. Bitte stattdessen herunterladen.",transcriptTitle:"Chat-Protokoll",transcriptExported:"Exportiert am {date}",transcriptUser:"Nutzer",transcriptAssistant:"Assistent",transcriptAttachments:"Anhänge:",transcriptSources:"Quellen:",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.",errorAttachmentRejected:"Ein Anhang wurde abgelehnt. Bitte entfernen Sie ihn und versuchen Sie es erneut.",errorAttachmentQuota:"Upload-Limit erreicht. Bitte versuchen Sie es später erneut.",errorRetry:"Erneut versuchen"},ke={en:Je,es:Gn,fr:Vn,de:Kn};function We(e){if(!e)return;const t=e.toLowerCase().split("-")[0];return Object.prototype.hasOwnProperty.call(ke,t)?t:void 0}function Ae(){const e=typeof document<"u"?We(document.documentElement.lang):void 0;if(e)return e;const t=typeof navigator<"u"?We(navigator.language):void 0;return t||"en"}function tt(e={}){const{locale:t,translations:n}=e,r=ke[t??Ae()];return n?{...r,...n}:{...r}}const Ge=["accent","accentText","accentSoft","accentTextMuted","surface","surfaceMuted","text","textMuted","border","userBubble","userBubbleText","assistantBubble","assistantBubbleText","field","error","errorSurface","errorText","link","scrim"],qn=["sm","md","lg","full","tail"],Yn=["elevated","floating","floatingHover"],Zn=["heading","body"],Ce={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 Jn(e){return Object.prototype.hasOwnProperty.call(Ce,e)}const Qn=new Set(["light","dark","auto"]);function Xn(e){if(e===void 0)return{mode:"light"};if(typeof e=="string"){if(Qn.has(e))return{mode:e};if(Jn(e)){const t=Ce[e];return{mode:t.colorScheme??"light",theme:t}}return{mode:"light",url:e}}return{mode:e.colorScheme??"light",theme:e}}function er(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function tr(e,t){console.warn(`[Claudius] Ignoring unknown theme token "${t}" in "${e}"`)}function me(e,t,n,r,s,o=""){if(s)for(const[i,l]of Object.entries(s)){if(!r.includes(i)){tr(t,i);continue}typeof l=="string"&&(e[`${n}${er(i)}${o}`]=l)}}function nr(e){const t={};me(t,"colors","--cl-color-",Ge,e.colors);for(const[n,r]of Object.entries({...t}))t[`${n}-dark`]=r;return me(t,"colorsDark","--cl-color-",Ge,e.colorsDark,"-dark"),me(t,"radii","--cl-radius-",qn,e.radii),me(t,"shadows","--cl-shadow-",Yn,e.shadows),me(t,"fonts","--cl-font-",Zn,e.fonts),t}function rr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sr(e){const t=c.useMemo(()=>Xn(e),[e]),[n,r]=c.useState(null),s=t.url;c.useEffect(()=>{if(r(null),!s)return;const u=new AbortController;return fetch(s,{signal:u.signal}).then(d=>{if(!d.ok)throw new Error(`HTTP ${d.status}`);return d.json()}).then(d=>{if(!rr(d))throw new Error("theme JSON must be an object");r(d)}).catch(d=>{u.signal.aborted||console.error(`[Claudius] Failed to load theme from ${s}:`,d)}),()=>u.abort()},[s]);const o=t.theme??n??null,i=(n==null?void 0:n.colorScheme)??t.mode,l=c.useMemo(()=>o?nr(o):{},[o]);return{mode:i,cssVars:l}}const nt="claudius:triggers:dismissed";function or(){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(nt)==="1"}catch{return!1}}function ar(){if(!(typeof window>"u"))try{window.sessionStorage.setItem(nt,"1")}catch{}}function ir({apiUrl:e,title:t,subtitle:n,welcomeMessage:r,placeholder:s,persistMessages:o,storageKeyPrefix:i,requestTimeoutMs:l,theme:u="light",accentColor:d,position:f="bottom-right",locale:w,translations:S,triggers:x,plugins:h,streaming:p=!0,attachments:j=!1,voice:b=!1,conversationExport:E=!1}){const[y,v]=c.useState(!1),k=c.useMemo(()=>pt(j),[j]),L=c.useMemo(()=>w??Ae(),[w]),C=c.useMemo(()=>Qt(b,L),[b,L]),R=c.useMemo(()=>Qe(L),[L]),[P,N]=c.useState(null),[$,V]=c.useState(or),F=c.useRef(!1),K=At("(max-width: 639px)"),U=c.useMemo(()=>tt({locale:w,translations:S}),[w,S]),{messages:te,isLoading:ne,isStreaming:re,streamingMessageId:X,error:m,canRetry:I,sendMessage:O,stop:Z,retry:J}=kt({apiUrl:e,persistMessages:o,storageKeyPrefix:i,timeoutMs:l,translations:U,plugins:h,streaming:p}),Q=c.useRef(null),_=c.useRef(y),{mode:B,cssVars:T}=sr(u),[A,M]=c.useState(!1);c.useEffect(()=>{if(B!=="auto")return;const Y=window.matchMedia("(prefers-color-scheme: dark)");M(Y.matches);const xe=g=>M(g.matches);return Y.addEventListener("change",xe),()=>Y.removeEventListener("change",xe)},[B]),c.useEffect(()=>{var Y;_.current&&!y&&((Y=Q.current)==null||Y.focus()),_.current=y},[y]);const z=c.useCallback(()=>{V(!0),ar()},[]),q=c.useCallback(()=>{v(!1),F.current&&(F.current=!1,z())},[z]),se=c.useCallback(()=>{v(Y=>!Y)},[]),W=c.useCallback(()=>{F.current=!0,N(null),v(!0)},[]),de=c.useCallback(Y=>{N(Y)},[]),oe=c.useCallback(()=>{N(null),W()},[W]),H=c.useCallback(()=>{N(null),z()},[z]);Mt({triggers:x,enabled:!$&&!y,onOpen:W,onGreeting:de});const ee=B==="dark"||B==="auto"&&A,ie={...T,...d?{"--cl-color-accent":d,"--cl-color-accent-dark":d}:{}},ae=Object.keys(ie).length>0?ie:void 0;return a.jsx("div",{className:"claudius-root",style:ae,children:a.jsxs("div",{"data-claudius-dark":ee?"true":"false",children:[y&&K&&a.jsx("div",{className:"claudius-scrim fixed inset-0 z-40 bg-claudius-scrim",onClick:q,"aria-hidden":"true"}),y&&a.jsx(Hn,{messages:te,isLoading:ne,isStreaming:re,streamingMessageId:X,error:m,canRetry:I,onSend:O,onStop:Z,onRetry:J,onClose:q,title:t??U.title,subtitle:n??U.subtitle,welcomeMessage:r??U.welcomeMessage,placeholder:s??U.placeholder,position:f,translations:U,isMobile:K,attachments:k,voice:C,conversationExport:E===!0,locale:R}),!(y&&K)&&a.jsx(Dt,{ref:Q,isOpen:y,onClick:se,position:f,translations:U}),!y&&P&&a.jsx(Wn,{message:P,position:f,onOpen:oe,onDismiss:H,dismissLabel:U.dismissGreeting})]})})}function cr(e){const{onEvent:t,includeContent:n=!0}=e,r=s=>n?s:"";return{name:"analytics",onBeforeSend(s){t({type:"message_sent",role:"user",content:r(s.content),chars:s.content.length})},onAfterReceive(s){t({type:"message_received",role:"assistant",content:r(s.content),chars:s.content.length})},onError(s){t({type:"chat_error",message:s.message,code:s.code})}}}const rt=[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,/\b\d{3}-\d{2}-\d{4}\b/g,/\b(?:\d[ -]?){13,16}\b/g,/\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g];function st(e,t,n){return t.reduce((r,s)=>(s.lastIndex=0,r.replace(s,n)),e)}function lr(e={}){const{patterns:t=rt,replacement:n="[redacted]",redactReplies:r=!1}=e,s=o=>{const i=st(o.content,t,n);if(i!==o.content)return{...o,content:i}};return{name:"redact-pii",onBeforeSend:s,onAfterReceive:r?s:void 0}}function ur(e,t,n){return typeof e=="function"?e(t):e instanceof RegExp?e.test(t):n?t.includes(e):t.toLowerCase().includes(e.toLowerCase())}function dr(e){const{rules:t,caseSensitive:n=!1}=e;return{name:"canned-responses",onBeforeSend(r,s){for(const o of t)if(ur(o.match,r.content,n)){s.respondWith(o.reply);return}}}}exports.ChatApiClient=Ve;exports.ChatApiError=G;exports.ChatWidget=ir;exports.DEFAULT_ATTACHMENT_OPTIONS=ge;exports.DEFAULT_PII_PATTERNS=rt;exports.DebounceError=ve;exports.builtinThemes=Ce;exports.createTranslations=Kt;exports.defaultTranslations=Ee;exports.detectLocale=Ae;exports.locales=ke;exports.pluginAnalytics=cr;exports.pluginCannedResponses=dr;exports.pluginRedactPII=lr;exports.redactText=st;exports.resolveTranslations=tt;
|
package/dist/claudius.iife.js
CHANGED
|
@@ -44,7 +44,7 @@ Error generating stack: `+o.message+`
|
|
|
44
44
|
`));return typeof c!="object"||c===null?null:{event:a,data:c}}catch{return null}}function du(u){return typeof u=="string"?{content:u}:u}function ao(u,a,i){console.error(`[claudius] plugin "${u.name}" failed in ${a}:`,i)}async function Hc(u,a,i){let c=a;for(const f of u){if(!f.onBeforeSend)continue;let p=null;const v={...i,respondWith(k){p={type:"respond",message:c,reply:du(k)}},abort(k){p={type:"abort",reason:k}}};try{const k=await f.onBeforeSend(c,v);if(p)return p;k&&(c=k)}catch(k){ao(f,"onBeforeSend",k)}}return{type:"send",message:c}}async function $c(u,a,i){let c=a;for(const f of u)if(f.onAfterReceive)try{const p=await f.onAfterReceive(c,i);p&&(c=p)}catch(p){ao(f,"onAfterReceive",p)}return c}async function Vc(u,a,i){for(const c of u){if(!c.onError)continue;let f=null;const p={...i,respondWith(v){f=du(v)}};try{if(await c.onError(a,p),f)return f}catch(v){ao(c,"onError",v)}}return null}const $r={maxSizeBytes:5*1024*1024,maxCount:5,allowedTypes:["image/jpeg","image/png","image/gif","image/webp","application/pdf"]};function Wc(u){return u?u===!0?$r:{maxSizeBytes:u.maxSizeBytes??$r.maxSizeBytes,maxCount:u.maxCount??$r.maxCount,allowedTypes:(u.allowedTypes??$r.allowedTypes).map(a=>a.trim().toLowerCase()).filter(Boolean)}:null}function Vr(u){if(!Number.isFinite(u)||u<0)return"0 B";if(u<1024)return`${u} B`;const a=u/1024;if(a<1024)return`${Math.round(a)} KB`;const i=a/1024;return`${Number.isInteger(i)?i:i.toFixed(1)} MB`}const Qc={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",pdf:"application/pdf"};function fu(u){var c;const a=(u.type||"").trim().toLowerCase();if(a)return a;const i=((c=u.name.split(".").pop())==null?void 0:c.toLowerCase())??"";return Qc[i]??""}function Kc(u){return u.startsWith("image/")}function bc(u){if(Kc(u.mediaType)){if(u.url)try{const a=new URL(u.url);if(a.protocol==="http:"||a.protocol==="https:")return u.url}catch{}if(u.data)return`data:${u.mediaType};base64,${u.data}`}}function Gc(u,a,i){const c=[],f=[];let p=Math.max(0,i.maxCount-a);for(const v of u){const k=fu(v);!k||!i.allowedTypes.includes(k)?f.push({file:v,reason:"type"}):v.size>i.maxSizeBytes||v.size===0?f.push({file:v,reason:"size"}):p<=0?f.push({file:v,reason:"count"}):(c.push(v),p-=1)}return{accepted:c,rejected:f}}function Yc(u){return new Promise((a,i)=>{const c=new FileReader;c.onerror=()=>i(c.error??new Error("Failed to read file")),c.onload=()=>{const f=String(c.result??""),p=f.indexOf(",");a(p>=0?f.slice(p+1):f)},c.readAsDataURL(u)})}let pu=0;function Xc(){return pu+=1,`att-${Date.now().toString(36)}-${pu}`}async function Zc(u){const a=await Yc(u);return{id:Xc(),name:u.name||"attachment",mediaType:fu(u),size:u.size,data:a}}function hu(u){return u.map(a=>{var i;return(i=a.attachments)!=null&&i.some(c=>c.data)?{...a,attachments:a.attachments.map(c=>{if(!c.data)return c;const f={...c};return delete f.data,f})}:a})}function Jc(u,a){if(!a||a.length===0)return u;const i=new Map(a.map(c=>[c.id,c]));return u.map(c=>{var f;return(f=c.attachments)!=null&&f.some(p=>i.has(p.id))?{...c,attachments:c.attachments.map(p=>{const v=i.get(p.id);if(!v)return p;const k={...p,key:v.key,url:v.url,expiresAt:v.expiresAt};return delete k.data,k})}:c})}const qc=200,ed="claudius:messages",qn=()=>new Date().toISOString();function td(u,a){let i;try{i=new URL(a).host}catch{i=a}return`${u}:${i}`}function co(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function nd(u){const a=co();if(!a)return[];try{const i=a.getItem(u);if(!i)return[];const c=JSON.parse(i);return Array.isArray(c)?c:[]}catch{return[]}}function rd({apiUrl:u,persistMessages:a=!0,storageKeyPrefix:i=ed,timeoutMs:c,translations:f,plugins:p,streaming:v=!0}){const k=R.useMemo(()=>new Uc(u,{debounceMs:0,timeoutMs:c}),[u,c]),S=td(i,u),N=a?nd(S):[],[j,O]=R.useState(N),[V,I]=R.useState(!1),[D,P]=R.useState(!1),[F,$]=R.useState(null),[J,B]=R.useState(null),[Q,ue]=R.useState(!1),de=R.useRef(N.length),ae=R.useRef(!1),Z=R.useRef(N),xe=R.useRef(null),pe=R.useRef(p??[]);pe.current=p??[];const Se=R.useCallback(C=>{if(!a)return;const m=co();if(m)try{const T=hu(C.slice(-qc));m.setItem(S,JSON.stringify(T))}catch{}},[a,S]),Ce=()=>(de.current+=1,`msg-${de.current}`),ve=R.useCallback((C,m)=>{if(!f)return m??"Something went wrong. Please try again.";switch(C){case"TIMEOUT":return f.errorTimeout;case"NETWORK_ERROR":return f.errorConnection;case"RATE_LIMITED":return m!=null&&m.includes("minute")?f.errorRateLimitMinute:f.errorRateLimitHour;case"ATTACHMENT_QUOTA_EXCEEDED":return f.errorAttachmentQuota;case"ATTACHMENTS_DISABLED":case"ATTACHMENT_INVALID":case"ATTACHMENT_TOO_LARGE":return f.errorAttachmentRejected;case"VALIDATION_ERROR":case"CONFIG_ERROR":case"SERVICE_ERROR":case"UNKNOWN_ERROR":default:return m??f.errorGeneric}},[f]),Re=R.useCallback(C=>!(C instanceof tt)||C.code==="TIMEOUT"||C.code==="NETWORK_ERROR"||C.code==="RATE_LIMITED"||C.code==="SERVICE_ERROR"||C.code==="UNKNOWN_ERROR"||C.status>=500||C.status===0,[]),ye=R.useCallback(async C=>{var se,ne,ie;I(!0),ae.current=!0,B(null),ue(!1);const m=v&&typeof k.streamMessage=="function";let T=null;const re=K=>{if(T===null){T=Ce(),$(T);const q=[...Z.current,{id:T,role:"assistant",content:"",createdAt:qn(),...K}];Z.current=q,O(q)}else{const q=T,ce=Z.current.map(Ae=>Ae.id===q?{...Ae,...K}:Ae);Z.current=ce,O(ce)}},le=()=>{if(T===null)return;const K=T,q=Z.current.filter(ce=>ce.id!==K);Z.current=q,O(q)};try{let K,q,ce,Ae,Ze=!1;if(m){const Oe=new AbortController;xe.current=Oe,P(!0);const pt=await k.streamMessage(C,{signal:Oe.signal,onChunk:(Mt,ut)=>re({content:ut}),onToolUse:(Mt,ut)=>re({toolUses:[...ut]})});K=pt.reply,q=pt.sources,ce=pt.toolUses,Ae=pt.attachments,Ze=pt.aborted??!1}else{const Oe=await k.sendMessage(C);K=Oe.reply,q=Oe.sources,ce=Oe.toolUses,Ae=Oe.attachments}if(Ze&&!K){le();return}const ft=((se=Z.current.find(Oe=>Oe.id===T))==null?void 0:se.createdAt)??qn();let Fe={id:T??Ce(),role:"assistant",content:K,createdAt:ft,sources:q,toolUses:ce};pe.current.length>0&&!Ze&&(Fe=await $c(pe.current,Fe,{messages:C,apiUrl:u}),Fe.createdAt||(Fe={...Fe,createdAt:ft}));const Kt=T!==null?Z.current.map(Oe=>Oe.id===Fe.id?Fe:Oe):[...C,Fe],_t=Jc(Kt,Ae);Z.current=_t,O(_t),Se(_t)}catch(K){if(K instanceof so)return;if(K instanceof tt&&((ne=K.code)!=null&&ne.startsWith("ATTACHMENT"))&&C.length>0){const q=C[C.length-1];if(q.role==="user"&&((ie=q.attachments)!=null&&ie.length)){const ce=C.slice(0,-1);Z.current=ce,O(ce),Se(ce)}}if(T!==null){Se(Z.current),K instanceof tt?B(ve(K.code,K.message)):B((f==null?void 0:f.errorConnection)??"Failed to connect. Please try again."),ue(!1);return}if(pe.current.length>0){const q=K instanceof Error?K:new Error(String(K)),ce=await Vc(pe.current,q,{messages:C,apiUrl:u});if(ce){const Ae={id:Ce(),role:"assistant",content:ce.content,createdAt:qn(),sources:ce.sources},Ze=[...C,Ae];Z.current=Ze,O(Ze),Se(Ze),B(null),ue(!1);return}}K instanceof tt?B(ve(K.code,K.message)):B((f==null?void 0:f.errorConnection)??"Failed to connect. Please try again."),ue(Re(K))}finally{I(!1),ae.current=!1,P(!1),$(null),xe.current=null}},[u,k,ve,Re,Se,v,f]),_e=R.useCallback(()=>{var C;(C=xe.current)==null||C.abort()},[]),ge=R.useCallback(async(C,m)=>{const T=C.trim(),re=(m==null?void 0:m.filter(ie=>ie&&ie.id))??[];if(!T&&re.length===0||ae.current)return;const le={id:Ce(),role:"user",content:T,createdAt:qn(),...re.length>0?{attachments:re}:{}};let se=le;if(pe.current.length>0){const ie=await Hc(pe.current,le,{messages:Z.current,apiUrl:u});if(ie.type==="abort")return;const K=q=>q.createdAt?q:{...q,createdAt:le.createdAt};if(ie.type==="respond"){const q={id:Ce(),role:"assistant",content:ie.reply.content,createdAt:qn(),sources:ie.reply.sources},ce=[...Z.current,K(ie.message),q];Z.current=ce,O(ce),Se(ce),B(null),ue(!1);return}se=K(ie.message)}const ne=[...Z.current,se];Z.current=ne,O(ne),Se(ne),await ye(ne)},[u,Se,ye]),z=R.useCallback(async()=>{if(ae.current)return;const C=Z.current[Z.current.length-1];!C||C.role!=="user"||await ye(Z.current)},[ye]),X=R.useCallback(()=>{if(Z.current=[],O([]),B(null),ue(!1),a){const C=co();if(!C)return;try{C.removeItem(S)}catch{}}},[a,S]);return{messages:j,isLoading:V,isStreaming:D,streamingMessageId:F,error:J,canRetry:Q,sendMessage:ge,stop:_e,retry:z,clearMessages:X}}function ld(u){const[a,i]=R.useState(()=>typeof window>"u"?!1:window.matchMedia(u).matches);return R.useEffect(()=>{const c=window.matchMedia(u);i(c.matches);const f=p=>i(p.matches);return c.addEventListener("change",f),()=>c.removeEventListener("change",f)},[u]),a}function Wr(u,a){return u instanceof RegExp?u.test(a):a.toLowerCase().includes(u.toLowerCase())}function od(){const u=document.documentElement,a=document.body,i=u.scrollTop||a.scrollTop||0,c=Math.max(u.scrollHeight,a.scrollHeight),f=u.clientHeight||window.innerHeight,p=c-f;return p<=0?100:i/p*100}function id({triggers:u,enabled:a,onOpen:i,onGreeting:c}){R.useEffect(()=>{if(!a||!u||u.length===0)return;const f=new Set,p=[],v=typeof window<"u"?window.location.href:"",k=(S,N)=>{f.has(S)||(f.add(S),N==="open"?i():c(N.greeting))};return u.forEach((S,N)=>{switch(S.on){case"url":{Wr(S.pattern,v)&&k(N,S.action);break}case"time":{if(S.matchUrl&&!Wr(S.matchUrl,v))return;const j=window.setTimeout(()=>k(N,S.action),Math.max(0,S.seconds*1e3));p.push(()=>window.clearTimeout(j));break}case"scroll":{if(S.matchUrl&&!Wr(S.matchUrl,v))return;const j=()=>{od()>=S.percent&&k(N,S.action)};j(),window.addEventListener("scroll",j,{passive:!0}),p.push(()=>window.removeEventListener("scroll",j));break}case"exit-intent":{if(S.matchUrl&&!Wr(S.matchUrl,v))return;const j=O=>{O.clientY<=0&&k(N,S.action)};document.addEventListener("mouseleave",j),p.push(()=>document.removeEventListener("mouseleave",j));break}}}),()=>{p.forEach(S=>S())}},[u,a,i,c])}const ud={"bottom-right":"bottom-6 right-6","bottom-left":"bottom-6 left-6","top-right":"top-6 right-6","top-left":"top-6 left-6"},sd=R.forwardRef(function({isOpen:a,onClick:i,position:c="bottom-right",translations:f},p){const v=a?(f==null?void 0:f.closeChat)??"Close chat":(f==null?void 0:f.openChat)??"Open chat";return y.jsx("button",{ref:p,onClick:i,"aria-label":v,className:`fixed ${ud[c]} 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:a?y.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:[y.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}):y.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:y.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"})})})}),ad=R.memo(function({count:a,isActive:i,onClick:c}){return y.jsxs("button",{onClick:c,"aria-label":"View sources",title:"View sources",className:`group relative flex h-7 w-7 items-center justify-center rounded-claudius-full transition-colors ${i?"bg-claudius-accent text-claudius-accent-text":"text-claudius-text-muted hover:bg-claudius-surface-muted hover:text-claudius-text"}`,children:[y.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:[y.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),y.jsx("polyline",{points:"14 2 14 8 20 8"}),y.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),y.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]}),y.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:a})]})}),cd=["http:","https:"];function Qr(u){if(!u||typeof u!="string")return null;const a=u.trim();if(!a)return null;try{const i=new URL(a);return cd.includes(i.protocol)?a:null}catch{return null}}function dd(){return y.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:[y.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),y.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function mu({label:u,onClick:a}){return y.jsx("button",{type:"button",onClick:a,"aria-label":u,className:"absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-claudius-full bg-claudius-text text-claudius-surface shadow-claudius-floating hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-claudius-accent",children:y.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round","aria-hidden":"true",children:[y.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})}const gu=R.memo(function({attachment:a,variant:i,onRemove:c,removeLabel:f}){const p=bc(a),v=i==="composer",k=`${a.name} (${Vr(a.size)})`,S=a.url?Qr(a.url):null;if(p){const j=y.jsx("img",{src:p,alt:a.name,title:k,loading:"lazy",className:v?"h-12 w-12 rounded-claudius-sm border border-claudius-border object-cover":"max-h-48 max-w-full rounded-claudius-sm object-contain"});return y.jsxs("div",{className:"relative inline-block",children:[!v&&S?y.jsxs("a",{href:S,target:"_blank",rel:"noopener noreferrer",children:[j,y.jsxs("span",{className:"sr-only",children:[k," (opens in a new tab)"]})]}):j,c&&f&&y.jsx(mu,{label:f,onClick:c})]})}const N=y.jsxs("span",{title:k,className:`inline-flex max-w-[220px] items-center gap-1.5 rounded-claudius-sm border px-2 py-1 text-xs ${v?"border-claudius-border bg-claudius-field text-claudius-text":"border-current/30 bg-transparent"}`,children:[y.jsx(dd,{}),y.jsx("span",{className:"truncate",children:a.name}),y.jsx("span",{className:"shrink-0 opacity-70",children:Vr(a.size)})]});return y.jsxs("div",{className:"relative inline-block",children:[!v&&S?y.jsxs("a",{href:S,target:"_blank",rel:"noopener noreferrer",className:"underline-offset-2 hover:underline",children:[N,y.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]}):N,c&&f&&y.jsx(mu,{label:f,onClick:c})]})}),vu=R.forwardRef(function({label:a,onClick:i,children:c},f){return y.jsx("button",{ref:f,type:"button",onClick:i,"aria-label":a,title:a,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:y.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:c})})});function fd({state:u,labels:a,onPlay:i,onPause:c,onResume:f,onStop:p}){var j;const v=R.useRef(null),k=R.useRef(null),S=!!((j=v.current)!=null&&j.contains(document.activeElement));R.useEffect(()=>{var O,V;u==="idle"&&S&&!((O=v.current)!=null&&O.contains(document.activeElement))&&((V=k.current)==null||V.focus())},[u,S]);const N=u==="idle"?{label:a.play,onClick:i}:u==="paused"?{label:a.resume,onClick:f}:{label:a.pause,onClick:c};return y.jsxs("div",{ref:v,className:"flex items-center gap-1",children:[y.jsx(vu,{ref:k,...N,children:u==="idle"?y.jsxs(y.Fragment,{children:[y.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),y.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07",fill:"none"}),y.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14",fill:"none"})]}):u==="paused"?y.jsx("polygon",{points:"6 3 20 12 6 21 6 3"}):y.jsxs(y.Fragment,{children:[y.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1"}),y.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1"})]})}),u!=="idle"&&y.jsx(vu,{label:a.stop,onClick:p,children:y.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})]})}function pd(u){const a=u.lastIndexOf(`
|
|
45
45
|
`),i=a===-1?"":u.slice(0,a+1);let c=a===-1?u:u.slice(a+1);return c=gd(c),c=vd(c),i+c}function hd(u){const a=[];for(let i=0;i<u.length-1;i++)u[i]==="*"&&u[i+1]==="*"&&(a.push(i),i++);return a}function md(u){const a=[];for(let i=0;i<u.length;i++)if(u[i]==="*"){if(u[i+1]==="*"){i++;continue}a.push(i)}return a}function gd(u){const a=hd(u);if(a.length%2===0)return u;const i=a[a.length-1],c=u.slice(i+2);return c.trim()===""?u.slice(0,i)+c:u+"**"}function vd(u){const a=md(u);if(a.length%2===0)return u;const i=a[a.length-1],c=u.slice(i+1);return c.trim()===""?u.slice(0,i)+c:u+"*"}function yd({toolUse:u,usedLabel:a,detailsLabel:i}){const[c,f]=R.useState(!1),p=u.input!==void 0||u.result!==void 0;return y.jsxs("div",{className:"text-xs text-claudius-text-muted",children:[y.jsxs("button",{type:"button",disabled:!p,onClick:()=>f(v=>!v),"aria-expanded":p?c: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:[y.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:y.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"})}),y.jsxs("span",{children:[a," ",y.jsx("span",{className:"font-mono text-claudius-text",children:u.name}),u.isError&&y.jsx("span",{className:"text-claudius-error",children:" ✕"})]}),p&&y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"sr-only",children:i}),y.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:c?"rotate-180":void 0,children:y.jsx("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&p&&y.jsxs("div",{className:"mt-1 overflow-x-auto rounded-claudius-sm border border-claudius-border bg-claudius-field p-2 font-mono",children:[u.input!==void 0&&y.jsx("pre",{className:"whitespace-pre-wrap break-all",children:JSON.stringify(u.input,null,2)}),u.result!==void 0&&y.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-all border-t border-claudius-border pt-1",children:u.result})]})]})}const yu=/(https?:\/\/[^\s)]+)/,wu=/(\*\*[^*]+\*\*)/,xu=/(\*[^*]+\*)/;function wd(u,a){const i=u.match(/[.,;:!?'"]+$/),c=i?u.slice(0,-i[0].length):u,f=i?i[0]:"",p=Qr(c);return p?y.jsxs(y.Fragment,{children:[y.jsxs("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"underline font-medium hover:opacity-80 text-claudius-link",children:[p.replace(/^https?:\/\//,""),y.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]},a),f]}):u}function xd(u,a){const i=u.split(wu),c=[];return i.forEach((f,p)=>{if(wu.test(f)){const v=f.slice(2,-2);c.push(y.jsx("strong",{children:v},`${a}-b${p}`))}else f.split(xu).forEach((k,S)=>{if(xu.test(k)){const N=k.slice(1,-1);c.push(y.jsx("em",{children:N},`${a}-b${p}-i${S}`))}else k.split(yu).forEach((j,O)=>{yu.test(j)?c.push(wd(j,`${a}-b${p}-i${S}-u${O}`)):j&&c.push(j)})})}),c}function Sd(u){const a=u.split(`
|
|
46
46
|
`);return a.map((i,c)=>y.jsxs("span",{children:[xd(i,`l${c}`),c<a.length-1&&y.jsx("br",{})]},c))}const kd=R.memo(function({role:a,content:i,isStreaming:c=!1,sources:f,attachments:p,toolUses:v,toolUsedLabel:k="Used tool:",toolDetailsLabel:S="Tool details",onSourceClick:N,isSourceActive:j,speech:O}){const V=a==="user",I=!!p&&p.length>0,D=c?pd(i):i,P=V||i!==""||!(v!=null&&v.length);return y.jsxs("div",{className:`${V?"ml-auto":"mr-auto"} max-w-[85%]`,children:[P&&y.jsxs("div",{className:`rounded-claudius-bubble px-4 py-2.5 text-sm leading-relaxed font-body ${V?"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:[I&&y.jsx("ul",{className:`flex flex-wrap gap-2 ${i?"mb-2":""}`,"aria-label":"Attachments",children:p.map(F=>y.jsx("li",{children:y.jsx(gu,{attachment:F,variant:"message"})},F.id))}),(i!==""||!I)&&Sd(D)]}),!V&&v&&v.length>0&&y.jsx("div",{className:"mt-1 space-y-1",children:v.map((F,$)=>y.jsx(yd,{toolUse:F,usedLabel:k,detailsLabel:S},`${F.name}-${$}`))}),!V&&f&&f.length>0&&N&&y.jsx("div",{className:"mt-1",children:y.jsx(ad,{count:f.length,isActive:j??!1,onClick:N})}),!V&&O&&y.jsx("div",{className:"mt-1",children:y.jsx(fd,{...O})})]})}),Su={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",attachFile:"Attach a file",removeAttachment:"Remove attachment",attachmentsLabel:"Attachments",dropFilesHint:"Drop files to attach",attachmentTooLarge:"{name} is too large. The maximum size is {max}.",attachmentTypeNotAllowed:"{name} is not a supported file type.",attachmentTooMany:"You can attach up to {max} files per message.",voiceInput:"Voice input",voiceInputHold:"Hold to talk",voiceListening:"Listening...",voicePermissionDenied:"Microphone access is blocked. Allow it in your browser settings to use voice input.",voiceNoSpeech:"No speech was detected. Please try again.",voiceNoMicrophone:"No microphone was found.",voiceUnavailable:"Voice input is not available right now.",readAloud:"Read aloud",pauseReading:"Pause reading",resumeReading:"Resume reading",stopReading:"Stop reading",moreOptions:"More options",copyAsMarkdown:"Copy as Markdown",downloadAsMarkdown:"Download as Markdown",downloadAsJson:"Download as JSON",copiedToClipboard:"Copied to clipboard",copyFailed:"Could not copy. Try downloading instead.",transcriptTitle:"Chat transcript",transcriptExported:"Exported {date}",transcriptUser:"User",transcriptAssistant:"Assistant",transcriptAttachments:"Attachments:",transcriptSources:"Sources:",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.",errorAttachmentRejected:"An attachment was rejected. Please remove it and try again.",errorAttachmentQuota:"Upload limit reached. Please try again later.",errorRetry:"Retry"},ku=Su;function Eu(u){return u.key===" "||u.key==="Enter"}function Ed({mode:u,isListening:a,disabled:i=!1,onStart:c,onStop:f,label:p}){const v=u==="hold",k=R.useRef(!1),S=()=>{i||k.current||(k.current=!0,c({held:!0}))},N=()=>{k.current&&(k.current=!1,f())},j=D=>{v&&D.detail!==0||(a?f():c({held:!1}))},O=D=>{var P,F;!v||D.button!==0||((F=(P=D.currentTarget).setPointerCapture)==null||F.call(P,D.pointerId),S())},V=D=>{!v||!Eu(D)||(D.preventDefault(),D.repeat||S())},I=D=>{!v||!Eu(D)||(D.preventDefault(),N())};return y.jsx("button",{type:"button",disabled:i,"aria-label":p,"aria-pressed":a,title:p,onClick:j,onPointerDown:O,onPointerUp:N,onPointerCancel:N,onLostPointerCapture:N,onKeyDown:V,onKeyUp:I,onBlur:N,onContextMenu:v?D=>D.preventDefault():void 0,style:v?{WebkitTouchCallout:"none"}:void 0,className:`flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm border transition-colors focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50 ${a?"border-claudius-accent bg-claudius-accent text-claudius-accent-text focus:ring-2 focus:ring-offset-2 focus:ring-offset-claudius-surface":"border-claudius-border bg-claudius-field text-claudius-text-muted hover:text-claudius-text focus:border-claudius-accent"} ${v?"touch-none select-none":""}`,children:a&&!v?y.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:y.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})}):y.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:[y.jsx("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),y.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),y.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]})})}function Cd({active:u}){return y.jsxs("span",{"aria-hidden":"true","data-claudius-voice-level":u?"active":"idle",className:"claudius-voice-level pointer-events-none absolute right-3 top-1/2 flex h-4 -translate-y-1/2 items-center gap-0.5 text-claudius-accent",children:[y.jsx("span",{}),y.jsx("span",{}),y.jsx("span",{}),y.jsx("span",{})]})}function Kr(u,a){return u.replace(/\{(\w+)\}/g,(i,c)=>c in a?String(a[c]):i)}const Rd={en:"en-US",es:"es-ES",fr:"fr-FR",de:"de-DE"},Td=["toggle","hold"];function Cu(u,a){if(!(!u||!u.includes("-")))return u.toLowerCase().split("-")[0]===a?u:void 0}function Ru(u,a){const i=a==null?void 0:a.trim();if(i)return i;const c=typeof document<"u"?Cu(document.documentElement.lang,u):void 0;if(c)return c;const f=typeof navigator<"u"?Cu(navigator.language,u):void 0;return f||Rd[u]}function Nd(u,a){const i=typeof u=="object"&&u!==null&&!Array.isArray(u);if(u!==!0&&!i)return null;const c=u===!0?{}:u,f={input:c.input??!0,output:c.output??!0,mode:Td.includes(c.mode)?c.mode:"toggle",autoSubmit:c.autoSubmit??!1,lang:Ru(a,c.lang)};return f.input||f.output?f:null}function jd(u){const a=u("voice");if(a===null)return;if(a==="false")return!1;const i={},c=N=>{const j=u(N);return j===null?void 0:j!=="false"},f=u("voice-mode");f!==null&&(i.mode=f);const p=c("voice-auto-submit");p!==void 0&&(i.autoSubmit=p);const v=c("voice-input");v!==void 0&&(i.input=v);const k=c("voice-output");k!==void 0&&(i.output=k);const S=u("voice-lang");return S!==null&&(i.lang=S),Object.keys(i).length>0?i:!0}function _d(u,a,i){const c=a.trim();if(!c)return u;const f=u.trimEnd();return(f?`${f} ${c}`:c).slice(0,i)}function Md(u){const a=[];let i=0;for(let c=0;c<u.length;c++){const f=u[c];(f===`
|
|
47
|
-
`||f==="。"||f==="!"||f==="?"||(f==="."||f==="!"||f==="?")&&(c+1===u.length||/\s/.test(u[c+1])))&&(a.push(u.slice(i,c+1)),i=c+1)}return i<u.length&&a.push(u.slice(i)),a}function Ld(u,a=150){const i=[];let c="";const f=()=>{const p=c.trim();p&&i.push(p),c=""};for(const p of Md(u)){if((c+p).trim().length<=a){c+=p;continue}if(f(),p.trim().length<=a){c=p;continue}for(let v of p.trim().split(/\s+/)){for(c&&`${c} ${v}`.length>a&&f();v.length>a;)i.push(v.slice(0,a)),v=v.slice(a);c=c?`${c} ${v}`:v}}return f(),i}function Tu(){if(typeof window>"u")return;const u=window;return u.SpeechRecognition??u.webkitSpeechRecognition}function Pd(u){switch(u){case"not-allowed":case"service-not-allowed":return"permission";case"no-speech":return"no-speech";case"audio-capture":return"no-microphone";default:return"unavailable"}}function Ad(u){const[a]=R.useState(()=>Tu()!==void 0),[i,c]=R.useState(!1),[f,p]=R.useState(!1),v=R.useRef(null),k=R.useRef(!1),S=R.useRef(u);R.useEffect(()=>{S.current=u});const N=R.useCallback(I=>{I.onstart=null,I.onend=null,I.onerror=null,I.onresult=null,I.onspeechstart=null,I.onspeechend=null,v.current===I&&(v.current=null),c(!1),p(!1)},[]),j=R.useCallback(()=>{const I=v.current;I&&(N(I),I.abort())},[N]),O=R.useCallback(()=>{const I=v.current;return I?(k.current?I.stop():j(),!0):!1},[j]),V=R.useCallback(()=>{var $,J;const I=Tu();if(!I||v.current)return!1;const D=new I;D.lang=S.current.lang,D.interimResults=!0,D.continuous=!1;let P="";const F=()=>{k.current=!0};D.onstart=F,D.onspeechstart=()=>{F(),p(!0)},D.onspeechend=()=>p(!1),D.onresult=B=>{var de,ae;let Q="",ue="";for(let Z=0;Z<B.results.length;Z++){const xe=B.results[Z];xe.isFinal?Q+=xe[0].transcript:ue+=xe[0].transcript}P=Q,F(),p(!0),(ae=(de=S.current).onTranscript)==null||ae.call(de,Q+ue)},D.onerror=B=>{var Q,ue;B.error!=="aborted"&&((ue=(Q=S.current).onError)==null||ue.call(Q,Pd(B.error))),N(D),D.abort()},D.onend=()=>{var B,Q;N(D),(Q=(B=S.current).onEnd)==null||Q.call(B,P)},v.current=D,k.current=!1,c(!0);try{D.start()}catch{return N(D),(J=($=S.current).onError)==null||J.call($,"unavailable"),!1}return!0},[N]);return R.useEffect(()=>j,[j]),{isSupported:a,isListening:i,isSpeechDetected:f,start:V,stop:O,abort:j}}const er=2e3,Dd=1800;function Nu(u){var i;const a=(i=u.dataTransfer)==null?void 0:i.types;return!!a&&Array.from(a).includes("Files")}function zd({onSend:u,isLoading:a,isStreaming:i=!1,onStop:c,placeholder:f,translations:p,attachments:v=null,voice:k=null,onVoiceStart:S,isReadingAloud:N=!1}){const j=p??ku,[O,V]=R.useState(""),[I,D]=R.useState([]),[P,F]=R.useState(null),[$,J]=R.useState(!1),[B,Q]=R.useState(null),ue=R.useRef(null),de=R.useRef(null),ae=R.useRef([]),Z=R.useRef(0),xe=R.useRef(""),pe=R.useRef(""),Se=R.useRef(!1),Ce=R.useRef(!1),ve=R.useRef(!1),Re=H=>{xe.current=H,V(H)},ye=O.length,_e=ye>=Dd,ge=ye>=er,z=f??j.placeholder,X=!!v&&I.length<v.maxCount,C=i&&!!c;R.useEffect(()=>{var H;a||(H=ue.current)==null||H.focus()},[a]);const m=R.useCallback((H,ke)=>{if(!v)return"";switch(ke){case"size":return Kr(j.attachmentTooLarge,{name:H,max:Vr(v.maxSizeBytes)});case"type":return Kr(j.attachmentTypeNotAllowed,{name:H});case"count":return Kr(j.attachmentTooMany,{max:v.maxCount})}},[v,j]),T=R.useCallback(async H=>{if(!v||H.length===0)return;const{accepted:ke,rejected:It}=Gc(H,ae.current.length,v);if(F(It.length>0?m(It[0].file.name,It[0].reason):null),ke.length===0)return;const Gr=await Promise.all(ke.map(Zc));ae.current=[...ae.current,...Gr],D(ae.current)},[v,m]),re=R.useCallback(H=>{ae.current=ae.current.filter(ke=>ke.id!==H),D(ae.current),F(null)},[]),le=()=>{const H=xe.current.trim(),ke=ae.current;!H&&ke.length===0||xe.current.length>=er||(ke.length>0?u(H,ke):u(H),Re(""),ae.current=[],D([]),F(null),Q(null))},se=H=>{switch(H){case"permission":return j.voicePermissionDenied;case"no-speech":return j.voiceNoSpeech;case"no-microphone":return j.voiceNoMicrophone;case"unavailable":return j.voiceUnavailable}},ne=Ad({lang:(k==null?void 0:k.lang)??"en-US",onTranscript:H=>Re(_d(pe.current,H,er)),onEnd:H=>{const ke=H.trim()!=="";if(ke&&(Ce.current=!0),!Se.current){q();return}ke&&ce()},onError:H=>{H==="no-speech"&&Ce.current||(ve.current=!0,Q(se(H)))}}),ie=!!(k!=null&&k.input)&&ne.isSupported,K=ne.isListening;R.useEffect(()=>{const H=ue.current;K&&H&&(H.scrollLeft=H.scrollWidth)},[K,O]);const q=()=>{k!=null&&k.autoSubmit&&Ce.current&&!ve.current&&le()},ce=()=>{const H=xe.current;ne.start()&&(pe.current=H)},Ae=({held:H})=>{Q(null),Se.current=H,Ce.current=!1,ve.current=!1,S==null||S(),ce()},Ze=()=>{const H=Se.current;Se.current=!1,!ne.stop()&&H&&q()},ft=()=>{Se.current=!1,ne.abort()},{abort:Fe}=ne;R.useEffect(()=>{!a&&!N||(Se.current=!1,Fe())},[a,N,Fe]);const Kt=H=>{H.preventDefault(),ft(),le()},_t=H=>{const ke=H.target.value;ke.length<=er&&(ft(),Q(null),Re(ke))},Oe=H=>{const ke=Array.from(H.target.files??[]);H.target.value="",T(ke)},pt=H=>{var It;if(!v)return;const ke=Array.from(((It=H.clipboardData)==null?void 0:It.files)??[]);ke.length!==0&&(H.preventDefault(),T(ke))},Mt=H=>{!v||!Nu(H)||(H.preventDefault(),Z.current+=1,J(!0))},ut=H=>{!v||!Nu(H)||H.preventDefault()},Ue=()=>{v&&(Z.current=Math.max(0,Z.current-1),Z.current===0&&J(!1))},bt=H=>{var ke;v&&(H.preventDefault(),Z.current=0,J(!1),T(Array.from(((ke=H.dataTransfer)==null?void 0:ke.files)??[])))};return y.jsxs("form",{onSubmit:Kt,onDragEnter:Mt,onDragOver:ut,onDragLeave:Ue,onDrop:bt,"data-drag-over":$||void 0,className:`relative border-t border-claudius-border bg-claudius-surface p-3 ${$?"ring-2 ring-inset ring-claudius-accent":""}`,children:[$&&y.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-claudius-surface text-sm font-medium text-claudius-accent",children:j.dropFilesHint}),v&&I.length>0&&y.jsx("ul",{"aria-label":j.attachmentsLabel,className:"mb-2 flex flex-wrap gap-3 pt-1",children:I.map(H=>y.jsx("li",{children:y.jsx(gu,{attachment:H,variant:"composer",onRemove:()=>re(H.id),removeLabel:`${j.removeAttachment}: ${H.name}`})},H.id))}),y.jsxs("div",{className:"flex gap-2",children:[v&&y.jsxs(y.Fragment,{children:[y.jsx("input",{ref:de,type:"file",multiple:!0,hidden:!0,tabIndex:-1,accept:v.allowedTypes.join(","),onChange:Oe,"aria-label":j.attachFile}),y.jsx("button",{type:"button",onClick:()=>{var H;return(H=de.current)==null?void 0:H.click()},disabled:a||!X,"aria-label":j.attachFile,title:j.attachFile,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm border border-claudius-border bg-claudius-field text-claudius-text-muted transition-colors hover:text-claudius-text focus:border-claudius-accent focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50",children:y.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:y.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})})})]}),y.jsxs("div",{className:"relative min-w-0 flex-1",children:[y.jsx("input",{ref:ue,type:"text",value:O,onChange:_t,onPaste:pt,placeholder:K?j.voiceListening:z,disabled:a,"aria-label":j.typeYourMessage,"aria-describedby":_e?"char-count":void 0,className:`h-full w-full rounded-claudius-sm border border-claudius-border bg-claudius-field py-2 pl-3 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 ${K?"pr-10":"pr-3"}`}),K&&y.jsx(Cd,{active:ne.isSpeechDetected})]}),ie&&k&&y.jsx(Ed,{mode:k.mode,isListening:K,disabled:a,onStart:Ae,onStop:Ze,label:k.mode==="hold"?j.voiceInputHold:j.voiceInput}),C?y.jsx("button",{type:"button",onClick:c,"aria-label":j.stopGenerating,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:y.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:y.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})}):y.jsx("button",{type:"submit",disabled:a||ge,"aria-label":j.sendMessage,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:y.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:[y.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),y.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),(P??B)&&y.jsx("div",{role:"alert",className:"mt-1 text-xs text-claudius-error",children:P??B}),_e&&y.jsxs("div",{id:"char-count",className:`mt-1 text-xs text-right ${ge?"text-claudius-error":"text-claudius-text-muted"}`,"aria-live":"polite",children:[ye,"/",er]})]})}const Od=["blog","page","external"],Id={blog:"Blog",page:"Page",external:"External"};function Fd(u){try{return new URL(u).hostname}catch{return u}}const Ud=R.memo(function({sources:a,onClose:i}){const c=Od.map(p=>({type:p,label:Id[p],items:a.filter(v=>v.type===p)})).filter(p=>p.items.length>0),f=a.length===1?"1 source found":`${a.length} sources found`;return y.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:[y.jsxs("div",{className:"flex items-center justify-between border-b border-claudius-border px-4 py-3",children:[y.jsxs("div",{children:[y.jsx("h3",{className:"text-sm font-heading font-semibold text-claudius-text",children:"Sources"}),y.jsx("p",{className:"text-xs text-claudius-text-muted",children:f})]}),y.jsx("button",{onClick:i,"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:y.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:[y.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),y.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-4",children:c.map(p=>y.jsxs("div",{children:[y.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-claudius-text-muted",children:p.label}),y.jsx("div",{className:"space-y-2",children:p.items.map(v=>{const k=Qr(v.url);return k?y.jsxs("a",{href:k,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:[y.jsx("p",{className:"truncate text-sm font-medium text-claudius-text",children:v.title}),y.jsx("p",{className:"mt-0.5 text-xs text-claudius-text-muted",children:Fd(k)})]},k):null})})]},p.type))})]})});function Bd({title:u,subtitle:a,titleId:i,closeLabel:c,onClose:f,actions:p}){return y.jsxs("div",{className:"flex items-center gap-3 bg-claudius-accent px-5 py-4",children:[y.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:u.charAt(0).toUpperCase()}),y.jsxs("div",{className:"flex-1",children:[y.jsx("h2",{id:i,className:"text-sm font-heading font-semibold text-claudius-accent-text",children:u}),y.jsx("p",{className:"text-xs text-claudius-accent-text",children:a})]}),p,y.jsx("button",{onClick:f,"aria-label":c,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:y.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:[y.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}function Hd({message:u,retryLabel:a,onRetry:i}){return y.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:[y.jsx("span",{children:u}),i&&y.jsx("button",{type:"button",onClick:i,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:a})]})}function $d({label:u}){return y.jsx("div",{role:"status","aria-live":"polite","aria-label":u,className:"mr-auto flex max-w-[85%]",children:y.jsxs("div",{className:"flex gap-1 rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-3",children:[y.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:0ms]"}),y.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:150ms]"}),y.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:300ms]"})]})})}function Vd({label:u,items:a,onOpen:i}){const[c,f]=R.useState(!1),p=R.useId(),v=R.useId(),k=R.useRef(null),S=R.useRef(null),N=R.useRef([]),j=R.useRef(null),O=$=>{j.current=$,f(!0),i==null||i()},V=$=>{var J;f(!1),(J=S.current)==null||J.focus()};R.useEffect(()=>{var J;if(!c)return;j.current!==null&&((J=N.current[j.current])==null||J.focus(),j.current=null);const $=B=>{var Q;(Q=k.current)!=null&&Q.contains(B.target)||f(!1)};return document.addEventListener("pointerdown",$),()=>document.removeEventListener("pointerdown",$)},[c]);const I=$=>{var B;const J=a.length;(B=N.current[($+J)%J])==null||B.focus()},D=$=>{$.key==="ArrowDown"?($.preventDefault(),O(0)):$.key==="ArrowUp"&&($.preventDefault(),O(a.length-1))},P=$=>{const J=N.current.findIndex(B=>B===document.activeElement);switch($.key){case"ArrowDown":$.preventDefault(),I(J+1);break;case"ArrowUp":$.preventDefault(),I(J===-1?a.length-1:J-1);break;case"Home":$.preventDefault(),I(0);break;case"End":$.preventDefault(),I(a.length-1);break;case"Escape":$.preventDefault(),$.stopPropagation(),V();break;case"Tab":$.shiftKey&&($.preventDefault(),V());break}},F=$=>{var B;const J=$.relatedTarget;J&&((B=k.current)!=null&&B.contains(J)||f(!1))};return y.jsxs("div",{ref:k,className:"relative",children:[y.jsx("button",{ref:S,id:p,type:"button","aria-label":u,"aria-haspopup":"menu","aria-expanded":c,"aria-controls":c?v:void 0,onClick:()=>c?V():O(0),onKeyDown:D,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:y.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[y.jsx("circle",{cx:"12",cy:"5",r:"1.75"}),y.jsx("circle",{cx:"12",cy:"12",r:"1.75"}),y.jsx("circle",{cx:"12",cy:"19",r:"1.75"})]})}),c&&y.jsx("div",{id:v,role:"menu","aria-labelledby":p,tabIndex:-1,onKeyDown:P,onBlur:F,className:"absolute right-0 top-full z-20 mt-1 min-w-[12rem] rounded-claudius-md border border-claudius-border bg-claudius-surface py-1 shadow-claudius-elevated",children:a.map(($,J)=>y.jsx("button",{ref:B=>{N.current[J]=B},type:"button",role:"menuitem",tabIndex:-1,"aria-disabled":$.disabled||void 0,onClick:()=>{$.disabled||(V(),$.onSelect())},className:"flex min-h-[40px] w-full items-center whitespace-nowrap px-4 text-left text-sm text-claudius-text hover:bg-claudius-surface-muted focus:bg-claudius-surface-muted aria-disabled:cursor-default aria-disabled:opacity-50 aria-disabled:hover:bg-transparent",children:$.label},$.id))})]})}function Wd(u,a,i){const[c,f]=R.useState(0),p=R.useRef(0),v=R.useRef(0),k=R.useRef(0),S=R.useRef(!1);return R.useEffect(()=>{const N=u.current;if(!i||!N)return;const j=I=>{if(N.scrollTop>0){S.current=!1;return}S.current=!0,v.current=I.touches[0].clientY,k.current=Date.now()},O=I=>{if(!S.current)return;let D=I.touches[0].clientY-v.current;D<0&&(D=D*.3),p.current=D,f(D)},V=()=>{if(!S.current)return;S.current=!1;const I=p.current,D=(Date.now()-k.current)/1e3,P=N.getBoundingClientRect().height,F=D>.05&&I>0&&I/D>500,$=I>P*.3;F||$?a():(p.current=0,f(0))};return N.addEventListener("touchstart",j,{passive:!0}),N.addEventListener("touchmove",O,{passive:!0}),N.addEventListener("touchend",V),()=>{N.removeEventListener("touchstart",j),N.removeEventListener("touchmove",O),N.removeEventListener("touchend",V)}},[u,a,i]),{offsetY:c}}const Qd='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Kd(u,a){R.useEffect(()=>{const i=u.current;if(!i)return;const c=f=>{if(f.key!=="Tab")return;const p=Array.from(i.querySelectorAll(Qd)).filter(N=>!N.hasAttribute("aria-hidden"));if(p.length===0)return;const v=p[0],k=p[p.length-1],S=document.activeElement;f.shiftKey&&S===v?(f.preventDefault(),k.focus()):!f.shiftKey&&S===k&&(f.preventDefault(),v.focus())};return i.addEventListener("keydown",c),()=>i.removeEventListener("keydown",c)},[u,a])}function tr(){if(!(typeof window>"u")&&!(typeof window.SpeechSynthesisUtterance>"u"))return window.speechSynthesis??void 0}function bd(u){const[a]=R.useState(()=>tr()!==void 0),[i,c]=R.useState(null),[f,p]=R.useState(!1),v=R.useRef(0),k=R.useRef(!1),S=R.useRef([]),N=R.useCallback(()=>{v.current+=1,k.current=!1,S.current=[],c(null),p(!1)},[]),j=R.useCallback(()=>{const D=S.current.length>0;N();const P=tr();!D||!P||(P.cancel(),P.paused&&P.resume())},[N]),O=R.useCallback((D,P)=>{const F=tr();if(!F)return;N(),(F.speaking||F.pending)&&F.cancel(),F.paused&&F.resume();const $=Ld(P);if($.length===0)return;const J=v.current,B=()=>v.current===J;S.current=$.map((Q,ue)=>{const de=new SpeechSynthesisUtterance(Q);return de.lang=u,de.onerror=ae=>{if(!B())return;(ae.error==="interrupted"||ae.error==="canceled")&&!k.current?N():j()},de.onpause=()=>{B()&&p(!0)},de.onresume=()=>{B()&&p(!1)},de.onend=()=>{B()&&(k.current&&!F.paused?j():ue===$.length-1&&N())},de}),c(D);for(const Q of S.current)F.speak(Q)},[u,j,N]),V=R.useCallback(()=>{const D=tr();D&&(k.current=!0,D.pause(),D.paused&&p(!0))},[]),I=R.useCallback(()=>{const D=tr();D&&(k.current=!1,D.resume(),p(!1))},[]);return R.useEffect(()=>j,[j]),{isSupported:a,activeId:i,isPaused:f,speak:O,pause:V,resume:I,cancel:j}}const Gd=/^([ \t]*)(`{3,}|~{3,})(.*)$/,Yd=/^( {0,3})<(?![A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\s]*>|[^\s<>@]+@[^\s<>]+>)(?=[A-Za-z!?/])/,Xd=/^(?: {4}|\t)/;function ju(u){let a=0;for(const i of u)if(i===" ")a+=1;else if(i===" ")a+=4-a%4;else break;return a}function _u(u){let a=u.length;for(;a>0&&(u[a-1]===" "||u[a-1]===" ");)a-=1;return a===u.length?u:u.slice(0,a)}function Zd(u){const a=Gd.exec(u);if(!a)return null;const[,i,c,f]=a;return c[0]==="`"&&f.includes("`")?null:{indent:i,indentColumns:ju(i),char:c[0],length:c.length}}function Jd(u,a){const i=u.trim();if(i.length<a.length)return!1;for(const c of i)if(c!==a.char)return!1;return ju(u)<=a.indentColumns+3}function qd(u){const a=u.replace(/\r\n?/g,`
|
|
47
|
+
`||f==="。"||f==="!"||f==="?"||(f==="."||f==="!"||f==="?")&&(c+1===u.length||/\s/.test(u[c+1])))&&(a.push(u.slice(i,c+1)),i=c+1)}return i<u.length&&a.push(u.slice(i)),a}function Ld(u,a=150){const i=[];let c="";const f=()=>{const p=c.trim();p&&i.push(p),c=""};for(const p of Md(u)){if((c+p).trim().length<=a){c+=p;continue}if(f(),p.trim().length<=a){c=p;continue}for(let v of p.trim().split(/\s+/)){for(c&&`${c} ${v}`.length>a&&f();v.length>a;)i.push(v.slice(0,a)),v=v.slice(a);c=c?`${c} ${v}`:v}}return f(),i}function Tu(){if(typeof window>"u")return;const u=window;return u.SpeechRecognition??u.webkitSpeechRecognition}function Pd(u){switch(u){case"not-allowed":case"service-not-allowed":return"permission";case"no-speech":return"no-speech";case"audio-capture":return"no-microphone";default:return"unavailable"}}function Ad(u){const[a]=R.useState(()=>Tu()!==void 0),[i,c]=R.useState(!1),[f,p]=R.useState(!1),v=R.useRef(null),k=R.useRef(!1),S=R.useRef(u);R.useEffect(()=>{S.current=u});const N=R.useCallback(I=>{I.onstart=null,I.onend=null,I.onerror=null,I.onresult=null,I.onspeechstart=null,I.onspeechend=null,v.current===I&&(v.current=null),c(!1),p(!1)},[]),j=R.useCallback(()=>{const I=v.current;I&&(N(I),I.abort())},[N]),O=R.useCallback(()=>{const I=v.current;return I?(k.current?I.stop():j(),!0):!1},[j]),V=R.useCallback(()=>{var $,J;const I=Tu();if(!I||v.current)return!1;const D=new I;D.lang=S.current.lang,D.interimResults=!0,D.continuous=!1;let P="";const F=()=>{k.current=!0};D.onstart=F,D.onspeechstart=()=>{F(),p(!0)},D.onspeechend=()=>p(!1),D.onresult=B=>{var de,ae;let Q="",ue="";for(let Z=0;Z<B.results.length;Z++){const xe=B.results[Z];xe.isFinal?Q+=xe[0].transcript:ue+=xe[0].transcript}P=Q,F(),p(!0),(ae=(de=S.current).onTranscript)==null||ae.call(de,Q+ue)},D.onerror=B=>{var Q,ue;B.error!=="aborted"&&((ue=(Q=S.current).onError)==null||ue.call(Q,Pd(B.error))),N(D),D.abort()},D.onend=()=>{var B,Q;N(D),(Q=(B=S.current).onEnd)==null||Q.call(B,P)},v.current=D,k.current=!1,c(!0);try{D.start()}catch{return N(D),(J=($=S.current).onError)==null||J.call($,"unavailable"),!1}return!0},[N]);return R.useEffect(()=>j,[j]),{isSupported:a,isListening:i,isSpeechDetected:f,start:V,stop:O,abort:j}}const er=2e3,Dd=1800;function Nu(u){var i;const a=(i=u.dataTransfer)==null?void 0:i.types;return!!a&&Array.from(a).includes("Files")}function zd({onSend:u,isLoading:a,isStreaming:i=!1,onStop:c,placeholder:f,translations:p,attachments:v=null,voice:k=null,onVoiceStart:S,isReadingAloud:N=!1}){const j=p??ku,[O,V]=R.useState(""),[I,D]=R.useState([]),[P,F]=R.useState(null),[$,J]=R.useState(!1),[B,Q]=R.useState(null),ue=R.useRef(null),de=R.useRef(null),ae=R.useRef([]),Z=R.useRef(0),xe=R.useRef(""),pe=R.useRef(""),Se=R.useRef(!1),Ce=R.useRef(!1),ve=R.useRef(!1),Re=H=>{xe.current=H,V(H)},ye=O.length,_e=ye>=Dd,ge=ye>=er,z=f??j.placeholder,X=!!v&&I.length<v.maxCount,C=i&&!!c;R.useEffect(()=>{var H;a||(H=ue.current)==null||H.focus()},[a]);const m=R.useCallback((H,ke)=>{if(!v)return"";switch(ke){case"size":return Kr(j.attachmentTooLarge,{name:H,max:Vr(v.maxSizeBytes)});case"type":return Kr(j.attachmentTypeNotAllowed,{name:H});case"count":return Kr(j.attachmentTooMany,{max:v.maxCount})}},[v,j]),T=R.useCallback(async H=>{if(!v||H.length===0)return;const{accepted:ke,rejected:It}=Gc(H,ae.current.length,v);if(F(It.length>0?m(It[0].file.name,It[0].reason):null),ke.length===0)return;const Gr=await Promise.all(ke.map(Zc));ae.current=[...ae.current,...Gr],D(ae.current)},[v,m]),re=R.useCallback(H=>{ae.current=ae.current.filter(ke=>ke.id!==H),D(ae.current),F(null)},[]),le=()=>{const H=xe.current.trim(),ke=ae.current;!H&&ke.length===0||xe.current.length>=er||(ke.length>0?u(H,ke):u(H),Re(""),ae.current=[],D([]),F(null),Q(null))},se=H=>{switch(H){case"permission":return j.voicePermissionDenied;case"no-speech":return j.voiceNoSpeech;case"no-microphone":return j.voiceNoMicrophone;case"unavailable":return j.voiceUnavailable}},ne=Ad({lang:(k==null?void 0:k.lang)??"en-US",onTranscript:H=>Re(_d(pe.current,H,er)),onEnd:H=>{const ke=H.trim()!=="";if(ke&&(Ce.current=!0),!Se.current){q();return}ke&&ce()},onError:H=>{H==="no-speech"&&Ce.current||(ve.current=!0,Q(se(H)))}}),ie=!!(k!=null&&k.input)&&ne.isSupported,K=ne.isListening;R.useEffect(()=>{const H=ue.current;K&&H&&(H.scrollLeft=H.scrollWidth)},[K,O]);const q=()=>{k!=null&&k.autoSubmit&&Ce.current&&!ve.current&&le()},ce=()=>{const H=xe.current;ne.start()&&(pe.current=H)},Ae=({held:H})=>{Q(null),Se.current=H,Ce.current=!1,ve.current=!1,S==null||S(),ce()},Ze=()=>{const H=Se.current;Se.current=!1,!ne.stop()&&H&&q()},ft=()=>{Se.current=!1,ne.abort()},{abort:Fe}=ne;R.useEffect(()=>{!a&&!N||(Se.current=!1,Fe())},[a,N,Fe]);const Kt=H=>{H.preventDefault(),ft(),le()},_t=H=>{const ke=H.target.value;ke.length<=er&&(ft(),Q(null),Re(ke))},Oe=H=>{const ke=Array.from(H.target.files??[]);H.target.value="",T(ke)},pt=H=>{var It;if(!v)return;const ke=Array.from(((It=H.clipboardData)==null?void 0:It.files)??[]);ke.length!==0&&(H.preventDefault(),T(ke))},Mt=H=>{!v||!Nu(H)||(H.preventDefault(),Z.current+=1,J(!0))},ut=H=>{!v||!Nu(H)||H.preventDefault()},Ue=()=>{v&&(Z.current=Math.max(0,Z.current-1),Z.current===0&&J(!1))},bt=H=>{var ke;v&&(H.preventDefault(),Z.current=0,J(!1),T(Array.from(((ke=H.dataTransfer)==null?void 0:ke.files)??[])))};return y.jsxs("form",{onSubmit:Kt,onDragEnter:Mt,onDragOver:ut,onDragLeave:Ue,onDrop:bt,"data-drag-over":$||void 0,className:`relative border-t border-claudius-border bg-claudius-surface p-3 ${$?"ring-2 ring-inset ring-claudius-accent":""}`,children:[$&&y.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-claudius-surface text-sm font-medium text-claudius-accent",children:j.dropFilesHint}),v&&I.length>0&&y.jsx("ul",{"aria-label":j.attachmentsLabel,className:"mb-2 flex flex-wrap gap-3 pt-1",children:I.map(H=>y.jsx("li",{children:y.jsx(gu,{attachment:H,variant:"composer",onRemove:()=>re(H.id),removeLabel:`${j.removeAttachment}: ${H.name}`})},H.id))}),y.jsxs("div",{className:"flex gap-2",children:[v&&y.jsxs(y.Fragment,{children:[y.jsx("input",{ref:de,type:"file",multiple:!0,hidden:!0,tabIndex:-1,accept:v.allowedTypes.join(","),onChange:Oe,"aria-label":j.attachFile}),y.jsx("button",{type:"button",onClick:()=>{var H;return(H=de.current)==null?void 0:H.click()},disabled:a||!X,"aria-label":j.attachFile,title:j.attachFile,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm border border-claudius-border bg-claudius-field text-claudius-text-muted transition-colors hover:text-claudius-text focus:border-claudius-accent focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50",children:y.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:y.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})})})]}),y.jsxs("div",{className:"relative min-w-0 flex-1",children:[y.jsx("input",{ref:ue,type:"text",value:O,onChange:_t,onPaste:pt,placeholder:K?j.voiceListening:z,disabled:a,"aria-label":j.typeYourMessage,"aria-describedby":_e?"char-count":void 0,className:`h-full w-full rounded-claudius-sm border border-claudius-border bg-claudius-field py-2 pl-3 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 ${K?"pr-10":"pr-3"}`}),K&&y.jsx(Cd,{active:ne.isSpeechDetected})]}),ie&&k&&y.jsx(Ed,{mode:k.mode,isListening:K,disabled:a,onStart:Ae,onStop:Ze,label:k.mode==="hold"?j.voiceInputHold:j.voiceInput}),C?y.jsx("button",{type:"button",onClick:c,"aria-label":j.stopGenerating,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:y.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:y.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})}):y.jsx("button",{type:"submit",disabled:a||ge,"aria-label":j.sendMessage,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:y.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:[y.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),y.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),(P??B)&&y.jsx("div",{role:"alert",className:"mt-1 text-xs text-claudius-error",children:P??B}),_e&&y.jsxs("div",{id:"char-count",className:`mt-1 text-xs text-right ${ge?"text-claudius-error":"text-claudius-text-muted"}`,"aria-live":"polite",children:[ye,"/",er]})]})}const Od=["blog","page","external"],Id={blog:"Blog",page:"Page",external:"External"};function Fd(u){try{return new URL(u).hostname}catch{return u}}const Ud=R.memo(function({sources:a,onClose:i}){const c=Od.map(p=>({type:p,label:Id[p],items:a.filter(v=>v.type===p)})).filter(p=>p.items.length>0),f=a.length===1?"1 source found":`${a.length} sources found`;return y.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:[y.jsxs("div",{className:"flex items-center justify-between border-b border-claudius-border px-4 py-3",children:[y.jsxs("div",{children:[y.jsx("h3",{className:"text-sm font-heading font-semibold text-claudius-text",children:"Sources"}),y.jsx("p",{className:"text-xs text-claudius-text-muted",children:f})]}),y.jsx("button",{onClick:i,"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:y.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:[y.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),y.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-4",children:c.map(p=>y.jsxs("div",{children:[y.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-claudius-text-muted",children:p.label}),y.jsx("div",{className:"space-y-2",children:p.items.map(v=>{const k=Qr(v.url);return k?y.jsxs("a",{href:k,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:[y.jsx("p",{className:"truncate text-sm font-medium text-claudius-text",children:v.title}),y.jsx("p",{className:"mt-0.5 text-xs text-claudius-text-muted",children:Fd(k)})]},k):null})})]},p.type))})]})});function Bd({title:u,subtitle:a,titleId:i,closeLabel:c,onClose:f,actions:p}){return y.jsxs("div",{className:"flex items-center gap-3 bg-claudius-accent px-5 py-4",children:[y.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:u.charAt(0).toUpperCase()}),y.jsxs("div",{className:"flex-1",children:[y.jsx("h2",{id:i,className:"text-sm font-heading font-semibold text-claudius-accent-text",children:u}),y.jsx("p",{className:"text-xs text-claudius-accent-text",children:a})]}),p,y.jsx("button",{onClick:f,"aria-label":c,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:y.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:[y.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),y.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}function Hd({message:u,retryLabel:a,onRetry:i}){return y.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:[y.jsx("span",{children:u}),i&&y.jsx("button",{type:"button",onClick:i,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:a})]})}function $d({label:u}){return y.jsx("div",{role:"status","aria-live":"polite","aria-label":u,className:"mr-auto flex max-w-[85%]",children:y.jsxs("div",{className:"flex gap-1 rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-3",children:[y.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:0ms]"}),y.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:150ms]"}),y.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:300ms]"})]})})}function Vd({label:u,items:a,onOpen:i}){const[c,f]=R.useState(!1),p=R.useId(),v=R.useId(),k=R.useRef(null),S=R.useRef(null),N=R.useRef([]),j=R.useRef(null),O=$=>{j.current=$,f(!0),i==null||i()},V=$=>{var J;f(!1),(J=S.current)==null||J.focus()};R.useEffect(()=>{var J;if(!c)return;j.current!==null&&((J=N.current[j.current])==null||J.focus(),j.current=null);const $=B=>{var Q;(Q=k.current)!=null&&Q.contains(B.target)||f(!1)};return document.addEventListener("pointerdown",$),()=>document.removeEventListener("pointerdown",$)},[c]);const I=$=>{var B;const J=a.length;(B=N.current[($+J)%J])==null||B.focus()},D=$=>{$.key==="ArrowDown"?($.preventDefault(),O(0)):$.key==="ArrowUp"&&($.preventDefault(),O(a.length-1))},P=$=>{const J=N.current.findIndex(B=>B===document.activeElement);switch($.key){case"ArrowDown":$.preventDefault(),I(J+1);break;case"ArrowUp":$.preventDefault(),I(J===-1?a.length-1:J-1);break;case"Home":$.preventDefault(),I(0);break;case"End":$.preventDefault(),I(a.length-1);break;case"Escape":$.preventDefault(),$.stopPropagation(),V();break;case"Tab":$.shiftKey&&($.preventDefault(),V());break}},F=$=>{var B;const J=$.relatedTarget;J&&((B=k.current)!=null&&B.contains(J)||f(!1))};return y.jsxs("div",{ref:k,className:"relative",children:[y.jsx("button",{ref:S,id:p,type:"button","aria-label":u,"aria-haspopup":"menu","aria-expanded":c,"aria-controls":c?v:void 0,onClick:()=>c?V():O(0),onKeyDown:D,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:y.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[y.jsx("circle",{cx:"12",cy:"5",r:"1.75"}),y.jsx("circle",{cx:"12",cy:"12",r:"1.75"}),y.jsx("circle",{cx:"12",cy:"19",r:"1.75"})]})}),c&&y.jsx("div",{id:v,role:"menu","aria-labelledby":p,tabIndex:-1,onKeyDown:P,onBlur:F,className:"absolute right-0 top-full z-20 mt-1 min-w-[12rem] rounded-claudius-md border border-claudius-border bg-claudius-surface py-1 shadow-claudius-elevated",children:a.map(($,J)=>y.jsx("button",{ref:B=>{N.current[J]=B},type:"button",role:"menuitem",tabIndex:-1,"aria-disabled":$.disabled||void 0,onClick:()=>{$.disabled||(V(),$.onSelect())},className:"flex min-h-[40px] w-full items-center whitespace-nowrap px-4 text-left text-sm text-claudius-text hover:bg-claudius-surface-muted focus:bg-claudius-surface-muted aria-disabled:cursor-default aria-disabled:opacity-50 aria-disabled:hover:bg-transparent",children:$.label},$.id))})]})}function Wd(u,a,i){const[c,f]=R.useState(0),p=R.useRef(0),v=R.useRef(0),k=R.useRef(0),S=R.useRef(!1);return R.useEffect(()=>{const N=u.current;if(!i||!N)return;const j=I=>{if(N.scrollTop>0){S.current=!1;return}S.current=!0,v.current=I.touches[0].clientY,k.current=Date.now()},O=I=>{if(!S.current)return;let D=I.touches[0].clientY-v.current;D<0&&(D=D*.3),p.current=D,f(D)},V=()=>{if(!S.current)return;S.current=!1;const I=p.current,D=(Date.now()-k.current)/1e3,P=N.getBoundingClientRect().height,F=D>.05&&I>0&&I/D>500,$=I>P*.3;F||$?a():(p.current=0,f(0))};return N.addEventListener("touchstart",j,{passive:!0}),N.addEventListener("touchmove",O,{passive:!0}),N.addEventListener("touchend",V),()=>{N.removeEventListener("touchstart",j),N.removeEventListener("touchmove",O),N.removeEventListener("touchend",V)}},[u,a,i]),{offsetY:c}}const Qd='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Kd(u,a){R.useEffect(()=>{const i=u.current;if(!i)return;const c=f=>{if(f.key!=="Tab")return;const p=Array.from(i.querySelectorAll(Qd)).filter(N=>!N.hasAttribute("aria-hidden"));if(p.length===0)return;const v=p[0],k=p[p.length-1],S=document.activeElement;f.shiftKey&&S===v?(f.preventDefault(),k.focus()):!f.shiftKey&&S===k&&(f.preventDefault(),v.focus())};return i.addEventListener("keydown",c),()=>i.removeEventListener("keydown",c)},[u,a])}function tr(){if(!(typeof window>"u")&&!(typeof window.SpeechSynthesisUtterance>"u"))return window.speechSynthesis??void 0}function bd(u){const[a]=R.useState(()=>tr()!==void 0),[i,c]=R.useState(null),[f,p]=R.useState(!1),v=R.useRef(0),k=R.useRef(!1),S=R.useRef([]),N=R.useCallback(()=>{v.current+=1,k.current=!1,S.current=[],c(null),p(!1)},[]),j=R.useCallback(()=>{const D=S.current.length>0;N();const P=tr();!D||!P||(P.cancel(),P.paused&&P.resume())},[N]),O=R.useCallback((D,P)=>{const F=tr();if(!F)return;N(),(F.speaking||F.pending)&&F.cancel(),F.paused&&F.resume();const $=Ld(P);if($.length===0)return;const J=v.current,B=()=>v.current===J;S.current=$.map((Q,ue)=>{const de=new SpeechSynthesisUtterance(Q);return de.lang=u,de.onerror=ae=>{if(!B())return;(ae.error==="interrupted"||ae.error==="canceled")&&!k.current?N():j()},de.onpause=()=>{B()&&p(!0)},de.onresume=()=>{B()&&p(!1)},de.onend=()=>{B()&&(k.current&&!F.paused?j():ue===$.length-1&&N())},de}),c(D);for(const Q of S.current)F.speak(Q)},[u,j,N]),V=R.useCallback(()=>{const D=tr();D&&(k.current=!0,D.pause(),D.paused&&p(!0))},[]),I=R.useCallback(()=>{const D=tr();D&&(k.current=!1,D.resume(),p(!1))},[]);return R.useEffect(()=>j,[j]),{isSupported:a,activeId:i,isPaused:f,speak:O,pause:V,resume:I,cancel:j}}const Gd=/^([ \t]*)(`{3,}|~{3,})(.*)$/,Yd=/^( {0,3})<(?![A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\s]*>|[A-Za-z0-9][^\s<>@]*@[^\s<>]+>)(?=[A-Za-z!?/])/,Xd=/^(?: {4}|\t)/;function ju(u){let a=0;for(const i of u)if(i===" ")a+=1;else if(i===" ")a+=4-a%4;else break;return a}function _u(u){let a=u.length;for(;a>0&&(u[a-1]===" "||u[a-1]===" ");)a-=1;return a===u.length?u:u.slice(0,a)}function Zd(u){const a=Gd.exec(u);if(!a)return null;const[,i,c,f]=a;return c[0]==="`"&&f.includes("`")?null:{indent:i,indentColumns:ju(i),char:c[0],length:c.length}}function Jd(u,a){const i=u.trim();if(i.length<a.length)return!1;for(const c of i)if(c!==a.char)return!1;return ju(u)<=a.indentColumns+3}function qd(u){const a=u.replace(/\r\n?/g,`
|
|
48
48
|
`).split(`
|
|
49
49
|
`),i=[];let c=null;for(let f=0;f<a.length;f++){const p=a[f];if(c){i.push(p),Jd(p,c)&&(c=null);continue}const v=Zd(p);if(v){c=v,i.push(p);continue}let k=p.replace(Yd,"$1\\<");const S=a[f+1];p.trim()!==""&&S!==void 0&&S.trim()!==""&&!Xd.test(p)&&!p.endsWith("\\")&&(k=_u(k)+" "),i.push(k)}if(c)i[i.length-1]===""&&i.pop(),i.push(c.indent+c.char.repeat(c.length));else{for(;i.length>0&&i[i.length-1].trim()==="";)i.pop();i.length>0&&(i[i.length-1]=_u(i[i.length-1]))}return i.join(`
|
|
50
50
|
`)}const ef=/[\u00a0\u202f]/g;function tf(u){if(u.formatDate)return u.formatDate;const a=f=>new Intl.DateTimeFormat(f,{dateStyle:"medium",timeStyle:"short",timeZone:u.timeZone});let i=null;try{i=a(u.locale)}catch{try{i=a(void 0)}catch{i=null}}const c=i;return c?f=>c.format(f):f=>f.toISOString()}function nf(u){const a=tf(u);return i=>a(i).replace(ef," ")}function rf(u,a){var i;try{return((i=new Intl.DateTimeFormat("en",{timeZone:a,timeZoneName:"longOffset"}).formatToParts(u).find(f=>f.type==="timeZoneName"))==null?void 0:i.value)??""}catch{return""}}function Mu(u){const a=u.replace(/\s+/g," ").trim();if(a==="")return"";const i=Math.max(0,...(a.match(/`+/g)??[]).map(p=>p.length)),c="`".repeat(i+1),f=a.startsWith("`")||a.endsWith("`")?" ":"";return`${c}${f}${a}${f}${c}`}const lf={"(":"%28",")":"%29","<":"%3C",">":"%3E","\\":"%5C"};function of(u,a){const i=jn(u.title||u.url).replace(/\s+/g," ").trim().replace(/[\\[\]<]/g,"\\$&"),c=Qr(jn(u.url));if(!c)return`${a+1}. ${i}`;const f=c.replace(/[()<>\\]/g,p=>lf[p]).replace(/\s/g,"%20");return`${a+1}. [${i}](${f})`}function uf(u){const a=Mu(jn(u.name)),i=Vr(Number(u.size));return`- ${a} (${jn(u.mediaType)}, ${i})`}function jn(u){return typeof u=="string"?u:String(u??"")}function br(u){return Array.isArray(u)?u.filter(a=>a!==null&&typeof a=="object"):[]}function sf(u,a){const{labels:i}=a,c=nf(a),f=a.now??new Date,p=rf(f,a.timeZone),v=c(f)+(p?` (${p})`:""),k=[`# ${i.title}`,Kr(i.exported,{date:v})];for(const S of u){if(S===null||typeof S!="object")continue;const N=S.role==="user"?i.user:i.assistant,j=S.createdAt?new Date(S.createdAt):null,O=j&&!Number.isNaN(j.getTime())?` · ${c(j)}`:"";k.push(`## ${N}${O}`);const V=qd(jn(S.content));V&&k.push(V);const I=br(S.attachments);I.length&&k.push(i.attachments,I.map(uf).join(`
|
|
@@ -54,4 +54,4 @@ Error generating stack: `+o.message+`
|
|
|
54
54
|
|
|
55
55
|
`)+`
|
|
56
56
|
`}function af(u){const a=u.filter(i=>i!==null&&typeof i=="object").map(i=>i.attachments===void 0?i:{...i,attachments:br(i.attachments)});return JSON.stringify(hu(a),null,2)+`
|
|
57
|
-
`}function Lu(u,a={}){const i=a.now??new Date;let c;try{const f=new Intl.DateTimeFormat("en",{timeZone:a.timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(i),p=v=>{var k;return((k=f.find(S=>S.type===v))==null?void 0:k.value)??""};c=`${p("year")}-${p("month")}-${p("day")}`}catch{c=i.toISOString().slice(0,10)}return`chat-transcript-${c}.${u}`}function cf(u){const a=document.activeElement;let i=null;try{return i=document.createElement("textarea"),i.value=u,i.setAttribute("readonly",""),i.setAttribute("aria-hidden","true"),i.style.position="fixed",i.style.top="0",i.style.left="0",i.style.opacity="0",document.body.appendChild(i),i.focus({preventScroll:!0}),i.select(),document.execCommand("copy")}catch{return!1}finally{i==null||i.remove(),a==null||a.focus()}}async function df(u){var a;try{if((a=navigator.clipboard)!=null&&a.writeText)return await navigator.clipboard.writeText(u),!0}catch{}return cf(u)}const ff=4e4;function Pu(u,a,i){const c=URL.createObjectURL(new Blob([a],{type:i})),f=document.createElement("a");f.href=c,f.download=u,f.style.display="none",document.body.appendChild(f),f.click(),f.remove(),setTimeout(()=>URL.revokeObjectURL(c),ff)}const pf=4e3;function hf({enabled:u,messages:a,busy:i,locale:c,translations:f}){const p=f??ku,[v,k]=R.useState(null),S=R.useRef(null),N=R.useRef(!0);R.useEffect(()=>(N.current=!0,()=>{N.current=!1,S.current&&clearTimeout(S.current)}),[]);const j=R.useCallback(()=>{S.current&&clearTimeout(S.current),S.current=null,k(null)},[]),O=R.useCallback(I=>{N.current&&(S.current&&clearTimeout(S.current),k(I),S.current=setTimeout(()=>{S.current=null,k(null)},pf))},[]);return{items:R.useMemo(()=>{if(!u)return[];const I=i||a.length===0,D=()=>sf(a,{locale:c,labels:{title:p.transcriptTitle,exported:p.transcriptExported,user:p.transcriptUser,assistant:p.transcriptAssistant,attachments:p.transcriptAttachments,sources:p.transcriptSources,toolUsed:p.toolUsed}});return[{id:"copy-markdown",label:p.copyAsMarkdown,disabled:I,onSelect:()=>{df(D()).then(P=>O(P?p.copiedToClipboard:p.copyFailed))}},{id:"download-markdown",label:p.downloadAsMarkdown,disabled:I,onSelect:()=>Pu(Lu("md"),D(),"text/markdown;charset=utf-8")},{id:"download-json",label:p.downloadAsJson,disabled:I,onSelect:()=>Pu(Lu("json"),af(a),"application/json")}]},[u,i,a,c,p,O]),status:v,clearStatus:j}}const mf=/\*\*([^*]+)\*\*/g,gf=/\*([^*]+)\*/g,vf=/https?:\/\/[^\s)]+/g;function Au(u){return u.replace(mf,"$1").replace(gf,"$1").replace(vf,a=>{var f;const i=((f=a.match(/[.,;:!?'"]+$/))==null?void 0:f[0])??"",c=i?a.slice(0,-i.length):a;try{return new URL(c).hostname+i}catch{return a}})}const yf={"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 wf({messages:u,isLoading:a,isStreaming:i=!1,streamingMessageId:c=null,error:f,canRetry:p=!1,onSend:v,onStop:k,onRetry:S,onClose:N,title:j="Chat",subtitle:O="Ask me anything",welcomeMessage:V="Hi! How can I help you today?",placeholder:I,position:D="bottom-right",translations:P,isMobile:F=!1,attachments:$=null,voice:J=null,conversationExport:B=!1,locale:Q="en-US"}){const ue=R.useId(),de=R.useRef(null),ae=R.useRef(null),[Z,xe]=R.useState(null);Kd(de,!0);const pe=bd((J==null?void 0:J.lang)??"en-US"),Se=!!(J!=null&&J.output)&&pe.isSupported,Ce={play:(P==null?void 0:P.readAloud)??"Read aloud",pause:(P==null?void 0:P.pauseReading)??"Pause reading",resume:(P==null?void 0:P.resumeReading)??"Resume reading",stop:(P==null?void 0:P.stopReading)??"Stop reading"},ve=hf({enabled:B,messages:u,busy:a,locale:Q,translations:P}),{offsetY:Re}=Wd(ae,N,F),ye=Re!==0,_e=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1;R.useEffect(()=>{const C=ae.current;C&&(C.scrollTop=C.scrollHeight)},[u,a]),R.useEffect(()=>{const C=m=>{m.key==="Escape"&&!m.isComposing&&!m.defaultPrevented&&N()};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[N]);const ge=(P==null?void 0:P.closeChat)??"Close chat",z=(P==null?void 0:P.chatMessages)??"Chat messages",X=[...u].reverse().find(C=>C.role==="assistant");return y.jsxs("div",{ref:de,role:"dialog","aria-modal":F?"true":void 0,"aria-labelledby":ue,className:F?"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 ${yf[D]} 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:F&&!_e?{transform:`translateY(${Math.max(0,Re)}px)`}:void 0,"data-dragging":ye||void 0,children:[F&&y.jsx("div",{className:"flex justify-center py-2","aria-hidden":"true",children:y.jsx("div",{className:"h-1 w-8 rounded-claudius-full bg-claudius-border"})}),y.jsx(Bd,{title:j,subtitle:O,titleId:ue,closeLabel:ge,onClose:N,actions:B?y.jsx(Vd,{label:(P==null?void 0:P.moreOptions)??"More options",items:ve.items,onOpen:ve.clearStatus}):void 0}),y.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[Z&&y.jsx(Ud,{sources:Z.sources,onClose:()=>xe(null)}),B&&y.jsx("div",{role:"status",className:"pointer-events-none absolute inset-x-0 top-2 z-10 flex justify-center px-4",children:ve.status&&y.jsx("span",{className:"rounded-claudius-full bg-claudius-text px-3 py-1 text-xs text-claudius-surface shadow-claudius-elevated",children:ve.status})}),y.jsxs("div",{ref:ae,role:"log","aria-label":z,className:"h-full space-y-3 overflow-y-auto px-4 py-4",children:[u.length===0&&!f&&y.jsx("div",{className:"mr-auto flex max-w-[85%]",children:y.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:V})}),u.map(C=>y.jsx(kd,{role:C.role,content:C.content,isStreaming:C.id===c,sources:C.sources,attachments:C.attachments,toolUses:C.toolUses,toolUsedLabel:P==null?void 0:P.toolUsed,toolDetailsLabel:P==null?void 0:P.toolDetails,isSourceActive:(Z==null?void 0:Z.messageId)===C.id,onSourceClick:()=>{(Z==null?void 0:Z.messageId)===C.id?xe(null):C.sources&&C.sources.length>0&&xe({messageId:C.id,sources:C.sources})},speech:Se&&C.role==="assistant"&&C.id!==c&&C.content.trim()!==""?{state:pe.activeId!==C.id?"idle":pe.isPaused?"paused":"speaking",labels:Ce,onPlay:()=>pe.speak(C.id,Au(C.content)),onPause:pe.pause,onResume:pe.resume,onStop:pe.cancel}:void 0},C.id)),a&&!(c!==null&&u.some(C=>C.id===c&&C.content.length>0))&&y.jsx($d,{label:(P==null?void 0:P.typingIndicator)??"Assistant is typing"}),f&&y.jsx(Hd,{message:f,retryLabel:(P==null?void 0:P.errorRetry)??"Retry",onRetry:p&&S&&!a?S:void 0})]})]}),y.jsx("div",{"data-claudius-live":"assistant","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:X&&X.id!==c?Au(X.content):""}),y.jsx(zd,{onSend:v,isLoading:a,isStreaming:i,onStop:k,placeholder:I,translations:P,attachments:$,voice:J,onVoiceStart:pe.cancel,isReadingAloud:pe.activeId!==null})]})}function xf({message:u,position:a,onOpen:i,onDismiss:c,dismissLabel:f}){const p=a.startsWith("bottom"),v=a.endsWith("right"),k=["claudius-greeting-bubble","fixed z-40 max-w-xs",p?"bottom-20":"top-20",v?"right-4":"left-4"].join(" ");return y.jsxs("div",{className:k,role:"status","aria-live":"polite",children:[y.jsx("button",{type:"button",onClick:i,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:u}),y.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),c()},"aria-label":f,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:y.jsx("span",{"aria-hidden":"true",children:"×"})})]})}const Du={en:Su,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",attachFile:"Adjuntar un archivo",removeAttachment:"Quitar adjunto",attachmentsLabel:"Adjuntos",dropFilesHint:"Suelta los archivos para adjuntarlos",attachmentTooLarge:"{name} es demasiado grande. El tamaño máximo es {max}.",attachmentTypeNotAllowed:"{name} no es un tipo de archivo compatible.",attachmentTooMany:"Puedes adjuntar hasta {max} archivos por mensaje.",voiceInput:"Entrada de voz",voiceInputHold:"Mantén pulsado para hablar",voiceListening:"Escuchando...",voicePermissionDenied:"El acceso al micrófono está bloqueado. Permítelo en la configuración de tu navegador para usar la entrada de voz.",voiceNoSpeech:"No se detectó ninguna voz. Inténtalo de nuevo.",voiceNoMicrophone:"No se encontró ningún micrófono.",voiceUnavailable:"La entrada de voz no está disponible en este momento.",readAloud:"Leer en voz alta",pauseReading:"Pausar la lectura",resumeReading:"Reanudar la lectura",stopReading:"Detener la lectura",moreOptions:"Más opciones",copyAsMarkdown:"Copiar como Markdown",downloadAsMarkdown:"Descargar como Markdown",downloadAsJson:"Descargar como JSON",copiedToClipboard:"Copiado al portapapeles",copyFailed:"No se pudo copiar. Prueba a descargarlo.",transcriptTitle:"Transcripción del chat",transcriptExported:"Exportado el {date}",transcriptUser:"Usuario",transcriptAssistant:"Asistente",transcriptAttachments:"Adjuntos:",transcriptSources:"Fuentes:",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.",errorAttachmentRejected:"Se rechazó un adjunto. Quítalo e inténtalo de nuevo.",errorAttachmentQuota:"Límite de subida alcanzado. 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",attachFile:"Joindre un fichier",removeAttachment:"Retirer la pièce jointe",attachmentsLabel:"Pièces jointes",dropFilesHint:"Déposez les fichiers pour les joindre",attachmentTooLarge:"{name} est trop volumineux. La taille maximale est de {max}.",attachmentTypeNotAllowed:"{name} n'est pas un type de fichier pris en charge.",attachmentTooMany:"Vous pouvez joindre jusqu'à {max} fichiers par message.",voiceInput:"Saisie vocale",voiceInputHold:"Maintenez pour parler",voiceListening:"Écoute en cours...",voicePermissionDenied:"L'accès au microphone est bloqué. Autorisez-le dans les paramètres de votre navigateur pour utiliser la saisie vocale.",voiceNoSpeech:"Aucune voix n'a été détectée. Veuillez réessayer.",voiceNoMicrophone:"Aucun microphone n'a été trouvé.",voiceUnavailable:"La saisie vocale n'est pas disponible pour le moment.",readAloud:"Lire à voix haute",pauseReading:"Mettre la lecture en pause",resumeReading:"Reprendre la lecture",stopReading:"Arrêter la lecture",moreOptions:"Plus d'options",copyAsMarkdown:"Copier en Markdown",downloadAsMarkdown:"Télécharger en Markdown",downloadAsJson:"Télécharger en JSON",copiedToClipboard:"Copié dans le presse-papiers",copyFailed:"Impossible de copier. Essayez plutôt de télécharger.",transcriptTitle:"Transcription du chat",transcriptExported:"Exporté le {date}",transcriptUser:"Utilisateur",transcriptAssistant:"Assistant",transcriptAttachments:"Pièces jointes :",transcriptSources:"Sources :",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.",errorAttachmentRejected:"Une pièce jointe a été refusée. Retirez-la et réessayez.",errorAttachmentQuota:"Limite d'envoi 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",attachFile:"Datei anhängen",removeAttachment:"Anhang entfernen",attachmentsLabel:"Anhänge",dropFilesHint:"Dateien hier ablegen, um sie anzuhängen",attachmentTooLarge:"{name} ist zu groß. Die maximale Größe beträgt {max}.",attachmentTypeNotAllowed:"{name} ist kein unterstützter Dateityp.",attachmentTooMany:"Sie können bis zu {max} Dateien pro Nachricht anhängen.",voiceInput:"Spracheingabe",voiceInputHold:"Zum Sprechen gedrückt halten",voiceListening:"Ich höre zu...",voicePermissionDenied:"Der Zugriff auf das Mikrofon ist blockiert. Erlauben Sie ihn in den Einstellungen Ihres Browsers, um die Spracheingabe zu nutzen.",voiceNoSpeech:"Es wurde keine Sprache erkannt. Bitte versuchen Sie es erneut.",voiceNoMicrophone:"Es wurde kein Mikrofon gefunden.",voiceUnavailable:"Die Spracheingabe ist momentan nicht verfügbar.",readAloud:"Vorlesen",pauseReading:"Vorlesen pausieren",resumeReading:"Vorlesen fortsetzen",stopReading:"Vorlesen beenden",moreOptions:"Weitere Optionen",copyAsMarkdown:"Als Markdown kopieren",downloadAsMarkdown:"Als Markdown herunterladen",downloadAsJson:"Als JSON herunterladen",copiedToClipboard:"In die Zwischenablage kopiert",copyFailed:"Kopieren nicht möglich. Bitte stattdessen herunterladen.",transcriptTitle:"Chat-Protokoll",transcriptExported:"Exportiert am {date}",transcriptUser:"Nutzer",transcriptAssistant:"Assistent",transcriptAttachments:"Anhänge:",transcriptSources:"Quellen:",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.",errorAttachmentRejected:"Ein Anhang wurde abgelehnt. Bitte entfernen Sie ihn und versuchen Sie es erneut.",errorAttachmentQuota:"Upload-Limit erreicht. Bitte versuchen Sie es später erneut.",errorRetry:"Erneut versuchen"}};function zu(u){if(!u)return;const a=u.toLowerCase().split("-")[0];return Object.prototype.hasOwnProperty.call(Du,a)?a:void 0}function Ou(){const u=typeof document<"u"?zu(document.documentElement.lang):void 0;if(u)return u;const a=typeof navigator<"u"?zu(navigator.language):void 0;return a||"en"}function Sf(u={}){const{locale:a,translations:i}=u,c=Du[a??Ou()];return i?{...c,...i}:{...c}}const Iu=["accent","accentText","accentSoft","accentTextMuted","surface","surfaceMuted","text","textMuted","border","userBubble","userBubbleText","assistantBubble","assistantBubbleText","field","error","errorSurface","errorText","link","scrim"],kf=["sm","md","lg","full","tail"],Ef=["elevated","floating","floatingHover"],Cf=["heading","body"],Fu={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 Rf(u){return Object.prototype.hasOwnProperty.call(Fu,u)}const Tf=new Set(["light","dark","auto"]);function Nf(u){if(u===void 0)return{mode:"light"};if(typeof u=="string"){if(Tf.has(u))return{mode:u};if(Rf(u)){const a=Fu[u];return{mode:a.colorScheme??"light",theme:a}}return{mode:"light",url:u}}return{mode:u.colorScheme??"light",theme:u}}function jf(u){return u.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`)}function _f(u,a){console.warn(`[Claudius] Ignoring unknown theme token "${a}" in "${u}"`)}function nr(u,a,i,c,f,p=""){if(f)for(const[v,k]of Object.entries(f)){if(!c.includes(v)){_f(a,v);continue}typeof k=="string"&&(u[`${i}${jf(v)}${p}`]=k)}}function Mf(u){const a={};nr(a,"colors","--cl-color-",Iu,u.colors);for(const[i,c]of Object.entries({...a}))a[`${i}-dark`]=c;return nr(a,"colorsDark","--cl-color-",Iu,u.colorsDark,"-dark"),nr(a,"radii","--cl-radius-",kf,u.radii),nr(a,"shadows","--cl-shadow-",Ef,u.shadows),nr(a,"fonts","--cl-font-",Cf,u.fonts),a}function Lf(u){return typeof u=="object"&&u!==null&&!Array.isArray(u)}function Pf(u){const a=R.useMemo(()=>Nf(u),[u]),[i,c]=R.useState(null),f=a.url;R.useEffect(()=>{if(c(null),!f)return;const S=new AbortController;return fetch(f,{signal:S.signal}).then(N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);return N.json()}).then(N=>{if(!Lf(N))throw new Error("theme JSON must be an object");c(N)}).catch(N=>{S.signal.aborted||console.error(`[Claudius] Failed to load theme from ${f}:`,N)}),()=>S.abort()},[f]);const p=a.theme??i??null,v=(i==null?void 0:i.colorScheme)??a.mode,k=R.useMemo(()=>p?Mf(p):{},[p]);return{mode:v,cssVars:k}}const Uu="claudius:triggers:dismissed";function Af(){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(Uu)==="1"}catch{return!1}}function Df(){if(!(typeof window>"u"))try{window.sessionStorage.setItem(Uu,"1")}catch{}}function Bu({apiUrl:u,title:a,subtitle:i,welcomeMessage:c,placeholder:f,persistMessages:p,storageKeyPrefix:v,requestTimeoutMs:k,theme:S="light",accentColor:N,position:j="bottom-right",locale:O,translations:V,triggers:I,plugins:D,streaming:P=!0,attachments:F=!1,voice:$=!1,conversationExport:J=!1}){const[B,Q]=R.useState(!1),ue=R.useMemo(()=>Wc(F),[F]),de=R.useMemo(()=>O??Ou(),[O]),ae=R.useMemo(()=>Nd($,de),[$,de]),Z=R.useMemo(()=>Ru(de),[de]),[xe,pe]=R.useState(null),[Se,Ce]=R.useState(Af),ve=R.useRef(!1),Re=ld("(max-width: 639px)"),ye=R.useMemo(()=>Sf({locale:O,translations:V}),[O,V]),{messages:_e,isLoading:ge,isStreaming:z,streamingMessageId:X,error:C,canRetry:m,sendMessage:T,stop:re,retry:le}=rd({apiUrl:u,persistMessages:p,storageKeyPrefix:v,timeoutMs:k,translations:ye,plugins:D,streaming:P}),se=R.useRef(null),ne=R.useRef(B),{mode:ie,cssVars:K}=Pf(S),[q,ce]=R.useState(!1);R.useEffect(()=>{if(ie!=="auto")return;const Ue=window.matchMedia("(prefers-color-scheme: dark)");ce(Ue.matches);const bt=H=>ce(H.matches);return Ue.addEventListener("change",bt),()=>Ue.removeEventListener("change",bt)},[ie]),R.useEffect(()=>{var Ue;ne.current&&!B&&((Ue=se.current)==null||Ue.focus()),ne.current=B},[B]);const Ae=R.useCallback(()=>{Ce(!0),Df()},[]),Ze=R.useCallback(()=>{Q(!1),ve.current&&(ve.current=!1,Ae())},[Ae]),ft=R.useCallback(()=>{Q(Ue=>!Ue)},[]),Fe=R.useCallback(()=>{ve.current=!0,pe(null),Q(!0)},[]),Kt=R.useCallback(Ue=>{pe(Ue)},[]),_t=R.useCallback(()=>{pe(null),Fe()},[Fe]),Oe=R.useCallback(()=>{pe(null),Ae()},[Ae]);id({triggers:I,enabled:!Se&&!B,onOpen:Fe,onGreeting:Kt});const pt=ie==="dark"||ie==="auto"&&q,Mt={...K,...N?{"--cl-color-accent":N,"--cl-color-accent-dark":N}:{}},ut=Object.keys(Mt).length>0?Mt:void 0;return y.jsx("div",{className:"claudius-root",style:ut,children:y.jsxs("div",{"data-claudius-dark":pt?"true":"false",children:[B&&Re&&y.jsx("div",{className:"claudius-scrim fixed inset-0 z-40 bg-claudius-scrim",onClick:Ze,"aria-hidden":"true"}),B&&y.jsx(wf,{messages:_e,isLoading:ge,isStreaming:z,streamingMessageId:X,error:C,canRetry:m,onSend:T,onStop:re,onRetry:le,onClose:Ze,title:a??ye.title,subtitle:i??ye.subtitle,welcomeMessage:c??ye.welcomeMessage,placeholder:f??ye.placeholder,position:j,translations:ye,isMobile:Re,attachments:ue,voice:ae,conversationExport:J===!0,locale:Z}),!(B&&Re)&&y.jsx(sd,{ref:se,isOpen:B,onClick:ft,position:j,translations:ye}),!B&&xe&&y.jsx(xf,{message:xe,position:j,onOpen:_t,onDismiss:Oe,dismissLabel:ye.dismissGreeting})]})})}const zf="1.17.0";typeof window<"u"&&(window.ClaudiusWidgetVersion=zf);function Hu(){const u=window.ClaudiusConfig;if(!(u!=null&&u.apiUrl)){console.error("[Claudius] Missing ClaudiusConfig.apiUrl");return}const a=document.createElement("div");a.id="claudius-chat-widget",document.body.appendChild(a),cu.createRoot(a).render(y.jsx(Bu,{apiUrl:u.apiUrl,title:u.title,subtitle:u.subtitle,welcomeMessage:u.welcomeMessage,placeholder:u.placeholder,persistMessages:u.persistMessages,storageKeyPrefix:u.storageKeyPrefix,requestTimeoutMs:u.requestTimeoutMs,theme:u.theme,accentColor:u.accentColor,position:u.position,locale:u.locale,translations:u.translations,triggers:u.triggers,attachments:u.attachments,voice:u.voice,conversationExport:u.conversationExport}))}class $u extends HTMLElement{constructor(){super(...arguments);hn(this,"root",null);hn(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","attachments","conversation-export","voice","voice-mode","voice-auto-submit","voice-input","voice-output","voice-lang"]}connectedCallback(){this.container=document.createElement("div"),this.appendChild(this.container),this.root=cu.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 i=this.getAttribute("api-url");if(!i){console.error("[Claudius] Missing api-url attribute on <claudius-chat>");return}const c=this.getAttribute("persist-messages"),f=c===null?void 0:c!=="false",p=this.getAttribute("request-timeout-ms"),v=p===null?void 0:Number(p),k=this.getAttribute("attachments"),S=k===null?void 0:k!=="false",N=this.getAttribute("conversation-export"),j=N==null?void 0:N.trim().toLowerCase(),O=N===null?void 0:j===""||j==="true";this.root.render(y.jsx(Bu,{apiUrl:i,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:f,storageKeyPrefix:this.getAttribute("storage-key-prefix")??void 0,requestTimeoutMs:v!==void 0&&Number.isFinite(v)?v:void 0,theme:this.getAttribute("theme")??void 0,accentColor:this.getAttribute("accent-color")??void 0,position:this.getAttribute("position")??void 0,attachments:S,conversationExport:O,voice:jd(V=>this.getAttribute(V))}))}}return typeof customElements<"u"&&!customElements.get("claudius-chat")&&customElements.define("claudius-chat",$u),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Hu):Hu(),Ot.ClaudiusChat=$u,Object.defineProperty(Ot,Symbol.toStringTag,{value:"Module"}),Ot})({});
|
|
57
|
+
`}function Lu(u,a={}){const i=a.now??new Date;let c;try{const f=new Intl.DateTimeFormat("en",{timeZone:a.timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(i),p=v=>{var k;return((k=f.find(S=>S.type===v))==null?void 0:k.value)??""};c=`${p("year")}-${p("month")}-${p("day")}`}catch{c=i.toISOString().slice(0,10)}return`chat-transcript-${c}.${u}`}function cf(u){const a=document.activeElement;let i=null;try{return i=document.createElement("textarea"),i.value=u,i.setAttribute("readonly",""),i.setAttribute("aria-hidden","true"),i.tabIndex=-1,i.style.position="fixed",i.style.top="0",i.style.left="0",i.style.opacity="0",document.body.appendChild(i),i.focus({preventScroll:!0}),i.select(),document.execCommand("copy")}catch{return!1}finally{try{i==null||i.remove()}catch{}try{a==null||a.focus()}catch{}}}async function df(u){var a;try{if((a=navigator.clipboard)!=null&&a.writeText)return await navigator.clipboard.writeText(u),!0}catch{}try{return cf(u)}catch{return!1}}const ff=4e4;function Pu(u,a,i){const c=URL.createObjectURL(new Blob([a],{type:i})),f=document.createElement("a");f.href=c,f.download=u,f.style.display="none",document.body.appendChild(f),f.click(),f.remove(),setTimeout(()=>URL.revokeObjectURL(c),ff)}const pf=4e3;function hf({enabled:u,messages:a,busy:i,locale:c,translations:f}){const p=f??ku,[v,k]=R.useState(null),S=R.useRef(null),N=R.useRef(!0);R.useEffect(()=>(N.current=!0,()=>{N.current=!1,S.current&&clearTimeout(S.current)}),[]);const j=R.useCallback(()=>{S.current&&clearTimeout(S.current),S.current=null,k(null)},[]),O=R.useCallback(I=>{N.current&&(S.current&&clearTimeout(S.current),k(I),S.current=setTimeout(()=>{S.current=null,k(null)},pf))},[]);return{items:R.useMemo(()=>{if(!u)return[];const I=i||a.length===0,D=()=>sf(a,{locale:c,labels:{title:p.transcriptTitle,exported:p.transcriptExported,user:p.transcriptUser,assistant:p.transcriptAssistant,attachments:p.transcriptAttachments,sources:p.transcriptSources,toolUsed:p.toolUsed}});return[{id:"copy-markdown",label:p.copyAsMarkdown,disabled:I,onSelect:()=>{df(D()).then(P=>O(P?p.copiedToClipboard:p.copyFailed))}},{id:"download-markdown",label:p.downloadAsMarkdown,disabled:I,onSelect:()=>Pu(Lu("md"),D(),"text/markdown;charset=utf-8")},{id:"download-json",label:p.downloadAsJson,disabled:I,onSelect:()=>Pu(Lu("json"),af(a),"application/json")}]},[u,i,a,c,p,O]),status:v,clearStatus:j}}const mf=/\*\*([^*]+)\*\*/g,gf=/\*([^*]+)\*/g,vf=/https?:\/\/[^\s)]+/g;function Au(u){return u.replace(mf,"$1").replace(gf,"$1").replace(vf,a=>{var f;const i=((f=a.match(/[.,;:!?'"]+$/))==null?void 0:f[0])??"",c=i?a.slice(0,-i.length):a;try{return new URL(c).hostname+i}catch{return a}})}const yf={"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 wf({messages:u,isLoading:a,isStreaming:i=!1,streamingMessageId:c=null,error:f,canRetry:p=!1,onSend:v,onStop:k,onRetry:S,onClose:N,title:j="Chat",subtitle:O="Ask me anything",welcomeMessage:V="Hi! How can I help you today?",placeholder:I,position:D="bottom-right",translations:P,isMobile:F=!1,attachments:$=null,voice:J=null,conversationExport:B=!1,locale:Q="en-US"}){const ue=R.useId(),de=R.useRef(null),ae=R.useRef(null),[Z,xe]=R.useState(null);Kd(de,!0);const pe=bd((J==null?void 0:J.lang)??"en-US"),Se=!!(J!=null&&J.output)&&pe.isSupported,Ce={play:(P==null?void 0:P.readAloud)??"Read aloud",pause:(P==null?void 0:P.pauseReading)??"Pause reading",resume:(P==null?void 0:P.resumeReading)??"Resume reading",stop:(P==null?void 0:P.stopReading)??"Stop reading"},ve=hf({enabled:B,messages:u,busy:a,locale:Q,translations:P}),{offsetY:Re}=Wd(ae,N,F),ye=Re!==0,_e=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1;R.useEffect(()=>{const C=ae.current;C&&(C.scrollTop=C.scrollHeight)},[u,a]),R.useEffect(()=>{const C=m=>{m.key==="Escape"&&!m.isComposing&&!m.defaultPrevented&&N()};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[N]);const ge=(P==null?void 0:P.closeChat)??"Close chat",z=(P==null?void 0:P.chatMessages)??"Chat messages",X=[...u].reverse().find(C=>C.role==="assistant");return y.jsxs("div",{ref:de,role:"dialog","aria-modal":F?"true":void 0,"aria-labelledby":ue,className:F?"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 ${yf[D]} 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:F&&!_e?{transform:`translateY(${Math.max(0,Re)}px)`}:void 0,"data-dragging":ye||void 0,children:[F&&y.jsx("div",{className:"flex justify-center py-2","aria-hidden":"true",children:y.jsx("div",{className:"h-1 w-8 rounded-claudius-full bg-claudius-border"})}),y.jsx(Bd,{title:j,subtitle:O,titleId:ue,closeLabel:ge,onClose:N,actions:B?y.jsx(Vd,{label:(P==null?void 0:P.moreOptions)??"More options",items:ve.items,onOpen:ve.clearStatus}):void 0}),y.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[Z&&y.jsx(Ud,{sources:Z.sources,onClose:()=>xe(null)}),B&&y.jsx("div",{role:"status",className:"pointer-events-none absolute inset-x-0 top-2 z-10 flex justify-center px-4",children:ve.status&&y.jsx("span",{className:"rounded-claudius-full bg-claudius-text px-3 py-1 text-xs text-claudius-surface shadow-claudius-elevated",children:ve.status})}),y.jsxs("div",{ref:ae,role:"log","aria-label":z,className:"h-full space-y-3 overflow-y-auto px-4 py-4",children:[u.length===0&&!f&&y.jsx("div",{className:"mr-auto flex max-w-[85%]",children:y.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:V})}),u.map(C=>y.jsx(kd,{role:C.role,content:C.content,isStreaming:C.id===c,sources:C.sources,attachments:C.attachments,toolUses:C.toolUses,toolUsedLabel:P==null?void 0:P.toolUsed,toolDetailsLabel:P==null?void 0:P.toolDetails,isSourceActive:(Z==null?void 0:Z.messageId)===C.id,onSourceClick:()=>{(Z==null?void 0:Z.messageId)===C.id?xe(null):C.sources&&C.sources.length>0&&xe({messageId:C.id,sources:C.sources})},speech:Se&&C.role==="assistant"&&C.id!==c&&C.content.trim()!==""?{state:pe.activeId!==C.id?"idle":pe.isPaused?"paused":"speaking",labels:Ce,onPlay:()=>pe.speak(C.id,Au(C.content)),onPause:pe.pause,onResume:pe.resume,onStop:pe.cancel}:void 0},C.id)),a&&!(c!==null&&u.some(C=>C.id===c&&C.content.length>0))&&y.jsx($d,{label:(P==null?void 0:P.typingIndicator)??"Assistant is typing"}),f&&y.jsx(Hd,{message:f,retryLabel:(P==null?void 0:P.errorRetry)??"Retry",onRetry:p&&S&&!a?S:void 0})]})]}),y.jsx("div",{"data-claudius-live":"assistant","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:X&&X.id!==c?Au(X.content):""}),y.jsx(zd,{onSend:v,isLoading:a,isStreaming:i,onStop:k,placeholder:I,translations:P,attachments:$,voice:J,onVoiceStart:pe.cancel,isReadingAloud:pe.activeId!==null})]})}function xf({message:u,position:a,onOpen:i,onDismiss:c,dismissLabel:f}){const p=a.startsWith("bottom"),v=a.endsWith("right"),k=["claudius-greeting-bubble","fixed z-40 max-w-xs",p?"bottom-20":"top-20",v?"right-4":"left-4"].join(" ");return y.jsxs("div",{className:k,role:"status","aria-live":"polite",children:[y.jsx("button",{type:"button",onClick:i,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:u}),y.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),c()},"aria-label":f,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:y.jsx("span",{"aria-hidden":"true",children:"×"})})]})}const Du={en:Su,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",attachFile:"Adjuntar un archivo",removeAttachment:"Quitar adjunto",attachmentsLabel:"Adjuntos",dropFilesHint:"Suelta los archivos para adjuntarlos",attachmentTooLarge:"{name} es demasiado grande. El tamaño máximo es {max}.",attachmentTypeNotAllowed:"{name} no es un tipo de archivo compatible.",attachmentTooMany:"Puedes adjuntar hasta {max} archivos por mensaje.",voiceInput:"Entrada de voz",voiceInputHold:"Mantén pulsado para hablar",voiceListening:"Escuchando...",voicePermissionDenied:"El acceso al micrófono está bloqueado. Permítelo en la configuración de tu navegador para usar la entrada de voz.",voiceNoSpeech:"No se detectó ninguna voz. Inténtalo de nuevo.",voiceNoMicrophone:"No se encontró ningún micrófono.",voiceUnavailable:"La entrada de voz no está disponible en este momento.",readAloud:"Leer en voz alta",pauseReading:"Pausar la lectura",resumeReading:"Reanudar la lectura",stopReading:"Detener la lectura",moreOptions:"Más opciones",copyAsMarkdown:"Copiar como Markdown",downloadAsMarkdown:"Descargar como Markdown",downloadAsJson:"Descargar como JSON",copiedToClipboard:"Copiado al portapapeles",copyFailed:"No se pudo copiar. Prueba a descargarlo.",transcriptTitle:"Transcripción del chat",transcriptExported:"Exportado el {date}",transcriptUser:"Usuario",transcriptAssistant:"Asistente",transcriptAttachments:"Adjuntos:",transcriptSources:"Fuentes:",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.",errorAttachmentRejected:"Se rechazó un adjunto. Quítalo e inténtalo de nuevo.",errorAttachmentQuota:"Límite de subida alcanzado. 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",attachFile:"Joindre un fichier",removeAttachment:"Retirer la pièce jointe",attachmentsLabel:"Pièces jointes",dropFilesHint:"Déposez les fichiers pour les joindre",attachmentTooLarge:"{name} est trop volumineux. La taille maximale est de {max}.",attachmentTypeNotAllowed:"{name} n'est pas un type de fichier pris en charge.",attachmentTooMany:"Vous pouvez joindre jusqu'à {max} fichiers par message.",voiceInput:"Saisie vocale",voiceInputHold:"Maintenez pour parler",voiceListening:"Écoute en cours...",voicePermissionDenied:"L'accès au microphone est bloqué. Autorisez-le dans les paramètres de votre navigateur pour utiliser la saisie vocale.",voiceNoSpeech:"Aucune voix n'a été détectée. Veuillez réessayer.",voiceNoMicrophone:"Aucun microphone n'a été trouvé.",voiceUnavailable:"La saisie vocale n'est pas disponible pour le moment.",readAloud:"Lire à voix haute",pauseReading:"Mettre la lecture en pause",resumeReading:"Reprendre la lecture",stopReading:"Arrêter la lecture",moreOptions:"Plus d'options",copyAsMarkdown:"Copier en Markdown",downloadAsMarkdown:"Télécharger en Markdown",downloadAsJson:"Télécharger en JSON",copiedToClipboard:"Copié dans le presse-papiers",copyFailed:"Impossible de copier. Essayez plutôt de télécharger.",transcriptTitle:"Transcription du chat",transcriptExported:"Exporté le {date}",transcriptUser:"Utilisateur",transcriptAssistant:"Assistant",transcriptAttachments:"Pièces jointes :",transcriptSources:"Sources :",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.",errorAttachmentRejected:"Une pièce jointe a été refusée. Retirez-la et réessayez.",errorAttachmentQuota:"Limite d'envoi 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",attachFile:"Datei anhängen",removeAttachment:"Anhang entfernen",attachmentsLabel:"Anhänge",dropFilesHint:"Dateien hier ablegen, um sie anzuhängen",attachmentTooLarge:"{name} ist zu groß. Die maximale Größe beträgt {max}.",attachmentTypeNotAllowed:"{name} ist kein unterstützter Dateityp.",attachmentTooMany:"Sie können bis zu {max} Dateien pro Nachricht anhängen.",voiceInput:"Spracheingabe",voiceInputHold:"Zum Sprechen gedrückt halten",voiceListening:"Ich höre zu...",voicePermissionDenied:"Der Zugriff auf das Mikrofon ist blockiert. Erlauben Sie ihn in den Einstellungen Ihres Browsers, um die Spracheingabe zu nutzen.",voiceNoSpeech:"Es wurde keine Sprache erkannt. Bitte versuchen Sie es erneut.",voiceNoMicrophone:"Es wurde kein Mikrofon gefunden.",voiceUnavailable:"Die Spracheingabe ist momentan nicht verfügbar.",readAloud:"Vorlesen",pauseReading:"Vorlesen pausieren",resumeReading:"Vorlesen fortsetzen",stopReading:"Vorlesen beenden",moreOptions:"Weitere Optionen",copyAsMarkdown:"Als Markdown kopieren",downloadAsMarkdown:"Als Markdown herunterladen",downloadAsJson:"Als JSON herunterladen",copiedToClipboard:"In die Zwischenablage kopiert",copyFailed:"Kopieren nicht möglich. Bitte stattdessen herunterladen.",transcriptTitle:"Chat-Protokoll",transcriptExported:"Exportiert am {date}",transcriptUser:"Nutzer",transcriptAssistant:"Assistent",transcriptAttachments:"Anhänge:",transcriptSources:"Quellen:",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.",errorAttachmentRejected:"Ein Anhang wurde abgelehnt. Bitte entfernen Sie ihn und versuchen Sie es erneut.",errorAttachmentQuota:"Upload-Limit erreicht. Bitte versuchen Sie es später erneut.",errorRetry:"Erneut versuchen"}};function zu(u){if(!u)return;const a=u.toLowerCase().split("-")[0];return Object.prototype.hasOwnProperty.call(Du,a)?a:void 0}function Ou(){const u=typeof document<"u"?zu(document.documentElement.lang):void 0;if(u)return u;const a=typeof navigator<"u"?zu(navigator.language):void 0;return a||"en"}function Sf(u={}){const{locale:a,translations:i}=u,c=Du[a??Ou()];return i?{...c,...i}:{...c}}const Iu=["accent","accentText","accentSoft","accentTextMuted","surface","surfaceMuted","text","textMuted","border","userBubble","userBubbleText","assistantBubble","assistantBubbleText","field","error","errorSurface","errorText","link","scrim"],kf=["sm","md","lg","full","tail"],Ef=["elevated","floating","floatingHover"],Cf=["heading","body"],Fu={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 Rf(u){return Object.prototype.hasOwnProperty.call(Fu,u)}const Tf=new Set(["light","dark","auto"]);function Nf(u){if(u===void 0)return{mode:"light"};if(typeof u=="string"){if(Tf.has(u))return{mode:u};if(Rf(u)){const a=Fu[u];return{mode:a.colorScheme??"light",theme:a}}return{mode:"light",url:u}}return{mode:u.colorScheme??"light",theme:u}}function jf(u){return u.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`)}function _f(u,a){console.warn(`[Claudius] Ignoring unknown theme token "${a}" in "${u}"`)}function nr(u,a,i,c,f,p=""){if(f)for(const[v,k]of Object.entries(f)){if(!c.includes(v)){_f(a,v);continue}typeof k=="string"&&(u[`${i}${jf(v)}${p}`]=k)}}function Mf(u){const a={};nr(a,"colors","--cl-color-",Iu,u.colors);for(const[i,c]of Object.entries({...a}))a[`${i}-dark`]=c;return nr(a,"colorsDark","--cl-color-",Iu,u.colorsDark,"-dark"),nr(a,"radii","--cl-radius-",kf,u.radii),nr(a,"shadows","--cl-shadow-",Ef,u.shadows),nr(a,"fonts","--cl-font-",Cf,u.fonts),a}function Lf(u){return typeof u=="object"&&u!==null&&!Array.isArray(u)}function Pf(u){const a=R.useMemo(()=>Nf(u),[u]),[i,c]=R.useState(null),f=a.url;R.useEffect(()=>{if(c(null),!f)return;const S=new AbortController;return fetch(f,{signal:S.signal}).then(N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);return N.json()}).then(N=>{if(!Lf(N))throw new Error("theme JSON must be an object");c(N)}).catch(N=>{S.signal.aborted||console.error(`[Claudius] Failed to load theme from ${f}:`,N)}),()=>S.abort()},[f]);const p=a.theme??i??null,v=(i==null?void 0:i.colorScheme)??a.mode,k=R.useMemo(()=>p?Mf(p):{},[p]);return{mode:v,cssVars:k}}const Uu="claudius:triggers:dismissed";function Af(){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(Uu)==="1"}catch{return!1}}function Df(){if(!(typeof window>"u"))try{window.sessionStorage.setItem(Uu,"1")}catch{}}function Bu({apiUrl:u,title:a,subtitle:i,welcomeMessage:c,placeholder:f,persistMessages:p,storageKeyPrefix:v,requestTimeoutMs:k,theme:S="light",accentColor:N,position:j="bottom-right",locale:O,translations:V,triggers:I,plugins:D,streaming:P=!0,attachments:F=!1,voice:$=!1,conversationExport:J=!1}){const[B,Q]=R.useState(!1),ue=R.useMemo(()=>Wc(F),[F]),de=R.useMemo(()=>O??Ou(),[O]),ae=R.useMemo(()=>Nd($,de),[$,de]),Z=R.useMemo(()=>Ru(de),[de]),[xe,pe]=R.useState(null),[Se,Ce]=R.useState(Af),ve=R.useRef(!1),Re=ld("(max-width: 639px)"),ye=R.useMemo(()=>Sf({locale:O,translations:V}),[O,V]),{messages:_e,isLoading:ge,isStreaming:z,streamingMessageId:X,error:C,canRetry:m,sendMessage:T,stop:re,retry:le}=rd({apiUrl:u,persistMessages:p,storageKeyPrefix:v,timeoutMs:k,translations:ye,plugins:D,streaming:P}),se=R.useRef(null),ne=R.useRef(B),{mode:ie,cssVars:K}=Pf(S),[q,ce]=R.useState(!1);R.useEffect(()=>{if(ie!=="auto")return;const Ue=window.matchMedia("(prefers-color-scheme: dark)");ce(Ue.matches);const bt=H=>ce(H.matches);return Ue.addEventListener("change",bt),()=>Ue.removeEventListener("change",bt)},[ie]),R.useEffect(()=>{var Ue;ne.current&&!B&&((Ue=se.current)==null||Ue.focus()),ne.current=B},[B]);const Ae=R.useCallback(()=>{Ce(!0),Df()},[]),Ze=R.useCallback(()=>{Q(!1),ve.current&&(ve.current=!1,Ae())},[Ae]),ft=R.useCallback(()=>{Q(Ue=>!Ue)},[]),Fe=R.useCallback(()=>{ve.current=!0,pe(null),Q(!0)},[]),Kt=R.useCallback(Ue=>{pe(Ue)},[]),_t=R.useCallback(()=>{pe(null),Fe()},[Fe]),Oe=R.useCallback(()=>{pe(null),Ae()},[Ae]);id({triggers:I,enabled:!Se&&!B,onOpen:Fe,onGreeting:Kt});const pt=ie==="dark"||ie==="auto"&&q,Mt={...K,...N?{"--cl-color-accent":N,"--cl-color-accent-dark":N}:{}},ut=Object.keys(Mt).length>0?Mt:void 0;return y.jsx("div",{className:"claudius-root",style:ut,children:y.jsxs("div",{"data-claudius-dark":pt?"true":"false",children:[B&&Re&&y.jsx("div",{className:"claudius-scrim fixed inset-0 z-40 bg-claudius-scrim",onClick:Ze,"aria-hidden":"true"}),B&&y.jsx(wf,{messages:_e,isLoading:ge,isStreaming:z,streamingMessageId:X,error:C,canRetry:m,onSend:T,onStop:re,onRetry:le,onClose:Ze,title:a??ye.title,subtitle:i??ye.subtitle,welcomeMessage:c??ye.welcomeMessage,placeholder:f??ye.placeholder,position:j,translations:ye,isMobile:Re,attachments:ue,voice:ae,conversationExport:J===!0,locale:Z}),!(B&&Re)&&y.jsx(sd,{ref:se,isOpen:B,onClick:ft,position:j,translations:ye}),!B&&xe&&y.jsx(xf,{message:xe,position:j,onOpen:_t,onDismiss:Oe,dismissLabel:ye.dismissGreeting})]})})}const zf="1.17.1";typeof window<"u"&&(window.ClaudiusWidgetVersion=zf);function Hu(){const u=window.ClaudiusConfig;if(!(u!=null&&u.apiUrl)){console.error("[Claudius] Missing ClaudiusConfig.apiUrl");return}const a=document.createElement("div");a.id="claudius-chat-widget",document.body.appendChild(a),cu.createRoot(a).render(y.jsx(Bu,{apiUrl:u.apiUrl,title:u.title,subtitle:u.subtitle,welcomeMessage:u.welcomeMessage,placeholder:u.placeholder,persistMessages:u.persistMessages,storageKeyPrefix:u.storageKeyPrefix,requestTimeoutMs:u.requestTimeoutMs,theme:u.theme,accentColor:u.accentColor,position:u.position,locale:u.locale,translations:u.translations,triggers:u.triggers,attachments:u.attachments,voice:u.voice,conversationExport:u.conversationExport}))}class $u extends HTMLElement{constructor(){super(...arguments);hn(this,"root",null);hn(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","attachments","conversation-export","voice","voice-mode","voice-auto-submit","voice-input","voice-output","voice-lang"]}connectedCallback(){this.container=document.createElement("div"),this.appendChild(this.container),this.root=cu.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 i=this.getAttribute("api-url");if(!i){console.error("[Claudius] Missing api-url attribute on <claudius-chat>");return}const c=this.getAttribute("persist-messages"),f=c===null?void 0:c!=="false",p=this.getAttribute("request-timeout-ms"),v=p===null?void 0:Number(p),k=this.getAttribute("attachments"),S=k===null?void 0:k!=="false",N=this.getAttribute("conversation-export"),j=N==null?void 0:N.trim().toLowerCase(),O=N===null?void 0:j===""||j==="true";this.root.render(y.jsx(Bu,{apiUrl:i,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:f,storageKeyPrefix:this.getAttribute("storage-key-prefix")??void 0,requestTimeoutMs:v!==void 0&&Number.isFinite(v)?v:void 0,theme:this.getAttribute("theme")??void 0,accentColor:this.getAttribute("accent-color")??void 0,position:this.getAttribute("position")??void 0,attachments:S,conversationExport:O,voice:jd(V=>this.getAttribute(V))}))}}return typeof customElements<"u"&&!customElements.get("claudius-chat")&&customElements.define("claudius-chat",$u),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Hu):Hu(),Ot.ClaudiusChat=$u,Object.defineProperty(Ot,Symbol.toStringTag,{value:"Module"}),Ot})({});
|
package/dist/claudius.js
CHANGED
|
@@ -2333,7 +2333,7 @@ function En(e) {
|
|
|
2333
2333
|
}, []);
|
|
2334
2334
|
return W(() => d, [d]), { isSupported: t, activeId: n, isPaused: o, speak: x, pause: A, resume: g, cancel: d };
|
|
2335
2335
|
}
|
|
2336
|
-
const Rn = /^([ \t]*)(`{3,}|~{3,})(.*)$/, An = /^( {0,3})<(?![A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\s]*>|[^\s<>@]
|
|
2336
|
+
const Rn = /^([ \t]*)(`{3,}|~{3,})(.*)$/, An = /^( {0,3})<(?![A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\s]*>|[A-Za-z0-9][^\s<>@]*@[^\s<>]+>)(?=[A-Za-z!?/])/, Sn = /^(?: {4}|\t)/;
|
|
2337
2337
|
function ot(e) {
|
|
2338
2338
|
let t = 0;
|
|
2339
2339
|
for (const n of e)
|
|
@@ -2532,11 +2532,18 @@ function Bn(e) {
|
|
|
2532
2532
|
const t = document.activeElement;
|
|
2533
2533
|
let n = null;
|
|
2534
2534
|
try {
|
|
2535
|
-
return n = document.createElement("textarea"), n.value = e, n.setAttribute("readonly", ""), n.setAttribute("aria-hidden", "true"), n.style.position = "fixed", n.style.top = "0", n.style.left = "0", n.style.opacity = "0", document.body.appendChild(n), n.focus({ preventScroll: !0 }), n.select(), document.execCommand("copy");
|
|
2535
|
+
return n = document.createElement("textarea"), n.value = e, n.setAttribute("readonly", ""), n.setAttribute("aria-hidden", "true"), n.tabIndex = -1, n.style.position = "fixed", n.style.top = "0", n.style.left = "0", n.style.opacity = "0", document.body.appendChild(n), n.focus({ preventScroll: !0 }), n.select(), document.execCommand("copy");
|
|
2536
2536
|
} catch {
|
|
2537
2537
|
return !1;
|
|
2538
2538
|
} finally {
|
|
2539
|
-
|
|
2539
|
+
try {
|
|
2540
|
+
n == null || n.remove();
|
|
2541
|
+
} catch {
|
|
2542
|
+
}
|
|
2543
|
+
try {
|
|
2544
|
+
t == null || t.focus();
|
|
2545
|
+
} catch {
|
|
2546
|
+
}
|
|
2540
2547
|
}
|
|
2541
2548
|
}
|
|
2542
2549
|
async function _n(e) {
|
|
@@ -2546,7 +2553,11 @@ async function _n(e) {
|
|
|
2546
2553
|
return await navigator.clipboard.writeText(e), !0;
|
|
2547
2554
|
} catch {
|
|
2548
2555
|
}
|
|
2549
|
-
|
|
2556
|
+
try {
|
|
2557
|
+
return Bn(e);
|
|
2558
|
+
} catch {
|
|
2559
|
+
return !1;
|
|
2560
|
+
}
|
|
2550
2561
|
}
|
|
2551
2562
|
const zn = 4e4;
|
|
2552
2563
|
function Ve(e, t, n) {
|
package/package.json
CHANGED