@aikaara/chat-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,502 @@
1
+ var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o,h,p)=>h in o?te(o,h,{enumerable:!0,configurable:!0,writable:!0,value:p}):o[h]=p;var a=(o,h,p)=>se(o,typeof h!="symbol"?h+"":h,p);class h{constructor(t,e){a(this,"identifier");a(this,"callbacks",{});a(this,"sendFn");this.identifier=t,this.sendFn=e}onReceived(t){return this.callbacks.received=t,this}onConnected(t){return this.callbacks.connected=t,this}onDisconnected(t){return this.callbacks.disconnected=t,this}onRejected(t){return this.callbacks.rejected=t,this}perform(t,e={}){this.sendFn({action:t,...e})}_notifyReceived(t){var e,s;(s=(e=this.callbacks).received)==null||s.call(e,t)}_notifyConnected(){var t,e;(e=(t=this.callbacks).connected)==null||e.call(t)}_notifyDisconnected(){var t,e;(e=(t=this.callbacks).disconnected)==null||e.call(t)}_notifyRejected(){var t,e;(e=(t=this.callbacks).rejected)==null||e.call(t)}}class p{constructor(t){a(this,"ws",null);a(this,"url");a(this,"subscriptions",new Map);a(this,"welcomePromise",null);a(this,"pendingSubscriptions",new Map);this.url=t}connect(){return new Promise((t,e)=>{this.welcomePromise={resolve:t,reject:e},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=s=>{this.handleMessage(s)},this.ws.onerror=()=>{var i;const s=new Error("WebSocket connection error");(i=this.welcomePromise)==null||i.reject(s),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(s=>s._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(t=>t._notifyDisconnected()),this.subscriptions.clear()}subscribe(t){const e=JSON.stringify(t),s=new h(e,i=>{this.send({command:"message",identifier:e,data:JSON.stringify(i)})});return this.subscriptions.set(e,s),this.send({command:"subscribe",identifier:e}),s}subscribeAsync(t){const e=this.subscribe(t),s=e.identifier;return new Promise((i,n)=>{this.pendingSubscriptions.set(s,{resolve:()=>i(e),reject:n}),setTimeout(()=>{this.pendingSubscriptions.has(s)&&(this.pendingSubscriptions.delete(s),n(new Error(`Subscription timeout for ${s}`)))},1e4)})}unsubscribe(t){this.send({command:"unsubscribe",identifier:t}),this.subscriptions.delete(t)}perform(t,e,s={}){this.send({command:"message",identifier:t,data:JSON.stringify({action:e,...s})})}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}handleMessage(t){var s;let e;try{e=JSON.parse(t.data)}catch{return}switch(e.type){case"welcome":(s=this.welcomePromise)==null||s.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const i=e.identifier,n=this.subscriptions.get(i);n==null||n._notifyConnected();const c=this.pendingSubscriptions.get(i);c&&(c.resolve(),this.pendingSubscriptions.delete(i));break}case"reject_subscription":{const i=e.identifier,n=this.subscriptions.get(i);n==null||n._notifyRejected(),this.subscriptions.delete(i);const c=this.pendingSubscriptions.get(i);c&&(c.reject(new Error(`Subscription rejected: ${i}`)),this.pendingSubscriptions.delete(i));break}case"disconnect":this.subscriptions.forEach(i=>i._notifyDisconnected());break;default:{if(e.identifier&&e.message!==void 0){const i=this.subscriptions.get(e.identifier);i==null||i._notifyReceived(e.message)}break}}}}class y{constructor(){a(this,"handlers",new Map)}on(t,e){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.handlers.get(t))==null||s.delete(e)}emit(t,e){var s;(s=this.handlers.get(t))==null||s.forEach(i=>{try{i(e)}catch(n){console.error(`Error in event handler for "${t}":`,n)}})}removeAllListeners(){this.handlers.clear()}}const N=1e3,q=10,P=400,R=600,x="#6366f1",j=12,W="system-ui, -apple-system, sans-serif",S="Type a message...",K="bottom-right",J="light",Y={x:20,y:20},k="aikaara_conversation_id";class _ extends y{constructor(e){super();a(this,"client");a(this,"config");a(this,"state","disconnected");a(this,"reconnectAttempt",0);a(this,"reconnectTimer",null);this.config=e;const s=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new p(s)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,s){const i=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(i,"send_message",{content:s})}sendUserEvent(e,s,i,n){const c=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(c,"send_user_event",{event_key:s,...i&&{value:i},...n&&{source:n}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??q;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const i=(this.config.reconnectInterval??N)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const n=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new p(n),await this.connect()}catch{}},i)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,s){return`${e.replace(/^http/,"ws")}/cable?token=${s}`}}class C{constructor(t,e,s){a(this,"baseUrl");a(this,"apiKey");a(this,"userToken");this.baseUrl=t,this.userToken=e,this.apiKey=s}async createConversation(t){const e={conversation:{...t.systemPromptId&&{system_prompt_id:t.systemPromptId},...t.channel&&{channel:t.channel},...t.title&&{title:t.title}}};return this.request("POST","/api/v1/conversations",e)}async getMessages(t){return(await this.request("GET",`/api/v1/conversations/${t}/messages`)).map(this.mapMessage)}mapMessage(t){var e;return{id:String(t.id),conversationId:String(t.conversation_id),role:t.role,content:t.content||"",toolCalls:(e=t.tool_calls)==null?void 0:e.map(s=>({id:s.id,type:s.type,function:s.function})),toolCallResults:t.tool_call_results,tokensInput:t.tokens_input,tokensOutput:t.tokens_output,metadata:t.metadata,createdAt:t.created_at,status:"complete"}}async request(t,e,s){const i={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(i["X-Api-Key"]=this.apiKey);const n=`${this.baseUrl}${e}`,c={method:t,headers:i};s&&(c.body=JSON.stringify(s));const d=await fetch(n,c);if(!d.ok){const g=await d.text();let b;try{const v=JSON.parse(g);b=v.error||v.message||g}catch{b=g}throw new Error(`API error ${d.status}: ${b}`)}return d.json()}}class T{constructor(){a(this,"_messages",[]);a(this,"optimisticCounter",0)}get messages(){return[...this._messages]}addOptimistic(t,e,s){const i={id:`optimistic_${++this.optimisticCounter}`,conversationId:s,role:t,content:e,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(i),i}confirmOptimistic(t){const e=this._messages.find(s=>s.id===t);e&&(e.status="sent")}addStreamingMessage(t){const e={id:`streaming_${Date.now()}`,conversationId:t,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(e),e}updateStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");e&&(e.content=t)}finalizeStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");return e&&(e.status="complete",t&&(e.tokensInput=t.tokensInput,e.tokensOutput=t.tokensOutput)),e}addMessage(t){this._messages.push(t)}setMessages(t){this._messages=[...t]}clear(){this._messages=[]}}class M{constructor(t,e=!0){a(this,"_conversationId");a(this,"persist");this.persist=e,this._conversationId=t||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(t){this._conversationId=t,this.persist&&t&&this.saveToStorage(t)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(k)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(k)}catch{return null}}saveToStorage(t){try{localStorage.setItem(k,t)}catch{}}}class A extends y{constructor(e){super();a(this,"connection");a(this,"api");a(this,"messageStore");a(this,"conversationManager");a(this,"subscription",null);a(this,"config");this.config=e,this.connection=new _(e),this.api=new C(e.baseUrl,e.userToken,e.apiKey),this.messageStore=new T,this.conversationManager=new M(e.conversationId),this.connection.on("connection:state",s=>{var i,n;this.emit("connection:state",s),(n=(i=this.config).onConnectionStateChange)==null||n.call(i,s)}),this.connection.on("error",s=>{var i,n;this.emit("error",s),(n=(i=this.config).onError)==null||n.call(i,s)})}async connect(){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget"});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}async sendMessage(e){var n,c;const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const i=this.messageStore.addOptimistic("user",e,s);this.emit("message:sent",i),(c=(n=this.config).onMessage)==null||c.call(n,i),this.connection.sendMessage(s,e)}async sendUserEvent(e,s,i){const n=this.conversationManager.conversationId;if(!n)throw new Error("No active conversation");this.connection.sendUserEvent(n,e,s,i)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const s=await this.api.getMessages(e);return this.messageStore.setMessages(s),s}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){return this.connection.connectionState==="connected"}async disconnect(){this.subscription&&(this.subscription=null),await this.connection.disconnect()}handleBroadcast(e){var i,n,c,d,g,b,v,D;const s=this.conversationManager.conversationId;switch(e.type){case"status":{const l=e.status;this.emit("status",l),(n=(i=this.config).onStatusChange)==null||n.call(i,l),l==="processing"&&this.emit("typing:start",void 0);break}case"error":{const l=new Error(e.message||"Unknown error");this.emit("error",l),(d=(c=this.config).onError)==null||d.call(c,l);break}case"message_start":{if(e.role==="assistant"){const l=this.messageStore.addStreamingMessage(s);this.emit("stream:start",{messageId:l.id}),this.emit("typing:start",void 0)}break}case"message_update":{const l=e.content||"",u=e.delta||"";this.messageStore.updateStreaming(l),this.emit("stream:update",{delta:u,content:l}),(b=(g=this.config).onStreamUpdate)==null||b.call(g,u,l);break}case"message_end":{const l=e.usage,u=this.messageStore.finalizeStreaming(l?{tokensInput:l.tokens_input||0,tokensOutput:l.tokens_output||0}:void 0);this.emit("typing:stop",void 0),u&&(this.emit("stream:end",{messageId:u.id,usage:l?{tokensInput:l.tokens_input||0,tokensOutput:l.tokens_output||0}:void 0}),this.emit("message:received",u),(D=(v=this.config).onMessage)==null||D.call(v,u));break}case"message_queued":{const l=this.messageStore.messages.findLast(u=>u.status==="sending");l&&this.messageStore.confirmOptimistic(l.id);break}case"tool_execution_start":case"tool_execution_update":case"tool_execution_end":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class G{constructor(t,e){a(this,"client");a(this,"panel");a(this,"bubble");a(this,"header");a(this,"messageList");a(this,"input");a(this,"errorBanner");a(this,"isOpen",!1);this.client=new A(t),this.bubble=e.querySelector("aikaara-chat-bubble"),this.panel=e.querySelector(".aikaara-panel"),this.header=e.querySelector("aikaara-chat-header"),this.messageList=e.querySelector("aikaara-message-list"),this.input=e.querySelector("aikaara-chat-input"),this.errorBanner=e.querySelector("aikaara-error-banner"),t.welcomeMessage&&this.messageList.setWelcomeMessage(t.welcomeMessage),t.showTimestamps!==void 0&&this.messageList.setShowTimestamps(t.showTimestamps),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble.addEventListener("toggle",()=>{this.togglePanel()}),this.header.addEventListener("close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(t=>{this.handleSend(t.detail.content)})),this.client.on("message:sent",t=>{this.messageList.addMessage(t)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const t=this.client.messages[this.client.messages.length-1];t&&this.messageList.addMessage(t)}),this.client.on("stream:update",({content:t})=>{this.messageList.updateStreamingContent(t)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const t=this.client.messages,e=t[t.length-1];(!e||e.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",t=>{this.header.setStatus(t),t==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):t==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):t==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",t=>{this.errorBanner.show(t.message,5e3)})}async handleSend(t){try{await this.client.sendMessage(t)}catch{this.errorBanner.show("Failed to send message",3e3)}}togglePanel(t){this.isOpen=t!==void 0?t:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200))}}class E extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"controller",null);a(this,"_config",{});this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["base-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url"]}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){var e;(e=this.controller)==null||e.disconnect()}attributeChangedCallback(e,s,i){s!==i&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||J,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||x,position:this.getAttribute("position")||this._config.position||K,width:Number(this.getAttribute("width"))||this._config.width||P,height:Number(this.getAttribute("height"))||this._config.height||R,fontFamily:this._config.fontFamily||W,borderRadius:this._config.borderRadius??j,placeholder:this.getAttribute("placeholder")||this._config.placeholder||S,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showBubble:this._config.showBubble??!0,offset:this._config.offset||Y,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange}}render(){var s,i;const e=this.getConfig();this.shadow.innerHTML=`
2
+ <style>
3
+ :host {
4
+ --aikaara-primary: ${e.primaryColor};
5
+ --aikaara-primary-hover: ${this.darkenColor(e.primaryColor||x)};
6
+ --aikaara-bg: #ffffff;
7
+ --aikaara-bg-secondary: #f9fafb;
8
+ --aikaara-text: #1f2937;
9
+ --aikaara-text-secondary: #6b7280;
10
+ --aikaara-border: #e5e7eb;
11
+ --aikaara-radius: ${e.borderRadius}px;
12
+ --aikaara-font: ${e.fontFamily};
13
+ --aikaara-panel-width: ${e.width}px;
14
+ --aikaara-panel-height: ${e.height}px;
15
+ --aikaara-bubble-size: 60px;
16
+ --aikaara-offset-x: ${((s=e.offset)==null?void 0:s.x)??20}px;
17
+ --aikaara-offset-y: ${((i=e.offset)==null?void 0:i.y)??20}px;
18
+ font-family: var(--aikaara-font);
19
+ position: fixed;
20
+ z-index: 9999;
21
+ bottom: var(--aikaara-offset-y);
22
+ ${e.position==="bottom-left"?"left":"right"}: var(--aikaara-offset-x);
23
+ }
24
+
25
+ .aikaara-panel {
26
+ width: var(--aikaara-panel-width);
27
+ height: var(--aikaara-panel-height);
28
+ max-height: calc(100vh - 100px);
29
+ background: var(--aikaara-bg);
30
+ border-radius: var(--aikaara-radius);
31
+ box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12);
32
+ border: 1px solid var(--aikaara-border);
33
+ display: flex;
34
+ flex-direction: column;
35
+ overflow: hidden;
36
+ position: absolute;
37
+ bottom: calc(var(--aikaara-bubble-size) + 16px);
38
+ ${e.position==="bottom-left"?"left":"right"}: 0;
39
+ transition: opacity 200ms ease, transform 200ms ease;
40
+ }
41
+
42
+ .aikaara-panel[hidden] {
43
+ display: none;
44
+ }
45
+
46
+ .aikaara-panel.entering {
47
+ opacity: 0;
48
+ transform: translateY(8px) scale(0.98);
49
+ }
50
+
51
+ .aikaara-panel.visible {
52
+ opacity: 1;
53
+ transform: translateY(0) scale(1);
54
+ }
55
+ </style>
56
+
57
+ <aikaara-chat-bubble></aikaara-chat-bubble>
58
+
59
+ <div class="aikaara-panel entering" hidden role="dialog" aria-label="Chat">
60
+ <aikaara-chat-header
61
+ title="${e.title||"Chat"}"
62
+ ${e.subtitle?`subtitle="${e.subtitle}"`:""}
63
+ ${e.avatarUrl?`avatar-url="${e.avatarUrl}"`:""}
64
+ ></aikaara-chat-header>
65
+ <aikaara-message-list></aikaara-message-list>
66
+ <aikaara-chat-input placeholder="${e.placeholder||S}"></aikaara-chat-input>
67
+ <aikaara-error-banner></aikaara-error-banner>
68
+ </div>
69
+ `}async initController(){var s;const e=this.getConfig();!e.baseUrl||!e.userToken||((s=this.controller)==null||s.disconnect(),this.controller=new G(e,this.shadow),await this.controller.connect())}darkenColor(e){try{const s=parseInt(e.replace("#",""),16),i=Math.max(0,(s>>16)-20),n=Math.max(0,(s>>8&255)-20),c=Math.max(0,(s&255)-20);return`#${(i<<16|n<<8|c).toString(16).padStart(6,"0")}`}catch{return e}}}class L extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){var e;this.render(),(e=this.shadow.querySelector(".bubble"))==null||e.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("toggle",{bubbles:!0,composed:!0}))})}render(){this.shadow.innerHTML=`
70
+ <style>
71
+ .bubble {
72
+ width: var(--aikaara-bubble-size, 60px);
73
+ height: var(--aikaara-bubble-size, 60px);
74
+ border-radius: 50%;
75
+ background: var(--aikaara-primary, #6366f1);
76
+ color: #ffffff;
77
+ border: none;
78
+ cursor: pointer;
79
+ display: flex;
80
+ align-items: center;
81
+ justify-content: center;
82
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
83
+ transition: transform 200ms ease, box-shadow 200ms ease;
84
+ }
85
+ .bubble:hover {
86
+ transform: scale(1.05);
87
+ box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
88
+ }
89
+ .bubble svg {
90
+ width: 28px;
91
+ height: 28px;
92
+ }
93
+ .bubble-text {
94
+ font-family: var(--aikaara-font, system-ui, sans-serif);
95
+ font-size: 12px;
96
+ font-weight: 500;
97
+ }
98
+ </style>
99
+ <button class="bubble" aria-label="Open chat">
100
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
101
+ <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
102
+ </svg>
103
+ </button>
104
+ `}setIcon(e){const s=this.shadow.querySelector(".bubble");s&&(s.innerHTML=e)}}class I extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["title","subtitle","avatar-url","status"]}connectedCallback(){var e;this.render(),(e=this.shadow.querySelector(".close-btn"))==null||e.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("close",{bubbles:!0,composed:!0}))})}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("title")||"Chat",s=this.getAttribute("subtitle")||"",i=this.getAttribute("avatar-url"),n=this.getAttribute("status")||"connected",c=n==="connected"?"#10b981":n==="connecting"||n==="reconnecting"?"#f59e0b":"#ef4444";this.shadow.innerHTML=`
105
+ <style>
106
+ .header {
107
+ display: flex;
108
+ align-items: center;
109
+ gap: 12px;
110
+ padding: 14px 16px;
111
+ background: var(--aikaara-primary, #6366f1);
112
+ color: #ffffff;
113
+ flex-shrink: 0;
114
+ }
115
+ .avatar {
116
+ width: 36px;
117
+ height: 36px;
118
+ border-radius: 50%;
119
+ background: rgba(255,255,255,0.2);
120
+ display: flex;
121
+ align-items: center;
122
+ justify-content: center;
123
+ flex-shrink: 0;
124
+ overflow: hidden;
125
+ }
126
+ .avatar img {
127
+ width: 100%;
128
+ height: 100%;
129
+ object-fit: cover;
130
+ }
131
+ .avatar svg {
132
+ width: 20px;
133
+ height: 20px;
134
+ }
135
+ .info {
136
+ flex: 1;
137
+ min-width: 0;
138
+ }
139
+ .title {
140
+ font-size: 15px;
141
+ font-weight: 600;
142
+ line-height: 1.2;
143
+ display: flex;
144
+ align-items: center;
145
+ gap: 6px;
146
+ }
147
+ .status-dot {
148
+ width: 8px;
149
+ height: 8px;
150
+ border-radius: 50%;
151
+ flex-shrink: 0;
152
+ }
153
+ .subtitle {
154
+ font-size: 12px;
155
+ opacity: 0.85;
156
+ white-space: nowrap;
157
+ overflow: hidden;
158
+ text-overflow: ellipsis;
159
+ }
160
+ .close-btn {
161
+ background: none;
162
+ border: none;
163
+ color: #ffffff;
164
+ cursor: pointer;
165
+ padding: 4px;
166
+ border-radius: 4px;
167
+ display: flex;
168
+ align-items: center;
169
+ justify-content: center;
170
+ opacity: 0.8;
171
+ transition: opacity 200ms;
172
+ }
173
+ .close-btn:hover {
174
+ opacity: 1;
175
+ }
176
+ .close-btn svg {
177
+ width: 20px;
178
+ height: 20px;
179
+ }
180
+ </style>
181
+ <div class="header">
182
+ <div class="avatar">
183
+ ${i?`<img src="${i}" alt="Avatar" />`:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>'}
184
+ </div>
185
+ <div class="info">
186
+ <div class="title">
187
+ ${e}
188
+ <span class="status-dot" style="background:${c}"></span>
189
+ </div>
190
+ ${s?`<div class="subtitle">${s}</div>`:""}
191
+ </div>
192
+ <button class="close-btn" aria-label="Close chat">
193
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
194
+ <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
195
+ </svg>
196
+ </button>
197
+ </div>
198
+ `}setStatus(e){this.setAttribute("status",e)}}function m(r){let t=V(r);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(e,s,i)=>`<pre><code>${i.trim()}</code></pre>`),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),t=t.replace(/\n/g,"<br>"),t}function V(r){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return r.replace(/[&<>"']/g,e=>t[e])}const X=new Set(["p","br","strong","em","code","pre","a","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div"]),Q={a:new Set(["href","target","rel"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function f(r){const t=document.createElement("template");return t.innerHTML=r,$(t.content),t.innerHTML}function $(r){const t=Array.from(r.childNodes);for(const e of t)if(e.nodeType===Node.ELEMENT_NODE){const s=e,i=s.tagName.toLowerCase();if(!X.has(i)){const d=document.createTextNode(s.textContent||"");r.replaceChild(d,e);continue}const n=Q[i]||new Set,c=Array.from(s.attributes);for(const d of c)n.has(d.name)||s.removeAttribute(d.name);if(s.hasAttribute("href")){const d=s.getAttribute("href")||"";!d.startsWith("http://")&&!d.startsWith("https://")&&!d.startsWith("/")&&s.removeAttribute("href")}$(e)}}class O extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"container");a(this,"welcomeMessage","");a(this,"showTimestamps",!0);this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
199
+ <style>
200
+ .message-list {
201
+ flex: 1;
202
+ overflow-y: auto;
203
+ padding: 16px;
204
+ display: flex;
205
+ flex-direction: column;
206
+ gap: 8px;
207
+ scroll-behavior: smooth;
208
+ }
209
+ .message-list::-webkit-scrollbar { width: 6px; }
210
+ .message-list::-webkit-scrollbar-track { background: transparent; }
211
+ .message-list::-webkit-scrollbar-thumb { background: var(--aikaara-border, #e5e7eb); border-radius: 3px; }
212
+ .message-wrap { display: flex; flex-direction: column; }
213
+ .message-wrap.user { align-items: flex-end; }
214
+ .message-wrap.assistant { align-items: flex-start; }
215
+ .bubble {
216
+ max-width: 85%;
217
+ padding: 10px 14px;
218
+ border-radius: var(--aikaara-radius, 12px);
219
+ font-size: 14px;
220
+ line-height: 1.5;
221
+ word-wrap: break-word;
222
+ overflow-wrap: break-word;
223
+ }
224
+ .bubble.user {
225
+ background: var(--aikaara-primary, #6366f1);
226
+ color: #ffffff;
227
+ border-bottom-right-radius: 4px;
228
+ }
229
+ .bubble.assistant {
230
+ background: var(--aikaara-bg-secondary, #f9fafb);
231
+ color: var(--aikaara-text, #1f2937);
232
+ border-bottom-left-radius: 4px;
233
+ }
234
+ .bubble pre {
235
+ background: rgba(0,0,0,0.06);
236
+ padding: 8px 12px;
237
+ border-radius: 6px;
238
+ overflow-x: auto;
239
+ font-size: 13px;
240
+ margin: 8px 0;
241
+ }
242
+ .bubble code {
243
+ font-family: 'SF Mono', 'Fira Code', monospace;
244
+ font-size: 13px;
245
+ }
246
+ .bubble.assistant code:not(pre code) {
247
+ background: rgba(0,0,0,0.06);
248
+ padding: 2px 4px;
249
+ border-radius: 3px;
250
+ }
251
+ .bubble a { color: inherit; text-decoration: underline; }
252
+ .timestamp {
253
+ font-size: 11px;
254
+ color: var(--aikaara-text-secondary, #6b7280);
255
+ margin-top: 2px;
256
+ padding: 0 4px;
257
+ }
258
+ .welcome {
259
+ text-align: center;
260
+ color: var(--aikaara-text-secondary, #6b7280);
261
+ font-size: 14px;
262
+ padding: 24px 16px;
263
+ }
264
+ .streaming-cursor::after {
265
+ content: '\\25CF';
266
+ animation: blink 1s infinite;
267
+ margin-left: 2px;
268
+ font-size: 10px;
269
+ vertical-align: middle;
270
+ }
271
+ @keyframes blink {
272
+ 0%, 100% { opacity: 1; }
273
+ 50% { opacity: 0; }
274
+ }
275
+ .typing-indicator {
276
+ display: flex;
277
+ align-items: center;
278
+ gap: 4px;
279
+ padding: 10px 14px;
280
+ align-self: flex-start;
281
+ background: var(--aikaara-bg-secondary, #f9fafb);
282
+ border-radius: var(--aikaara-radius, 12px);
283
+ border-bottom-left-radius: 4px;
284
+ }
285
+ .typing-indicator .dot {
286
+ width: 6px;
287
+ height: 6px;
288
+ border-radius: 50%;
289
+ background: var(--aikaara-text-secondary, #6b7280);
290
+ animation: typing-bounce 1.4s infinite ease-in-out;
291
+ }
292
+ .typing-indicator .dot:nth-child(1) { animation-delay: 0ms; }
293
+ .typing-indicator .dot:nth-child(2) { animation-delay: 200ms; }
294
+ .typing-indicator .dot:nth-child(3) { animation-delay: 400ms; }
295
+ @keyframes typing-bounce {
296
+ 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
297
+ 30% { transform: translateY(-4px); opacity: 1; }
298
+ }
299
+ </style>
300
+ <div class="message-list"></div>
301
+ `,this.container=this.shadow.querySelector(".message-list")}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(this.container){if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${f(m(this.welcomeMessage))}</div>`;return}for(const s of e)this.appendMessageElement(s);this.scrollToBottom()}}addMessage(e){const s=this.container.querySelector(".welcome");s&&s.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const s=this.container.querySelector('[data-streaming="true"] .bubble');s&&(s.innerHTML=f(m(e)),s.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');if(e){e.removeAttribute("data-streaming");const s=e.querySelector(".bubble");s==null||s.classList.remove("streaming-cursor")}}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){var e;(e=this.container.querySelector('[data-typing="true"]'))==null||e.remove()}appendMessageElement(e){const s=document.createElement("div");s.classList.add("message-wrap",e.role),e.status==="streaming"&&s.setAttribute("data-streaming","true");const i=document.createElement("div");if(i.classList.add("bubble",e.role),e.role==="user"?i.textContent=e.content:(i.innerHTML=f(m(e.content||"")),e.status==="streaming"&&i.classList.add("streaming-cursor")),s.appendChild(i),this.showTimestamps&&e.createdAt){const n=document.createElement("div");n.classList.add("timestamp"),n.textContent=this.formatTime(e.createdAt),s.appendChild(n)}this.container.appendChild(s)}scrollToBottom(){requestAnimationFrame(()=>{this.container.scrollTop=this.container.scrollHeight})}formatTime(e){try{return new Date(e).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}catch{return""}}}class H extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["role","content","timestamp"]}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("role")||"user",s=this.getAttribute("content")||"",i=this.getAttribute("timestamp")||"",n=e==="user"?document.createTextNode(s).textContent||"":f(m(s));this.shadow.innerHTML=`
302
+ <style>
303
+ :host { display: flex; flex-direction: column; }
304
+ :host([role="user"]) { align-items: flex-end; }
305
+ :host([role="assistant"]) { align-items: flex-start; }
306
+ .bubble {
307
+ max-width: 85%;
308
+ padding: 10px 14px;
309
+ border-radius: var(--aikaara-radius, 12px);
310
+ font-size: 14px;
311
+ line-height: 1.5;
312
+ word-wrap: break-word;
313
+ }
314
+ .bubble.user {
315
+ background: var(--aikaara-primary, #6366f1);
316
+ color: #fff;
317
+ border-bottom-right-radius: 4px;
318
+ }
319
+ .bubble.assistant {
320
+ background: var(--aikaara-bg-secondary, #f9fafb);
321
+ color: var(--aikaara-text, #1f2937);
322
+ border-bottom-left-radius: 4px;
323
+ }
324
+ .timestamp {
325
+ font-size: 11px;
326
+ color: var(--aikaara-text-secondary, #6b7280);
327
+ margin-top: 2px;
328
+ padding: 0 4px;
329
+ }
330
+ </style>
331
+ <div class="bubble ${e}">${n}</div>
332
+ ${i?`<div class="timestamp">${i}</div>`:""}
333
+ `}}class U extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"textarea");a(this,"sendBtn");a(this,"_disabled",!1);this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...";this.shadow.innerHTML=`
334
+ <style>
335
+ .input-container {
336
+ display: flex;
337
+ align-items: flex-end;
338
+ gap: 8px;
339
+ padding: 12px 16px;
340
+ border-top: 1px solid var(--aikaara-border, #e5e7eb);
341
+ background: var(--aikaara-bg, #ffffff);
342
+ }
343
+ textarea {
344
+ flex: 1;
345
+ resize: none;
346
+ border: 1px solid var(--aikaara-border, #e5e7eb);
347
+ border-radius: 8px;
348
+ padding: 10px 12px;
349
+ font-family: var(--aikaara-font, system-ui, sans-serif);
350
+ font-size: 14px;
351
+ color: var(--aikaara-text, #1f2937);
352
+ background: var(--aikaara-bg, #ffffff);
353
+ outline: none;
354
+ min-height: 40px;
355
+ max-height: 120px;
356
+ line-height: 1.4;
357
+ transition: border-color 200ms ease;
358
+ }
359
+ textarea:focus {
360
+ border-color: var(--aikaara-primary, #6366f1);
361
+ }
362
+ textarea::placeholder {
363
+ color: var(--aikaara-text-secondary, #6b7280);
364
+ }
365
+ .send-btn {
366
+ width: 40px;
367
+ height: 40px;
368
+ border: none;
369
+ border-radius: 50%;
370
+ background: var(--aikaara-primary, #6366f1);
371
+ color: #ffffff;
372
+ cursor: pointer;
373
+ display: flex;
374
+ align-items: center;
375
+ justify-content: center;
376
+ flex-shrink: 0;
377
+ transition: background 200ms, opacity 200ms;
378
+ }
379
+ .send-btn:hover { background: var(--aikaara-primary-hover, #4f46e5); }
380
+ .send-btn:disabled { opacity: 0.5; cursor: not-allowed; }
381
+ .send-btn svg { width: 18px; height: 18px; }
382
+ </style>
383
+ <div class="input-container">
384
+ <textarea rows="1" placeholder="${e}"></textarea>
385
+ <button class="send-btn" aria-label="Send message" disabled>
386
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
387
+ <line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
388
+ </svg>
389
+ </button>
390
+ </div>
391
+ `,this.textarea=this.shadow.querySelector("textarea"),this.sendBtn=this.shadow.querySelector(".send-btn"),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.sendBtn.disabled=this._disabled||!this.textarea.value.trim()}),this.textarea.addEventListener("keydown",s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),this.handleSend())}),this.sendBtn.addEventListener("click",()=>this.handleSend())}set disabled(e){var s;this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.sendBtn&&(this.sendBtn.disabled=e||!((s=this.textarea)!=null&&s.value.trim()))}get disabled(){return this._disabled}focus(){var e;(e=this.textarea)==null||e.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.sendBtn.disabled=!0)}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class B extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
392
+ <style>
393
+ :host { display: none; }
394
+ :host([visible]) { display: block; }
395
+ .typing {
396
+ display: flex;
397
+ align-items: center;
398
+ gap: 4px;
399
+ padding: 10px 14px;
400
+ background: var(--aikaara-bg-secondary, #f9fafb);
401
+ border-radius: var(--aikaara-radius, 12px);
402
+ border-bottom-left-radius: 4px;
403
+ width: fit-content;
404
+ }
405
+ .dot {
406
+ width: 6px;
407
+ height: 6px;
408
+ border-radius: 50%;
409
+ background: var(--aikaara-text-secondary, #6b7280);
410
+ animation: bounce 1.4s infinite ease-in-out;
411
+ }
412
+ .dot:nth-child(1) { animation-delay: 0ms; }
413
+ .dot:nth-child(2) { animation-delay: 200ms; }
414
+ .dot:nth-child(3) { animation-delay: 400ms; }
415
+ @keyframes bounce {
416
+ 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
417
+ 30% { transform: translateY(-4px); opacity: 1; }
418
+ }
419
+ </style>
420
+ <div class="typing">
421
+ <span class="dot"></span>
422
+ <span class="dot"></span>
423
+ <span class="dot"></span>
424
+ </div>
425
+ `}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class z extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"bubble");this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
426
+ <style>
427
+ :host {
428
+ display: flex;
429
+ flex-direction: column;
430
+ align-items: flex-start;
431
+ }
432
+ .bubble {
433
+ max-width: 85%;
434
+ padding: 10px 14px;
435
+ border-radius: var(--aikaara-radius, 12px);
436
+ border-bottom-left-radius: 4px;
437
+ background: var(--aikaara-bg-secondary, #f9fafb);
438
+ color: var(--aikaara-text, #1f2937);
439
+ font-size: 14px;
440
+ line-height: 1.5;
441
+ word-wrap: break-word;
442
+ min-height: 20px;
443
+ }
444
+ .bubble pre {
445
+ background: rgba(0,0,0,0.06);
446
+ padding: 8px 12px;
447
+ border-radius: 6px;
448
+ overflow-x: auto;
449
+ font-size: 13px;
450
+ margin: 8px 0;
451
+ }
452
+ .bubble code {
453
+ font-family: 'SF Mono', 'Fira Code', monospace;
454
+ font-size: 13px;
455
+ }
456
+ .bubble code:not(pre code) {
457
+ background: rgba(0,0,0,0.06);
458
+ padding: 2px 4px;
459
+ border-radius: 3px;
460
+ }
461
+ .cursor::after {
462
+ content: '\\25CF';
463
+ animation: blink 1s infinite;
464
+ margin-left: 2px;
465
+ font-size: 10px;
466
+ vertical-align: middle;
467
+ }
468
+ @keyframes blink {
469
+ 0%, 100% { opacity: 1; }
470
+ 50% { opacity: 0; }
471
+ }
472
+ </style>
473
+ <div class="bubble cursor"></div>
474
+ `,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=f(m(e)),this.bubble.classList.add("cursor"))}finalize(){var e;(e=this.bubble)==null||e.classList.remove("cursor")}}class F extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"container");a(this,"dismissTimer",null);this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){var e;this.shadow.innerHTML=`
475
+ <style>
476
+ .banner {
477
+ display: none;
478
+ padding: 8px 16px;
479
+ background: #fef2f2;
480
+ color: #dc2626;
481
+ font-size: 13px;
482
+ text-align: center;
483
+ border-top: 1px solid #fecaca;
484
+ }
485
+ .banner.visible {
486
+ display: block;
487
+ }
488
+ .dismiss {
489
+ background: none;
490
+ border: none;
491
+ color: #dc2626;
492
+ cursor: pointer;
493
+ font-size: 12px;
494
+ text-decoration: underline;
495
+ margin-left: 8px;
496
+ }
497
+ </style>
498
+ <div class="banner">
499
+ <span class="message"></span>
500
+ <button class="dismiss">Dismiss</button>
501
+ </div>
502
+ `,this.container=this.shadow.querySelector(".banner"),(e=this.shadow.querySelector(".dismiss"))==null||e.addEventListener("click",()=>this.hide())}show(e,s){const i=this.container.querySelector(".message");i&&(i.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),s&&(this.dismissTimer=setTimeout(()=>this.hide(),s))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}function w(){const r=[["aikaara-chat-widget",E],["aikaara-chat-bubble",L],["aikaara-chat-header",I],["aikaara-message-list",O],["aikaara-message-bubble",H],["aikaara-chat-input",U],["aikaara-typing-indicator",B],["aikaara-streaming-message",z],["aikaara-error-banner",F]];for(const[t,e]of r)customElements.get(t)||customElements.define(t,e)}w();function Z(r){w();const t=document.createElement("aikaara-chat-widget"),e={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[s,i]of Object.entries(e)){const n=r[s];n!=null&&t.setAttribute(i,String(n))}return t.configure(r),document.body.appendChild(t),t}function ee(){const r=document.querySelector("aikaara-chat-widget");r&&r.remove()}return o.ActionCableClient=p,o.AikaaraChatBubble=L,o.AikaaraChatClient=A,o.AikaaraChatHeader=I,o.AikaaraChatInput=U,o.AikaaraChatWidget=E,o.AikaaraErrorBanner=F,o.AikaaraMessageBubble=H,o.AikaaraMessageList=O,o.AikaaraStreamingMessage=z,o.AikaaraTypingIndicator=B,o.ApiClient=C,o.ChannelSubscription=h,o.ConnectionManager=_,o.ConversationManager=M,o.EventEmitter=y,o.MessageStore=T,o.mount=Z,o.registerComponents=w,o.unmount=ee,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),o})({});
@@ -0,0 +1 @@
1
+ "use strict";var w=Object.defineProperty;var T=(a,t,e)=>t in a?w(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e;var o=(a,t,e)=>T(a,typeof t!="symbol"?t+"":t,e);class b{constructor(t,e){o(this,"identifier");o(this,"callbacks",{});o(this,"sendFn");this.identifier=t,this.sendFn=e}onReceived(t){return this.callbacks.received=t,this}onConnected(t){return this.callbacks.connected=t,this}onDisconnected(t){return this.callbacks.disconnected=t,this}onRejected(t){return this.callbacks.rejected=t,this}perform(t,e={}){this.sendFn({action:t,...e})}_notifyReceived(t){var e,s;(s=(e=this.callbacks).received)==null||s.call(e,t)}_notifyConnected(){var t,e;(e=(t=this.callbacks).connected)==null||e.call(t)}_notifyDisconnected(){var t,e;(e=(t=this.callbacks).disconnected)==null||e.call(t)}_notifyRejected(){var t,e;(e=(t=this.callbacks).rejected)==null||e.call(t)}}class p{constructor(t){o(this,"ws",null);o(this,"url");o(this,"subscriptions",new Map);o(this,"welcomePromise",null);o(this,"pendingSubscriptions",new Map);this.url=t}connect(){return new Promise((t,e)=>{this.welcomePromise={resolve:t,reject:e},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=s=>{this.handleMessage(s)},this.ws.onerror=()=>{var n;const s=new Error("WebSocket connection error");(n=this.welcomePromise)==null||n.reject(s),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(s=>s._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(t=>t._notifyDisconnected()),this.subscriptions.clear()}subscribe(t){const e=JSON.stringify(t),s=new b(e,n=>{this.send({command:"message",identifier:e,data:JSON.stringify(n)})});return this.subscriptions.set(e,s),this.send({command:"subscribe",identifier:e}),s}subscribeAsync(t){const e=this.subscribe(t),s=e.identifier;return new Promise((n,i)=>{this.pendingSubscriptions.set(s,{resolve:()=>n(e),reject:i}),setTimeout(()=>{this.pendingSubscriptions.has(s)&&(this.pendingSubscriptions.delete(s),i(new Error(`Subscription timeout for ${s}`)))},1e4)})}unsubscribe(t){this.send({command:"unsubscribe",identifier:t}),this.subscriptions.delete(t)}perform(t,e,s={}){this.send({command:"message",identifier:t,data:JSON.stringify({action:e,...s})})}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}handleMessage(t){var s;let e;try{e=JSON.parse(t.data)}catch{return}switch(e.type){case"welcome":(s=this.welcomePromise)==null||s.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const n=e.identifier,i=this.subscriptions.get(n);i==null||i._notifyConnected();const c=this.pendingSubscriptions.get(n);c&&(c.resolve(),this.pendingSubscriptions.delete(n));break}case"reject_subscription":{const n=e.identifier,i=this.subscriptions.get(n);i==null||i._notifyRejected(),this.subscriptions.delete(n);const c=this.pendingSubscriptions.get(n);c&&(c.reject(new Error(`Subscription rejected: ${n}`)),this.pendingSubscriptions.delete(n));break}case"disconnect":this.subscriptions.forEach(n=>n._notifyDisconnected());break;default:{if(e.identifier&&e.message!==void 0){const n=this.subscriptions.get(e.identifier);n==null||n._notifyReceived(e.message)}break}}}}class _{constructor(){o(this,"handlers",new Map)}on(t,e){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.handlers.get(t))==null||s.delete(e)}emit(t,e){var s;(s=this.handlers.get(t))==null||s.forEach(n=>{try{n(e)}catch(i){console.error(`Error in event handler for "${t}":`,i)}})}removeAllListeners(){this.handlers.clear()}}const I=1e3,A=10,k=400,C=600,M="#6366f1",O=12,D="system-ui, -apple-system, sans-serif",U="Type a message...",F="bottom-right",L="light",R={x:20,y:20},m="aikaara_conversation_id";class S extends _{constructor(e){super();o(this,"client");o(this,"config");o(this,"state","disconnected");o(this,"reconnectAttempt",0);o(this,"reconnectTimer",null);this.config=e;const s=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new p(s)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,s){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_message",{content:s})}sendUserEvent(e,s,n,i){const c=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(c,"send_user_event",{event_key:s,...n&&{value:n},...i&&{source:i}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??A;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const n=(this.config.reconnectInterval??I)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const i=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new p(i),await this.connect()}catch{}},n)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,s){return`${e.replace(/^http/,"ws")}/cable?token=${s}`}}class v{constructor(t,e,s){o(this,"baseUrl");o(this,"apiKey");o(this,"userToken");this.baseUrl=t,this.userToken=e,this.apiKey=s}async createConversation(t){const e={conversation:{...t.systemPromptId&&{system_prompt_id:t.systemPromptId},...t.channel&&{channel:t.channel},...t.title&&{title:t.title}}};return this.request("POST","/api/v1/conversations",e)}async getMessages(t){return(await this.request("GET",`/api/v1/conversations/${t}/messages`)).map(this.mapMessage)}mapMessage(t){var e;return{id:String(t.id),conversationId:String(t.conversation_id),role:t.role,content:t.content||"",toolCalls:(e=t.tool_calls)==null?void 0:e.map(s=>({id:s.id,type:s.type,function:s.function})),toolCallResults:t.tool_call_results,tokensInput:t.tokens_input,tokensOutput:t.tokens_output,metadata:t.metadata,createdAt:t.created_at,status:"complete"}}async request(t,e,s){const n={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(n["X-Api-Key"]=this.apiKey);const i=`${this.baseUrl}${e}`,c={method:t,headers:n};s&&(c.body=JSON.stringify(s));const d=await fetch(i,c);if(!d.ok){const l=await d.text();let u;try{const g=JSON.parse(l);u=g.error||g.message||l}catch{u=l}throw new Error(`API error ${d.status}: ${u}`)}return d.json()}}class y{constructor(){o(this,"_messages",[]);o(this,"optimisticCounter",0)}get messages(){return[...this._messages]}addOptimistic(t,e,s){const n={id:`optimistic_${++this.optimisticCounter}`,conversationId:s,role:t,content:e,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(n),n}confirmOptimistic(t){const e=this._messages.find(s=>s.id===t);e&&(e.status="sent")}addStreamingMessage(t){const e={id:`streaming_${Date.now()}`,conversationId:t,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(e),e}updateStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");e&&(e.content=t)}finalizeStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");return e&&(e.status="complete",t&&(e.tokensInput=t.tokensInput,e.tokensOutput=t.tokensOutput)),e}addMessage(t){this._messages.push(t)}setMessages(t){this._messages=[...t]}clear(){this._messages=[]}}class E{constructor(t,e=!0){o(this,"_conversationId");o(this,"persist");this.persist=e,this._conversationId=t||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(t){this._conversationId=t,this.persist&&t&&this.saveToStorage(t)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(m)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(m)}catch{return null}}saveToStorage(t){try{localStorage.setItem(m,t)}catch{}}}class N extends _{constructor(e){super();o(this,"connection");o(this,"api");o(this,"messageStore");o(this,"conversationManager");o(this,"subscription",null);o(this,"config");this.config=e,this.connection=new S(e),this.api=new v(e.baseUrl,e.userToken,e.apiKey),this.messageStore=new y,this.conversationManager=new E(e.conversationId),this.connection.on("connection:state",s=>{var n,i;this.emit("connection:state",s),(i=(n=this.config).onConnectionStateChange)==null||i.call(n,s)}),this.connection.on("error",s=>{var n,i;this.emit("error",s),(i=(n=this.config).onError)==null||i.call(n,s)})}async connect(){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget"});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}async sendMessage(e){var i,c;const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const n=this.messageStore.addOptimistic("user",e,s);this.emit("message:sent",n),(c=(i=this.config).onMessage)==null||c.call(i,n),this.connection.sendMessage(s,e)}async sendUserEvent(e,s,n){const i=this.conversationManager.conversationId;if(!i)throw new Error("No active conversation");this.connection.sendUserEvent(i,e,s,n)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const s=await this.api.getMessages(e);return this.messageStore.setMessages(s),s}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){return this.connection.connectionState==="connected"}async disconnect(){this.subscription&&(this.subscription=null),await this.connection.disconnect()}handleBroadcast(e){var n,i,c,d,l,u,g,f;const s=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),(i=(n=this.config).onStatusChange)==null||i.call(n,r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),(d=(c=this.config).onError)==null||d.call(c,r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(s);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.content||"",h=e.delta||"";this.messageStore.updateStreaming(r),this.emit("stream:update",{delta:h,content:r}),(u=(l=this.config).onStreamUpdate)==null||u.call(l,h,r);break}case"message_end":{const r=e.usage,h=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),h&&(this.emit("stream:end",{messageId:h.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",h),(f=(g=this.config).onMessage)==null||f.call(g,h));break}case"message_queued":{const r=this.messageStore.messages.findLast(h=>h.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":case"tool_execution_update":case"tool_execution_end":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}exports.ActionCableClient=p;exports.AikaaraChatClient=N;exports.ApiClient=v;exports.ChannelSubscription=b;exports.ConnectionManager=S;exports.ConversationManager=E;exports.DEFAULT_BORDER_RADIUS=O;exports.DEFAULT_FONT_FAMILY=D;exports.DEFAULT_OFFSET=R;exports.DEFAULT_PLACEHOLDER=U;exports.DEFAULT_POSITION=F;exports.DEFAULT_PRIMARY_COLOR=M;exports.DEFAULT_THEME=L;exports.DEFAULT_WIDGET_HEIGHT=C;exports.DEFAULT_WIDGET_WIDTH=k;exports.EventEmitter=_;exports.MessageStore=y;