@nimbusai/webchat-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,183 @@
1
+ "use strict";var oe=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Pe=Object.prototype.hasOwnProperty;var Ue=(o,e)=>{for(var t in e)oe(o,t,{get:e[t],enumerable:!0})},je=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ze(e))!Pe.call(o,n)&&n!==t&&oe(o,n,{get:()=>e[n],enumerable:!(i=He(e,n))||i.enumerable});return o};var We=o=>je(oe({},"__esModule",{value:!0}),o);var at={};Ue(at,{ICON_NAMES:()=>m,ICON_SIZES:()=>p,NimbusChat:()=>I,default:()=>rt,getInstance:()=>De,init:()=>_e});module.exports=We(at);var m={MESSAGE_CIRCLE:"message-circle",SEND:"send",CLOSE:"x",NEW_CHAT:"rotate-cw",CHEVRON_DOWN:"chevron-down",PAPERCLIP:"paperclip",TYPE:"type"},p={BUTTON_SMALL:16,BUTTON_MEDIUM:18,AVATAR:28,BUBBLE_OPEN:26},b={OPEN_CHAT:"Open chat",CLOSE_CHAT:"Close chat",NEW_CHAT:"New Chat",SEND:"Send",CONNECTED:"Connected",SHOW_MORE:"Show More",DOWNLOAD_FILE:"Download file",START_NEW_CHAT:"Start new chat",USE_HERE:"Use here",UPLOAD_FILE:"Upload file"},le={MAX_LINES:8,LINE_HEIGHT:21,VERTICAL_PADDING:20,get MAX_HEIGHT(){return this.MAX_LINES*this.LINE_HEIGHT+this.VERTICAL_PADDING}},fe={WIDGET_ROOT:2147483647},ce={NORMAL:1e3,SESSION_UNAVAILABLE:4403,SESSION_CONFLICT:4409},be={REPLY_WAIT:1e4,RECONNECT:5e3},C={WIDTH:"380px",HEIGHT:"560px",MESSAGE_LIMIT:10,MESSAGES_PER_PAGE:10,MAX_RECONNECT_ATTEMPTS:5,MAX_FILE_SIZE:5*1024*1024,ERROR_DISPLAY_DURATION:2e3},O={DEFAULT_BUBBLE_MAX_WIDTH:280,DEFAULT_ICON_SIZE_FACTOR:.75,MESSAGE_AVATAR_SIZE_FACTOR:1},de={MILLISECONDS_TO_SECONDS:1e3},re={primary:"#ffce1c",secondary:"#f3f1ef"},we="80%",L={background:"#DCF8C6",width:we,text:{color:"#111B21",size:13},icon:{img:"user",size:{width:20,height:20}}},B={background:"#FFFFFF",width:we,text:{color:"#111B21",size:13},icon:{img:"bot",size:{width:20,height:20}}},z={position:"bottom-right",autoHide:!1,icon:{img:"message-circle",size:{width:35,height:35}}},A={display:!0,preTitle:{value:"Welcome to :",text:{color:"#1e293b"}},title:{value:" Nimbus Chat!",text:{color:"#1e293b"}},subtitle:{value:"Send a message to start a conversation",text:{color:"gray"}}},ye={align:!1},ne={position:"top",title:{value:"AI Assistant is typing...",text:{color:"#1e293b",font:""}}},xe={timeout:be.REPLY_WAIT},$e={value:"Show More",sticky:!0,background:"#FFF4CC",text:{color:"black",size:13},icon:{img:"chevron-down",size:{width:16,height:16}}},se={maxFileSize:C.MAX_FILE_SIZE,errorDisplayDuration:C.ERROR_DISPLAY_DURATION,allowedFileTypes:["image/jpeg","image/png","image/gif","image/webp","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]},ae={attempts:C.MAX_RECONNECT_ATTEMPTS,timeout:be.RECONNECT},F={inactivity:{background:"#f3f1ef",title:{value:"This chat session is ended due to inactivity.",text:{color:"#1e293b",size:15}},subtitle:{value:"Click 'Connect' to begin a new conversation.",text:{color:"gray",size:13}},button:{background:"#ffce1c",text:{color:"white",size:15},icon:null}},conflict:{background:"#f3f1ef",title:{value:"Chat is already open in another tab.",text:{color:"#1e293b",size:15}},subtitle:{value:"Click 'Use Here' to open the chat in this tab.",text:{color:"gray",size:13}},button:{background:"#ffce1c",text:{color:"white",size:15},icon:null}},session_ttl:{background:"#f3f1ef",title:{value:"Your chat session has expired.",text:{color:"#1e293b",size:15}},subtitle:{value:"Click 'Connect' to start a new conversation.",text:{color:"gray",size:13}},button:{background:"#ffce1c",text:{color:"white",size:15},icon:null}},unauthorized:{background:"#f3f1ef",title:{value:"This SDK agent link is not authorized.",text:{color:"#1e293b",size:15}},subtitle:{value:"Contact us for assistance at sdk@nmbs.ai.",text:{color:"gray",size:13}}}},R={position:"bottom-right",width:C.WIDTH,height:C.HEIGHT,background:"#f3f1ef"},f={dns:"api.nimbus.ai/api/v1/webchat",style:R,messagesPerPage:C.MESSAGES_PER_PAGE,bubble:z,theme:re,userMessage:L,botMessage:B,header:{icon:null,text:{value:"Nimbus AI",color:"#1e293b"},color:{primary:"#f3f1ef",secondary:"#ffce1c"}},input:{placeholder:"Ask Nimbus",expandable:!0,text:{color:"#1e293b"},background:{primary:"white",secondary:"#f3f1ef"}},sendButton:{...ye,icon:{img:"send",size:{width:20,height:20}}},welcome:A,error:F,debug:!1,reconnect:ae,allowNewChat:!1,waitForReply:xe,showMore:$e,icon:{defaultSize:24,defaultColor:"currentColor"}};function ve(o){let e=o.style;return{agent_id:o.agent_id,dns:o.dns??f.dns,resumeConversation:o.resumeConversation??!1,style:{position:e?.position??R.position,mobile:e?.mobile?{position:e.mobile.position,breakpoint:e.mobile.breakpoint}:void 0,width:e?.width??R.width,height:e?.height??R.height,font:e?.font,background:e?.background??R.background},messagesPerPage:o.messagesPerPage??f.messagesPerPage,bubble:{position:o.bubble?.position??z.position,autoHide:o.bubble?.autoHide??z.autoHide,icon:o.bubble?.icon??z.icon},theme:{...re,...o.theme},userMessage:{background:o.userMessage?.background??L.background,width:o.userMessage?.width??L.width,text:{...L.text,...o.userMessage?.text},icon:o.userMessage?.icon!==void 0?o.userMessage.icon:L.icon},botMessage:{background:o.botMessage?.background??B.background,width:o.botMessage?.width??B.width,text:{...B.text,...o.botMessage?.text},icon:o.botMessage?.icon??B.icon},header:{icon:o.header?.icon!==void 0?o.header.icon:f.header.icon,text:o.header?.text??f.header.text,color:o.header?.color??f.header.color},input:{placeholder:o.input?.placeholder??f.input.placeholder,expandable:o.input?.expandable??f.input.expandable,text:o.input?.text??f.input.text,background:o.input?.background??f.input.background,upload:o.input?.upload?{maxFileSize:o.input.upload.maxFileSize??se.maxFileSize,errorDisplayDuration:o.input.upload.errorDisplayDuration??se.errorDisplayDuration,allowedFileTypes:o.input.upload.allowedFileTypes??se.allowedFileTypes,icon:o.input.upload.icon}:void 0,maxCharacters:o.input?.maxCharacters?{limit:o.input.maxCharacters.limit,text:o.input.maxCharacters.text}:void 0},sendButton:{align:o.sendButton?.align??ye.align,icon:o.sendButton?.icon??f.sendButton.icon},welcome:{display:o.welcome?.display??A.display,preTitle:{...A.preTitle,...o.welcome?.preTitle},title:{...A.title,...o.welcome?.title},subtitle:{...A.subtitle,...o.welcome?.subtitle}},error:{inactivity:{...F.inactivity,...o.error?.inactivity},conflict:{...F.conflict,...o.error?.conflict},session_ttl:{...F.session_ttl,...o.error?.session_ttl},unauthorized:{...F.unauthorized,...o.error?.unauthorized}},debug:o.debug??f.debug,reconnect:{attempts:o.reconnect?.attempts??ae.attempts,timeout:o.reconnect?.timeout??ae.timeout},allowNewChat:o.allowNewChat??f.allowNewChat,waitForReply:o.waitForReply?{timeout:o.waitForReply.timeout??xe.timeout,firstReply:o.waitForReply.firstReply??!1}:void 0,isTypingIndicator:o.isTypingIndicator?{position:o.isTypingIndicator.position??ne.position,title:{value:o.isTypingIndicator.title?.value??ne.title?.value,text:o.isTypingIndicator.title?.text??ne.title?.text}}:void 0,showMore:{value:o.showMore?.value??f.showMore.value,sticky:o.showMore?.sticky??f.showMore.sticky,background:o.showMore?.background??{...re,...o.theme}.secondary,text:{color:o.showMore?.text?.color??f.showMore.text?.color,font:o.showMore?.text?.font??e?.font,size:o.showMore?.text?.size??f.showMore.text?.size},icon:o.showMore?.icon??f.showMore.icon}}}var Ce={BUBBLE_OFFSET:84,EDGE_DISTANCE:20,BUTTON_OFFSET:7,AVATAR_MARGIN:2},Ee={AVATAR:"50%",PANEL:"12px",PANEL_MOBILE:"12px 12px 0 0"},Te={BUBBLE_ICON:.65};var Se=["bottom-right","bottom-left","sidepanel-left","sidepanel-right"],Me=["bottom-right","bottom-left"];function S(o,e){if(typeof o!="object"||o===null)throw new Error(`[NimbusChat] ${e} must be an object`);let t=o;if(t.display!==void 0&&typeof t.display!="boolean")throw new Error(`[NimbusChat] ${e}.display must be a boolean`);if(t.value!==void 0&&typeof t.value!="string")throw new Error(`[NimbusChat] ${e}.value must be a string`);if(t.color!==void 0&&typeof t.color!="string")throw new Error(`[NimbusChat] ${e}.color must be a string`);if(t.font!==void 0&&typeof t.font!="string")throw new Error(`[NimbusChat] ${e}.font must be a string`);if(t.size!==void 0&&typeof t.size!="number")throw new Error(`[NimbusChat] ${e}.size must be a number`)}function _(o,e){if(o===null)return;if(typeof o!="object")throw new Error(`[NimbusChat] ${e} must be an object or null`);let t=o;if(t.img!==void 0&&typeof t.img!="string")throw new Error(`[NimbusChat] ${e}.img must be a string`);if(t.size!==void 0){if(typeof t.size!="object"||t.size===null)throw new Error(`[NimbusChat] ${e}.size must be an object`);let i=t.size;if(i.width!==void 0&&typeof i.width!="number")throw new Error(`[NimbusChat] ${e}.size.width must be a number`);if(i.height!==void 0&&typeof i.height!="number")throw new Error(`[NimbusChat] ${e}.size.height must be a number`)}}function ke(o){if(!o||typeof o!="object")throw new Error("[NimbusChat] Config must be an object");let e=o;if(!e.agent_id||typeof e.agent_id!="string"||e.agent_id.trim()==="")throw new Error("[NimbusChat] agent_id is required and must be a non-empty UUID string");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e.agent_id.trim()))throw new Error("[NimbusChat] agent_id must be a valid UUID (e.g. 550e8400-e29b-41d4-a716-446655440000)");if(e.wsUrl!==void 0&&typeof e.wsUrl!="string")throw new Error("[NimbusChat] wsUrl must be a string");if(e.style!==void 0){if(typeof e.style!="object"||e.style===null)throw new Error("[NimbusChat] style must be an object");let i=e.style;if(i.position!==void 0&&!Se.includes(i.position))throw new Error(`[NimbusChat] style.position must be one of: ${Se.join(", ")}`);if(i.background!==void 0&&typeof i.background!="string")throw new Error("[NimbusChat] style.background must be a string");if(i.font!==void 0&&typeof i.font!="string")throw new Error("[NimbusChat] style.font must be a string")}if(e.theme!==void 0){if(typeof e.theme!="object"||e.theme===null)throw new Error("[NimbusChat] theme must be an object");let i=e.theme;if(i.primary!==void 0&&typeof i.primary!="string")throw new Error("[NimbusChat] theme.primary must be a string");if(i.secondary!==void 0&&typeof i.secondary!="string")throw new Error("[NimbusChat] theme.secondary must be a string")}if(e.bubble!==void 0){if(typeof e.bubble!="object"||e.bubble===null)throw new Error("[NimbusChat] bubble must be an object");let i=e.bubble;if(i.position!==void 0&&!Me.includes(i.position))throw new Error(`[NimbusChat] bubble.position must be one of: ${Me.join(", ")}`);if(i.autoHide!==void 0&&typeof i.autoHide!="boolean")throw new Error("[NimbusChat] bubble.autoHide must be a boolean");i.icon!==void 0&&_(i.icon,"bubble.icon")}if(e.userMessage!==void 0){if(typeof e.userMessage!="object"||e.userMessage===null)throw new Error("[NimbusChat] userMessage must be an object");let i=e.userMessage;if(i.background!==void 0&&typeof i.background!="string")throw new Error("[NimbusChat] userMessage.background must be a string");i.text!==void 0&&S(i.text,"userMessage.text"),i.icon!==void 0&&_(i.icon,"userMessage.icon")}if(e.botMessage!==void 0){if(typeof e.botMessage!="object"||e.botMessage===null)throw new Error("[NimbusChat] botMessage must be an object");let i=e.botMessage;if(i.background!==void 0&&typeof i.background!="string")throw new Error("[NimbusChat] botMessage.background must be a string");i.text!==void 0&&S(i.text,"botMessage.text"),i.icon!==void 0&&_(i.icon,"botMessage.icon")}if(e.header!==void 0){if(typeof e.header!="object"||e.header===null)throw new Error("[NimbusChat] header must be an object");let i=e.header;if(i.icon!==void 0&&_(i.icon,"header.icon"),i.text!==void 0&&S(i.text,"header.text"),i.color!==void 0){if(typeof i.color!="object"||i.color===null)throw new Error("[NimbusChat] header.color must be an object");let n=i.color;if(n.primary!==void 0&&typeof n.primary!="string")throw new Error("[NimbusChat] header.color.primary must be a string");if(n.secondary!==void 0&&typeof n.secondary!="string")throw new Error("[NimbusChat] header.color.secondary must be a string")}}if(e.input!==void 0){if(typeof e.input!="object"||e.input===null)throw new Error("[NimbusChat] input must be an object");let i=e.input;if(i.placeholder!==void 0&&typeof i.placeholder!="string")throw new Error("[NimbusChat] input.placeholder must be a string");if(i.expandable!==void 0&&typeof i.expandable!="boolean")throw new Error("[NimbusChat] input.expandable must be a boolean");if(i.text!==void 0&&S(i.text,"input.text"),i.background!==void 0){if(typeof i.background!="object"||i.background===null)throw new Error("[NimbusChat] input.background must be an object");let n=i.background;if(n.primary!==void 0&&typeof n.primary!="string")throw new Error("[NimbusChat] input.background.primary must be a string");if(n.secondary!==void 0&&typeof n.secondary!="string")throw new Error("[NimbusChat] input.background.secondary must be a string")}}if(e.sendButton!==void 0){if(typeof e.sendButton!="object"||e.sendButton===null)throw new Error("[NimbusChat] sendButton must be an object");let i=e.sendButton;if(i.icon!==void 0&&_(i.icon,"sendButton.icon"),i.align!==void 0&&typeof i.align!="boolean")throw new Error("[NimbusChat] sendButton.align must be a boolean")}if(e.welcome!==void 0){if(typeof e.welcome!="object"||e.welcome===null)throw new Error("[NimbusChat] welcome must be an object");let i=e.welcome;if(i.display!==void 0&&typeof i.display!="boolean")throw new Error("[NimbusChat] welcome.display must be a boolean");i.preTitle!==void 0&&S(i.preTitle,"welcome.preTitle"),i.title!==void 0&&S(i.title,"welcome.title"),i.subtitle!==void 0&&S(i.subtitle,"welcome.subtitle")}}var pe,P=null;function Ie(o){o&&(pe=o,P=null)}function D(){if(P===null){let o=navigator.userAgent.toLowerCase();P=/mobile|android|iphone|ipad|ipod|blackberry|windows phone/.test(o)}if(pe){let o=parseInt(pe,10);if(!isNaN(o)&&window.innerWidth<=o)return!0}return P}var Ge={debug:{badge:"DBG",bg:"#6B7280",fg:"#fff",consoleFn:"log"},info:{badge:"INF",bg:"#3B82F6",fg:"#fff",consoleFn:"info"},warn:{badge:"WRN",bg:"#F59E0B",fg:"#000",consoleFn:"warn"},error:{badge:"ERR",bg:"#EF4444",fg:"#fff",consoleFn:"error"}},Ve={websocket:"#10B981",ws:"#10B981",api:"#F97316",ui:"#EC4899",window:"#EC4899",session:"#06B6D4",perf:"#22C55E"},Ke="#8B5CF6",Xe=(o,e)=>`background:${o};color:${e};padding:1px 6px;border-radius:3px;font-weight:600;font-size:11px`,Ne=o=>`background:${o}22;color:${o};padding:1px 6px;border-radius:3px;font-weight:600;font-size:11px`,Ye="color:#9CA3AF;font-size:10px;font-weight:400",Le="color:#E5E7EB;font-weight:400";function Ze(o){let e=o.toLowerCase();for(let[t,i]of Object.entries(Ve))if(e.includes(t))return i;return Ke}function qe(o){return o.map(e=>{if(e&&typeof e=="object"){let t=e;if(t.type==="file"&&t.content)return{...t,content:"[base64 omitted]"}}return e})}function Be(o){try{return JSON.parse(o)}catch{return null}}function Je(o){let e=o.match(/^(Sending:|Received:)\s*(.+)$/s);if(e){let[,i,n]=e,s=Be(n);if(s&&typeof s=="object"){let a=s;if(a.type==="file"&&a.content){let l={...a,content:"[base64 omitted]"};return{sanitized:`${i}`,json:l}}return{sanitized:`${i}`,json:s}}}let t=Be(o);if(t&&typeof t=="object"){let i=t;return i.type==="file"&&i.content?{sanitized:"",json:{...i,content:"[base64 omitted]"}}:{sanitized:"",json:t}}return{sanitized:o,json:null}}var ue=class o{constructor(e,t=!1){this.component=e,this.enabled=t,this.color=Ze(e)}log(e,t,...i){if(!this.enabled)return;let{badge:n,bg:s,fg:a,consoleFn:l}=Ge[e],d=new Date().toISOString().substring(11,23),{sanitized:c,json:x}=Je(t),w=qe(i),h=[`%c${n}%c ${this.component} %c${d}`],E=[Xe(s,a),Ne(this.color),Ye];c&&(h[0]+=` %c${c}`,E.push(Le));let N=[h[0],...E];x&&N.push(x),N.push(...w),console[l](...N)}debug(e,...t){this.log("debug",e,...t)}info(e,...t){this.log("info",e,...t)}warn(e,...t){this.log("warn",e,...t)}error(e,...t){this.log("error",e,...t)}object(e,t){this.enabled&&(this.debug(e),console.dir(t,{depth:3,colors:!0}))}group(e){this.enabled&&console.groupCollapsed(`%c${this.component}%c ${e}`,Ne(this.color),Le)}groupEnd(){this.enabled&&console.groupEnd()}child(e){return new o(`${this.component}:${e}`,this.enabled)}setEnabled(e){this.enabled=e}table(e){this.enabled&&console.table(e)}};function g(o,e=!1){return new ue(o,e)}var Ae=!1;function Fe(o){if(Ae)return;Ae=!0;let e=[""," %c"," \u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551"," \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551"," \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D",""].join(`
2
+ `),t=o?`%c WebChat SDK v${o}`:"%c WebChat SDK";console.log(e+`
3
+ `+t+`
4
+ `+"%c \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"+`
5
+ `,"color:#ffce1c;font-weight:bold","color:#9CA3AF;font-size:11px","color:#374151")}var U=class{constructor(e){this.sessionStartTime=null;this.messageSendTime=null;this.waitingForFirstMessage=!1;this.waitingForReply=!1;this.logger=g("Perf",e)}markSessionStarted(){this.sessionStartTime=performance.now(),this.waitingForFirstMessage=!0,this.logger.debug("Session started \u2014 waiting for first AI message")}markMessageSent(){this.messageSendTime=performance.now(),this.waitingForReply=!0,this.logger.debug("User message sent \u2014 waiting for AI response")}markBotMessageReceived(){let e=performance.now();if(this.waitingForFirstMessage&&this.sessionStartTime!==null){let t=e-this.sessionStartTime;this.logger.info(`First AI message: ${t.toFixed(0)}ms (from session start)`),this.waitingForFirstMessage=!1,this.sessionStartTime=null}if(this.waitingForReply&&this.messageSendTime!==null){let t=e-this.messageSendTime;this.logger.info(`AI response time: ${t.toFixed(0)}ms (from user message)`),this.waitingForReply=!1,this.messageSendTime=null}}reset(){this.sessionStartTime=null,this.messageSendTime=null,this.waitingForFirstMessage=!1,this.waitingForReply=!1}};var j=class{constructor(){this.listeners=new Map;this.logger=g("EventBus",!1)}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}once(e,t){let i=((...n)=>{t(...n),this.off(e,i)});this.on(e,i)}emit(e,...t){this.listeners.get(e)?.forEach(i=>{try{i(...t)}catch(n){this.logger.error(`EventBus error in "${e}" handler:`,n)}})}removeAll(){this.listeners.clear()}};var W=class{constructor(e){this.flowId=null;this.messages=[];this.eventBus=e}setFlowId(e){this.flowId=e,this.eventBus.emit("session:id",e)}getFlowId(){return this.flowId}addMessage(e){this.messages.push(e),this.eventBus.emit("message:added",e)}getMessages(){return[...this.messages]}clearMessages(){this.messages=[]}createUserMessage(e,t="text"){let i={id:crypto.randomUUID(),direction:"INBOUND",message_type:t,content:e,created_at:Date.now()/de.MILLISECONDS_TO_SECONDS};return this.addMessage(i),i}createBotMessage(e,t,i){let n={id:t??crypto.randomUUID(),direction:"OUTBOUND",message_type:"text",content:e,created_at:i??Date.now()/de.MILLISECONDS_TO_SECONDS};return this.addMessage(n),n}loadHistoryMessages(e){this.messages=e,this.eventBus.emit("history:loaded",this.messages)}loadHistoryMessagesWithMerge(e){let t=[...this.messages],n=[...e,...t],s=new Map;for(let a of n){let l=a.id;s.has(l)||s.set(l,a)}this.messages=Array.from(s.values()).sort((a,l)=>a.created_at-l.created_at),this.eventBus.emit("history:merged",this.messages)}clear(){this.flowId=null,this.messages=[],this.eventBus.emit("session:cleared")}};var he={FLOW_ID:"nimbus_webchat_flow_id"},$=class{constructor(e,t,i,n,s){this.ws=null;this.flowId=null;this.reconnectAttempts=0;this.reconnectTimer=null;this._state="idle";this.intentionalClose=!1;this.dns=e,this.agentId=t,this.eventBus=i,this.reconnectConfig=n,this.logger=g("WebSocket",s),this.flowId=this.loadFlowId()}get state(){return this._state}getFlowId(){return this.flowId}connect(e=!1){if(this.logger.debug(`connect() called with forceNew=${e}, ws state=${this.ws?.readyState}, flowId=${this.flowId}`),this.clearReconnectTimer(),!e&&this.isConnectedOrConnecting()){this.logger.debug("Already connected or connecting, skipping new connection");return}let t=this.closeExistingConnection(e);this.resetConnectionState(t),this.createWebSocketConnection()}isConnectedOrConnecting(){return this.ws!==null&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)}closeExistingConnection(e){return!e||!this.ws?!1:this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING?(this.intentionalClose=!0,this.ws.onopen=null,this.ws.onmessage=null,this.ws.onerror=null,this.ws.onclose=null,this.ws.close(ce.NORMAL,"Creating new connection"),this.ws=null,!0):(this.ws=null,!1)}resetConnectionState(e){e||(this.intentionalClose=!1),this.setState("connecting")}createWebSocketConnection(){let e=this.buildWebSocketUrl();this.logger.info(`Connecting to ${e}`),this.ws=new WebSocket(e),this.ws.onopen=this.onOpen.bind(this),this.ws.onmessage=this.onMessage.bind(this),this.ws.onerror=this.onError.bind(this),this.ws.onclose=this.onClose.bind(this)}buildWebSocketUrl(){let e=`wss://${this.dns}`,t=new URLSearchParams;return t.set("agent_id",this.agentId),this.flowId&&t.set("flow_id",this.flowId),`${e}?${t.toString()}`}disconnect(){this.intentionalClose=!0,this.clearReconnectTimer(),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.close(ce.NORMAL,"Client disconnect"),this.ws=null,this.setState("disconnected")}send(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.logger.warn("Cannot send message \u2014 WebSocket not connected");return}let t=JSON.stringify(e);this.logger.debug(`Sending: ${t}`),this.ws.send(t)}onOpen(){this.logger.info("Connected"),this.reconnectAttempts=0,this.intentionalClose=!1,this.setState("connected"),this.eventBus.emit("ws:open")}onMessage(e){this.logger.debug(`Received: ${e.data}`);try{let t=JSON.parse(e.data);if(t.type==="connected")this.flowId=t.flow_id,this.saveFlowId(t.flow_id),this.logger.info(`Connected with flow_id: ${t.flow_id}`);else if(t.type==="message"){if(t.direction!=="outbound"||!t.content){this.logger.debug("Ignoring invalid message: missing/empty content or wrong direction");return}}else{this.logger.debug(`Ignoring unknown event type: ${t.type}`);return}this.eventBus.emit("ws:message",t)}catch(t){this.logger.error("Failed to parse WebSocket message:",t)}}onError(e){this.logger.error("WebSocket error:",e),this.eventBus.emit("ws:error",e)}onClose(e){this.logger.info(`Connection closed: code=${e.code} reason="${e.reason}"`),this.ws===e.target&&(this.ws=null),this.eventBus.emit("ws:close",e),this.intentionalClose?this.setState("disconnected"):this.attemptReconnect()}attemptReconnect(){if(this.hasExceededMaxReconnectAttempts()){this.logger.error("Max reconnect attempts reached"),this.setState("disconnected");return}let e=this.calculateReconnectDelay();this.scheduleReconnect(e)}hasExceededMaxReconnectAttempts(){return this.reconnectAttempts>=this.reconnectConfig.attempts}calculateReconnectDelay(){return this.reconnectConfig.timeout}scheduleReconnect(e){this.setState("connecting"),this.reconnectAttempts++,this.logger.info(`Reconnecting in ${e}ms (attempt ${this.reconnectAttempts}/${this.reconnectConfig.attempts})`),this.reconnectTimer=setTimeout(()=>{this.connect()},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}setState(e){this._state=e,this.eventBus.emit("connection:state",e)}clearSession(){this.flowId=null,this.clearFlowId(),this.eventBus.emit("session:cleared")}saveFlowId(e){try{localStorage.setItem(he.FLOW_ID,e)}catch{}}loadFlowId(){try{return localStorage.getItem(he.FLOW_ID)}catch{return null}}clearFlowId(){try{localStorage.removeItem(he.FLOW_ID)}catch{}}};var G=class{constructor(e,t){this.abortController=null;this.dns=e,this.logger=g("API",t)}async fetchMessageHistory(e,t=C.MESSAGE_LIMIT,i){this.abortController?.abort(),this.abortController=new AbortController;let n=new URL(`https://${this.dns}/sessions/${e}/messages`);n.searchParams.set("limit",t.toString()),i&&n.searchParams.set("before",i.toString()),this.logger.debug(`Fetching history: ${n.toString()}`);try{let s=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"},signal:this.abortController.signal});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);let a=await s.json();return this.logger.debug(`Retrieved ${a.messages.length} messages, has_more: ${a.has_more}`),a}catch(s){throw s instanceof DOMException&&s.name==="AbortError"?(this.logger.debug("Request aborted"),s):(this.logger.error("Failed to fetch message history:",s),s)}}abort(){this.abortController?.abort(),this.abortController=null}};var Re='*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.19 | MIT License | https://tailwindcss.com*/*,:after,:before{box-sizing:border-box;border:0 solid #e5e7eb}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media (min-width:640px){.container{max-width:640px}}@media (min-width:768px){.container{max-width:768px}}@media (min-width:1024px){.container{max-width:1024px}}@media (min-width:1280px){.container{max-width:1280px}}@media (min-width:1536px){.container{max-width:1536px}}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.-right-1{right:-.25rem}.-top-1{top:-.25rem}.bottom-1{bottom:.25rem}.bottom-12{bottom:3rem}.bottom-2{bottom:.5rem}.bottom-5{bottom:1.25rem}.bottom-\\[10px\\]{bottom:10px}.left-0{left:0}.left-1{left:.25rem}.left-2{left:.5rem}.left-5{left:1.25rem}.right-0{right:0}.right-1{right:.25rem}.right-2{right:.5rem}.right-5{right:1.25rem}.top-0{top:0}.top-1{top:.25rem}.top-2{top:.5rem}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.mx-auto{margin-left:auto;margin-right:auto}.my-3{margin-top:.75rem;margin-bottom:.75rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.ml-2{margin-left:.5rem}.mr-2{margin-right:.5rem}.mt-0{margin-top:0}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.contents{display:contents}.hidden{display:none}.h-14{height:3.5rem}.h-2{height:.5rem}.h-3{height:.75rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-screen{height:100vh}.max-h-48{max-height:12rem}.max-h-64{max-height:16rem}.w-14{width:3.5rem}.w-2{width:.5rem}.w-3{width:.75rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-7{width:1.75rem}.w-full{width:100%}.max-w-\\[200px\\]{max-width:200px}.max-w-full{max-width:100%}.flex-1{flex:1 1 0%}.flex-shrink{flex-shrink:1}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.flex-grow{flex-grow:1}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(1turn)}}.animate-spin{animation:spin 1s linear infinite}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.resize{resize:both}.flex-row{flex-direction:row}.flex-row-reverse{flex-direction:row-reverse}.flex-col{flex-direction:column}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-2\\.5{gap:.625rem}.gap-3{gap:.75rem}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(.5rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem*var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(.75rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem*var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.break-words{overflow-wrap:break-word}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.rounded-t-xl{border-top-left-radius:.75rem;border-top-right-radius:.75rem}.rounded-bl-md{border-bottom-left-radius:.375rem}.rounded-br-md{border-bottom-right-radius:.375rem}.border{border-width:1px}.border-0{border-width:0}.border-t{border-top-width:1px}.border-slate-200{--tw-border-opacity:1;border-color:rgb(226 232 240/var(--tw-border-opacity,1))}.bg-black{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity,1))}.bg-black\\/10{background-color:rgba(0,0,0,.1)}.bg-blue-50{--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity,1))}.bg-blue-500{--tw-bg-opacity:1;background-color:rgb(59 130 246/var(--tw-bg-opacity,1))}.bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity,1))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity,1))}.bg-gray-400{--tw-bg-opacity:1;background-color:rgb(156 163 175/var(--tw-bg-opacity,1))}.bg-green-400{--tw-bg-opacity:1;background-color:rgb(74 222 128/var(--tw-bg-opacity,1))}.bg-green-500{--tw-bg-opacity:1;background-color:rgb(34 197 94/var(--tw-bg-opacity,1))}.bg-orange-400{--tw-bg-opacity:1;background-color:rgb(251 146 60/var(--tw-bg-opacity,1))}.bg-red-400{--tw-bg-opacity:1;background-color:rgb(248 113 113/var(--tw-bg-opacity,1))}.bg-red-50{--tw-bg-opacity:1;background-color:rgb(254 242 242/var(--tw-bg-opacity,1))}.bg-red-500{--tw-bg-opacity:1;background-color:rgb(239 68 68/var(--tw-bg-opacity,1))}.bg-slate-100{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.bg-slate-300{--tw-bg-opacity:1;background-color:rgb(203 213 225/var(--tw-bg-opacity,1))}.bg-slate-50{--tw-bg-opacity:1;background-color:rgb(248 250 252/var(--tw-bg-opacity,1))}.bg-slate-600{--tw-bg-opacity:1;background-color:rgb(71 85 105/var(--tw-bg-opacity,1))}.bg-transparent{background-color:transparent}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.bg-yellow-400{--tw-bg-opacity:1;background-color:rgb(250 204 21/var(--tw-bg-opacity,1))}.bg-yellow-50{--tw-bg-opacity:1;background-color:rgb(254 252 232/var(--tw-bg-opacity,1))}.object-cover{-o-object-fit:cover;object-fit:cover}.p-1{padding:.25rem}.p-1\\.5{padding:.375rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-3\\.5{padding-left:.875rem;padding-right:.875rem}.px-4{padding-left:1rem;padding-right:1rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-2{padding-bottom:.5rem}.pl-12{padding-left:3rem}.pl-4{padding-left:1rem}.pl-5{padding-left:1.25rem}.pl-6{padding-left:1.5rem}.pl-8{padding-left:2rem}.pr-12{padding-right:3rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji}.text-\\[10px\\]{font-size:10px}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-medium{font-weight:500}.font-semibold{font-weight:600}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.text-blue-500{--tw-text-opacity:1;color:rgb(59 130 246/var(--tw-text-opacity,1))}.text-blue-700{--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity,1))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity,1))}.text-gray-600{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity,1))}.text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity,1))}.text-red-50{--tw-text-opacity:1;color:rgb(254 242 242/var(--tw-text-opacity,1))}.text-red-500{--tw-text-opacity:1;color:rgb(239 68 68/var(--tw-text-opacity,1))}.text-red-700{--tw-text-opacity:1;color:rgb(185 28 28/var(--tw-text-opacity,1))}.text-slate-400{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}.text-slate-500{--tw-text-opacity:1;color:rgb(100 116 139/var(--tw-text-opacity,1))}.text-slate-600{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}.text-slate-700{--tw-text-opacity:1;color:rgb(51 65 85/var(--tw-text-opacity,1))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.text-yellow-700{--tw-text-opacity:1;color:rgb(161 98 7/var(--tw-text-opacity,1))}.underline{text-decoration-line:underline}.opacity-50{opacity:.5}.opacity-75{opacity:.75}.shadow{--tw-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px -1px rgba(0,0,0,.1);--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color)}.shadow,.shadow-2xl{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px rgba(0,0,0,.25);--tw-shadow-colored:0 25px 50px -12px var(--tw-shadow-color)}.shadow-lg{--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.shadow-lg,.shadow-sm{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 2px 0 rgba(0,0,0,.05);--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color)}.outline-none{outline:2px solid transparent;outline-offset:2px}.ring-blue-500{--tw-ring-opacity:1;--tw-ring-color:rgb(59 130 246/var(--tw-ring-opacity,1))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-shadow{transition-property:box-shadow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}.hover\\:scale-110:hover{--tw-scale-x:1.1;--tw-scale-y:1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\\:bg-blue-600:hover{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity,1))}.hover\\:bg-gray-200:hover{--tw-bg-opacity:1;background-color:rgb(229 231 235/var(--tw-bg-opacity,1))}.hover\\:bg-gray-50:hover{--tw-bg-opacity:1;background-color:rgb(249 250 251/var(--tw-bg-opacity,1))}.hover\\:bg-red-500:hover{--tw-bg-opacity:1;background-color:rgb(239 68 68/var(--tw-bg-opacity,1))}.hover\\:bg-slate-100:hover{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.hover\\:bg-white\\/20:hover{background-color:hsla(0,0%,100%,.2)}.hover\\:text-blue-600:hover{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.hover\\:text-white:hover{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.hover\\:opacity-80:hover{opacity:.8}.focus\\:border-blue-300:focus{--tw-border-opacity:1;border-color:rgb(147 197 253/var(--tw-border-opacity,1))}.focus\\:ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\\:ring-blue-500\\/20:focus{--tw-ring-color:rgba(59,130,246,.2)}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:opacity-40:disabled{opacity:.4}';var r=class o{constructor(e){this.element=e}static create(e,t,...i){let n=document.createElement(e),s=new o(n);return t&&s.props(t),i.length>0&&s.append(...i),s}static div(e,...t){return this.create("div",e,...t)}static span(e,...t){return this.create("span",e,...t)}static button(e,...t){return this.create("button",e,...t)}static img(e){return this.create("img",e)}static input(e){return this.create("input",e)}static textarea(e){return this.create("textarea",e)}static form(e,...t){return this.create("form",e,...t)}static label(e,...t){return this.create("label",e,...t)}props(e){let{className:t,style:i,dataset:n,attrs:s,on:a,...l}=e;return t&&(this.element.className=t),i&&Object.assign(this.element.style,i),n&&Object.entries(n).forEach(([d,c])=>{this.element.dataset[d]=c}),s&&Object.entries(s).forEach(([d,c])=>{this.element.setAttribute(d,c)}),a&&Object.entries(a).forEach(([d,c])=>{this.element.addEventListener(d,c)}),Object.entries(l).forEach(([d,c])=>{this.element[d]=c}),this}addClass(...e){return this.element.classList.add(...e.filter(Boolean)),this}setStyle(e){return Object.assign(this.element.style,e),this}on(e,t){return this.element.addEventListener(e,t),this}append(...e){let t=i=>{i==null||i===!1||(Array.isArray(i)?i.forEach(t):i instanceof o?this.element.appendChild(i.build()):i instanceof Node?this.element.appendChild(i):typeof i=="string"?this.element.appendChild(document.createTextNode(i)):typeof i=="number"&&this.element.appendChild(document.createTextNode(String(i))))};return e.forEach(t),this}html(e){return this.element.innerHTML=e,this}text(e){return this.element.textContent=e,this}attr(e,t){return this.element.setAttribute(e,t),this}data(e,t){return this.element.dataset[e]=t,this}if(e,t){return e&&t(this),this}build(){return this.element}mountTo(e){return(e instanceof o?e.build():e).appendChild(this.element),this.element}};var V=class{constructor(e){this.host=r.div({id:"nimbus-chat-root",style:{all:"initial",position:"fixed",zIndex:String(fe.WIDGET_ROOT)}}).mountTo(document.body),this.root=this.host.attachShadow({mode:"open"}),this.injectCSS(Re||"*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }"),this.injectCSS(e.getCSSVariables()),this.injectCSS(this.getComponentCSS())}injectCSS(e){let t=r.create("style").text(e).build();this.root.appendChild(t)}getComponentCSS(){return`
6
+ :host {
7
+ font-family: var(--nimbus-font, inherit);
8
+ font-size: 14px;
9
+ line-height: 1.5;
10
+ color: #1e293b;
11
+ }
12
+
13
+ .nimbus-header {
14
+ background-color: var(--nimbus-header-bg, var(--nimbus-theme-primary, #2563eb));
15
+ color: var(--nimbus-theme-secondary, #ffffff);
16
+ }
17
+
18
+ .nimbus-header button svg {
19
+ color: var(--nimbus-header-close, var(--nimbus-theme-secondary, #ffffff));
20
+ stroke: var(--nimbus-header-close, var(--nimbus-theme-secondary, #ffffff));
21
+ }
22
+
23
+ .nimbus-sidepanel {
24
+ background-color: var(--nimbus-bg-color, #ffffff);
25
+ }
26
+
27
+ .nimbus-bubble {
28
+ background-color: var(--nimbus-theme-primary, #2563eb);
29
+ }
30
+
31
+ .nimbus-bubble svg {
32
+ color: var(--nimbus-theme-secondary, #ffffff);
33
+ stroke: var(--nimbus-theme-secondary, #ffffff);
34
+ }
35
+
36
+ .nimbus-send-btn {
37
+ background-color: var(--nimbus-theme-primary, #2563eb);
38
+ }
39
+
40
+ .nimbus-send-btn:hover {
41
+ filter: brightness(0.9);
42
+ }
43
+
44
+ .nimbus-send-btn svg {
45
+ color: var(--nimbus-theme-secondary, #ffffff);
46
+ stroke: var(--nimbus-theme-secondary, #ffffff);
47
+ }
48
+
49
+ .nimbus-msg-user {
50
+ background-color: var(--nimbus-user-msg-bg, #2563eb);
51
+ color: var(--nimbus-user-msg-text, #fff);
52
+ font-family: var(--nimbus-user-msg-font, inherit);
53
+ font-size: var(--nimbus-user-msg-size, inherit);
54
+ }
55
+
56
+ .nimbus-msg-bot {
57
+ background-color: var(--nimbus-bot-msg-bg, #f1f5f9);
58
+ color: var(--nimbus-bot-msg-text, #1e293b);
59
+ font-family: var(--nimbus-bot-msg-font, inherit);
60
+ font-size: var(--nimbus-bot-msg-size, inherit);
61
+ }
62
+
63
+ .nimbus-input-field {
64
+ font-family: var(--nimbus-input-font, inherit);
65
+ background-color: var(--nimbus-input-bg, #f8fafc);
66
+ }
67
+
68
+ .nimbus-input-container {
69
+ background-color: var(--nimbus-input-container-bg, #ffffff);
70
+ }
71
+
72
+ .nimbus-send-btn-square {
73
+ border-radius: 0.375rem;
74
+ }
75
+
76
+ .nimbus-send-btn-text {
77
+ display: flex;
78
+ align-items: center;
79
+ gap: 6px;
80
+ color: var(--nimbus-theme-secondary, #fff);
81
+ font-size: 13px;
82
+ font-weight: 600;
83
+ padding: 8px 16px;
84
+ }
85
+
86
+ /* Auto-expanding textarea (no manual resize) */
87
+ .nimbus-textarea {
88
+ resize: none;
89
+ overflow-y: hidden;
90
+ min-height: 45px;
91
+ padding-right: 52px; /* room for send button inside */
92
+ line-height: 1.5;
93
+ transition: height 0.1s ease;
94
+ }
95
+
96
+ /* Scrollable once it hits max height */
97
+ .nimbus-textarea.nimbus-textarea-scroll {
98
+ overflow-y: auto !important;
99
+ }
100
+
101
+ .nimbus-textarea::-webkit-scrollbar {
102
+ width: 4px;
103
+ }
104
+ .nimbus-textarea::-webkit-scrollbar-track {
105
+ background: transparent;
106
+ margin-right: 4px;
107
+ }
108
+ .nimbus-textarea::-webkit-scrollbar-thumb {
109
+ background: #cbd5e1;
110
+ border-radius: 2px;
111
+ }
112
+
113
+ /* Textarea wrapper for send btn */
114
+ .nimbus-textarea-wrap {
115
+ position: relative;
116
+ }
117
+
118
+ /* Send button positioned inside textarea (bottom-right) */
119
+ .nimbus-send-inside {
120
+ position: absolute;
121
+ bottom: 9px;
122
+ right: 5px;
123
+ height: 35px;
124
+ width: 35px;
125
+ }
126
+
127
+ .nimbus-chat-body {
128
+ background-color: var(--nimbus-bg-color, #ffffff);
129
+ background-image: var(--nimbus-bg-image, none);
130
+ background-size: cover;
131
+ background-position: center;
132
+ }
133
+
134
+ /* Scrollbar */
135
+ .nimbus-message-list::-webkit-scrollbar {
136
+ width: 6px;
137
+ }
138
+ .nimbus-message-list::-webkit-scrollbar-track {
139
+ background: transparent;
140
+ }
141
+ .nimbus-message-list::-webkit-scrollbar-thumb {
142
+ background: #cbd5e1;
143
+ border-radius: 3px;
144
+ }
145
+
146
+ /* Typing indicator animation */
147
+ @keyframes nimbus-bounce {
148
+ 0%, 80%, 100% { transform: scale(0); }
149
+ 40% { transform: scale(1); }
150
+ }
151
+ .nimbus-typing-dot {
152
+ animation: nimbus-bounce 1.4s infinite ease-in-out both;
153
+ }
154
+ .nimbus-typing-dot:nth-child(1) { animation-delay: -0.32s; }
155
+ .nimbus-typing-dot:nth-child(2) { animation-delay: -0.16s; }
156
+
157
+ /* Loader spin */
158
+ @keyframes nimbus-spin {
159
+ to { transform: rotate(360deg); }
160
+ }
161
+ .nimbus-spin {
162
+ animation: nimbus-spin 1s linear infinite;
163
+ }
164
+
165
+ /* Bubble pulse */
166
+ @keyframes nimbus-pulse {
167
+ 0%, 100% { transform: scale(1); }
168
+ 50% { transform: scale(1.05); }
169
+ }
170
+
171
+ /* Transition helpers */
172
+ .nimbus-fade-in {
173
+ animation: nimbus-fade 0.2s ease-out;
174
+ }
175
+ @keyframes nimbus-fade {
176
+ from { opacity: 0; transform: translateY(8px); }
177
+ to { opacity: 1; transform: translateY(0); }
178
+ }
179
+ `}destroy(){this.host.remove()}};var K=class{constructor(e){this.config=e}getCSSVariables(){let e=this.config,t=e.style.background,i=t.startsWith("url(")||t.startsWith("http")||t.startsWith("/");return`:host {
180
+ ${[` --nimbus-theme-primary: ${e.theme.primary};`,` --nimbus-theme-secondary: ${e.theme.secondary};`,` --nimbus-bg-color: ${i?"transparent":t};`,` --nimbus-bg-image: ${i?t.startsWith("url(")?t:`url(${t})`:"none"};`,` --nimbus-user-msg-bg: ${e.userMessage.background};`,` --nimbus-user-msg-text: ${e.userMessage.text.color};`,` --nimbus-bot-msg-bg: ${e.botMessage.background};`,` --nimbus-bot-msg-text: ${e.botMessage.text.color};`,e.style.font?` --nimbus-font: ${e.style.font};`:null,e.userMessage.text.font?` --nimbus-user-msg-font: ${e.userMessage.text.font};`:null,e.userMessage.text.size?` --nimbus-user-msg-size: ${e.userMessage.text.size}px;`:null,e.botMessage.text.font?` --nimbus-bot-msg-font: ${e.botMessage.text.font};`:null,e.botMessage.text.size?` --nimbus-bot-msg-size: ${e.botMessage.text.size}px;`:null,e.input.text?.font?` --nimbus-input-font: ${e.input.text.font};`:null,e.input.background?.primary?` --nimbus-input-bg: ${e.input.background.primary};`:null,e.input.background?.secondary?` --nimbus-input-container-bg: ${e.input.background.secondary};`:null].filter(Boolean).join(`
181
+ `)}
182
+ }`}};var Oe=require("lucide");var Qe=g("Icons"),ge=new Map;function et(o){return o.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function tt(o){if(ge.has(o))return ge.get(o);let e=et(o),t=Oe.icons[e];return t&&ge.set(o,t),t}function it(o){return o.startsWith("http://")||o.startsWith("https://")}function me(o,e,t="currentColor",i){return it(o)?ot(o,e,i):nt(o,e,t,i)}function ot(o,e,t){return r.img({src:o,width:e,height:e,className:t||"",style:{display:"block"}}).build()}function nt(o,e,t,i){let n=tt(o);if(!n)return Qe.warn(`Unknown icon: ${o}`),document.createElementNS("http://www.w3.org/2000/svg","svg");let s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("width",String(e)),s.setAttribute("height",String(e)),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width","2"),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),i&&s.setAttribute("class",i);function a(l){let[d,c,...x]=l,w=document.createElementNS("http://www.w3.org/2000/svg",d);return c&&typeof c=="object"&&Object.entries(c).forEach(([h,E])=>{w.setAttribute(h,String(E))}),x.forEach(h=>{Array.isArray(h)&&w.appendChild(a(h))}),w}return n.forEach(l=>{s.appendChild(a(l))}),s}var u=class o{static create(e,t=m.MESSAGE_CIRCLE,i=24,n={}){let s=e?.size?.width??i,a=e?.size?.height??i,l={alignItems:"center",justifySelf:"anchor-center",width:`${s}px`,height:`${a}px`,overflow:"hidden",flexShrink:"0"};n.borderRadius&&(l.borderRadius=n.borderRadius),n.marginBottom&&(l.marginBottom=n.marginBottom);let d=e?.img??t,c=null;if(d){let x=n.sizeFactor??O.DEFAULT_ICON_SIZE_FACTOR,w=Math.min(s,a)*x,h=e?.color??"currentColor",E=me(d,w,h),N=n.objectFit??"contain";E.style.cssText=`width: 100%; height: 100%; object-fit: ${N}; border: none;`,c=E}return r.div({style:l},c).build()}static createSimple(e,t=18,i="currentColor"){return me(e,t,i)}static createExceptionIcon(e,t,i,n){if(!e)return null;let s=e.img||"alert-triangle",a=e.size?.width||20,l=e.color,d=o.createSimple(s,a,l);return d?r.span({title:t,className:n,style:{marginLeft:i?"0":"4px",marginRight:i?"4px":"0",display:"inline-flex",alignItems:"center"}},d).build():null}};var v=class o{static applyTextStyle(e,t,i){if(!t&&!i)return;let n=t?.color??i?.color;n&&(e.style.color=n);let s=t?.font??i?.font;s&&(e.style.fontFamily=s);let a=t?.size??i?.size;a&&(e.style.fontSize=`${a}px`)}static buildClassNames(...e){return e.filter(Boolean).join(" ")}static applyStyles(e,t){Object.entries(t).forEach(([i,n])=>{n&&e.style.setProperty(i,n)})}static cssVar(e){return`--nimbus-${e}`}static setCssVariables(e,t){Object.entries(t).forEach(([i,n])=>{n&&e.style.setProperty(o.cssVar(i),n)})}};var M=class{static createIconButton(e,t,i="action"){let n=u.createSimple(e,t.iconSize||p.BUTTON_MEDIUM),s=[this.VARIANTS[i],t.className||""].filter(Boolean).join(" ");return r.button({className:s,title:t.title,type:"button",on:{click:t.onClick}},n).build()}static createTextButton(e,t,i="action"){let n=[this.VARIANTS[i],t.className||""].filter(Boolean).join(" ");return r.button({className:n,title:t.title,type:"button",on:{click:t.onClick}}).text(e).build()}static createIconTextButton(e,t,i,n="action"){let s=u.createSimple(e,i.iconSize||p.BUTTON_SMALL),a=[this.VARIANTS[n],"flex items-center gap-2",i.className||""].filter(Boolean).join(" ");return r.button({className:a,title:i.title,type:"button",on:{click:i.onClick}},s,r.span().text(t)).build()}static createCloseButton(e,t="Close"){return this.createTextButton("\xD7",{onClick:e,title:t,className:"absolute top-2 right-2 z-10 flex items-center justify-center"},"remove")}};M.VARIANTS={header:"p-1 rounded-lg hover:bg-white/20 transition-colors cursor-pointer",action:"px-4 py-2 rounded transition-opacity hover:opacity-80",remove:"w-5 h-5 rounded-full bg-slate-300 hover:bg-red-500 text-slate-600 hover:text-white transition-colors",primary:"px-3 py-1 bg-blue-500 text-white rounded text-sm hover:bg-blue-600",secondary:"block w-full text-left p-2 border rounded hover:bg-gray-50"};var y=class{constructor(e={}){this._element=null;this.destroyed=!1;this.mounted=!1;this.eventListeners=[];this.hooks=e,this.logger=g(this.constructor.name)}get element(){return this._element||(this._element=this.render(),this.afterRender()),this._element}afterRender(){}addEventListener(e,t,i){e.addEventListener(t,i),this.eventListeners.push({element:e,event:t,handler:i})}mount(e){this.mounted||this.destroyed||(e.appendChild(this.element),this.mounted=!0,this.hooks.onMount?.())}unmount(){!this.mounted||this.destroyed||(this.element.remove(),this.mounted=!1,this.hooks.onUnmount?.())}update(e){this.destroyed||this.hooks.onUpdate?.(e)}destroy(){this.destroyed||(this.unmount(),this.eventListeners.forEach(({element:e,event:t,handler:i})=>{e.removeEventListener(t,i)}),this.eventListeners=[],this.hooks.onDestroy?.(),this.destroyed=!0,this._element=null)}};var X=class extends y{constructor(t,i,n,s){super();this.currentConnectionState="idle";this.isTyping=!1;this.headerConfig=t,this.onClose=i,this.allowNewChat=n,this.onNewChat=s,this.el=this.element}render(){let t=this.headerConfig.color,i=[],n=this.headerConfig.icon;n&&i.push(u.create(n,m.MESSAGE_CIRCLE,p.AVATAR));let s=this.headerConfig.text;if(s?.display!==!1){let w=r.span({className:"font-semibold truncate"}).text(s?.value??"Nimbus").build();v.applyTextStyle(w,s,{size:14}),i.push(w)}this.statusDot=r.span({className:"inline-block w-2 h-2 rounded-full bg-green-400 shrink-0",title:b.CONNECTED}).build(),i.push(this.statusDot),this.statusText=r.span({className:"text-xs"}).text("Online").build(),s&&v.applyTextStyle(this.statusText,s,{size:12}),i.push(this.statusText);let l=r.div({className:"flex items-center gap-2.5"},...i),d=[];this.allowNewChat&&this.onNewChat&&d.push(M.createIconButton(m.NEW_CHAT,{onClick:this.onNewChat,title:b.NEW_CHAT,iconSize:p.BUTTON_MEDIUM},"header")),d.push(M.createIconButton(m.CLOSE,{onClick:this.onClose,title:"Close",iconSize:p.BUTTON_MEDIUM},"header"));let c=r.div({className:"flex items-center gap-1"},...d),x=r.div({className:"nimbus-header flex items-center justify-between px-4 py-3 rounded-t-xl select-none",style:t?.primary?{backgroundColor:t.primary}:void 0},l,c).build();return t?.secondary&&x.style.setProperty("--nimbus-header-close",t.secondary),x}setConnectionState(t){this.currentConnectionState=t,this.statusDot.className=`inline-block w-2 h-2 rounded-full shrink-0 ${this.getStatusDotColor()}`,this.statusDot.title=t.charAt(0).toUpperCase()+t.slice(1),!this.isTyping&&this.statusText&&(this.statusText.textContent=this.getStatusText())}showTypingIndicator(t){this.isTyping=!0,this.statusText&&t.title?.value&&(this.statusText.textContent=t.title.value,t.title.text&&v.applyTextStyle(this.statusText,t.title.text,{size:12}))}hideTypingIndicator(){this.isTyping=!1,this.statusText&&(this.statusText.textContent=this.getStatusText(),v.applyTextStyle(this.statusText,this.headerConfig.text,{size:12}))}getStatusText(){switch(this.currentConnectionState){case"connected":return"Online";case"connecting":return"Connecting...";case"disconnected":return"Offline";default:return"Offline"}}getStatusDotColor(){return{idle:"bg-gray-400",connected:"bg-green-400",connecting:"bg-yellow-400",disconnected:"bg-red-400"}[this.currentConnectionState]}};var T=class{static formatFileSize(e,t=!1){if(e===0)return t?"0 B":"0 Bytes";let i=1024,n=t?["B","KB","MB","GB"]:["Bytes","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(i));return Math.round(e/Math.pow(i,s)*100)/100+" "+n[s]}static fileToBase64(e){return new Promise((t,i)=>{let n=new FileReader;n.onload=()=>{if(typeof n.result=="string"){let s=n.result.split(",")[1];t(s)}else i(new Error("Failed to read file as base64"))},n.onerror=i,n.readAsDataURL(e)})}};var Y=class extends y{constructor(e,t){super(),this.message=e,this.options=t,this.el=this.element}render(){let e=this.message.direction==="INBOUND",t=this.options?.width??`${O.DEFAULT_BUBBLE_MAX_WIDTH}px`,i=this.options?.icon,n=i?u.create(i,m.MESSAGE_CIRCLE,p.AVATAR,{borderRadius:Ee.AVATAR,marginBottom:`${Ce.AVATAR_MARGIN}px`,objectFit:"cover",sizeFactor:O.MESSAGE_AVATAR_SIZE_FACTOR}):null,s=r.div({className:[e?"nimbus-msg-user":"nimbus-msg-bot","px-3.5 py-2.5 text-sm leading-relaxed",e?"rounded-2xl rounded-br-md":"rounded-2xl rounded-bl-md","break-words whitespace-pre-wrap overflow-wrap-anywhere"].join(" "),style:{maxWidth:"100%",wordBreak:"break-word"}},this.renderContent(this.message),r.div({className:"text-[10px] mt-1 opacity-50 select-none"}).text(this.formatTime(new Date(this.message.created_at*1e3)))),a=r.div({className:`flex items-end gap-2 ${e?"flex-row-reverse":"flex-row"}`,style:{maxWidth:t}});return n&&a.append(n),a.append(s),r.div({className:`flex ${e?"justify-end":"justify-start"} nimbus-fade-in`},a).build()}renderContent(e){switch(e.message_type){case"json":return this.renderJson(e.content);case"file":if(e.content==="SHARED_FILE")return this.renderSharedFile(e);if(e.direction==="OUTBOUND"&&e.filename){let i={content:typeof e.content=="string"?e.content:JSON.stringify(e.content),filename:e.filename??void 0,filetype:e.filetype??void 0,filesize:e.filesize??void 0,description:e.description??void 0};return this.renderFile(i)}let t=e.content;if(typeof t=="string"){let i=this.tryParseJson(t);i&&(t=i)}return this.renderFile(t);default:return this.renderText(typeof e.content=="string"?e.content:JSON.stringify(e.content))}}renderText(e){return r.span().text(e).build()}renderJson(e){let t;if(typeof e=="object")t=JSON.stringify(e,null,2);else try{t=JSON.stringify(JSON.parse(e),null,2)}catch{t=e}return r.create("pre",{className:"text-xs font-mono bg-black/10 rounded p-2 overflow-x-auto"}).text(t).build()}renderSharedFile(e){let t=r.div({className:"space-y-2"});return e.description&&e.description.trim()&&t.append(r.div({className:"text-sm mb-2"}).text(e.description)),t.append(this.createFileInfo(e.filename,e.filesize)),t.append(this.createSharedFileIndicator()),t.build()}renderFile(e){if(typeof e=="object")return this.renderFileObject(e);if(typeof e=="string"){let i=this.tryParseJson(e);return i?this.renderFileObject(i):this.renderRawContent(e)}let t=r.div({className:"space-y-2"});return t.append(r.div({className:"text-red-500 text-sm"}).text("Invalid file format")),t.build()}renderFileObject(e){let t=r.div({className:"space-y-2"});return e.description&&e.description.trim()&&t.append(r.div({className:"text-sm mb-2"}).text(e.description)),t.append(this.createFileInfo(e.filename,e.filesize)),e.content&&e.content.trim()?t.append(this.renderFileContent(e)):t.append(this.createSharedFileIndicator()),t.build()}renderFileContent(e){let t=this.message.direction==="INBOUND";if(e.filetype&&e.filetype.startsWith("image/"))return r.img({src:`data:${e.filetype};base64,${e.content}`,className:"max-w-full rounded-lg max-h-64",alt:e.filename||"Uploaded image"}).build();{if(t)return this.createSharedFileIndicator();let i=r.create("a",{href:`data:${e.filetype||"application/octet-stream"};base64,${e.content}`,download:e.filename||"download",className:"inline-flex items-center gap-2 px-3 py-2 bg-gray-100 rounded hover:bg-gray-200"}),n=u.create(null,"file",p.BUTTON_SMALL);return i.append(n),i.append(r.span().text(b.DOWNLOAD_FILE)),i.build()}}createSharedFileIndicator(){let e=r.div({className:"inline-flex items-center gap-2 px-3 py-2 bg-gray-100 rounded text-gray-600"}),t=u.create(null,"file",p.BUTTON_SMALL);return e.append(t),e.append(r.span().text("Shared a file")),e.build()}createFileInfo(e,t){let i=r.div({className:"text-xs opacity-75 mb-1"});return i.append(r.span().text(`${e||"File"} `),r.span({className:"text-gray-500"}).text(t?`(${T.formatFileSize(t)})`:"")),i.build()}tryParseJson(e){try{return JSON.parse(e)}catch{return null}}renderRawContent(e){let t=this.message.direction==="INBOUND",i=r.div({className:"space-y-2"});return e.startsWith("data:")?e.startsWith("data:image")?i.append(r.img({src:e,className:"max-w-full rounded-lg max-h-64",alt:"Shared image"})):t?i.append(this.createSharedFileIndicator()):i.append(r.create("a",{href:e,download:"file",className:"inline-flex items-center gap-2 px-3 py-2 bg-gray-100 rounded hover:bg-gray-200"},u.create(null,"file",p.BUTTON_SMALL),r.span().text(b.DOWNLOAD_FILE))):e.match(/^[A-Za-z0-9+/=]+$/)?i.append(r.img({src:`data:image/png;base64,${e}`,className:"max-w-full rounded-lg max-h-64",alt:"Shared image"})):e.startsWith("http")?t?i.append(this.createSharedFileIndicator()):i.append(r.create("a",{href:e,className:"underline text-blue-500 hover:text-blue-600",target:"_blank",rel:"noopener noreferrer"}).text(b.DOWNLOAD_FILE)):i.append(r.div({className:"text-gray-600 text-sm"}).text(`File: ${e.substring(0,50)}${e.length>50?"...":""}`)),i.build()}formatTime(e){return e.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}};var Z=class extends y{constructor(t,i,n,s,a,l){super();this.hasMoreMessages=!1;this.userIcon=a,this.botIcon=l,this.userMessageWidth=n,this.botMessageWidth=s,this.showMoreConfig=t,this.primaryColor=i,this.el=this.element}render(){return r.div({className:"nimbus-message-list nimbus-chat-body flex-1 overflow-y-auto p-4 space-y-3"}).build()}addMessage(t){this.hideWelcome();let i=t.direction==="INBOUND",n={icon:i?this.userIcon:this.botIcon,width:i?this.userMessageWidth:this.botMessageWidth},s=new Y(t,n);s.el.setAttribute("data-message-id",t.id),this.el.appendChild(s.el),this.scrollToBottom()}clear(){this.el.replaceChildren(),this.showMoreButton=void 0}showWelcome(t){if(t.display===!1)return;let i=r.div(),n=this.getWelcomeTextValue(t.preTitle);if(n){let c=r.span().text(n).build();this.applyWelcomeTextStyle(c,t.preTitle),i.append(c)}let s=this.getWelcomeTextValue(t.title);if(s){let c=r.create("strong").text(s).build();this.applyWelcomeTextStyle(c,t.title),i.append(c)}let a=this.getWelcomeTextValue(t.subtitle),l=a?(()=>{let c=r.div({className:"mt-1 text-xs"}).text(a).build();return this.applyWelcomeTextStyle(c,t.subtitle),c})():null,d=r.div({className:"nimbus-welcome text-center text-sm py-8 select-none"},i,l).build();this.el.appendChild(d)}hideWelcome(){let t=this.el.querySelector(".nimbus-welcome");t&&t.remove()}getWelcomeTextValue(t){return t?.value??t?.value}applyWelcomeTextStyle(t,i){i&&("text"in i&&i.text?v.applyTextStyle(t,i.text):v.applyTextStyle(t,i))}showError(t){let n=r.div({className:"nimbus-system-message text-center p-3 rounded bg-red-50 text-red-700"},r.div().text(t)).build();this.el.appendChild(n)}showShowMoreButton(t){this.hideShowMoreButton();let i="nimbus-show-more mx-auto mb-4 px-4 py-2 rounded-full text-sm transition-colors flex items-center gap-2",n=this.showMoreConfig.sticky?"sticky top-0 z-10":"",s=[];if(this.showMoreConfig.icon){let l=u.create(this.showMoreConfig.icon,m.CHEVRON_DOWN,p.BUTTON_SMALL,{borderRadius:"50%"});l&&s.push(l)}let a=r.span().text(this.showMoreConfig.value||b.SHOW_MORE).build();this.showMoreConfig.text&&v.applyTextStyle(a,this.showMoreConfig.text),s.push(a),this.showMoreButton=r.button({className:`${i} ${n}`.trim(),style:{backgroundColor:this.showMoreConfig.background||"#ffffff",border:`1px solid ${this.primaryColor}`},type:"button",on:{click:t}},...s).build(),this.el.insertBefore(this.showMoreButton,this.el.firstChild)}hideShowMoreButton(){this.showMoreButton&&(this.showMoreButton.remove(),this.showMoreButton=void 0)}updateHasMore(t){this.hasMoreMessages=t,t||this.hideShowMoreButton()}scrollToBottom(){requestAnimationFrame(()=>{this.el.scrollTop=this.el.scrollHeight})}scrollToTop(){requestAnimationFrame(()=>{this.el.scrollTop=0})}};var q=class{constructor(e,t,i){this.config=e,this.callbacks=t,this.logger=g("FileUploadButton",i),this.inputEl=r.input({type:"file",className:"hidden",accept:this.config.allowedFileTypes?.join(",")||"*",on:{change:()=>this.handleFileChange()}}).build();let n=u.create(this.config.icon,m.PAPERCLIP,p.BUTTON_SMALL);this.buttonEl=r.button({className:["nimbus-upload-btn","p-2","rounded-full","transition-all cursor-pointer","hover:bg-slate-100","disabled:opacity-40 disabled:cursor-not-allowed","flex items-center justify-center"].join(" "),title:b.UPLOAD_FILE,type:"button",on:{click:()=>this.openFileDialog()}},n,this.inputEl).build()}get element(){return this.buttonEl}openFileDialog(){this.inputEl.click()}async handleFileChange(){let e=this.inputEl.files?.[0];if(!e)return;let t=this.config.maxFileSize??C.MAX_FILE_SIZE;if(e.size>t){let i=T.formatFileSize(t);this.callbacks.onError(`Max File Size: ${i}`),this.inputEl.value="";return}if(this.config.allowedFileTypes&&this.config.allowedFileTypes.length>0&&!this.config.allowedFileTypes.includes(e.type)){this.callbacks.onError(`File type ${e.type} is not allowed`),this.inputEl.value="";return}try{let i=await T.fileToBase64(e);this.logger.debug(`File selected: ${e.name} (${e.size} bytes)`),this.callbacks.onFileSelected(e,i),this.inputEl.value=""}catch(i){this.logger.error("Error processing file:",i),this.callbacks.onError("Failed to process file"),this.inputEl.value=""}}enable(){this.buttonEl.disabled=!1}disable(){this.buttonEl.disabled=!0}setEnabled(e){this.buttonEl.disabled=!e}};var J=class{constructor(e){this.fileData=null;this.onRemove=e,this.container=this.createContainer()}createContainer(){return r.div({className:"nimbus-file-preview hidden"}).build()}setFile(e){if(this.fileData=e,!e){this.container.classList.add("hidden"),this.container.innerHTML="";return}this.container.innerHTML="",this.container.classList.remove("hidden");let t=r.div({className:"relative w-full px-3 py-2 bg-slate-100 border border-slate-200 rounded-lg"}).build(),i=r.button({className:["absolute top-1 right-1","flex items-center justify-center","w-5 h-5 rounded-full","bg-slate-300 hover:bg-red-500 text-slate-600 hover:text-white","transition-colors duration-200","text-xs leading-none"].join(" "),type:"button",title:"Remove file",on:{click:d=>{d.preventDefault(),d.stopPropagation(),this.removeFile()}}}).text("\xD7").build();t.appendChild(i);let n=u.create(null,"file-text",p.BUTTON_MEDIUM),s=r.span({className:"text-sm font-medium text-slate-700 truncate max-w-[200px]"}).text(e.file.name),a=r.span({className:"text-xs text-slate-500 flex-shrink-0"}).text(T.formatFileSize(e.file.size,!0)),l=r.div({className:"flex items-center justify-between pr-6"},r.div({className:"flex items-center gap-3"},n,s),a);t.appendChild(l.build()),this.container.appendChild(t)}removeFile(){this.setFile(null),this.onRemove()}getFileData(){return this.fileData}get element(){return this.container}};var Q=class extends y{constructor(t,i,n){super();this.pendingFile=null;this.errorContainer=null;this.errorTimeout=null;this.config=t,this.debug=n,this.logger=g("InputArea",n),this.callbacks=i,this.expandable=t.expandable,this.el=this.element}render(){this.config.upload&&(this.filePreview=new J(()=>{this.pendingFile=null,this.toggleUploadButton(!0)})),this.config.upload&&this.callbacks.onFileUpload&&(this.uploadButton=new q(this.config.upload,{onFileSelected:(h,E)=>{this.pendingFile={file:h,base64Content:E},this.filePreview?.setFile(this.pendingFile),this.toggleUploadButton(!1)},onError:h=>{this.logger.error("File upload error:",h),this.showError(h)}},this.debug));let t=u.create(this.config.sendButton.icon,m.SEND,p.BUTTON_SMALL);this.sendBtn=r.button({className:["nimbus-send-btn","rounded-full","p-1.5","transition-all cursor-pointer shrink-0","disabled:opacity-40 disabled:cursor-not-allowed"].join(" "),title:b.SEND,type:"button",on:{click:()=>this.handleSend()}},t).build();let s=["nimbus-input-field","w-full py-2.5 text-sm outline-none","focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300 transition-all",this.config.upload&&this.uploadButton?"pl-12 pr-12":"pl-4 pr-12"],a=h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),this.handleSend())};this.typingBar=r.div({className:"nimbus-typing-bar hidden px-4 py-1.5 text-xs border-t border-slate-200"}).build();let l=r.div({className:"nimbus-input-container border-t border-slate-200"}),d={};this.config.text?.color&&(d.color=this.config.text.color),this.config.text?.font&&(d.fontFamily=this.config.text.font),this.config.text?.size&&(d.fontSize=`${this.config.text.size}px`),this.config.expandable?this.inputEl=r.textarea({placeholder:this.config.placeholder,rows:1,className:[...s,"nimbus-textarea border border-slate-200 rounded-xl"].join(" "),style:d,on:{keydown:a,input:()=>{this.autoResize(this.inputEl),this.updateCharacterCounter()}}}).build():this.inputEl=r.input({type:"text",placeholder:this.config.placeholder,className:[...s,"border border-slate-200 rounded-full"].join(" "),style:d,on:{keydown:a,input:()=>this.updateCharacterCounter()}}).build();let c=r.div({className:this.config.expandable?"relative w-full":"relative w-full flex items-center"}).build();if(c.appendChild(this.inputEl),this.uploadButton){let h=this.config.expandable?["absolute","left-1","bottom-2","z-10"]:["absolute","left-1","z-10"];this.uploadButton.element.classList.add(...h),c.appendChild(this.uploadButton.element)}let x=["absolute","right-1","bottom-[10px]","z-10"];this.sendBtn.classList.add(...x),c.appendChild(this.sendBtn),l.append(this.typingBar);let w=r.div({className:"p-3"});return w.append(c),this.errorContainer=null,this.bottomArea=r.div({className:"nimbus-bottom-area"}).build(),this.filePreview&&this.bottomArea.appendChild(this.filePreview.element),w.append(this.bottomArea),this.config.maxCharacters&&(this.characterCounter=this.createCharacterCounter(),w.append(this.characterCounter)),l.append(w),l.build()}createCharacterCounter(){let t=this.config.maxCharacters,i={};return t.text?.color&&(i.color=t.text.color),t.text?.size&&(i.fontSize=`${t.text.size}px`),t.text?.font&&(i.fontFamily=t.text.font),r.div({className:"nimbus-character-counter text-right px-3 py-1",style:i}).text(`0/${t.limit}`).build()}updateCharacterCounter(){if(!this.characterCounter||!this.config.maxCharacters)return;let t=this.inputEl.value.length,i=this.config.maxCharacters.limit;this.characterCounter.textContent=`${t}/${i}`,t>i?this.characterCounter.style.color="red":t>i*.9?this.characterCounter.style.color="orange":this.characterCounter.style.color=this.config.maxCharacters.text?.color||"#6b7280"}autoResize(t){t.style.height="auto";let i=t.scrollHeight;i>le.MAX_HEIGHT?(t.style.height=le.MAX_HEIGHT+"px",t.classList.add("nimbus-textarea-scroll")):(t.style.height=i+"px",t.classList.remove("nimbus-textarea-scroll"))}handleSend(){let t=this.inputEl.value.trim();if(this.config.maxCharacters&&t.length>this.config.maxCharacters.limit){this.logger.warn(`Message exceeds character limit: ${t.length}/${this.config.maxCharacters.limit}`);return}if(this.pendingFile)this.callbacks.onFileUpload&&this.callbacks.onFileUpload(this.pendingFile.file,this.pendingFile.base64Content,t),this.pendingFile=null,this.filePreview?.setFile(null),this.toggleUploadButton(!0);else if(t)this.callbacks.onSend(t);else return;this.inputEl.value="",this.updateCharacterCounter(),this.expandable&&this.inputEl instanceof HTMLTextAreaElement&&(this.inputEl.style.height="auto",this.inputEl.classList.remove("nimbus-textarea-scroll")),this.inputEl.focus()}toggleUploadButton(t){this.uploadButton&&this.uploadButton.element.classList.toggle("hidden",!t),this.updateInputPadding(!t)}updateInputPadding(t){t?(this.inputEl.classList.remove("pl-12"),this.inputEl.classList.add("pl-4")):this.config.upload&&(this.inputEl.classList.remove("pl-4"),this.inputEl.classList.add("pl-12"))}disable(){this.inputEl.disabled=!0,this.sendBtn.disabled=!0,this.uploadButton?.disable()}enable(){this.inputEl.disabled=!1,this.sendBtn.disabled=!1,this.uploadButton?.enable()}setEnabled(t){t?this.enable():this.disable()}focus(){this.inputEl.focus()}showTypingIndicator(t){this.typingBar&&(this.typingBar.textContent=t.title?.value??"",t.title?.text?.color&&(this.typingBar.style.color=t.title.text.color),t.title?.text?.font&&(this.typingBar.style.fontFamily=t.title.text.font),t.title?.text?.size&&(this.typingBar.style.fontSize=`${t.title.text.size}px`),this.typingBar.classList.remove("hidden"))}hideTypingIndicator(){this.typingBar&&this.typingBar.classList.add("hidden")}showError(t){this.hideError(),this.errorContainer=r.div({className:"nimbus-upload-error bg-red-500 text-white text-sm px-3 py-2 mt-2 rounded-lg"}).text(t).build(),this.bottomArea.appendChild(this.errorContainer);let i=this.config.upload?.errorDisplayDuration||2e3;this.errorTimeout=setTimeout(()=>{this.hideError()},i)}hideError(){this.errorTimeout&&(clearTimeout(this.errorTimeout),this.errorTimeout=null),this.errorContainer&&(this.errorContainer.remove(),this.errorContainer=null)}};var ee=class extends y{constructor(t,i){super();this.isOpen=!1;this.config=t,this.onToggle=i,this.el=this.element}render(){return r.button({className:["nimbus-bubble","fixed z-50 w-14 h-14 shadow-lg","rounded-full","flex items-center justify-center cursor-pointer","transition-all duration-200 hover:scale-110",this.config.position==="bottom-right"?"right-5 bottom-5":"left-5 bottom-5"].join(" "),title:b.OPEN_CHAT,type:"button",on:{click:()=>{this.isOpen=!this.isOpen,this.updateIcon(),this.onToggle()}}},this.createBubbleIcon()).build()}setOpen(t){this.isOpen=t,this.updateIcon()}createBubbleIcon(){return u.create(this.config.icon,m.MESSAGE_CIRCLE,p.AVATAR,{sizeFactor:Te.BUBBLE_ICON})}updateIcon(){if(this.el.replaceChildren(),this.isOpen){let t=u.createSimple(m.CHEVRON_DOWN,p.BUBBLE_OPEN);this.el.appendChild(t),this.el.title=b.CLOSE_CHAT}else{let t=this.createBubbleIcon();t&&this.el.appendChild(t),this.el.title=b.OPEN_CHAT}}};var k=class{constructor(e,t,i,n){this.isOpen=!1;this.hasRequestedConnect=!1;this.waitForReplyTimeout=null;this.shouldScrollToTop=!1;this.waitingForFirstReply=!1;this.firstReplyTimeout=null;this.eventUnsubscribers=[];this.config=e,this.eventBus=t,this.session=i,this.wsManager=n,this.initializeComponents(),this.panel=this.buildPanel(),this.setupDOM(),this.messageList.showWelcome(e.welcome),this.bindEvents()}initializeComponents(){let e=new K(this.config);this.shadow=new V(e),this.header=new X(this.config.header,()=>this.close(),this.config.allowNewChat,()=>this.eventBus.emit("ui:start-new-chat")),this.messageList=new Z(this.config.showMore,this.config.theme.primary,this.config.userMessage.width,this.config.botMessage.width,this.config.userMessage.icon,this.config.botMessage.icon),this.inputArea=new Q({placeholder:this.config.input.placeholder,expandable:this.config.input.expandable,text:this.config.input.text,background:this.config.input.background,sendButton:this.config.sendButton,upload:this.config.input.upload,maxCharacters:this.config.input.maxCharacters},{onSend:t=>this.handleSend(t),onFileUpload:this.config.input.upload?(t,i,n)=>this.handleFileUpload(t,i,n):void 0},this.config.debug),this.bubble=new ee({position:this.config.bubble.position,autoHide:this.config.bubble.autoHide,icon:this.config.bubble.icon},()=>this.toggle())}setupDOM(){this.shadow.root.appendChild(this.bubble.el),this.shadow.root.appendChild(this.panel)}open(){this.hasRequestedConnect||(this.hasRequestedConnect=!0,this.eventBus.emit("ws:request-connect")),this.isOpen=!0,this.showPanel(),this.inputArea.focus()}close(){this.isOpen=!1,this.hidePanel()}toggle(){this.isOpen?this.close():this.open()}destroy(){this.waitForReplyTimeout&&(clearTimeout(this.waitForReplyTimeout),this.waitForReplyTimeout=null),this.firstReplyTimeout&&(clearTimeout(this.firstReplyTimeout),this.firstReplyTimeout=null),this.eventUnsubscribers.forEach(e=>e()),this.eventUnsubscribers=[],this.shadow.destroy()}onMessageSent(){this.config.waitForReply&&this.setupWaitForReplyTimeout(),this.showTypingIndicator()}handleFileUpload(e,t,i){let n={filename:e.name,filetype:e.type,filesize:e.size,content:t,description:i||""};this.session.createUserMessage(n,"file"),this.onMessageSent(),this.wsManager.send({type:"message",direction:"inbound",content:JSON.stringify(n)})}handleSend(e){this.session.createUserMessage(e,"text");let t={type:"message",direction:"inbound",content:e};this.onMessageSent(),this.wsManager.send(t)}subscribe(e,t){this.eventBus.on(e,t),this.eventUnsubscribers.push(()=>this.eventBus.off(e,t))}bindEvents(){this.subscribe("message:added",t=>{this.messageList.addMessage(t),t.direction==="OUTBOUND"&&(this.waitingForFirstReply?(this.waitingForFirstReply=!1,this.inputArea.setEnabled(!0),this.hideTypingIndicator(),this.firstReplyTimeout&&(clearTimeout(this.firstReplyTimeout),this.firstReplyTimeout=null)):this.waitForReplyTimeout?(clearTimeout(this.waitForReplyTimeout),this.waitForReplyTimeout=null,this.inputArea.setEnabled(!0),this.hideTypingIndicator()):this.hideTypingIndicator())});let e=t=>{this.messageList.clear(),t.length===0?this.messageList.showWelcome(this.config.welcome):(t.forEach(i=>this.messageList.addMessage(i)),this.shouldScrollToTop&&(this.messageList.scrollToTop(),this.shouldScrollToTop=!1))};this.subscribe("history:loaded",e),this.subscribe("history:merged",e),this.config.resumeConversation&&this.subscribe("history:has_more",t=>{t?this.messageList.showShowMoreButton(()=>{this.shouldScrollToTop=!0,this.eventBus.emit("ui:show-more")}):this.messageList.hideShowMoreButton(),this.messageList.updateHasMore(t)}),this.subscribe("connection:state",t=>{this.header.setConnectionState(t),t==="connected"&&(this.waitingForFirstReply||this.inputArea.setEnabled(!0))}),this.subscribe("session:connected",()=>{this.config.waitForReply?.firstReply&&(this.waitingForFirstReply=!0,this.inputArea.setEnabled(!1),this.showTypingIndicator(),this.firstReplyTimeout=setTimeout(()=>{this.waitingForFirstReply=!1,this.inputArea.setEnabled(!0),this.hideTypingIndicator(),this.firstReplyTimeout=null},this.config.waitForReply.timeout))}),this.subscribe("session:cleared",()=>{this.messageList.clear(),this.messageList.showWelcome(this.config.welcome),this.config.waitForReply?.firstReply||this.inputArea.setEnabled(!0)}),this.subscribe("ui:show-error",t=>{this.messageList.showError(t)})}createPanelElement(){return r.div({},this.header.el,this.messageList.el,this.inputArea.el).build()}isMobileDevice(){return D()}getEffectivePosition(){return D()&&this.config.style.mobile?.position?this.config.style.mobile.position:this.config.style.position}isSidepanelPosition(){return this.getEffectivePosition().startsWith("sidepanel")}isWindowPosition(){return this.getEffectivePosition().startsWith("bottom")}showTypingIndicator(){this.config.isTypingIndicator&&(this.config.isTypingIndicator.position==="bottom"?this.inputArea.showTypingIndicator(this.config.isTypingIndicator):this.header.showTypingIndicator(this.config.isTypingIndicator))}hideTypingIndicator(){this.config.isTypingIndicator&&(this.config.isTypingIndicator.position==="bottom"?this.inputArea.hideTypingIndicator():this.header.hideTypingIndicator())}setupWaitForReplyTimeout(){this.config.waitForReply&&(this.inputArea.setEnabled(!1),this.waitForReplyTimeout=setTimeout(()=>{this.inputArea.setEnabled(!0),this.hideTypingIndicator(),this.waitForReplyTimeout=null},this.config.waitForReply.timeout))}};var te=class extends k{constructor(e,t,i,n){super(e,t,i,n)}buildPanel(){let e=this.createPanelElement(),t=this.config.style.position==="bottom-right",i=this.isMobileDevice(),n=this.config.style.width,s=this.config.style.height;return e.className="font-sans fixed flex flex-col rounded-xl shadow-2xl overflow-hidden nimbus-fade-in",i?e.style.cssText=["display: none","width: 100%",`height: ${s}`,"bottom: 84px","left: 0","right: 0","border: 1px solid #e2e8f0","border-radius: 12px 12px 0 0"].join(";"):e.style.cssText=["display: none",`width: ${n}`,`height: ${s}`,"bottom: 84px",t?"right: 20px":"left: 20px","border: 1px solid #e2e8f0"].join(";"),e}showPanel(){this.panel.style.display="flex",this.bubble.setOpen(!0),this.config.bubble.autoHide&&(this.bubble.el.style.display="none",this.panel.style.bottom="20px")}hidePanel(){this.panel.style.display="none",this.bubble.setOpen(!1),this.config.bubble.autoHide&&(this.bubble.el.style.display="flex",this.panel.style.bottom="84px")}};var ie=class extends k{constructor(e,t,i,n){super(e,t,i,n),this.bubble.el.style.display="flex",this.bubble.setOpen(!1)}buildPanel(){let e=this.createPanelElement(),t=this.config.style.position==="sidepanel-right",i=this.isMobileDevice(),n=this.config.style.width;return e.className="font-sans fixed top-0 h-screen flex flex-col shadow-2xl overflow-hidden nimbus-panel-slide",i?e.style.cssText=["display: none","width: 100%","left: 0","right: 0","border: 1px solid #e2e8f0","border-radius: 12px 12px 0 0"].join(";"):e.style.cssText=["display: none",`width: ${n}`,t?"right: 0":"left: 0","border: 1px solid #e2e8f0","border-radius: 12px 12px 0 0"].join(";"),e}showPanel(){this.panel.style.display="flex",this.bubble.el.style.display="none",this.bubble.setOpen(!0)}hidePanel(){this.panel.style.display="none",this.bubble.el.style.display="flex",this.bubble.setOpen(!1)}};var I=class{constructor(e){this.destroyed=!1;this.hasMoreMessages=!1;ke(e),this.config=ve(e),this.config.debug&&Fe(),this.logger=g("Main",this.config.debug),this.messageLimit=this.config.messagesPerPage,this.perf=new U(this.config.debug),this.eventBus=new j,this.session=new W(this.eventBus),this.wsManager=new $(this.config.dns,this.config.agent_id,this.eventBus,this.config.reconnect,this.config.debug),this.apiClient=new G(this.config.dns,this.config.debug),Ie(this.config.style.mobile?.breakpoint),(D()&&this.config.style.mobile?.position?this.config.style.mobile.position:this.config.style.position).startsWith("sidepanel")?this.ui=new ie(this.config,this.eventBus,this.session,this.wsManager):this.ui=new te(this.config,this.eventBus,this.session,this.wsManager),this.setupEventHandlers(),this.logger.info("Initialized",this.config)}setupEventHandlers(){this.eventBus.on("ws:request-connect",()=>{this.wsManager.connect()}),this.eventBus.on("ws:message",e=>{this.handleServerEvent(e)}),this.eventBus.on("message:added",e=>{e.direction==="INBOUND"&&this.perf.markMessageSent()}),this.config.resumeConversation&&this.eventBus.on("ui:show-more",()=>{this.fetchAndDisplayHistory(!0)}),this.eventBus.on("ui:start-new-chat",()=>{this.wsManager.clearSession(),this.session.clear(),this.perf.reset(),this.messageLimit=this.config.messagesPerPage,this.hasMoreMessages=!1,this.wsManager.connect(!0)})}async handleServerEvent(e){switch(e.type){case"connected":this.session.setFlowId(e.flow_id),this.perf.markSessionStarted(),this.eventBus.emit("session:connected"),this.config.resumeConversation&&await this.fetchAndDisplayHistory();break;case"message":this.perf.markBotMessageReceived(),this.session.createBotMessage(e.content);break}}open(){this.ui.open()}close(){this.ui.close()}toggle(){this.ui.toggle()}destroy(){this.destroyed||(this.destroyed=!0,this.apiClient.abort(),this.wsManager.disconnect(),this.ui.destroy(),this.eventBus.removeAll(),this.logger.info("Destroyed"))}async fetchAndDisplayHistory(e=!1,t=!1){let i=this.session.getFlowId()||this.wsManager.getFlowId();if(i)try{this.logger.debug(`fetchAndDisplayHistory called with loadMore=${e}`),e?(this.messageLimit+=this.config.messagesPerPage,this.logger.debug(`Incrementing limit to ${this.messageLimit}`)):(this.messageLimit=this.config.messagesPerPage,this.logger.debug(`Resetting limit to ${this.messageLimit}`));let n=await this.apiClient.fetchMessageHistory(i,this.messageLimit);this.logger.debug(`Received ${n.messages.length} messages from API`),this.hasMoreMessages=n.has_more,this.logger.debug(`has_more flag: ${this.hasMoreMessages}`),t?this.session.loadHistoryMessagesWithMerge(n.messages):(this.session.clearMessages(),this.session.loadHistoryMessages(n.messages)),this.eventBus.emit("history:has_more",this.hasMoreMessages)}catch(n){this.logger.error("Failed to load message history:",n)}}};var st=g("SDK"),H=null;function _e(o){return H?(st.warn("Already initialized. Returning existing instance."),H):(H=new I(o),H)}function De(){return H}var rt={NimbusChat:I,init:_e,getInstance:De};0&&(module.exports={ICON_NAMES,ICON_SIZES,NimbusChat,getInstance,init});
183
+ //# sourceMappingURL=index.js.map