claudius-chat-widget 1.6.0 → 1.8.2
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 +1 -1
- package/dist/claudius.iife.js +11 -11
- package/dist/claudius.js +210 -153
- package/dist/index.d.cts +422 -0
- package/dist/index.d.ts +422 -12
- package/package.json +19 -6
- package/dist/api/client.d.ts +0 -24
- package/dist/api/errors.d.ts +0 -9
- package/dist/api/index.d.ts +0 -4
- package/dist/api/types.d.ts +0 -22
- package/dist/components/ChatInput.d.ts +0 -9
- package/dist/components/ChatMessage.d.ts +0 -10
- package/dist/components/ChatSources.d.ts +0 -7
- package/dist/components/ChatToggleButton.d.ts +0 -10
- package/dist/components/ChatWidget.d.ts +0 -29
- package/dist/components/ChatWindow.d.ts +0 -21
- package/dist/components/GreetingBubble.d.ts +0 -10
- package/dist/components/SourceIcon.d.ts +0 -7
- package/dist/embed.d.ts +0 -38
- package/dist/hooks/useChat.d.ts +0 -20
- package/dist/hooks/useFocusTrap.d.ts +0 -2
- package/dist/hooks/useMediaQuery.d.ts +0 -1
- package/dist/hooks/useSwipeToDismiss.d.ts +0 -4
- package/dist/hooks/useTriggers.d.ts +0 -32
- package/dist/i18n.d.ts +0 -21
- package/dist/locales/de.d.ts +0 -2
- package/dist/locales/en.d.ts +0 -2
- package/dist/locales/es.d.ts +0 -2
- package/dist/locales/fr.d.ts +0 -2
- package/dist/locales/index.d.ts +0 -9
- package/dist/main.d.ts +0 -1
- package/dist/test-utils/MockChatApiClient.d.ts +0 -64
- package/dist/theme/index.d.ts +0 -4
- package/dist/theme/resolve.d.ts +0 -19
- package/dist/theme/themes.d.ts +0 -8
- package/dist/theme/types.d.ts +0 -34
- package/dist/theme/useTheme.d.ts +0 -14
- package/dist/utils/sanitize.d.ts +0 -36
- package/dist/utils/stripAnnouncementFormatting.d.ts +0 -1
package/dist/claudius.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use strict";var be=Object.defineProperty;var pe=(t,e,s)=>e in t?be(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var D=(t,e,s)=>pe(t,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),i=require("react");class O extends Error{constructor(e,s,a,n){super(e),this.status=s,this.code=a,this.retryAfter=n,this.name="ChatApiError"}}class W extends Error{constructor(){super("Request debounced"),this.name="DebounceError"}}const ye=3e4;class te{constructor(e,s){D(this,"baseUrl");D(this,"maxRetries");D(this,"debounceMs");D(this,"timeoutMs");D(this,"lastSendTime",0);this.baseUrl=e,this.maxRetries=(s==null?void 0:s.maxRetries)??2,this.debounceMs=(s==null?void 0:s.debounceMs)??300,this.timeoutMs=(s==null?void 0:s.timeoutMs)??ye}async sendMessage(e){if(this.debounceMs>0&&Date.now()-this.lastSendTime<this.debounceMs)throw new W;this.lastSendTime=Date.now();let s;for(let a=0;a<=this.maxRetries;a++)try{const n=await this.fetchWithTimeout(e);if(n.ok)return await n.json();const o=await n.json().catch(()=>({})),c=n.headers.get("Retry-After"),d=c?Number(c):void 0;if(s=new O(o.error??`Request failed with status ${n.status}`,n.status,o.code,d),!this.isRetryable(n.status))throw s;if(a<this.maxRetries){const u=this.getRetryDelay(n,a);await this.delay(u)}}catch(n){if(n instanceof O){if(!this.isRetryable(n.status,n.code))throw n;if(s=n,a<this.maxRetries){const o=this.getRetryDelay(null,a);await this.delay(o)}}else if(s=new O("Failed to connect. Please try again.",0,"NETWORK_ERROR"),a<this.maxRetries){const o=this.getRetryDelay(null,a);await this.delay(o)}}throw s}async fetchWithTimeout(e){if(this.timeoutMs<=0)return fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:e})});const s=new AbortController,a=setTimeout(()=>s.abort(),this.timeoutMs);try{return await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:e}),signal:s.signal})}catch(n){throw s.signal.aborted?new O("Request timed out. Please try again.",0,"TIMEOUT"):n}finally{clearTimeout(a)}}isRetryable(e,s){return s==="TIMEOUT"||s==="NETWORK_ERROR"?!0:e===429||e===503}getRetryDelay(e,s){if(e&&e.status===429){const a=e.headers.get("Retry-After");if(a){const n=Number(a);return Math.min(n*1e3,6e4)}}return s===0?1e3:3e3}delay(e){return new Promise(s=>setTimeout(s,e))}}const we=200,ve="claudius:messages";function Ee(t,e){let s;try{s=new URL(e).host}catch{s=e}return`${t}:${s}`}function P(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function Re(t){const e=P();if(!e)return[];try{const s=e.getItem(t);if(!s)return[];const a=JSON.parse(s);return Array.isArray(a)?a:[]}catch{return[]}}function je({apiUrl:t,persistMessages:e=!0,storageKeyPrefix:s=ve,timeoutMs:a,translations:n}){const o=i.useMemo(()=>new te(t,{debounceMs:0,timeoutMs:a}),[t,a]),c=Ee(s,t),d=e?Re(c):[],[u,l]=i.useState(d),[f,E]=i.useState(!1),[x,b]=i.useState(null),[h,w]=i.useState(!1),v=i.useRef(d.length),y=i.useRef(!1),R=i.useRef(d),M=i.useCallback(m=>{if(!e)return;const p=P();if(p)try{const L=m.slice(-we);p.setItem(c,JSON.stringify(L))}catch{}},[e,c]),S=()=>(v.current+=1,`msg-${v.current}`),k=i.useCallback((m,p)=>{if(!n)return p??"Something went wrong. Please try again.";switch(m){case"TIMEOUT":return n.errorTimeout;case"NETWORK_ERROR":return n.errorConnection;case"RATE_LIMITED":return p!=null&&p.includes("minute")?n.errorRateLimitMinute:n.errorRateLimitHour;case"VALIDATION_ERROR":case"CONFIG_ERROR":case"SERVICE_ERROR":case"UNKNOWN_ERROR":default:return p??n.errorGeneric}},[n]),j=i.useCallback(m=>!(m instanceof O)||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,[]),N=i.useCallback(async m=>{E(!0),y.current=!0,b(null),w(!1);try{const p=await o.sendMessage(m),L={id:S(),role:"assistant",content:p.reply,sources:p.sources},T=[...m,L];R.current=T,l(T),M(T)}catch(p){if(p instanceof W)return;p instanceof O?b(k(p.code,p.message)):b((n==null?void 0:n.errorConnection)??"Failed to connect. Please try again."),w(j(p))}finally{E(!1),y.current=!1}},[o,k,j,M,n]),A=i.useCallback(async m=>{const p=m.trim();if(!p||y.current)return;const L={id:S(),role:"user",content:p},T=[...R.current,L];R.current=T,l(T),M(T),await N(T)},[M,N]),g=i.useCallback(async()=>{if(y.current)return;const m=R.current[R.current.length-1];!m||m.role!=="user"||await N(R.current)},[N]),I=i.useCallback(()=>{if(R.current=[],l([]),b(null),w(!1),e){const m=P();if(!m)return;try{m.removeItem(c)}catch{}}},[e,c]);return{messages:u,isLoading:f,error:x,canRetry:h,sendMessage:A,retry:g,clearMessages:I}}function Te(t){const[e,s]=i.useState(()=>typeof window>"u"?!1:window.matchMedia(t).matches);return i.useEffect(()=>{const a=window.matchMedia(t);s(a.matches);const n=o=>s(o.matches);return a.addEventListener("change",n),()=>a.removeEventListener("change",n)},[t]),e}function U(t,e){return t instanceof RegExp?t.test(e):e.toLowerCase().includes(t.toLowerCase())}function Ce(){const t=document.documentElement,e=document.body,s=t.scrollTop||e.scrollTop||0,a=Math.max(t.scrollHeight,e.scrollHeight),n=t.clientHeight||window.innerHeight,o=a-n;return o<=0?100:s/o*100}function Me({triggers:t,enabled:e,onOpen:s,onGreeting:a}){i.useEffect(()=>{if(!e||!t||t.length===0)return;const n=new Set,o=[],c=typeof window<"u"?window.location.href:"",d=(u,l)=>{n.has(u)||(n.add(u),l==="open"?s():a(l.greeting))};return t.forEach((u,l)=>{switch(u.on){case"url":{U(u.pattern,c)&&d(l,u.action);break}case"time":{if(u.matchUrl&&!U(u.matchUrl,c))return;const f=window.setTimeout(()=>d(l,u.action),Math.max(0,u.seconds*1e3));o.push(()=>window.clearTimeout(f));break}case"scroll":{if(u.matchUrl&&!U(u.matchUrl,c))return;const f=()=>{Ce()>=u.percent&&d(l,u.action)};f(),window.addEventListener("scroll",f,{passive:!0}),o.push(()=>window.removeEventListener("scroll",f));break}case"exit-intent":{if(u.matchUrl&&!U(u.matchUrl,c))return;const f=E=>{E.clientY<=0&&d(l,u.action)};document.addEventListener("mouseleave",f),o.push(()=>document.removeEventListener("mouseleave",f));break}}}),()=>{o.forEach(u=>u())}},[t,e,s,a])}const Se={"bottom-right":"bottom-6 right-6","bottom-left":"bottom-6 left-6","top-right":"top-6 right-6","top-left":"top-6 left-6"},ke=i.forwardRef(function({isOpen:e,onClick:s,position:a="bottom-right",translations:n},o){const c=e?(n==null?void 0:n.closeChat)??"Close chat":(n==null?void 0:n.openChat)??"Open chat";return r.jsx("button",{ref:o,onClick:s,"aria-label":c,className:`fixed ${Se[a]} 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:e?r.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:[r.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),r.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}):r.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:r.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"})})})}),Ne=i.memo(function({count:e,isActive:s,onClick:a}){return r.jsxs("button",{onClick:a,"aria-label":"View sources",title:"View sources",className:`group relative flex h-7 w-7 items-center justify-center rounded-claudius-full transition-colors ${s?"bg-claudius-accent text-claudius-accent-text":"text-claudius-text-muted hover:bg-claudius-surface-muted hover:text-claudius-text"}`,children:[r.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:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("polyline",{points:"14 2 14 8 20 8"}),r.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),r.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]}),r.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:e})]})}),Le=["http:","https:"];function se(t){if(!t||typeof t!="string")return null;const e=t.trim();if(!e)return null;try{const s=new URL(e);return Le.includes(s.protocol)?e:null}catch{return null}}const X=/(https?:\/\/[^\s)]+)/,J=/(\*\*[^*]+\*\*)/,Z=/(\*[^*]+\*)/;function Oe(t,e){const s=t.match(/[.,;:!?'"]+$/),a=s?t.slice(0,-s[0].length):t,n=s?s[0]:"",o=se(a);return o?r.jsxs(r.Fragment,{children:[r.jsxs("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"underline font-medium hover:opacity-80 text-claudius-link",children:[o.replace(/^https?:\/\//,""),r.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]},e),n]}):t}function Ae(t,e){const s=t.split(J),a=[];return s.forEach((n,o)=>{if(J.test(n)){const c=n.slice(2,-2);a.push(r.jsx("strong",{children:c},`${e}-b${o}`))}else n.split(Z).forEach((d,u)=>{if(Z.test(d)){const l=d.slice(1,-1);a.push(r.jsx("em",{children:l},`${e}-b${o}-i${u}`))}else d.split(X).forEach((f,E)=>{X.test(f)?a.push(Oe(f,`${e}-b${o}-i${u}-u${E}`)):f&&a.push(f)})})}),a}function Ie(t){const e=t.split(`
|
|
2
|
-
`);return e.map((s,a)=>r.jsxs("span",{children:[Ae(s,`l${a}`),a<e.length-1&&r.jsx("br",{})]},a))}const De=i.memo(function({role:e,content:s,sources:a,onSourceClick:n,isSourceActive:o}){const c=e==="user";return r.jsxs("div",{className:`${c?"ml-auto":"mr-auto"} max-w-[85%]`,children:[r.jsx("div",{className:`rounded-claudius-bubble px-4 py-2.5 text-sm leading-relaxed font-body ${c?"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:Ie(s)}),!c&&a&&a.length>0&&n&&r.jsx("div",{className:"mt-1",children:r.jsx(Ne,{count:a.length,isActive:o??!1,onClick:n})})]})}),G=2e3,He=1800;function _e({onSend:t,isLoading:e,placeholder:s,translations:a}){const[n,o]=i.useState(""),c=i.useRef(null),d=n.length,u=d>=He,l=d>=G,f=s??(a==null?void 0:a.placeholder)??"Type your message...",E=(a==null?void 0:a.sendMessage)??"Send message",x=(a==null?void 0:a.typeYourMessage)??"Type your message";i.useEffect(()=>{var w;e||(w=c.current)==null||w.focus()},[e]);const b=w=>{w.preventDefault();const v=n.trim();!v||l||(t(v),o(""))},h=w=>{const v=w.target.value;v.length<=G&&o(v)};return r.jsxs("form",{onSubmit:b,className:"border-t border-claudius-border bg-claudius-surface p-3",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{ref:c,type:"text",value:n,onChange:h,placeholder:f,disabled:e,"aria-label":x,"aria-describedby":u?"char-count":void 0,className:"flex-1 rounded-claudius-sm border border-claudius-border bg-claudius-field px-3 py-2 text-sm font-body text-claudius-text placeholder:text-claudius-text-muted focus:border-claudius-accent focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50"}),r.jsx("button",{type:"submit",disabled:e||l,"aria-label":E,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:r.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:[r.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),r.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),u&&r.jsxs("div",{id:"char-count",className:`mt-1 text-xs text-right ${l?"text-claudius-error":"text-claudius-text-muted"}`,"aria-live":"polite",children:[d,"/",G]})]})}const $e=["blog","page","external"],Ue={blog:"Blog",page:"Page",external:"External"};function Be(t){try{return new URL(t).hostname}catch{return t}}const Ge=i.memo(function({sources:e,onClose:s}){const a=$e.map(o=>({type:o,label:Ue[o],items:e.filter(c=>c.type===o)})).filter(o=>o.items.length>0),n=e.length===1?"1 source found":`${e.length} sources found`;return r.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:[r.jsxs("div",{className:"flex items-center justify-between border-b border-claudius-border px-4 py-3",children:[r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-heading font-semibold text-claudius-text",children:"Sources"}),r.jsx("p",{className:"text-xs text-claudius-text-muted",children:n})]}),r.jsx("button",{onClick:s,"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:r.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:[r.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),r.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-4",children:a.map(o=>r.jsxs("div",{children:[r.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-claudius-text-muted",children:o.label}),r.jsx("div",{className:"space-y-2",children:o.items.map(c=>{const d=se(c.url);return d?r.jsxs("a",{href:d,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:[r.jsx("p",{className:"truncate text-sm font-medium text-claudius-text",children:c.title}),r.jsx("p",{className:"mt-0.5 text-xs text-claudius-text-muted",children:Be(d)})]},d):null})})]},o.type))})]})});function Pe(t,e,s){const[a,n]=i.useState(0),o=i.useRef(0),c=i.useRef(0),d=i.useRef(0),u=i.useRef(!1);return i.useEffect(()=>{const l=t.current;if(!s||!l)return;const f=b=>{if(l.scrollTop>0){u.current=!1;return}u.current=!0,c.current=b.touches[0].clientY,d.current=Date.now()},E=b=>{if(!u.current)return;let h=b.touches[0].clientY-c.current;h<0&&(h=h*.3),o.current=h,n(h)},x=()=>{if(!u.current)return;u.current=!1;const b=o.current,h=(Date.now()-d.current)/1e3,w=l.getBoundingClientRect().height,v=h>.05&&b>0&&b/h>500,y=b>w*.3;v||y?e():(o.current=0,n(0))};return l.addEventListener("touchstart",f,{passive:!0}),l.addEventListener("touchmove",E,{passive:!0}),l.addEventListener("touchend",x),()=>{l.removeEventListener("touchstart",f),l.removeEventListener("touchmove",E),l.removeEventListener("touchend",x)}},[t,e,s]),{offsetY:a}}const We='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Fe(t,e){i.useEffect(()=>{const s=t.current;if(!s)return;const a=n=>{if(n.key!=="Tab")return;const o=Array.from(s.querySelectorAll(We)).filter(l=>!l.hasAttribute("aria-hidden"));if(o.length===0)return;const c=o[0],d=o[o.length-1],u=document.activeElement;n.shiftKey&&u===c?(n.preventDefault(),d.focus()):!n.shiftKey&&u===d&&(n.preventDefault(),c.focus())};return s.addEventListener("keydown",a),()=>s.removeEventListener("keydown",a)},[t,e])}const Ye=/\*\*([^*]+)\*\*/g,ze=/\*([^*]+)\*/g,Ve=/https?:\/\/[^\s)]+/g;function Ke(t){return t.replace(Ye,"$1").replace(ze,"$1").replace(Ve,e=>{try{return new URL(e).hostname}catch{return e}})}function qe({label:t}){return r.jsx("div",{role:"status","aria-live":"polite","aria-label":t,className:"mr-auto flex max-w-[85%]",children:r.jsxs("div",{className:"flex gap-1 rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-3",children:[r.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:0ms]"}),r.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:150ms]"}),r.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:300ms]"})]})})}const Xe={"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 Je({messages:t,isLoading:e,error:s,canRetry:a=!1,onSend:n,onRetry:o,onClose:c,title:d="Chat",subtitle:u="Ask me anything",welcomeMessage:l="Hi! How can I help you today?",placeholder:f,position:E="bottom-right",translations:x,isMobile:b=!1}){const h=i.useId(),w=i.useRef(null),v=i.useRef(null),[y,R]=i.useState(null);Fe(w,!0);const{offsetY:M}=Pe(v,c,b),S=M!==0,k=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1;i.useEffect(()=>{const g=v.current;g&&(g.scrollTop=g.scrollHeight)},[t,e]),i.useEffect(()=>{const g=I=>{I.key==="Escape"&&!I.isComposing&&c()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[c]);const j=(x==null?void 0:x.closeChat)??"Close chat",N=(x==null?void 0:x.chatMessages)??"Chat messages",A=[...t].reverse().find(g=>g.role==="assistant");return r.jsxs("div",{ref:w,role:"dialog","aria-modal":b?"true":void 0,"aria-labelledby":h,className:b?"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 ${Xe[E]} 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:b&&!k?{transform:`translateY(${Math.max(0,M)}px)`}:void 0,"data-dragging":S||void 0,children:[b&&r.jsx("div",{className:"flex justify-center py-2","aria-hidden":"true",children:r.jsx("div",{className:"h-1 w-8 rounded-claudius-full bg-claudius-border"})}),r.jsxs("div",{className:"flex items-center gap-3 bg-claudius-accent px-5 py-4",children:[r.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:d.charAt(0).toUpperCase()}),r.jsxs("div",{className:"flex-1",children:[r.jsx("h2",{id:h,className:"text-sm font-heading font-semibold text-claudius-accent-text",children:d}),r.jsx("p",{className:"text-xs text-claudius-accent-text",children:u})]}),r.jsx("button",{onClick:c,"aria-label":j,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:r.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:[r.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),r.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),r.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[y&&r.jsx(Ge,{sources:y.sources,onClose:()=>R(null)}),r.jsxs("div",{ref:v,role:"log","aria-label":N,className:"h-full space-y-3 overflow-y-auto px-4 py-4",children:[t.length===0&&!s&&r.jsx("div",{className:"mr-auto flex max-w-[85%]",children:r.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:l})}),t.map(g=>r.jsx(De,{role:g.role,content:g.content,sources:g.sources,isSourceActive:(y==null?void 0:y.messageId)===g.id,onSourceClick:()=>{(y==null?void 0:y.messageId)===g.id?R(null):g.sources&&g.sources.length>0&&R({messageId:g.id,sources:g.sources})}},g.id)),e&&r.jsx(qe,{label:(x==null?void 0:x.typingIndicator)??"Assistant is typing"}),s&&r.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:[r.jsx("span",{children:s}),a&&o&&!e&&r.jsx("button",{type:"button",onClick:o,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:(x==null?void 0:x.errorRetry)??"Retry"})]})]})]}),r.jsx("div",{"data-claudius-live":"assistant","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:A?Ke(A.content):""}),r.jsx(_e,{onSend:n,isLoading:e,placeholder:f,translations:x})]})}function Ze({message:t,position:e,onOpen:s,onDismiss:a,dismissLabel:n}){const o=e.startsWith("bottom"),c=e.endsWith("right"),d=["claudius-greeting-bubble","fixed z-40 max-w-xs",o?"bottom-20":"top-20",c?"right-4":"left-4"].join(" ");return r.jsxs("div",{className:d,role:"status","aria-live":"polite",children:[r.jsx("button",{type:"button",onClick:s,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:t}),r.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a()},"aria-label":n,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:r.jsx("span",{"aria-hidden":"true",children:"×"})})]})}const re={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",typeYourMessage:"Type your message",openChat:"Open chat",dismissGreeting:"Dismiss greeting",errorGeneric:"Something went wrong. Please try again.",errorConnection:"Failed to connect. Please try again.",errorTimeout:"Request timed out. Please try again.",errorRateLimitMinute:"Too many requests. Please wait a minute.",errorRateLimitHour:"Hourly limit reached. Please try again later.",errorRetry:"Retry"},ne=re;function Qe(t){return{...ne,...t}}const et={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",typeYourMessage:"Escribe tu mensaje",openChat:"Abrir chat",dismissGreeting:"Descartar saludo",errorGeneric:"Algo salió mal. Inténtalo de nuevo.",errorConnection:"No se pudo conectar. Inténtalo de nuevo.",errorTimeout:"La solicitud tardó demasiado. Inténtalo de nuevo.",errorRateLimitMinute:"Demasiadas solicitudes. Espera un minuto.",errorRateLimitHour:"Has alcanzado el límite por hora. Inténtalo más tarde.",errorRetry:"Reintentar"},tt={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",typeYourMessage:"Saisissez votre message",openChat:"Ouvrir le chat",dismissGreeting:"Ignorer le message d'accueil",errorGeneric:"Une erreur s'est produite. Veuillez réessayer.",errorConnection:"Échec de la connexion. Veuillez réessayer.",errorTimeout:"La requête a expiré. Veuillez réessayer.",errorRateLimitMinute:"Trop de requêtes. Veuillez patienter une minute.",errorRateLimitHour:"Limite horaire atteinte. Veuillez réessayer plus tard.",errorRetry:"Réessayer"},st={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",typeYourMessage:"Geben Sie Ihre Nachricht ein",openChat:"Chat öffnen",dismissGreeting:"Begrüßung schließen",errorGeneric:"Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.",errorConnection:"Verbindung fehlgeschlagen. Bitte versuchen Sie es erneut.",errorTimeout:"Zeitüberschreitung der Anfrage. Bitte versuchen Sie es erneut.",errorRateLimitMinute:"Zu viele Anfragen. Bitte warten Sie eine Minute.",errorRateLimitHour:"Stündliches Limit erreicht. Bitte versuchen Sie es später erneut.",errorRetry:"Erneut versuchen"},F={en:re,es:et,fr:tt,de:st};function Q(t){if(!t)return;const e=t.toLowerCase().split("-")[0];return Object.prototype.hasOwnProperty.call(F,e)?e:void 0}function ae(){const t=typeof document<"u"?Q(document.documentElement.lang):void 0;if(t)return t;const e=typeof navigator<"u"?Q(navigator.language):void 0;return e||"en"}function oe(t={}){const{locale:e,translations:s}=t,a=F[e??ae()];return s?{...a,...s}:{...a}}const ee=["accent","accentText","accentSoft","accentTextMuted","surface","surfaceMuted","text","textMuted","border","userBubble","userBubbleText","assistantBubble","assistantBubbleText","field","error","errorSurface","errorText","link","scrim"],rt=["sm","md","lg","full","tail"],nt=["elevated","floating","floatingHover"],at=["heading","body"],Y={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 ot(t){return Object.prototype.hasOwnProperty.call(Y,t)}const it=new Set(["light","dark","auto"]);function ct(t){if(t===void 0)return{mode:"light"};if(typeof t=="string"){if(it.has(t))return{mode:t};if(ot(t)){const e=Y[t];return{mode:e.colorScheme??"light",theme:e}}return{mode:"light",url:t}}return{mode:t.colorScheme??"light",theme:t}}function ut(t){return t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function lt(t,e){console.warn(`[Claudius] Ignoring unknown theme token "${e}" in "${t}"`)}function H(t,e,s,a,n,o=""){if(n)for(const[c,d]of Object.entries(n)){if(!a.includes(c)){lt(e,c);continue}typeof d=="string"&&(t[`${s}${ut(c)}${o}`]=d)}}function dt(t){const e={};H(e,"colors","--cl-color-",ee,t.colors);for(const[s,a]of Object.entries({...e}))e[`${s}-dark`]=a;return H(e,"colorsDark","--cl-color-",ee,t.colorsDark,"-dark"),H(e,"radii","--cl-radius-",rt,t.radii),H(e,"shadows","--cl-shadow-",nt,t.shadows),H(e,"fonts","--cl-font-",at,t.fonts),e}function ft(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ht(t){const e=i.useMemo(()=>ct(t),[t]),[s,a]=i.useState(null),n=e.url;i.useEffect(()=>{if(a(null),!n)return;const u=new AbortController;return fetch(n,{signal:u.signal}).then(l=>{if(!l.ok)throw new Error(`HTTP ${l.status}`);return l.json()}).then(l=>{if(!ft(l))throw new Error("theme JSON must be an object");a(l)}).catch(l=>{u.signal.aborted||console.error(`[Claudius] Failed to load theme from ${n}:`,l)}),()=>u.abort()},[n]);const o=e.theme??s??null,c=(s==null?void 0:s.colorScheme)??e.mode,d=i.useMemo(()=>o?dt(o):{},[o]);return{mode:c,cssVars:d}}const ie="claudius:triggers:dismissed";function mt(){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(ie)==="1"}catch{return!1}}function xt(){if(!(typeof window>"u"))try{window.sessionStorage.setItem(ie,"1")}catch{}}function gt({apiUrl:t,title:e,subtitle:s,welcomeMessage:a,placeholder:n,persistMessages:o,storageKeyPrefix:c,requestTimeoutMs:d,theme:u="light",accentColor:l,position:f="bottom-right",locale:E,translations:x,triggers:b}){const[h,w]=i.useState(!1),[v,y]=i.useState(null),[R,M]=i.useState(mt),S=i.useRef(!1),k=Te("(max-width: 639px)"),j=i.useMemo(()=>oe({locale:E,translations:x}),[E,x]),{messages:N,isLoading:A,error:g,canRetry:I,sendMessage:m,retry:p}=je({apiUrl:t,persistMessages:o,storageKeyPrefix:c,timeoutMs:d,translations:j}),L=i.useRef(null),T=i.useRef(h),{mode:_,cssVars:ce}=ht(u),[ue,z]=i.useState(!1);i.useEffect(()=>{if(_!=="auto")return;const C=window.matchMedia("(prefers-color-scheme: dark)");z(C.matches);const q=ge=>z(ge.matches);return C.addEventListener("change",q),()=>C.removeEventListener("change",q)},[_]),i.useEffect(()=>{var C;T.current&&!h&&((C=L.current)==null||C.focus()),T.current=h},[h]);const $=i.useCallback(()=>{M(!0),xt()},[]),V=i.useCallback(()=>{w(!1),S.current&&(S.current=!1,$())},[$]),le=i.useCallback(()=>{w(C=>!C)},[]),B=i.useCallback(()=>{S.current=!0,y(null),w(!0)},[]),de=i.useCallback(C=>{y(C)},[]),fe=i.useCallback(()=>{y(null),B()},[B]),he=i.useCallback(()=>{y(null),$()},[$]);Me({triggers:b,enabled:!R&&!h,onOpen:B,onGreeting:de});const me=_==="dark"||_==="auto"&&ue,K={...ce,...l?{"--cl-color-accent":l,"--cl-color-accent-dark":l}:{}},xe=Object.keys(K).length>0?K:void 0;return r.jsx("div",{className:"claudius-root",style:xe,children:r.jsxs("div",{"data-claudius-dark":me?"true":"false",children:[h&&k&&r.jsx("div",{className:"claudius-scrim fixed inset-0 z-40 bg-claudius-scrim",onClick:V,"aria-hidden":"true"}),h&&r.jsx(Je,{messages:N,isLoading:A,error:g,canRetry:I,onSend:m,onRetry:p,onClose:V,title:e??j.title,subtitle:s??j.subtitle,welcomeMessage:a??j.welcomeMessage,placeholder:n??j.placeholder,position:f,translations:j,isMobile:k}),!(h&&k)&&r.jsx(ke,{ref:L,isOpen:h,onClick:le,position:f,translations:j}),!h&&v&&r.jsx(Ze,{message:v,position:f,onOpen:fe,onDismiss:he,dismissLabel:j.dismissGreeting})]})})}exports.ChatApiClient=te;exports.ChatApiError=O;exports.ChatWidget=gt;exports.DebounceError=W;exports.builtinThemes=Y;exports.createTranslations=Qe;exports.defaultTranslations=ne;exports.detectLocale=ae;exports.locales=F;exports.resolveTranslations=oe;
|
|
2
|
+
`);return e.map((s,a)=>r.jsxs("span",{children:[Ae(s,`l${a}`),a<e.length-1&&r.jsx("br",{})]},a))}const De=i.memo(function({role:e,content:s,sources:a,onSourceClick:n,isSourceActive:o}){const c=e==="user";return r.jsxs("div",{className:`${c?"ml-auto":"mr-auto"} max-w-[85%]`,children:[r.jsx("div",{className:`rounded-claudius-bubble px-4 py-2.5 text-sm leading-relaxed font-body ${c?"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:Ie(s)}),!c&&a&&a.length>0&&n&&r.jsx("div",{className:"mt-1",children:r.jsx(Ne,{count:a.length,isActive:o??!1,onClick:n})})]})}),G=2e3,He=1800;function _e({onSend:t,isLoading:e,placeholder:s,translations:a}){const[n,o]=i.useState(""),c=i.useRef(null),d=n.length,u=d>=He,l=d>=G,f=s??(a==null?void 0:a.placeholder)??"Type your message...",E=(a==null?void 0:a.sendMessage)??"Send message",x=(a==null?void 0:a.typeYourMessage)??"Type your message";i.useEffect(()=>{var w;e||(w=c.current)==null||w.focus()},[e]);const b=w=>{w.preventDefault();const v=n.trim();!v||l||(t(v),o(""))},h=w=>{const v=w.target.value;v.length<=G&&o(v)};return r.jsxs("form",{onSubmit:b,className:"border-t border-claudius-border bg-claudius-surface p-3",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{ref:c,type:"text",value:n,onChange:h,placeholder:f,disabled:e,"aria-label":x,"aria-describedby":u?"char-count":void 0,className:"flex-1 rounded-claudius-sm border border-claudius-border bg-claudius-field px-3 py-2 text-sm font-body text-claudius-text placeholder:text-claudius-text-muted focus:border-claudius-accent focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50"}),r.jsx("button",{type:"submit",disabled:e||l,"aria-label":E,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:r.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:[r.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),r.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),u&&r.jsxs("div",{id:"char-count",className:`mt-1 text-xs text-right ${l?"text-claudius-error":"text-claudius-text-muted"}`,"aria-live":"polite",children:[d,"/",G]})]})}const $e=["blog","page","external"],Ue={blog:"Blog",page:"Page",external:"External"};function Be(t){try{return new URL(t).hostname}catch{return t}}const Ge=i.memo(function({sources:e,onClose:s}){const a=$e.map(o=>({type:o,label:Ue[o],items:e.filter(c=>c.type===o)})).filter(o=>o.items.length>0),n=e.length===1?"1 source found":`${e.length} sources found`;return r.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:[r.jsxs("div",{className:"flex items-center justify-between border-b border-claudius-border px-4 py-3",children:[r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-heading font-semibold text-claudius-text",children:"Sources"}),r.jsx("p",{className:"text-xs text-claudius-text-muted",children:n})]}),r.jsx("button",{onClick:s,"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:r.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:[r.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),r.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-4",children:a.map(o=>r.jsxs("div",{children:[r.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-claudius-text-muted",children:o.label}),r.jsx("div",{className:"space-y-2",children:o.items.map(c=>{const d=se(c.url);return d?r.jsxs("a",{href:d,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:[r.jsx("p",{className:"truncate text-sm font-medium text-claudius-text",children:c.title}),r.jsx("p",{className:"mt-0.5 text-xs text-claudius-text-muted",children:Be(d)})]},d):null})})]},o.type))})]})});function Pe({title:t,subtitle:e,titleId:s,closeLabel:a,onClose:n}){return r.jsxs("div",{className:"flex items-center gap-3 bg-claudius-accent px-5 py-4",children:[r.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:t.charAt(0).toUpperCase()}),r.jsxs("div",{className:"flex-1",children:[r.jsx("h2",{id:s,className:"text-sm font-heading font-semibold text-claudius-accent-text",children:t}),r.jsx("p",{className:"text-xs text-claudius-accent-text",children:e})]}),r.jsx("button",{onClick:n,"aria-label":a,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:r.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:[r.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),r.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}function We({message:t,retryLabel:e,onRetry:s}){return r.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:[r.jsx("span",{children:t}),s&&r.jsx("button",{type:"button",onClick:s,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:e})]})}function Fe({label:t}){return r.jsx("div",{role:"status","aria-live":"polite","aria-label":t,className:"mr-auto flex max-w-[85%]",children:r.jsxs("div",{className:"flex gap-1 rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-3",children:[r.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:0ms]"}),r.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:150ms]"}),r.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:300ms]"})]})})}function Ye(t,e,s){const[a,n]=i.useState(0),o=i.useRef(0),c=i.useRef(0),d=i.useRef(0),u=i.useRef(!1);return i.useEffect(()=>{const l=t.current;if(!s||!l)return;const f=b=>{if(l.scrollTop>0){u.current=!1;return}u.current=!0,c.current=b.touches[0].clientY,d.current=Date.now()},E=b=>{if(!u.current)return;let h=b.touches[0].clientY-c.current;h<0&&(h=h*.3),o.current=h,n(h)},x=()=>{if(!u.current)return;u.current=!1;const b=o.current,h=(Date.now()-d.current)/1e3,w=l.getBoundingClientRect().height,v=h>.05&&b>0&&b/h>500,y=b>w*.3;v||y?e():(o.current=0,n(0))};return l.addEventListener("touchstart",f,{passive:!0}),l.addEventListener("touchmove",E,{passive:!0}),l.addEventListener("touchend",x),()=>{l.removeEventListener("touchstart",f),l.removeEventListener("touchmove",E),l.removeEventListener("touchend",x)}},[t,e,s]),{offsetY:a}}const ze='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Ve(t,e){i.useEffect(()=>{const s=t.current;if(!s)return;const a=n=>{if(n.key!=="Tab")return;const o=Array.from(s.querySelectorAll(ze)).filter(l=>!l.hasAttribute("aria-hidden"));if(o.length===0)return;const c=o[0],d=o[o.length-1],u=document.activeElement;n.shiftKey&&u===c?(n.preventDefault(),d.focus()):!n.shiftKey&&u===d&&(n.preventDefault(),c.focus())};return s.addEventListener("keydown",a),()=>s.removeEventListener("keydown",a)},[t,e])}const Ke=/\*\*([^*]+)\*\*/g,qe=/\*([^*]+)\*/g,Xe=/https?:\/\/[^\s)]+/g;function Je(t){return t.replace(Ke,"$1").replace(qe,"$1").replace(Xe,e=>{try{return new URL(e).hostname}catch{return e}})}const Ze={"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 Qe({messages:t,isLoading:e,error:s,canRetry:a=!1,onSend:n,onRetry:o,onClose:c,title:d="Chat",subtitle:u="Ask me anything",welcomeMessage:l="Hi! How can I help you today?",placeholder:f,position:E="bottom-right",translations:x,isMobile:b=!1}){const h=i.useId(),w=i.useRef(null),v=i.useRef(null),[y,R]=i.useState(null);Ve(w,!0);const{offsetY:M}=Ye(v,c,b),S=M!==0,k=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1;i.useEffect(()=>{const g=v.current;g&&(g.scrollTop=g.scrollHeight)},[t,e]),i.useEffect(()=>{const g=I=>{I.key==="Escape"&&!I.isComposing&&c()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[c]);const j=(x==null?void 0:x.closeChat)??"Close chat",N=(x==null?void 0:x.chatMessages)??"Chat messages",A=[...t].reverse().find(g=>g.role==="assistant");return r.jsxs("div",{ref:w,role:"dialog","aria-modal":b?"true":void 0,"aria-labelledby":h,className:b?"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 ${Ze[E]} 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:b&&!k?{transform:`translateY(${Math.max(0,M)}px)`}:void 0,"data-dragging":S||void 0,children:[b&&r.jsx("div",{className:"flex justify-center py-2","aria-hidden":"true",children:r.jsx("div",{className:"h-1 w-8 rounded-claudius-full bg-claudius-border"})}),r.jsx(Pe,{title:d,subtitle:u,titleId:h,closeLabel:j,onClose:c}),r.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[y&&r.jsx(Ge,{sources:y.sources,onClose:()=>R(null)}),r.jsxs("div",{ref:v,role:"log","aria-label":N,className:"h-full space-y-3 overflow-y-auto px-4 py-4",children:[t.length===0&&!s&&r.jsx("div",{className:"mr-auto flex max-w-[85%]",children:r.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:l})}),t.map(g=>r.jsx(De,{role:g.role,content:g.content,sources:g.sources,isSourceActive:(y==null?void 0:y.messageId)===g.id,onSourceClick:()=>{(y==null?void 0:y.messageId)===g.id?R(null):g.sources&&g.sources.length>0&&R({messageId:g.id,sources:g.sources})}},g.id)),e&&r.jsx(Fe,{label:(x==null?void 0:x.typingIndicator)??"Assistant is typing"}),s&&r.jsx(We,{message:s,retryLabel:(x==null?void 0:x.errorRetry)??"Retry",onRetry:a&&o&&!e?o:void 0})]})]}),r.jsx("div",{"data-claudius-live":"assistant","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:A?Je(A.content):""}),r.jsx(_e,{onSend:n,isLoading:e,placeholder:f,translations:x})]})}function et({message:t,position:e,onOpen:s,onDismiss:a,dismissLabel:n}){const o=e.startsWith("bottom"),c=e.endsWith("right"),d=["claudius-greeting-bubble","fixed z-40 max-w-xs",o?"bottom-20":"top-20",c?"right-4":"left-4"].join(" ");return r.jsxs("div",{className:d,role:"status","aria-live":"polite",children:[r.jsx("button",{type:"button",onClick:s,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:t}),r.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a()},"aria-label":n,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:r.jsx("span",{"aria-hidden":"true",children:"×"})})]})}const re={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",typeYourMessage:"Type your message",openChat:"Open chat",dismissGreeting:"Dismiss greeting",errorGeneric:"Something went wrong. Please try again.",errorConnection:"Failed to connect. Please try again.",errorTimeout:"Request timed out. Please try again.",errorRateLimitMinute:"Too many requests. Please wait a minute.",errorRateLimitHour:"Hourly limit reached. Please try again later.",errorRetry:"Retry"},ne=re;function tt(t){return{...ne,...t}}const st={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",typeYourMessage:"Escribe tu mensaje",openChat:"Abrir chat",dismissGreeting:"Descartar saludo",errorGeneric:"Algo salió mal. Inténtalo de nuevo.",errorConnection:"No se pudo conectar. Inténtalo de nuevo.",errorTimeout:"La solicitud tardó demasiado. Inténtalo de nuevo.",errorRateLimitMinute:"Demasiadas solicitudes. Espera un minuto.",errorRateLimitHour:"Has alcanzado el límite por hora. Inténtalo más tarde.",errorRetry:"Reintentar"},rt={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",typeYourMessage:"Saisissez votre message",openChat:"Ouvrir le chat",dismissGreeting:"Ignorer le message d'accueil",errorGeneric:"Une erreur s'est produite. Veuillez réessayer.",errorConnection:"Échec de la connexion. Veuillez réessayer.",errorTimeout:"La requête a expiré. Veuillez réessayer.",errorRateLimitMinute:"Trop de requêtes. Veuillez patienter une minute.",errorRateLimitHour:"Limite horaire atteinte. Veuillez réessayer plus tard.",errorRetry:"Réessayer"},nt={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",typeYourMessage:"Geben Sie Ihre Nachricht ein",openChat:"Chat öffnen",dismissGreeting:"Begrüßung schließen",errorGeneric:"Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.",errorConnection:"Verbindung fehlgeschlagen. Bitte versuchen Sie es erneut.",errorTimeout:"Zeitüberschreitung der Anfrage. Bitte versuchen Sie es erneut.",errorRateLimitMinute:"Zu viele Anfragen. Bitte warten Sie eine Minute.",errorRateLimitHour:"Stündliches Limit erreicht. Bitte versuchen Sie es später erneut.",errorRetry:"Erneut versuchen"},F={en:re,es:st,fr:rt,de:nt};function Q(t){if(!t)return;const e=t.toLowerCase().split("-")[0];return Object.prototype.hasOwnProperty.call(F,e)?e:void 0}function ae(){const t=typeof document<"u"?Q(document.documentElement.lang):void 0;if(t)return t;const e=typeof navigator<"u"?Q(navigator.language):void 0;return e||"en"}function oe(t={}){const{locale:e,translations:s}=t,a=F[e??ae()];return s?{...a,...s}:{...a}}const ee=["accent","accentText","accentSoft","accentTextMuted","surface","surfaceMuted","text","textMuted","border","userBubble","userBubbleText","assistantBubble","assistantBubbleText","field","error","errorSurface","errorText","link","scrim"],at=["sm","md","lg","full","tail"],ot=["elevated","floating","floatingHover"],it=["heading","body"],Y={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 ct(t){return Object.prototype.hasOwnProperty.call(Y,t)}const ut=new Set(["light","dark","auto"]);function lt(t){if(t===void 0)return{mode:"light"};if(typeof t=="string"){if(ut.has(t))return{mode:t};if(ct(t)){const e=Y[t];return{mode:e.colorScheme??"light",theme:e}}return{mode:"light",url:t}}return{mode:t.colorScheme??"light",theme:t}}function dt(t){return t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function ft(t,e){console.warn(`[Claudius] Ignoring unknown theme token "${e}" in "${t}"`)}function H(t,e,s,a,n,o=""){if(n)for(const[c,d]of Object.entries(n)){if(!a.includes(c)){ft(e,c);continue}typeof d=="string"&&(t[`${s}${dt(c)}${o}`]=d)}}function ht(t){const e={};H(e,"colors","--cl-color-",ee,t.colors);for(const[s,a]of Object.entries({...e}))e[`${s}-dark`]=a;return H(e,"colorsDark","--cl-color-",ee,t.colorsDark,"-dark"),H(e,"radii","--cl-radius-",at,t.radii),H(e,"shadows","--cl-shadow-",ot,t.shadows),H(e,"fonts","--cl-font-",it,t.fonts),e}function mt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xt(t){const e=i.useMemo(()=>lt(t),[t]),[s,a]=i.useState(null),n=e.url;i.useEffect(()=>{if(a(null),!n)return;const u=new AbortController;return fetch(n,{signal:u.signal}).then(l=>{if(!l.ok)throw new Error(`HTTP ${l.status}`);return l.json()}).then(l=>{if(!mt(l))throw new Error("theme JSON must be an object");a(l)}).catch(l=>{u.signal.aborted||console.error(`[Claudius] Failed to load theme from ${n}:`,l)}),()=>u.abort()},[n]);const o=e.theme??s??null,c=(s==null?void 0:s.colorScheme)??e.mode,d=i.useMemo(()=>o?ht(o):{},[o]);return{mode:c,cssVars:d}}const ie="claudius:triggers:dismissed";function gt(){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(ie)==="1"}catch{return!1}}function bt(){if(!(typeof window>"u"))try{window.sessionStorage.setItem(ie,"1")}catch{}}function pt({apiUrl:t,title:e,subtitle:s,welcomeMessage:a,placeholder:n,persistMessages:o,storageKeyPrefix:c,requestTimeoutMs:d,theme:u="light",accentColor:l,position:f="bottom-right",locale:E,translations:x,triggers:b}){const[h,w]=i.useState(!1),[v,y]=i.useState(null),[R,M]=i.useState(gt),S=i.useRef(!1),k=Te("(max-width: 639px)"),j=i.useMemo(()=>oe({locale:E,translations:x}),[E,x]),{messages:N,isLoading:A,error:g,canRetry:I,sendMessage:m,retry:p}=je({apiUrl:t,persistMessages:o,storageKeyPrefix:c,timeoutMs:d,translations:j}),L=i.useRef(null),T=i.useRef(h),{mode:_,cssVars:ce}=xt(u),[ue,z]=i.useState(!1);i.useEffect(()=>{if(_!=="auto")return;const C=window.matchMedia("(prefers-color-scheme: dark)");z(C.matches);const q=ge=>z(ge.matches);return C.addEventListener("change",q),()=>C.removeEventListener("change",q)},[_]),i.useEffect(()=>{var C;T.current&&!h&&((C=L.current)==null||C.focus()),T.current=h},[h]);const $=i.useCallback(()=>{M(!0),bt()},[]),V=i.useCallback(()=>{w(!1),S.current&&(S.current=!1,$())},[$]),le=i.useCallback(()=>{w(C=>!C)},[]),B=i.useCallback(()=>{S.current=!0,y(null),w(!0)},[]),de=i.useCallback(C=>{y(C)},[]),fe=i.useCallback(()=>{y(null),B()},[B]),he=i.useCallback(()=>{y(null),$()},[$]);Me({triggers:b,enabled:!R&&!h,onOpen:B,onGreeting:de});const me=_==="dark"||_==="auto"&&ue,K={...ce,...l?{"--cl-color-accent":l,"--cl-color-accent-dark":l}:{}},xe=Object.keys(K).length>0?K:void 0;return r.jsx("div",{className:"claudius-root",style:xe,children:r.jsxs("div",{"data-claudius-dark":me?"true":"false",children:[h&&k&&r.jsx("div",{className:"claudius-scrim fixed inset-0 z-40 bg-claudius-scrim",onClick:V,"aria-hidden":"true"}),h&&r.jsx(Qe,{messages:N,isLoading:A,error:g,canRetry:I,onSend:m,onRetry:p,onClose:V,title:e??j.title,subtitle:s??j.subtitle,welcomeMessage:a??j.welcomeMessage,placeholder:n??j.placeholder,position:f,translations:j,isMobile:k}),!(h&&k)&&r.jsx(ke,{ref:L,isOpen:h,onClick:le,position:f,translations:j}),!h&&v&&r.jsx(et,{message:v,position:f,onOpen:fe,onDismiss:he,dismissLabel:j.dismissGreeting})]})})}exports.ChatApiClient=te;exports.ChatApiError=O;exports.ChatWidget=pt;exports.DebounceError=W;exports.builtinThemes=Y;exports.createTranslations=tt;exports.defaultTranslations=ne;exports.detectLocale=ae;exports.locales=F;exports.resolveTranslations=oe;
|