@navsi.ai/sdk 1.0.3 → 1.0.5

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,548 @@
1
+ import {a,c,d,e,f}from'./chunk-UWRZ4ZYG.js';import qe,{useMemo,useReducer,useRef,useState,useEffect,useCallback}from'react';import {z}from'zod';import {createLogger,normalizeWidgetConfig,createMessageId}from'@navsi.ai/shared';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var mt=z.object({type:z.string().min(1).max(50)}).passthrough(),bt=z.object({type:z.literal("auth_success"),sessionId:z.string().max(255),accessToken:z.string().max(4096),refreshToken:z.string().max(4096),expiresAt:z.number(),reconnectToken:z.string().max(255).optional()}).passthrough(),vt=z.object({type:z.literal("token_refreshed"),accessToken:z.string().max(4096),refreshToken:z.string().max(4096),expiresAt:z.number()}).passthrough(),Fe=class{queue=[];maxSize;constructor(e=100){this.maxSize=e;}enqueue(e){this.queue.length>=this.maxSize&&this.queue.shift(),this.queue.push(e);}dequeueAll(){let e=[...this.queue];return this.queue=[],e}get length(){return this.queue.length}clear(){this.queue=[];}},ce=class i{ws=null;config;state="disconnected";logger=createLogger("SDK.WebSocket");reconnectAttempts=0;reconnectTimeout=null;heartbeatInterval=null;lastPongTime=0;messageQueue=new Fe;sessionId=null;refreshToken=null;tokenExpiresAt=0;tokenRefreshTimeout=null;listeners=new Map;constructor(e){this.config={serverUrl:e.serverUrl,apiKey:e.apiKey,autoReconnect:e.autoReconnect??true,maxReconnectAttempts:e.maxReconnectAttempts??10,reconnectDelay:e.reconnectDelay??1e3,heartbeatInterval:e.heartbeatInterval??3e4,debug:e.debug??false},this.logger=createLogger("SDK.WebSocket",{enabled:this.config.debug,level:"debug"});}connect(){if(this.state==="connecting"||this.state==="connected"){this.log("Already connected or connecting");return}this.setState("connecting"),this.createWebSocket();}disconnect(){this.closeSocket(),this.setState("disconnected"),this.log("Disconnected");}destroy(){this.cleanup(),this.setState("disconnected"),this.log("Destroyed");}send(e){this.state==="connected"&&this.ws?.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(e)),this.log("Sent message:",e.type,Qe(e))):(this.messageQueue.enqueue(e),this.log("Queued message (offline):",e.type,Qe(e)));}getState(){return this.state}getSessionId(){return this.sessionId}isConnected(){return this.state==="connected"}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.listeners.get(e)?.delete(t);}}emit(e,t){this.listeners.get(e)?.forEach(n=>{try{n(t);}catch(r){this.logger.error(`Error in ${e} listener`,r);}});}createWebSocket(){try{let e=new URL(this.config.serverUrl);this.sessionId&&e.searchParams.set("sessionId",this.sessionId);let t=e.toString();this.ws=new WebSocket(t),this.ws.onopen=this.handleOpen.bind(this),this.ws.onmessage=this.handleMessage.bind(this),this.ws.onclose=this.handleClose.bind(this),this.ws.onerror=this.handleError.bind(this);}catch(e){this.logger.error("Failed to create WebSocket",e),this.handleConnectionFailure();}}handleOpen(){this.log("WebSocket connected, sending auth message..."),this.ws?.send(JSON.stringify({type:"auth",apiKey:this.config.apiKey,sessionId:this.sessionId}));}handleMessage(e){try{let t=JSON.parse(e.data),n=mt.safeParse(t);if(!n.success){this.logger.warn("Invalid server message shape",n.error.issues);return}let r=t;switch(this.log("Received message:",r.type),r.type){case "connected":this.handleConnected();break;case "auth_success":{let o=bt.safeParse(r);if(!o.success){this.logger.warn("Invalid auth_success message",o.error.issues);return}this.handleAuthSuccess(o.data);break}case "auth_error":this.handleAuthError(r);break;case "pong":this.handlePong(r);break;case "token_refreshed":{let o=vt.safeParse(r);if(!o.success){this.logger.warn("Invalid token_refreshed message",o.error.issues);return}this.handleTokenRefreshed(o.data);break}default:this.emit("message",r);}}catch(t){this.logger.warn("Failed to parse message",t);}}static NON_RETRIABLE_CLOSE_CODES=new Set([1008,4001,4003,4004,4010]);handleClose(e){this.log("WebSocket closed:",e.code,e.reason),this.stopHeartbeat(),this.state!=="disconnected"&&(this.emit("disconnected",{reason:e.reason,code:e.code}),this.config.autoReconnect&&!i.NON_RETRIABLE_CLOSE_CODES.has(e.code)?this.scheduleReconnect():this.setState("disconnected"));}handleError(e){this.logger.error("WebSocket error",e),this.emit("error",{error:new Error("WebSocket error")});}handleConnected(){this.log("Server connection acknowledged");}handleAuthSuccess(e){this.sessionId=e.sessionId,this.refreshToken=e.refreshToken,this.tokenExpiresAt=e.expiresAt,this.reconnectAttempts=0,this.setState("connected"),this.startHeartbeat(),this.scheduleTokenRefresh(),this.flushMessageQueue(),this.emit("authenticated",{sessionId:e.sessionId,expiresAt:e.expiresAt}),this.emit("connected",{sessionId:e.sessionId}),this.log("Authenticated successfully, session:",e.sessionId);}handleAuthError(e){this.logger.warn("Authentication failed",e.error),this.emit("error",{error:new Error(e.error),code:e.code}),this.disconnect();}scheduleTokenRefresh(){this.tokenRefreshTimeout&&clearTimeout(this.tokenRefreshTimeout);let e=Math.max(0,this.tokenExpiresAt-Date.now()-300*1e3);this.tokenRefreshTimeout=setTimeout(()=>{this.refreshAccessToken();},e),this.log("Token refresh scheduled in",Math.round(e/1e3),"seconds");}refreshAccessToken(){!this.refreshToken||this.state!=="connected"||(this.log("Refreshing token..."),this.ws?.send(JSON.stringify({type:"token_refresh",refreshToken:this.refreshToken})));}handleTokenRefreshed(e){this.refreshToken=e.refreshToken,this.tokenExpiresAt=e.expiresAt,this.scheduleTokenRefresh(),this.emit("token_refreshed",{expiresAt:e.expiresAt}),this.log("Token refreshed successfully");}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.heartbeatInterval=setInterval(()=>{if(this.state==="connected"){if(Date.now()-this.lastPongTime>this.config.heartbeatInterval*2){this.logger.warn("Heartbeat timeout, reconnecting..."),this.ws?.close();return}this.ws?.send(JSON.stringify({type:"ping",timestamp:Date.now()})),this.log("Sent ping");}},this.config.heartbeatInterval);}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);}handlePong(e){this.lastPongTime=Date.now();let t=Date.now()-e.timestamp;this.log("Received pong, latency:",t,"ms");}scheduleReconnect(){if(this.reconnectAttempts>=this.config.maxReconnectAttempts){this.handleConnectionFailure();return}this.setState("reconnecting"),this.reconnectAttempts++;let e=Math.min(this.config.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),3e4);this.log(`Reconnecting in ${e}ms (attempt ${this.reconnectAttempts}/${this.config.maxReconnectAttempts})`),this.emit("reconnecting",{attempt:this.reconnectAttempts,maxAttempts:this.config.maxReconnectAttempts}),this.reconnectTimeout=setTimeout(()=>{this.createWebSocket();},e);}handleConnectionFailure(){this.setState("failed"),this.emit("reconnect_failed",{reason:"Max reconnection attempts reached"}),this.logger.error("Connection failed - max reconnection attempts reached");}flushMessageQueue(){let e=this.messageQueue.dequeueAll();e.length>0&&(this.log(`Flushing ${e.length} queued messages`),e.forEach(t=>this.send(t)));}setState(e){this.state!==e&&(this.log("State:",this.state,"->",e),this.state=e);}closeSocket(){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.tokenRefreshTimeout&&(clearTimeout(this.tokenRefreshTimeout),this.tokenRefreshTimeout=null),this.stopHeartbeat(),this.ws){let e=this.ws;if(e.onopen=null,e.onmessage=null,e.onclose=null,e.onerror=null,this.ws=null,e.readyState===WebSocket.CONNECTING||e.readyState===WebSocket.OPEN)try{e.close(1e3,"Client disconnect");}catch{}}}cleanup(){this.closeSocket(),this.listeners.clear();}log(...e){this.logger.debug(...e);}};function Qe(i){switch(i.type){case "message":return {messageId:i.messageId,mode:i.mode,length:i.content.length,route:i.context?.route};case "context":return {route:i.context?.route,actions:i.context?.actions?.length??0,headings:i.context?.content?.headings?.length??0};case "action_result":return {actionId:i.actionId,success:i.success,commandId:i.commandId};case "server_action_request":return {actionId:i.actionId,requestId:i.requestId};case "auth":return {hasSessionId:!!i.sessionId};case "token_refresh":return {};case "ping":return {timestamp:i.timestamp};default:return {}}}function en(i){return new ce(i)}function Ze(i="/"){let e=i,t=new Set;return {navigate(n){e=n,t.forEach(r=>r(n));},getCurrentPath(){return e},onRouteChange(n){return t.add(n),()=>t.delete(n)},async waitForRoute(n,r=1e4){return new Promise(o=>{if(e===n){o(true);return}let s=this.onRouteChange(a=>{a===n&&(s(),o(true));});setTimeout(()=>{s(),o(e===n);},r);})}}}var le=class{adapter;config;scanCallback=null;logger=createLogger("SDK.Navigation");constructor(e,t={}){this.adapter=e,this.config={domStabilityDelay:t.domStabilityDelay??300,domStabilityTimeout:t.domStabilityTimeout??5e3,debug:t.debug??false,onDOMStable:t.onDOMStable},this.logger=createLogger("SDK.Navigation",{enabled:this.config.debug,level:"debug"});}setScanner(e){this.scanCallback=e;}getCurrentRoute(){return this.adapter.getCurrentPath()}async navigateTo(e,t){if(this.adapter.getCurrentPath()===e)return this.log("Already on route:",e),true;this.log("Navigating to:",e),this.adapter.navigate(e);let r=await this.adapter.waitForRoute(e,t);return r||this.log("Navigation timeout for route:",e),r}async executeNavigation(e){if(!await this.navigateTo(e))return this.log("Navigation failed to:",e),null;if(await this.waitForDOMStable(),this.scanCallback){let n=await this.scanCallback();return this.log("Rescanned context on route:",e),n}return null}async waitForDOMStable(){this.logger.debug("Waiting for DOM stability",{delayMs:this.config.domStabilityDelay,timeoutMs:this.config.domStabilityTimeout});let e=()=>{this.config.onDOMStable?.();};return new Promise(t=>{let n=false,r=()=>{n||(n=true,e(),t());};if(typeof document>"u"||typeof MutationObserver>"u"){r();return}let o,s,a=Date.now(),c=()=>{u.disconnect(),clearTimeout(o),clearTimeout(s);},u=new MutationObserver(()=>{if(clearTimeout(o),Date.now()-a>=this.config.domStabilityTimeout){c(),this.log("DOM stability timeout reached"),r();return}o=setTimeout(()=>{c(),this.log("DOM is stable"),r();},this.config.domStabilityDelay);});u.observe(document.body,{childList:true,subtree:true,attributes:false}),o=setTimeout(()=>{c(),this.log("DOM is stable (no initial mutations)"),r();},this.config.domStabilityDelay),s=setTimeout(()=>{c(),this.log("DOM stability max timeout reached"),r();},this.config.domStabilityTimeout);})}onRouteChange(e){return this.adapter.onRouteChange(e)}log(...e){this.logger.debug(...e);}};function on(i,e){return new le(i,e)}var yt=["button:not([disabled])","a[href]:not([disabled])",'input:not([type="hidden"]):not([disabled])',"select:not([disabled])","textarea:not([disabled])",'[contenteditable="true"]','[contenteditable="plaintext-only"]','[role="textbox"]','[role="searchbox"]','[role="combobox"]','[role="checkbox"]','[role="switch"]','[role="radio"]','[role="button"]:not([disabled])','[role="link"]','[role="menuitem"]','[role="tab"]',"[onclick]","[data-chatbot-action]"],xt=["[data-chatbot-ignore]",'[aria-hidden="true"]',"[hidden]",".chatbot-widget",".navsi-chatbot-container",'[type="password"]','[autocomplete*="cc-"]'];function Et(i){let e=i.getAttribute("data-chatbot-action");if(e)return `[data-chatbot-action="${e}"]`;if(i.id)return `#${CSS.escape(i.id)}`;let t=i.getAttribute("data-testid");if(t)return `[data-testid="${CSS.escape(t)}"]`;let n=i.getAttribute("aria-label");if(n){let o=`[aria-label="${CSS.escape(n)}"]`;if(document.querySelectorAll(o).length===1)return o}let r=i.getAttribute?.("name");if(r&&/^(input|select|textarea|button)$/i.test(i.tagName)){let o=`${i.tagName.toLowerCase()}[name="${CSS.escape(r)}"]`;if(document.querySelectorAll(o).length===1)return o}if(i.className&&typeof i.className=="string"){let o=i.className.split(/\s+/).filter(Boolean).slice(0,3);if(o.length>0){let s=`${i.tagName.toLowerCase()}.${o.map(c=>CSS.escape(c)).join(".")}`;if(document.querySelectorAll(s).length===1)return s}}return St(i)}function St(i){let e=[],t=i;for(;t&&t!==document.body;){let n=t.tagName.toLowerCase();if(t.id){n=`#${CSS.escape(t.id)}`,e.unshift(n);break}let r=t.parentElement;if(r){let o=t.tagName,s=r.children,a=[];for(let c=0;c<s.length;c++)s[c].tagName===o&&a.push(s[c]);if(a.length>1){let c=a.indexOf(t)+1;n+=`:nth-of-type(${c})`;}}e.unshift(n),t=r;}return e.join(" > ")}function wt(i){let e=window.getComputedStyle(i);if(e.display==="none"||e.visibility==="hidden"||e.opacity==="0")return false;let t=i.getBoundingClientRect();return !(t.width===0&&t.height===0||i.closest('[aria-hidden="true"]'))}function Ct(i){for(let e of xt)if(i.matches(e)||i.closest(e))return true;return false}function Rt(i){let e=i.tagName.toLowerCase(),t=i.getAttribute("role")?.toLowerCase();if(e==="input"){let n=i.type;return n==="checkbox"||n==="radio"?"click":"type"}return e==="textarea"?"type":e==="select"?"select":t==="textbox"||t==="searchbox"?"type":"click"}function At(i){let e=i.getAttribute("data-chatbot-action");if(e)return e.replace(/-/g," ");let t=i.getAttribute("aria-label");if(t)return t;let n=i.getAttribute("aria-labelledby");if(n){let c=n.split(/\s+/).map(u=>document.getElementById(u)?.textContent?.trim()).filter(Boolean).join(" ");if(c)return c}let r=i.getAttribute("title");if(r)return r;let o=i.textContent?.trim();if(o&&o.length<50)return o;let s=i.getAttribute("placeholder");if(s)return s;let a=i.getAttribute("name");if(a)return a.replace(/[-_]/g," ");if(i.id){let c=document.querySelector(`label[for="${i.id}"]`);if(c?.textContent)return c.textContent.trim()}return i.tagName.toLowerCase()}var Tt=["tr",'[role="row"]',"article",'[role="listitem"]',"section",'[role="group"]',"main",'[role="region"]'],nt=120;function kt(i){let e=i,t=0,n=8;for(;e&&e!==document.body&&t<n;){for(let r of Tt)try{if(e.matches(r)){let o=e.textContent?.trim().replace(/\s+/g," ");if(o&&o.length>0)return o.length>nt?o.slice(0,nt)+"\u2026":o;break}}catch{}e=e.parentElement,t++;}}function Mt(i){let e=i.parentElement,t=0,n=5;for(;e&&t<n;){let r=e.querySelector("h1, h2, h3, h4, h5, h6");if(r?.textContent)return r.textContent.trim();let o=e.previousElementSibling;for(;o;){if(/^H[1-6]$/.test(o.tagName))return o.textContent?.trim();o=o.previousElementSibling;}e=e.parentElement,t++;}}var Te=class{config;mutationObserver=null;scanTimeout=null;onChangeCallback=null;logger=createLogger("SDK.Scanner");constructor(e={}){this.config={root:e.root??(typeof document<"u"?document.body:null),debug:e.debug??false,maxActions:e.maxActions??100,debounceMs:e.debounceMs??300},this.logger=createLogger("SDK.Scanner",{enabled:this.config.debug,level:"debug"});}scan(){if(typeof document>"u")return [];let e=this.config.root??document.body,t=[],n=typeof window<"u"?window.location.pathname:"/",r=yt.join(", "),o=this.collectInteractiveElements(e,r);this.log(`Found ${o.length} potential interactive elements`);for(let s of o){if(t.length>=this.config.maxActions)break;if(Ct(s)||!wt(s))continue;let a=this.createElement(s,n);a&&t.push(a);}return this.log(`Discovered ${t.length} actions`),t}createElement(e,t){try{let n=Et(e),r=At(e),o=Rt(e),s=Mt(e),u={id:`action_${btoa(unescape(encodeURIComponent(n))).replace(/[^a-zA-Z0-9]/g,"").slice(0,16)}`,type:o,selector:n,label:r,route:t,isAutoDiscovered:!0,priority:e.hasAttribute("data-chatbot-action")?10:1},h=kt(e);return (s||h)&&(u.metadata={...s?{context:s}:{},...h?{containerText:h}:{}}),u}catch(n){return this.log("Error creating action:",n),null}}collectInteractiveElements(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.shift();if(!o)break;let a=(o).querySelectorAll(t);for(let h of a)n.add(h);let u=(o).querySelectorAll("*");for(let h of u){let E=h.shadowRoot;E&&r.push(E);}}return Array.from(n)}observe(e){typeof MutationObserver>"u"||(this.disconnect(),this.onChangeCallback=e,this.mutationObserver=new MutationObserver(()=>{this.debouncedScan();}),this.mutationObserver.observe(this.config.root??document.body,{childList:true,subtree:true,attributes:true,attributeFilter:["disabled","hidden","aria-hidden"]}));}disconnect(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.scanTimeout&&(clearTimeout(this.scanTimeout),this.scanTimeout=null);}debouncedScan(){this.scanTimeout&&clearTimeout(this.scanTimeout),this.scanTimeout=setTimeout(()=>{let e=this.scan();this.onChangeCallback?.(e);},this.config.debounceMs);}log(...e){this.logger.debug(...e);}};var ke=class{actionsByRoute=new Map;serverActions=new Map;manualActions=new Map;debug;logger=createLogger("SDK.Registry");constructor(e={}){this.debug=e.debug??false,this.logger=createLogger("SDK.Registry",{enabled:this.debug,level:"debug"});}registerDiscoveredActions(e,t){this.actionsByRoute.has(e)||this.actionsByRoute.set(e,new Map);let n=this.actionsByRoute.get(e);for(let[r,o]of n)o.isAutoDiscovered&&n.delete(r);for(let r of t){let o=this.manualActions.get(r.id);o?n.set(r.id,{...r,...o}):n.set(r.id,r);}this.log(`Registered ${t.length} discovered actions for route: ${e}`);}registerManualAction(e){this.manualActions.set(e.id,e);let t=this.actionsByRoute.get(e.route);if(t?.has(e.id)){let n=t.get(e.id);t.set(e.id,{...n,...e,isAutoDiscovered:false});}this.log(`Registered manual action: ${e.id}`);}getActionsForRoute(e){let t=this.actionsByRoute.get(e);return t?Array.from(t.values()).sort((n,r)=>(r.priority??0)-(n.priority??0)):[]}findActionById(e){for(let t of this.actionsByRoute.values()){let n=t.get(e);if(n)return n}return null}findActionBySelector(e,t){let n=this.actionsByRoute.get(e);if(!n)return null;for(let r of n.values())if(r.selector===t)return r;return null}findActionByLabel(e,t,n){let r=this.actionsByRoute.get(e);if(!r)return null;let o=t.toLowerCase().trim(),s=n?.toLowerCase().trim(),a=c=>{if(!s)return true;let u=c.metadata?.containerText?.toLowerCase(),h=c.metadata?.context?.toLowerCase();return (u?.includes(s)??false)||(h?.includes(s)??false)};if(s){for(let c of r.values())if(c.label.toLowerCase()===o&&a(c))return c;for(let c of r.values())if(c.label.toLowerCase().includes(o)&&a(c))return c}for(let c of r.values())if(c.label.toLowerCase()===o)return c;for(let c of r.values())if(c.label.toLowerCase().includes(o))return c;return null}clearRoute(e){this.actionsByRoute.delete(e);}clearAll(){this.actionsByRoute.clear();}registerServerAction(e){this.serverActions.set(e.id,e),this.log(`Registered server action: ${e.id}`);}getServerActions(){return Array.from(this.serverActions.values())}findServerActionById(e){return this.serverActions.get(e)??null}findServerActionByName(e){let t=e.toLowerCase().trim();for(let n of this.serverActions.values())if(n.name.toLowerCase()===t)return n;for(let n of this.serverActions.values())if(n.name.toLowerCase().includes(t))return n;return null}removeServerAction(e){this.serverActions.delete(e);}getStats(){let e=0;for(let t of this.actionsByRoute.values())e+=t.size;return {routes:this.actionsByRoute.size,actions:e,serverActions:this.serverActions.size}}log(...e){this.logger.debug(...e);}};function Nt(i){return i.replace(/\s+/g," ").trim()}function It(){if(typeof document>"u")return [];let i=["chatbot","ai assistant","ask mode","navigate mode","navsi","intelligent agent"],e=[],t=document.querySelectorAll("h1, h2, h3, h4, h5, h6");for(let n of t){if(n.closest(".chatbot-widget")||n.closest(".navsi-chatbot-container"))continue;let r=n.textContent?.trim();if(r&&r.length<200){let o=r.toLowerCase();i.some(a=>o.includes(a))||e.push(r);}}return e.slice(0,20)}function Dt(i){if(typeof document>"u")return "";let e=document.querySelector("main")??document.querySelector('[role="main"]')??document.querySelector("article")??document.querySelector(".content")??document.body,t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:o=>{let s=o.parentElement;if(!s)return NodeFilter.FILTER_REJECT;let a=s.tagName.toLowerCase();return ["script","style","noscript"].includes(a)||s.closest(".chatbot-widget")||s.closest(".navsi-chatbot-container")?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),n="",r;for(;(r=t.nextNode())&&n.length<i;){let o=r.textContent?.trim();o&&o.length>0&&(n+=o+" ");}return Nt(n).slice(0,i)}function Ot(){if(typeof document>"u")return [];let i=[],e=document.querySelectorAll("form");for(let t of e){if(t.closest(".chatbot-widget")||t.closest(".navsi-chatbot-container"))continue;let n=[],r=t.querySelectorAll("input, select, textarea");for(let o of r){let s=o;if(s.type==="hidden")continue;let a;s.id&&(a=document.querySelector(`label[for="${s.id}"]`)?.textContent?.trim()),!a&&s.getAttribute("aria-label")&&(a=s.getAttribute("aria-label")??void 0),n.push({name:s.name||s.id||"",type:s.type||s.tagName.toLowerCase(),label:a,placeholder:"placeholder"in s?s.placeholder:void 0,required:s.required});}n.length>0&&i.push({id:t.id||`form_${i.length}`,name:t.name||void 0,action:t.action?(()=>{try{return new URL(t.action).pathname}catch{return}})():void 0,method:t.method||void 0,fields:n});}return i.slice(0,10)}function _t(){return typeof document>"u"?void 0:document.querySelector('meta[name="description"]')?.getAttribute("content")??void 0}var Me=class{config;logger=createLogger("SDK.Context");constructor(e={}){this.config={maxContentLength:e.maxContentLength??2e3,maxActions:e.maxActions??50,debug:e.debug??false},this.logger=createLogger("SDK.Context",{enabled:this.config.debug,level:"debug"});}build(e,t,n){let r=n??(typeof window<"u"?window.location.pathname:"/"),o=typeof document<"u"?document.title:"",s={headings:It(),mainContent:Dt(this.config.maxContentLength),forms:Ot(),metaDescription:_t()},a=e.slice(0,this.config.maxActions),c={route:r,title:o,actions:a,serverActions:t,content:s,timestamp:Date.now()};return this.log("Built page context:",{route:c.route,title:c.title,actions:c.actions.length,serverActions:c.serverActions.length,headings:c.content.headings.length,forms:c.content.forms.length}),c}buildMinimal(e,t,n){return {route:n??(typeof window<"u"?window.location.pathname:"/"),title:typeof document<"u"?document.title:"",actions:e.slice(0,this.config.maxActions),serverActions:t,content:{headings:[],mainContent:"",forms:[]},timestamp:Date.now()}}log(...e){this.logger.debug(...e);}};function ge(i,e){let t=e?.preferVisible??false,n=[document],r=null;for(;n.length>0;){let o=n.shift(),s=o.querySelector(i);if(s){if(!t||X(s))return s;r||(r=s);}let a=o instanceof Document?o.body??o.documentElement:o;if(!a)continue;let c=a.querySelectorAll("*");for(let u of c){let h=u.shadowRoot;h&&n.push(h);}}return t?r:null}async function ue(i,e,t=true){let r=o=>o?!t||X(o):false;return new Promise(o=>{let s=ge(i,{preferVisible:t});if(r(s)){o(s);return}let a=false,c=null,u=null,h=()=>{a=true,c&&clearInterval(c),u&&clearTimeout(u),E.disconnect();},E=new MutationObserver(()=>{if(a)return;let S=ge(i,{preferVisible:t});r(S)&&(h(),o(S));});E.observe(document.body,{childList:true,subtree:true}),c=setInterval(()=>{if(a)return;let S=ge(i,{preferVisible:t});r(S)&&(h(),o(S));},100),u=setTimeout(()=>{if(a)return;h();let S=ge(i,{preferVisible:t});o(r(S)?S:null);},e);})}function X(i){let e=window.getComputedStyle(i);if(e.display==="none"||e.visibility==="hidden"||e.opacity==="0")return false;let t=i.getBoundingClientRect();if(t.width===0&&t.height===0)return false;let n=window.innerWidth||document.documentElement.clientWidth,r=window.innerHeight||document.documentElement.clientHeight,o=t.right>0&&t.left<n,s=t.bottom>0&&t.top<r;return o&&s}function Lt(i){let e=i.getBoundingClientRect();return {x:e.left+e.width/2,y:e.top+e.height/2}}function Ue(i,e){let t=i instanceof HTMLInputElement?HTMLInputElement.prototype:HTMLTextAreaElement.prototype,n=Object.getOwnPropertyDescriptor(t,"value")?.set;n?n.call(i,e):i.value=e;}function Ne(i){i.scrollIntoView({behavior:"smooth",block:"center",inline:"center"});}function de(i,e=500){let t=i,n=t.style.outline,r=t.style.transition;t.style.transition="outline 0.2s ease",t.style.outline="3px solid #6366f1",setTimeout(()=>{t.style.outline=n,t.style.transition=r;},e);}async function Pt(i,e,t){i.focus(),Ue(i,""),i.dispatchEvent(new Event("input",{bubbles:true}));for(let n of e){try{typeof InputEvent<"u"&&i.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,data:n,inputType:"insertText"}));}catch{}let r=(i.value??"")+n;Ue(i,r),i.dispatchEvent(new Event("input",{bubbles:true})),i.dispatchEvent(new KeyboardEvent("keydown",{key:n,bubbles:true})),i.dispatchEvent(new KeyboardEvent("keypress",{key:n,bubbles:true})),i.dispatchEvent(new KeyboardEvent("keyup",{key:n,bubbles:true})),t>0&&await new Promise(o=>setTimeout(o,t));}i.dispatchEvent(new Event("change",{bubbles:true}));}async function $t(i,e,t){i.focus(),i.textContent="",i.dispatchEvent(new Event("input",{bubbles:true}));for(let n of e){try{typeof InputEvent<"u"&&i.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,data:n,inputType:"insertText"}));}catch{}i.textContent=(i.textContent??"")+n,i.dispatchEvent(new Event("input",{bubbles:true})),i.dispatchEvent(new KeyboardEvent("keydown",{key:n,bubbles:true})),i.dispatchEvent(new KeyboardEvent("keypress",{key:n,bubbles:true})),i.dispatchEvent(new KeyboardEvent("keyup",{key:n,bubbles:true})),t>0&&await new Promise(r=>setTimeout(r,t));}i.dispatchEvent(new Event("change",{bubbles:true}));}function P(i){let e=i.getBoundingClientRect(),t=i.tagName.toLowerCase(),n={};if(i instanceof HTMLElement)for(let r of Array.from(i.attributes))(r.name.startsWith("data-")||r.name==="aria-label"||r.name==="name"||r.name==="id")&&(n[r.name]=r.value);return {tagName:t,text:(i.textContent??"").trim().slice(0,80),rect:{x:e.x,y:e.y,width:e.width,height:e.height},attributes:n}}var Ie=class i{config;logger=createLogger("SDK.Executor");constructor(e={}){this.config={elementTimeout:e.elementTimeout??6e3,typeDelay:e.typeDelay??30,scrollIntoView:e.scrollIntoView??true,highlightOnInteract:e.highlightOnInteract??true,debug:e.debug??false},this.logger=createLogger("SDK.Executor",{enabled:this.config.debug,level:"debug"});}static RETRY_DELAY_MS=600;static MAX_RETRIES=2;async click(e){let t=Date.now(),n=async()=>{let o=await ue(e,this.config.elementTimeout,true);if(!o)return this.createResult(e,"click",t,false,"Element not found","ELEMENT_NOT_FOUND");if(this.config.scrollIntoView&&!X(o)&&(Ne(o),await new Promise(h=>setTimeout(h,100))),this.config.highlightOnInteract&&de(o),!X(o))return this.createResult(e,"click",t,false,"Element is not visible","NOT_VISIBLE",P(o));let s=o;if(s.disabled===true||s.getAttribute("aria-disabled")==="true")return this.createResult(e,"click",t,false,"Element is disabled","DISABLED",P(o));s.focus();let{x:c,y:u}=Lt(o);try{typeof PointerEvent<"u"&&(o.dispatchEvent(new PointerEvent("pointerover",{bubbles:!0,cancelable:!0,clientX:c,clientY:u})),o.dispatchEvent(new PointerEvent("pointerenter",{bubbles:!0,cancelable:!0,clientX:c,clientY:u})),o.dispatchEvent(new PointerEvent("pointermove",{bubbles:!0,cancelable:!0,clientX:c,clientY:u})));}catch{}o.dispatchEvent(new MouseEvent("mouseover",{bubbles:true,cancelable:true,clientX:c,clientY:u})),o.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true,cancelable:true,clientX:c,clientY:u})),o.dispatchEvent(new MouseEvent("mousemove",{bubbles:true,cancelable:true,clientX:c,clientY:u}));try{typeof PointerEvent<"u"&&(o.dispatchEvent(new PointerEvent("pointerdown",{bubbles:!0,cancelable:!0,button:0,clientX:c,clientY:u})),o.dispatchEvent(new PointerEvent("pointerup",{bubbles:!0,cancelable:!0,button:0,clientX:c,clientY:u})));}catch{}return o.dispatchEvent(new MouseEvent("mousedown",{bubbles:true,cancelable:true,clientX:c,clientY:u})),o.dispatchEvent(new MouseEvent("mouseup",{bubbles:true,cancelable:true,clientX:c,clientY:u})),o.dispatchEvent(new MouseEvent("click",{bubbles:true,cancelable:true,clientX:c,clientY:u})),s.click(),this.log("Clicked:",e),this.createResult(e,"click",t,true,void 0,void 0,P(o))};return (async()=>{let o=null;for(let s=0;s<=i.MAX_RETRIES;s++){s>0&&(this.log(`Click retry ${s}/${i.MAX_RETRIES} for:`,e),await new Promise(a=>setTimeout(a,i.RETRY_DELAY_MS*s)));try{if(o=await n(),o.success)return o}catch(a){o=this.createResult(e,"click",t,false,String(a),"RUNTIME_ERROR");}}return o})()}async type(e,t,n=true){let r=Date.now(),o=async()=>{let a=await ue(e,this.config.elementTimeout,true);if(!a)return this.createResult(e,"type",r,false,"Element not found","ELEMENT_NOT_FOUND");if(!this.isTypeable(a))return this.createResult(e,"type",r,false,"Element is not typeable","TYPE_MISMATCH",P(a));this.config.scrollIntoView&&!X(a)&&(Ne(a),await new Promise(u=>setTimeout(u,100))),this.config.highlightOnInteract&&de(a);let c=P(a);if(!X(a))return this.createResult(e,"type",r,false,"Element is not visible","NOT_VISIBLE",c);if(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement){let u=a;if(u.disabled||u.getAttribute("aria-disabled")==="true")return this.createResult(e,"type",r,false,"Element is disabled","DISABLED",c);n?await Pt(u,t,this.config.typeDelay):(u.focus(),Ue(u,(u.value??"")+t),u.dispatchEvent(new Event("input",{bubbles:true})),u.dispatchEvent(new Event("change",{bubbles:true})));}else if(a instanceof HTMLElement&&a.isContentEditable){if(a.getAttribute("aria-disabled")==="true")return this.createResult(e,"type",r,false,"Element is disabled","DISABLED",c);await $t(a,t,this.config.typeDelay);}else return this.createResult(e,"type",r,false,"Element is not a supported type target","TYPE_MISMATCH",c);return this.log("Typed into:",e,"text:",t.slice(0,20)+(t.length>20?"...":"")),this.createResult(e,"type",r,true,void 0,void 0,{...c,textLength:t.length})};return (async()=>{let a=null;for(let c=0;c<=i.MAX_RETRIES;c++){c>0&&(this.log(`Type retry ${c}/${i.MAX_RETRIES} for:`,e),await new Promise(u=>setTimeout(u,i.RETRY_DELAY_MS*c)));try{if(a=await o(),a.success)return a}catch(u){a=this.createResult(e,"type",r,false,String(u),"RUNTIME_ERROR");}}return a})()}async select(e,t){let n=Date.now(),r=async()=>{let s=await ue(e,this.config.elementTimeout,true);if(!s)return this.createResult(e,"select",n,false,"Element not found","ELEMENT_NOT_FOUND");if(s.tagName.toLowerCase()!=="select")return this.createResult(e,"select",n,false,"Element is not a select","TYPE_MISMATCH",P(s));if(this.config.scrollIntoView&&!X(s)&&(Ne(s),await new Promise(E=>setTimeout(E,100))),this.config.highlightOnInteract&&de(s),!X(s))return this.createResult(e,"select",n,false,"Element is not visible","NOT_VISIBLE",P(s));let a=s;if(a.disabled||a.getAttribute("aria-disabled")==="true")return this.createResult(e,"select",n,false,"Element is disabled","DISABLED",P(s));let c=false,u="";for(let E of a.options)if(E.value===t||E.textContent?.toLowerCase().includes(t.toLowerCase())){u=E.value,c=true;break}if(!c)return this.createResult(e,"select",n,false,`Option not found: ${t}`,"OPTION_NOT_FOUND",{...P(s),attemptedValue:t});let h=Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,"value")?.set;return h?h.call(a,u):a.value=u,a.dispatchEvent(new Event("input",{bubbles:true})),a.dispatchEvent(new Event("change",{bubbles:true})),this.log("Selected:",e,"value:",t),this.createResult(e,"select",n,true,void 0,void 0,{...P(s),selectedValue:t})};return (async()=>{let s=null;for(let a=0;a<=i.MAX_RETRIES;a++){a>0&&(this.log(`Select retry ${a}/${i.MAX_RETRIES} for:`,e),await new Promise(c=>setTimeout(c,i.RETRY_DELAY_MS*a)));try{if(s=await r(),s.success)return s}catch(c){s=this.createResult(e,"select",n,false,String(c),"RUNTIME_ERROR");}}return s})()}async scroll(e){let t=Date.now(),n=typeof e=="string"?e:`${e.x},${e.y}`;try{if(typeof e=="string"){let r=await ue(e,this.config.elementTimeout,!1);if(!r)return this.createResult(n,"scroll",t,!1,"Element not found","ELEMENT_NOT_FOUND");this.config.highlightOnInteract&&de(r),Ne(r);}else window.scrollTo({left:e.x,top:e.y,behavior:"smooth"});return this.log("Scrolled to:",e),this.createResult(n,"scroll",t,!0,void 0,void 0,typeof e=="string"?(()=>{let r=ge(e);return r?P(r):{selector:e}})():{position:e})}catch(r){return this.createResult(n,"scroll",t,false,String(r),"RUNTIME_ERROR")}}async submit(e){let t=Date.now();try{let n=await ue(e,this.config.elementTimeout,!0);if(!n)return this.createResult(e,"submit",t,!1,"Element not found","ELEMENT_NOT_FOUND");let r=n.tagName.toLowerCase()==="form"?n:n.closest("form");if(!r){let s=n.querySelector('button[type="submit"], input[type="submit"]');return s?this.click(this.generateSelector(s)):this.createResult(e,"submit",t,!1,"No form found","NO_FORM",P(n))}this.config.highlightOnInteract&&de(r);let o=r.querySelector('button[type="submit"], input[type="submit"]');if(typeof r.requestSubmit=="function")r.requestSubmit(o??void 0);else {let s=new Event("submit",{bubbles:!0,cancelable:!0});r.dispatchEvent(s)&&r.submit();}return this.log("Submitted form:",e),this.createResult(e,"submit",t,!0,void 0,void 0,P(r))}catch(n){return this.createResult(e,"submit",t,false,String(n),"RUNTIME_ERROR")}}isTypeable(e){let t=e.tagName.toLowerCase();if(t==="input"){let n=e.type;return ["text","email","password","search","tel","url","number"].includes(n)}return !!(t==="textarea"||e.hasAttribute("contenteditable"))}generateSelector(e){if(e.id)return `#${e.id}`;let t=e.getAttribute("data-testid");return t?`[data-testid="${t}"]`:e.tagName.toLowerCase()}createResult(e,t,n,r,o,s,a){return r||this.logger.warn("Action failed",{action:t,selector:e,error:o,errorCode:s,metadata:a}),{success:r,selector:e,action:t,duration:Date.now()-n,errorCode:s,error:o,metadata:a}}log(...e){this.logger.debug(...e);}};var De=class{config;executor;navController;registry;logger=createLogger("SDK.Processor");isExecuting=false;shouldAbort=false;listeners=new Map;serverActionHandler=null;constructor(e,t,n,r={}){this.executor=e,this.navController=t,this.registry=n,this.config={commandDelay:r.commandDelay??300,commandTimeout:r.commandTimeout??3e4,debug:r.debug??false},this.logger=createLogger("SDK.Processor",{enabled:this.config.debug,level:"debug"});}setServerActionHandler(e){this.serverActionHandler=e;}async execute(e){if(this.isExecuting)throw new Error("Already executing commands");this.isExecuting=true,this.shouldAbort=false;let t=[],n=null;try{for(let r=0;r<e.length;r++){if(this.shouldAbort){this.log("Execution aborted");break}let o=e[r],s=["click","type","select","scroll"].includes(o.type),a=n&&["navigate","wait_for_route"].includes(n);s&&a&&(this.log("Auto-waiting for DOM stability before:",o.type),await this.navController.waitForDOMStable()),this.emit("stateChange",{isExecuting:!0,currentCommand:o,currentIndex:r,totalCommands:e.length,description:this.describeCommand(o)}),this.emit("commandStart",o,r);let c=await this.executeCommand(o);if(t.push(c),this.emit("commandComplete",c),n=o.type,!c.success){this.logger.warn("Command failed, stopping execution",{type:o.type,error:c.error,result:c.result});break}r<e.length-1&&await new Promise(u=>setTimeout(u,this.config.commandDelay));}return this.emit("complete",t),t}catch(r){let o=r instanceof Error?r:new Error(String(r));throw this.logger.error("Execution error",o),this.emit("error",o),o}finally{this.isExecuting=false,this.emit("stateChange",{isExecuting:false,currentCommand:void 0,currentIndex:0,totalCommands:e.length,description:void 0});}}abort(){this.shouldAbort=true;}getIsExecuting(){return this.isExecuting}async executeCommand(e){let t=Date.now();try{switch(e.type){case "navigate":return await this.executeNavigate(e,t);case "wait_for_route":return await this.executeWaitForRoute(e,t);case "wait_for_dom_stable":return await this.executeWaitForDomStable(e,t);case "scan_context":return await this.executeScanContext(e,t);case "click":return await this.executeClick(e,t);case "type":return await this.executeType(e,t);case "select":return await this.executeSelect(e,t);case "scroll":return await this.executeScroll(e,t);case "server_action":return await this.executeServerAction(e,t);case "report_result":return await this.executeReportResult(e,t);default:return this.createResult(e,t,!1,"Unknown command type")}}catch(n){return this.logger.error("Command execution error",{type:e.type,error:String(n)}),this.createResult(e,t,false,String(n))}}async executeNavigate(e,t){return this.log("Navigating to:",e.target),await this.navController.executeNavigation(e.target)?this.createResult(e,t,true):this.createResult(e,t,false,"Navigation failed")}async executeWaitForRoute(e,t){this.log("Waiting for route:",e.target);let n=await this.navController.navigateTo(e.target,e.timeout);return this.createResult(e,t,n,n?void 0:"Route timeout")}async executeWaitForDomStable(e,t){return this.log("Waiting for DOM to stabilize"),await this.navController.waitForDOMStable(),this.createResult(e,t,true)}async executeScanContext(e,t){return this.log("Scanning page context"),this.createResult(e,t,true)}async executeClick(e,t){let n=e.selector,r=this.navController.getCurrentRoute();if(n){if(this.log("Clicking with selector:",n),(await this.executor.click(n)).success)return this.createResult(e,t,true);this.log("Selector failed, trying text fallback:",e.text||n);}if(e.text){let s=this.registry.findActionByLabel(r,e.text,e.context);if(s&&s.selector!==n&&(this.log("Found action by label, clicking:",s.selector),(await this.executor.click(s.selector)).success))return this.createResult(e,t,true)}if(e.text){let s=e.text.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,""),a=`[data-chatbot-action*="${CSS.escape(s)}"]`;if(this.log("Trying data-chatbot-action selector:",a),(await this.executor.click(a)).success)return this.createResult(e,t,true)}if(e.text){let s=`[aria-label="${CSS.escape(e.text)}"]`;if(this.log("Trying aria-label selector:",s),(await this.executor.click(s)).success)return this.createResult(e,t,true)}if(e.text){let s=e.text.toLowerCase().trim(),a=document.querySelectorAll('button, a, [role="button"], [data-chatbot-action]');for(let c of a){let u=c.textContent?.toLowerCase().trim()||"",h=c.getAttribute("aria-label")?.toLowerCase().trim()||"",E=c.getAttribute("data-chatbot-action")?.toLowerCase().replace(/-/g," ")||"";if(u===s||h===s||u.includes(s)||E===s||E.includes(s.replace(/\s+/g,"-"))){let S="";if(c.id?S=`#${CSS.escape(c.id)}`:c.getAttribute("data-chatbot-action")?S=`[data-chatbot-action="${CSS.escape(c.getAttribute("data-chatbot-action")??"")}"]`:c.getAttribute("aria-label")&&(S=`[aria-label="${CSS.escape(c.getAttribute("aria-label")??"")}"]`),S&&(this.log("Found element by text content, clicking:",S),(await this.executor.click(S)).success))return this.createResult(e,t,true)}}}let o=n?`Element not found or click failed: ${n}`:`No selector found for: ${e.text||"unknown"}`;return this.createResult(e,t,false,o)}async executeType(e,t){let n=e.selector;if(!n&&e.text){let o=this.registry.findActionByLabel(this.navController.getCurrentRoute(),e.text);o&&(n=o.selector);}if(!n)return this.createResult(e,t,false,"No selector provided");this.log("Typing into:",n,"value:",e.value);let r=await this.executor.type(n,e.value,e.clear??true);if(!r.success&&e.text&&r.error?.includes("not found")){let o=this.registry.findActionByLabel(this.navController.getCurrentRoute(),e.text);o&&(r=await this.executor.type(o.selector,e.value,e.clear??true));}return this.createResult(e,t,r.success,r.error)}async executeSelect(e,t){let n=e.selector;if(!n&&e.text){let o=this.registry.findActionByLabel(this.navController.getCurrentRoute(),e.text);o&&(n=o.selector);}if(!n)return this.createResult(e,t,false,"No selector provided");this.log("Selecting:",n,"value:",e.value);let r=await this.executor.select(n,e.value);if(!r.success&&e.text&&r.error?.includes("not found")){let o=this.registry.findActionByLabel(this.navController.getCurrentRoute(),e.text);o&&(r=await this.executor.select(o.selector,e.value));}return this.createResult(e,t,r.success,r.error)}async executeScroll(e,t){let n=e.selector??e.position??{x:0,y:0};this.log("Scrolling to:",n);let r=await this.executor.scroll(n);return this.createResult(e,t,r.success,r.error)}async executeServerAction(e,t){if(!this.serverActionHandler)return this.createResult(e,t,false,"No server action handler set");if(!this.registry.findServerActionById(e.actionId))return this.createResult(e,t,false,`Server action not found: ${e.actionId}`);this.log("Executing server action:",e.actionId);try{let r=await this.serverActionHandler(e.actionId,e.params);return this.createResult(e,t,!0,void 0,r)}catch(r){return this.createResult(e,t,false,String(r))}}async executeReportResult(e,t){return this.log("Report result command executed"),this.createResult(e,t,true)}createResult(e,t,n,r,o){return {command:e,success:n,result:o,error:r,duration:Date.now()-t}}describeCommand(e){switch(e.type){case "click":return e.text?`Click "${e.text}"`:`Click element${e.selector?` (${e.selector})`:""}`;case "type":return e.text?`Type into "${e.text}"`:`Type into element${e.selector?` (${e.selector})`:""}`;case "select":return e.text?`Select "${e.value}" in "${e.text}"`:`Select "${e.value}"${e.selector?` (${e.selector})`:""}`;case "scroll":return e.selector?`Scroll to element (${e.selector})`:e.position?`Scroll to (${e.position.x}, ${e.position.y})`:"Scroll";case "navigate":return `Navigate to "${e.target}"`;case "wait_for_route":return `Wait for route "${e.target}"`;case "wait_for_dom_stable":return "Wait for page to finish loading";case "scan_context":return "Scan page for available actions";case "server_action":return `Execute server action "${e.actionId}"`;case "report_result":return "Report result to server";default:return "Execute action"}}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.listeners.get(e)?.delete(t);}}emit(e,...t){this.listeners.get(e)?.forEach(n=>{try{n(...t);}catch(r){this.logger.error(`Error in ${e} listener`,r);}});}log(...e){this.logger.debug(...e);}};var Oe=class{config;actions=new Map;context=null;logger=createLogger("SDK.ServerAction");constructor(e={}){this.config={defaultTimeout:e.defaultTimeout??3e4,debug:e.debug??false,webhookHeaders:e.webhookHeaders??{},baseUrl:e.baseUrl??""},this.logger=createLogger("SDK.ServerAction",{enabled:this.config.debug,level:"debug"});}setContext(e){this.context=e;}register(e){this.actions.set(e.id,e),this.log(`Registered server action: ${e.id}`);}registerMany(e){for(let t of e)this.register(t);}unregister(e){this.actions.delete(e);}getActions(){return Array.from(this.actions.values())}getAction(e){return this.actions.get(e)}async execute(e,t){let n=this.actions.get(e);if(!n)return {success:false,error:`Server action not found: ${e}`};if(!this.context)return {success:false,error:"No execution context set"};let r=n.parameters.filter(s=>s.required&&!(s.name in t)).map(s=>s.name);if(r.length>0)return {success:false,error:`Missing required parameters: ${r.join(", ")}`};let o={...t};for(let s of n.parameters)!(s.name in o)&&s.defaultValue!==void 0&&(o[s.name]=s.defaultValue);this.log(`Executing server action: ${e}`,o);try{return n.handler?await this.executeHandler(n,o):n.webhookUrl?await this.executeWebhook(n,o):{success:!1,error:"Server action has no handler or webhookUrl"}}catch(s){let a=s instanceof Error?s.message:String(s);return this.log(`Server action error: ${a}`),{success:false,error:a}}}async executeHandler(e,t){if(!e.handler)return {success:false,error:"No handler defined"};let n=e.timeout??this.config.defaultTimeout;return await Promise.race([e.handler(t,this.context),new Promise((o,s)=>setTimeout(()=>s(new Error("Timeout")),n))])}async executeWebhook(e,t){if(!e.webhookUrl)return {success:false,error:"No webhookUrl defined"};let n=e.timeout??this.config.defaultTimeout,r=e.webhookUrl.startsWith("http")?e.webhookUrl:`${this.config.baseUrl}${e.webhookUrl}`,o={"Content-Type":"application/json",...this.config.webhookHeaders};if(e.webhookSecret){let c=await this.generateSignature(JSON.stringify(t),e.webhookSecret);o["X-Signature"]=c;}this.context&&(o["X-Session-Id"]=this.context.sessionId,this.context.authToken&&(o.Authorization=`Bearer ${this.context.authToken}`));let s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await fetch(r,{method:"POST",headers:o,body:JSON.stringify({actionId:e.id,params:t,context:{sessionId:this.context?.sessionId,userId:this.context?.userId,currentRoute:this.context?.currentRoute}}),signal:s.signal});if(clearTimeout(a),!c.ok)return this.logger.warn("Webhook failed",{actionId:e.id,status:c.status}),{success:!1,error:`Webhook failed with status ${c.status}`};let u=await c.json();return this.logger.debug("Webhook success",{actionId:e.id}),{success:!0,data:u}}catch(c){if(clearTimeout(a),c instanceof Error&&c.name==="AbortError")return {success:false,error:"Request timeout"};throw c}}async generateSignature(e,t){if(typeof crypto>"u"||!crypto.subtle)throw new Error("Web Crypto API (crypto.subtle) is unavailable. Webhook HMAC signing requires a secure context (HTTPS). Either serve the page over HTTPS or remove the webhookSecret.");let n=new TextEncoder,r=await crypto.subtle.importKey("raw",n.encode(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),o=await crypto.subtle.sign("HMAC",r,n.encode(e));return btoa(String.fromCharCode(...new Uint8Array(o)))}log(...e){this.logger.debug(...e);}};var Ht=z.object({type:z.enum(["click","type","navigate","scroll","select","scan_context","wait_for_dom_stable","wait_for_route","server_action","report_result"]),selector:z.string().max(500).optional(),text:z.string().max(1e3).optional(),value:z.string().max(5e3).optional(),target:z.string().max(1e3).refine(i=>/^\//.test(i)||/^https?:\/\//.test(i),"Only relative paths or http(s) URLs are allowed").optional(),actionId:z.string().max(255).optional(),params:z.record(z.string(),z.unknown()).optional(),context:z.string().max(500).optional()}),Ft=z.object({type:z.literal("command"),batchId:z.string().max(255),commands:z.array(Ht).max(50),message:z.string().max(5e3).optional()}),Ut=z.object({id:z.string(),role:z.enum(["user","assistant","system"]),content:z.string().max(32e3),timestamp:z.number(),status:z.enum(["sending","sent","error"]).optional()}),_e=createLogger("SDK.Storage",{enabled:true,level:"warn"});function zt(i){let e=null;return function(n){typeof window>"u"||(e&&clearTimeout(e),e=setTimeout(()=>{try{let r=n.slice(-100);localStorage.setItem(`${i}-messages`,JSON.stringify(r));}catch(r){_e.warn("Failed to save messages to localStorage",r);try{let o=n.slice(-50);localStorage.setItem(`${i}-messages`,JSON.stringify(o));}catch(o){_e.warn("Failed to save even reduced messages",o);}}},500));}}function qt(i){let e=zt(i);return function(n,r){let o;switch(r.type){case "ADD_MESSAGE":return o={...n,messages:[...n.messages,r.message]},e(o.messages),o;case "UPDATE_MESSAGE":return o={...n,messages:n.messages.map(s=>s.id===r.id?{...s,...r.updates}:s)},e(o.messages),o;case "SET_MESSAGES":return o={...n,messages:r.messages},e(o.messages),o;case "CLEAR_MESSAGES":return o={...n,messages:[]},e([]),o;case "SET_MODE":return {...n,mode:r.mode};case "SET_CONNECTION_STATE":return {...n,connectionState:r.state};case "SET_EXECUTING":return {...n,isExecuting:r.isExecuting};case "SET_EXECUTION_STATE":return {...n,executionState:r.state};case "SET_ERROR":return {...n,error:r.error};case "CLEAR_ERROR":return {...n,error:null};default:return n}}}function Vt(i="chatbot"){let e=[],t="ask";if(typeof window<"u"){try{let r=localStorage.getItem(`${i}-messages`);if(r){let o=JSON.parse(r);Array.isArray(o)?e=o.filter(a=>{let c=Ut.safeParse(a);return c.success||_e.warn("Skipping invalid persisted message",a),c.success}):localStorage.removeItem(`${i}-messages`);}}catch(r){_e.warn("Failed to load messages from localStorage",r);}let n=localStorage.getItem(`${i}-mode`);(n==="ask"||n==="navigate")&&(t=n);}return {messages:e,mode:t,connectionState:"disconnected",isExecuting:false,executionState:null,error:null}}function Kt({apiKey:i,serverUrl:e,navigationAdapter:t,serverActions:n=[],config:r,options:o,routes:s,debug:a$1=false,autoConnect:c=true,children:u}){let h=useMemo(()=>`chatbot-${i.slice(0,8)}`,[i]),E=useMemo(()=>createLogger("SDK",{enabled:a$1,level:"debug"}),[a$1]),S=useMemo(()=>normalizeWidgetConfig(r??void 0),[r]),D=useMemo(()=>{let l={...S};return o?.theme&&(l.theme={...l.theme,...o.theme}),{...l,...o,theme:l.theme}},[S,o]),pe=useMemo(()=>qt(h),[h]),[R,p]=useReducer(pe,h,Vt),me=useRef(R.messages),[J,V]=useState(()=>{if(typeof window<"u"){let l=localStorage.getItem(`${h}-widget-open`);if(l!==null)return l==="true"}return o?.defaultOpen??false}),[te,Pe]=useState(null),$=te??D?.voiceLanguage??void 0,be=useRef(false);useEffect(()=>{if(be.current)return;let l=D.defaultMode;(l==="ask"||l==="navigate")&&(p({type:"SET_MODE",mode:l}),be.current=true);},[D.defaultMode]),useEffect(()=>{typeof window<"u"&&localStorage.setItem(`${h}-widget-open`,String(J));},[J,h]),useEffect(()=>{me.current=R.messages;},[R.messages]),useEffect(()=>{typeof window<"u"&&localStorage.setItem(`${h}-mode`,R.mode);},[R.mode,h]);let A=useRef(null),Q=useRef(null),O=useRef(new Map),G=useRef(null),$e=useRef(null),y=useRef(null),ve=useRef(null),We=useRef(null),F=useRef(null),j=useRef(null),ne=useRef(void 0);useEffect(()=>{ne.current=s;},[s]);let K=useMemo(()=>t??Ze(),[t]);useEffect(()=>{let l=new ce({serverUrl:e,apiKey:i,debug:a$1});return A.current=l,l.on("connected",({sessionId:f})=>{_("Connected, session:",f),p({type:"SET_CONNECTION_STATE",state:"connected"});}),l.on("authenticated",({sessionId:f})=>{let m=j.current,v=K.getCurrentPath();m&&m.setContext({sessionId:f,currentRoute:v});}),l.on("disconnected",()=>{p({type:"SET_CONNECTION_STATE",state:"disconnected"});}),l.on("reconnecting",({attempt:f,maxAttempts:m})=>{_(`Reconnecting ${f}/${m}`),p({type:"SET_CONNECTION_STATE",state:"reconnecting"});}),l.on("reconnect_failed",()=>{p({type:"SET_CONNECTION_STATE",state:"failed"}),p({type:"SET_ERROR",error:new Error("Connection failed")});}),l.on("error",({error:f})=>{p({type:"SET_ERROR",error:f});}),l.on("message",f=>{g.current(f);}),c&&(l.connect(),p({type:"SET_CONNECTION_STATE",state:"connecting"})),()=>{l.destroy(),A.current=null;}},[e,i,a$1,c]),useEffect(()=>{let l=new ke({debug:a$1}),f=new Te({debug:a$1}),m=new Me({debug:a$1}),v=new Ie({debug:a$1}),x=new Oe({debug:a$1});y.current=l,$e.current=f,ve.current=m,We.current=v,j.current=x;let H=b=>{G.current=b,A.current?.send({type:"context",context:b});},C=b=>{x.setContext({sessionId:A.current?.getSessionId()??"",currentRoute:b});},U=()=>{let b=Q.current,B=b?b.getCurrentRoute():typeof window<"u"?window.location.pathname:"/",Ve=f.scan();l.registerDiscoveredActions(B,Ve);let He={...m.build(Ve,l.getServerActions(),B),...s?.length?{routes:s}:{}};return C(He.route),H(He),He},L=new le(K,{debug:a$1,onDOMStable:()=>U()});Q.current=L,L.setScanner(async()=>U());let z=new De(v,L,l,{debug:a$1});F.current=z,z.setServerActionHandler(async(b,B)=>x.execute(b,B));let ae=[];a$1&&(ae.push(z.on("commandStart",(b,B)=>{_("Command start:",{index:B,type:b.type,command:b});})),ae.push(z.on("commandComplete",b=>{_("Command complete:",{type:b.command.type,success:b.success,duration:b.duration,error:b.error});})),ae.push(z.on("complete",b=>{_("Command batch complete:",{total:b.length,failed:b.filter(B=>!B.success).length});})),ae.push(z.on("error",b=>{_("Command processor error:",b);}))),n.forEach(b=>{O.current.set(b.id,b),l.registerServerAction(b),x.register(b);}),f.observe(b=>{l.registerDiscoveredActions(L.getCurrentRoute(),b);let B={...m.build(b,l.getServerActions(),L.getCurrentRoute()),...s?.length?{routes:s}:{}};C(B.route),H(B);});let pt=L.onRouteChange(()=>{C(L.getCurrentRoute()),U();});return typeof window<"u"&&(document.readyState==="complete"?(C(L.getCurrentRoute()),U()):window.addEventListener("load",()=>{C(L.getCurrentRoute()),U();},{once:true})),()=>{f.disconnect(),z.abort(),ae.forEach(b=>b()),pt();}},[K,a$1,s]),useEffect(()=>{let l=y.current,f=j.current;!l||!f||n.forEach(m=>{O.current.set(m.id,m),l.registerServerAction(m),f.register(m);});},[n]);let Z=useRef([]),re=useRef(false),oe=useCallback(async()=>{if(!(re.current||Z.current.length===0)){re.current=true;try{for(;Z.current.length>0;){let l=Z.current.shift();await Be(l.commands,l.batchId);}}finally{re.current=false;}}},[]),ie=useCallback((l,f)=>{Z.current.push({commands:l,batchId:f}),oe();},[oe]),Be=useCallback(async(l,f)=>{let m=F.current;if(!m)return;p({type:"SET_EXECUTING",isExecuting:true});let v=[];v.push(m.on("stateChange",x=>{p({type:"SET_EXECUTION_STATE",state:x}),p({type:"SET_EXECUTING",isExecuting:x.isExecuting});})),v.push(m.on("error",x=>{p({type:"SET_ERROR",error:x});}));try{let x=await m.execute(l),H=A.current;x.forEach(C=>{H&&(C.command.type==="server_action"?H.send({type:"action_result",actionId:C.command.actionId,success:C.success,result:C.result,error:C.error,commandId:f}):H.send({type:"action_result",actionId:C.command.type,success:C.success,error:C.error,commandId:f}));});}catch(x){let H=x instanceof Error?x:new Error(String(x));p({type:"SET_ERROR",error:H});let C=A.current,U=H.message||"Execution failed";l.forEach(L=>{if(!C)return;let z=L.type==="server_action"?L.actionId:L.type;C.send({type:"action_result",actionId:z,success:false,error:U,commandId:f});});}finally{v.forEach(x=>x()),p({type:"SET_EXECUTING",isExecuting:false}),p({type:"SET_EXECUTION_STATE",state:null});}},[]),g=useRef(()=>{}),T=useCallback(l=>{switch(_("Server message received:",l.type,l),l.type){case "response":{let f=me.current.find(v=>v.id===l.messageId);l.isFinal===false?f&&f.role==="assistant"?p({type:"UPDATE_MESSAGE",id:f.id,updates:{content:f.content+l.message,timestamp:Date.now(),status:"sending"}}):p({type:"ADD_MESSAGE",message:{id:l.messageId,role:"assistant",content:l.message,timestamp:Date.now(),status:"sending"}}):f&&f.role==="assistant"?p({type:"UPDATE_MESSAGE",id:f.id,updates:{content:l.message,timestamp:Date.now(),status:"sent"}}):p({type:"ADD_MESSAGE",message:{id:l.messageId,role:"assistant",content:l.message,timestamp:Date.now(),status:"sent"}});}break;case "command":{let f=Ft.safeParse(l);if(!f.success){_("Rejected invalid command message from server:",f.error.issues);break}let m=f.data;_("Received commands:",m.commands);let v=m.commands,x=m.batchId;if(m.message&&p({type:"ADD_MESSAGE",message:{id:createMessageId(),role:"assistant",content:m.message,timestamp:Date.now(),commands:v.length>0?v:void 0}}),v.length===0)break;if(!F.current){p({type:"SET_ERROR",error:new Error("Action runner not ready")}),v.forEach(C=>{let U=C.type==="server_action"?C.actionId:C.type;A.current&&A.current.send({type:"action_result",actionId:U,success:false,error:"Action runner not ready",commandId:x});});break}ie(v,x);break}case "typing":break;case "server_action_result":_("Server action result:",l.actionId,l.result);break;case "error":_("Server error:",l.code,l.error,l.details),p({type:"SET_ERROR",error:new Error(l.error)});break;case "request_context":G.current&&A.current&&A.current.send({type:"context",context:G.current});break}},[ie]);useEffect(()=>{g.current=T;},[T]);let W=useCallback(l=>{let f=createMessageId();_("Sending message:",{messageId:f,mode:R.mode,length:l.length,connectionState:R.connectionState,route:G.current?.route??K.getCurrentPath()}),p({type:"ADD_MESSAGE",message:{id:f,role:"user",content:l,timestamp:Date.now(),status:"sending"}});let m=G.current??{route:K.getCurrentPath(),title:typeof document<"u"?document.title:"",actions:[],serverActions:Array.from(O.current.values()),content:{headings:[],mainContent:"",forms:[]},timestamp:Date.now(),...ne.current?.length?{routes:ne.current}:{}},v=te??D?.voiceLanguage??void 0;A.current?.send({type:"message",content:l,context:m,mode:R.mode,messageId:f,...v!=null?{locale:v}:{}}),p({type:"UPDATE_MESSAGE",id:f,updates:{status:"sent"}});},[R.mode,K,te,D?.voiceLanguage]),ye=useCallback(l=>{Pe(l??null);},[]),xe=useCallback(l=>{p({type:"SET_MODE",mode:l});},[]),Ee=useCallback(async(l,f)=>{let m=j.current;if(!m)throw new Error("Server action bridge not ready");if(!m.getAction(l)){let x=O.current.get(l);x&&m.register(x);}let v=await m.execute(l,f??{});return A.current&&A.current.send({type:"action_result",actionId:l,success:v.success,result:v.data,error:v.error}),v},[]),Se=useCallback(l=>{O.current.set(l.id,l),y.current?.registerServerAction(l),j.current?.register(l),E.debug("Registered server action:",l.id);},[E]),we=useCallback(()=>{p({type:"CLEAR_MESSAGES"});},[]),se=useCallback(()=>{p({type:"CLEAR_ERROR"});},[]),Ce=useCallback(()=>{F.current?.abort();},[]),Re=useCallback(()=>{p({type:"SET_CONNECTION_STATE",state:"connecting"}),A.current?.connect();},[]),Ae=useCallback(()=>{A.current?.disconnect(),p({type:"SET_CONNECTION_STATE",state:"disconnected"});},[]);function _(...l){E.debug(...l);}let ee=useMemo(()=>({widgetConfig:D,messages:R.messages,mode:R.mode,connectionState:R.connectionState,isExecuting:R.isExecuting,executionState:R.executionState,error:R.error,isWidgetOpen:J,setWidgetOpen:V,voiceLanguage:$,setVoiceLanguage:ye,sendMessage:W,setMode:xe,executeAction:Ee,registerServerAction:Se,clearMessages:we,clearError:se,stopExecution:Ce,connect:Re,disconnect:Ae,isConnected:R.connectionState==="connected"}),[D,R,J,$,ye,W,xe,Ee,Se,we,se,Ce,Re,Ae]);return jsx(a.Provider,{value:ee,children:u})}var dt=`
2
+ /* =============================================
3
+ Navsi Chatbot Widget \u2014 Base Styles
4
+ ============================================= */
5
+
6
+ .navsi-chatbot-container {
7
+ position: fixed;
8
+ bottom: 24px;
9
+ right: 24px;
10
+ z-index: 9999;
11
+ display: flex;
12
+ flex-direction: column;
13
+ align-items: flex-end;
14
+ gap: 12px;
15
+ font-family: var(--navsi-font, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif);
16
+ }
17
+
18
+ /* ---- Toggle (open/close) button ---- */
19
+
20
+ .navsi-chatbot-toggle {
21
+ width: var(--navsi-button-size, 56px);
22
+ height: var(--navsi-button-size, 56px);
23
+ border-radius: var(--navsi-radius-full, 9999px);
24
+ background: var(--navsi-primary, #2563eb);
25
+ color: #fff;
26
+ border: none;
27
+ cursor: pointer;
28
+ display: flex;
29
+ align-items: center;
30
+ justify-content: center;
31
+ box-shadow: 0 4px 16px color-mix(in srgb, var(--navsi-primary, #2563eb) 40%, transparent);
32
+ transition: transform 0.2s ease, box-shadow 0.2s ease;
33
+ flex-shrink: 0;
34
+ }
35
+
36
+ .navsi-chatbot-toggle:hover {
37
+ transform: scale(1.08);
38
+ box-shadow: 0 6px 20px color-mix(in srgb, var(--navsi-primary, #2563eb) 50%, transparent);
39
+ }
40
+
41
+ /* ---- Chat window ---- */
42
+
43
+ .navsi-chatbot-window {
44
+ width: var(--navsi-window-width, 360px);
45
+ height: var(--navsi-window-height, 520px);
46
+ background: var(--navsi-bg, #ffffff);
47
+ border-radius: var(--navsi-radius, 12px);
48
+ box-shadow: 0 8px 40px rgba(0, 0, 0, 0.18);
49
+ display: flex;
50
+ flex-direction: column;
51
+ overflow: hidden;
52
+ border: 1px solid #e5e7eb;
53
+ }
54
+
55
+ /* ---- Header ---- */
56
+
57
+ .navsi-chatbot-header {
58
+ background: var(--navsi-primary, #2563eb);
59
+ color: #fff;
60
+ padding: 14px 16px;
61
+ display: flex;
62
+ align-items: center;
63
+ justify-content: space-between;
64
+ flex-shrink: 0;
65
+ flex-wrap: wrap;
66
+ gap: 6px;
67
+ }
68
+
69
+ .navsi-chatbot-header-left {
70
+ display: flex;
71
+ align-items: center;
72
+ gap: 10px;
73
+ }
74
+
75
+ .navsi-chatbot-title {
76
+ font-weight: 600;
77
+ font-size: 0.95rem;
78
+ }
79
+
80
+ .navsi-chatbot-status {
81
+ font-size: 0.72rem;
82
+ opacity: 0.8;
83
+ margin-top: 1px;
84
+ }
85
+
86
+ /* ---- Voice indicator ---- */
87
+
88
+ .navsi-chatbot-voice-indicator {
89
+ display: flex;
90
+ align-items: center;
91
+ gap: 4px;
92
+ font-size: 0.72rem;
93
+ opacity: 0.85;
94
+ margin-top: 2px;
95
+ }
96
+
97
+ /* ---- Clear button ---- */
98
+
99
+ .navsi-chatbot-clear {
100
+ background: rgba(255, 255, 255, 0.2);
101
+ border: none;
102
+ color: #fff;
103
+ font-size: 0.72rem;
104
+ padding: 3px 8px;
105
+ border-radius: 4px;
106
+ cursor: pointer;
107
+ transition: background 0.15s ease;
108
+ }
109
+
110
+ .navsi-chatbot-clear:hover {
111
+ background: rgba(255, 255, 255, 0.35);
112
+ }
113
+
114
+ /* ---- Mode toggle ---- */
115
+
116
+ .navsi-chatbot-mode-toggle {
117
+ display: flex;
118
+ gap: 4px;
119
+ background: rgba(255, 255, 255, 0.15);
120
+ border-radius: var(--navsi-radius-sm, 6px);
121
+ padding: 3px;
122
+ margin: 8px 16px;
123
+ flex-shrink: 0;
124
+ }
125
+
126
+ .navsi-chatbot-mode-button {
127
+ flex: 1;
128
+ padding: 5px 10px;
129
+ border: none;
130
+ border-radius: calc(var(--navsi-radius-sm, 6px) - 2px);
131
+ background: transparent;
132
+ color: rgba(255, 255, 255, 0.75);
133
+ cursor: pointer;
134
+ font-size: 0.78rem;
135
+ font-weight: 500;
136
+ transition: all 0.15s ease;
137
+ font-family: inherit;
138
+ }
139
+
140
+ .navsi-chatbot-mode-active {
141
+ background: #fff;
142
+ color: var(--navsi-primary, #2563eb);
143
+ }
144
+
145
+ /* ---- Language toggle ---- */
146
+
147
+ .navsi-chatbot-lang-toggle {
148
+ display: flex;
149
+ gap: 4px;
150
+ padding: 4px 16px;
151
+ flex-shrink: 0;
152
+ border-bottom: 1px solid #f3f4f6;
153
+ }
154
+
155
+ .navsi-chatbot-lang-button {
156
+ padding: 3px 8px;
157
+ border: 1px solid #d1d5db;
158
+ border-radius: 4px;
159
+ background: #f9fafb;
160
+ color: #374151;
161
+ cursor: pointer;
162
+ font-size: 0.72rem;
163
+ transition: all 0.15s ease;
164
+ font-family: inherit;
165
+ }
166
+
167
+ .navsi-chatbot-lang-active {
168
+ background: var(--navsi-primary, #2563eb);
169
+ color: #fff;
170
+ border-color: var(--navsi-primary, #2563eb);
171
+ }
172
+
173
+ /* ---- Execution banner ---- */
174
+
175
+ .navsi-chatbot-banner {
176
+ display: flex;
177
+ align-items: center;
178
+ gap: 8px;
179
+ padding: 8px 16px;
180
+ font-size: 0.8rem;
181
+ background: #fffbeb;
182
+ color: #92400e;
183
+ border-bottom: 1px solid #fde68a;
184
+ flex-shrink: 0;
185
+ }
186
+
187
+ .navsi-chatbot-pill {
188
+ background: #fbbf24;
189
+ color: #78350f;
190
+ padding: 1px 8px;
191
+ border-radius: 9999px;
192
+ font-size: 0.72rem;
193
+ font-weight: 600;
194
+ }
195
+
196
+ .navsi-chatbot-step {
197
+ font-size: 0.72rem;
198
+ opacity: 0.8;
199
+ }
200
+
201
+ /* ---- Progress bar ---- */
202
+
203
+ .navsi-chatbot-progress-container {
204
+ padding: 0 16px 4px;
205
+ flex-shrink: 0;
206
+ }
207
+
208
+ .navsi-chatbot-progress-bar {
209
+ height: 4px;
210
+ background: #e5e7eb;
211
+ border-radius: 2px;
212
+ overflow: hidden;
213
+ }
214
+
215
+ .navsi-chatbot-progress-fill {
216
+ height: 100%;
217
+ background: var(--navsi-primary, #2563eb);
218
+ border-radius: 2px;
219
+ transition: width 0.3s ease;
220
+ }
221
+
222
+ /* ---- Messages area ---- */
223
+
224
+ .navsi-chatbot-messages {
225
+ flex: 1;
226
+ overflow-y: auto;
227
+ padding: 16px;
228
+ display: flex;
229
+ flex-direction: column;
230
+ gap: 12px;
231
+ }
232
+
233
+ .navsi-chatbot-messages::-webkit-scrollbar {
234
+ width: 4px;
235
+ }
236
+ .navsi-chatbot-messages::-webkit-scrollbar-thumb {
237
+ background: #d1d5db;
238
+ border-radius: 2px;
239
+ }
240
+
241
+ /* ---- Individual messages ---- */
242
+
243
+ .navsi-chatbot-message {
244
+ display: flex;
245
+ flex-direction: column;
246
+ max-width: 85%;
247
+ }
248
+
249
+ .navsi-chatbot-message-user {
250
+ align-self: flex-end;
251
+ align-items: flex-end;
252
+ }
253
+
254
+ .navsi-chatbot-message-assistant {
255
+ align-self: flex-start;
256
+ align-items: flex-start;
257
+ }
258
+
259
+ /* Message content wrapping div */
260
+ .navsi-chatbot-message-content {
261
+ padding: 10px 14px;
262
+ border-radius: var(--navsi-radius, 12px);
263
+ font-size: 0.875rem;
264
+ line-height: 1.5;
265
+ word-break: break-word;
266
+ }
267
+
268
+ /* User bubble \u2014 also style direct text (non-wrapped) */
269
+ .navsi-chatbot-message-user {
270
+ padding: 10px 14px;
271
+ border-radius: var(--navsi-radius, 12px);
272
+ font-size: 0.875rem;
273
+ line-height: 1.5;
274
+ word-break: break-word;
275
+ background: var(--navsi-primary, #2563eb);
276
+ color: #fff;
277
+ border-bottom-right-radius: 4px;
278
+ }
279
+
280
+ .navsi-chatbot-message-user .navsi-chatbot-message-content {
281
+ background: transparent;
282
+ color: inherit;
283
+ padding: 0;
284
+ border-radius: 0;
285
+ }
286
+
287
+ /* Assistant bubble */
288
+ .navsi-chatbot-message-assistant {
289
+ padding: 10px 14px;
290
+ border-radius: var(--navsi-radius, 12px);
291
+ font-size: 0.875rem;
292
+ line-height: 1.5;
293
+ word-break: break-word;
294
+ background: #f3f4f6;
295
+ color: var(--navsi-text, #1f2937);
296
+ border-bottom-left-radius: 4px;
297
+ }
298
+
299
+ .navsi-chatbot-message-assistant .navsi-chatbot-message-content {
300
+ background: transparent;
301
+ color: inherit;
302
+ padding: 0;
303
+ border-radius: 0;
304
+ }
305
+
306
+ /* Message markdown helpers */
307
+ .navsi-chatbot-message-paragraph {
308
+ margin: 0 0 0.5em 0;
309
+ }
310
+
311
+ .navsi-chatbot-message-paragraph:last-child {
312
+ margin-bottom: 0;
313
+ }
314
+
315
+ .navsi-chatbot-message-list {
316
+ margin: 0.25em 0 0.5em 1.25em;
317
+ padding: 0;
318
+ list-style: disc;
319
+ }
320
+
321
+ .navsi-chatbot-message-list:last-child {
322
+ margin-bottom: 0;
323
+ }
324
+
325
+ .navsi-chatbot-message-list-item {
326
+ margin-bottom: 0.15em;
327
+ }
328
+
329
+ /* ---- Welcome message ---- */
330
+
331
+ .navsi-chatbot-welcome {
332
+ text-align: center;
333
+ padding: 32px 16px;
334
+ color: #6b7280;
335
+ }
336
+
337
+ .navsi-chatbot-welcome-icon {
338
+ font-size: 2.5rem;
339
+ margin-bottom: 8px;
340
+ }
341
+
342
+ .navsi-chatbot-welcome-text {
343
+ font-size: 1rem;
344
+ font-weight: 600;
345
+ color: var(--navsi-text, #1f2937);
346
+ margin-bottom: 6px;
347
+ }
348
+
349
+ .navsi-chatbot-welcome-hint {
350
+ font-size: 0.8rem;
351
+ }
352
+
353
+ /* ---- Input area ---- */
354
+
355
+ .navsi-chatbot-input-area {
356
+ padding: 12px 16px;
357
+ border-top: 1px solid #e5e7eb;
358
+ display: flex;
359
+ align-items: center;
360
+ gap: 8px;
361
+ flex-shrink: 0;
362
+ background: var(--navsi-bg, #ffffff);
363
+ }
364
+
365
+ .navsi-chatbot-input {
366
+ flex: 1;
367
+ border: 1px solid #d1d5db;
368
+ border-radius: var(--navsi-radius-sm, 6px);
369
+ padding: 8px 12px;
370
+ font-size: 0.875rem;
371
+ outline: none;
372
+ resize: none;
373
+ min-height: 36px;
374
+ max-height: 100px;
375
+ font-family: inherit;
376
+ transition: border-color 0.15s ease;
377
+ background: var(--navsi-bg, #ffffff);
378
+ color: var(--navsi-text, #1f2937);
379
+ }
380
+
381
+ .navsi-chatbot-input:focus {
382
+ border-color: var(--navsi-primary, #2563eb);
383
+ }
384
+
385
+ .navsi-chatbot-input::placeholder {
386
+ color: #9ca3af;
387
+ }
388
+
389
+ /* ---- Action buttons (send / voice / stop) ---- */
390
+
391
+ .navsi-chatbot-send-button,
392
+ .navsi-chatbot-voice-button,
393
+ .navsi-chatbot-stop-button {
394
+ width: 36px;
395
+ height: 36px;
396
+ border-radius: var(--navsi-radius-sm, 6px);
397
+ border: none;
398
+ cursor: pointer;
399
+ display: flex;
400
+ align-items: center;
401
+ justify-content: center;
402
+ flex-shrink: 0;
403
+ transition: all 0.15s ease;
404
+ }
405
+
406
+ .navsi-chatbot-send-button {
407
+ background: var(--navsi-primary, #2563eb);
408
+ color: #fff;
409
+ }
410
+
411
+ .navsi-chatbot-send-button:hover {
412
+ background: var(--navsi-primary-hover, #1d4ed8);
413
+ }
414
+
415
+ .navsi-chatbot-send-button:disabled {
416
+ background: #d1d5db;
417
+ cursor: not-allowed;
418
+ }
419
+
420
+ .navsi-chatbot-voice-button {
421
+ background: #f3f4f6;
422
+ color: #374151;
423
+ }
424
+
425
+ .navsi-chatbot-voice-button:hover {
426
+ background: #e5e7eb;
427
+ }
428
+
429
+ .navsi-chatbot-voice-button:disabled {
430
+ opacity: 0.4;
431
+ cursor: not-allowed;
432
+ }
433
+
434
+ .navsi-chatbot-voice-button-active {
435
+ background: #fee2e2;
436
+ color: #dc2626;
437
+ }
438
+
439
+ .navsi-chatbot-stop-button {
440
+ background: #fee2e2;
441
+ color: #dc2626;
442
+ }
443
+
444
+ .navsi-chatbot-stop-button:hover {
445
+ background: #fecaca;
446
+ }
447
+
448
+ /* ---- Error banner ---- */
449
+
450
+ .navsi-chatbot-error {
451
+ background: #fef2f2;
452
+ color: #dc2626;
453
+ font-size: 0.8rem;
454
+ padding: 8px 16px;
455
+ display: flex;
456
+ align-items: center;
457
+ justify-content: space-between;
458
+ flex-shrink: 0;
459
+ }
460
+
461
+ .navsi-chatbot-error-close {
462
+ background: none;
463
+ border: none;
464
+ color: #dc2626;
465
+ cursor: pointer;
466
+ font-size: 1rem;
467
+ padding: 0 4px;
468
+ line-height: 1;
469
+ }
470
+
471
+ /* ---- Voice error ---- */
472
+
473
+ .navsi-chatbot-voice-error {
474
+ background: #fef2f2;
475
+ color: #dc2626;
476
+ font-size: 0.78rem;
477
+ padding: 6px 16px;
478
+ flex-shrink: 0;
479
+ }
480
+
481
+ /* ---- Voice transcript ---- */
482
+
483
+ .navsi-chatbot-voice-transcript {
484
+ padding: 6px 16px;
485
+ font-size: 0.78rem;
486
+ color: #6b7280;
487
+ font-style: italic;
488
+ border-top: 1px solid #f3f4f6;
489
+ flex-shrink: 0;
490
+ }
491
+
492
+ /* ---- Typing indicator ---- */
493
+
494
+ .navsi-chatbot-typing {
495
+ display: flex;
496
+ gap: 4px;
497
+ align-items: center;
498
+ padding: 10px 14px;
499
+ background: #f3f4f6;
500
+ border-radius: var(--navsi-radius, 12px);
501
+ border-bottom-left-radius: 4px;
502
+ width: fit-content;
503
+ }
504
+
505
+ .navsi-chatbot-typing span {
506
+ width: 6px;
507
+ height: 6px;
508
+ background: #9ca3af;
509
+ border-radius: 50%;
510
+ animation: navsi-bounce 1.2s infinite;
511
+ }
512
+
513
+ .navsi-chatbot-typing span:nth-child(2) { animation-delay: 0.2s; }
514
+ .navsi-chatbot-typing span:nth-child(3) { animation-delay: 0.4s; }
515
+
516
+ @keyframes navsi-bounce {
517
+ 0%, 80%, 100% { transform: translateY(0); }
518
+ 40% { transform: translateY(-6px); }
519
+ }
520
+
521
+ /* ---- Responsive (mobile) ---- */
522
+
523
+ @media (max-width: 480px) {
524
+ .navsi-chatbot-window {
525
+ width: calc(100vw - 32px);
526
+ height: calc(100vh - 120px);
527
+ max-height: 600px;
528
+ }
529
+ }
530
+ `;var gt="navsi-chatbot-styles",ze=false;function ht(){if(ze||typeof document>"u")return;if(document.getElementById(gt)){ze=true;return}let i=document.createElement("style");i.id=gt,i.textContent=dt,document.head.prepend(i),ze=true;}function ft(i){let e=[],t=0,n=i;for(;n.length>0;){let r=n.indexOf("**");if(r===-1){e.push(jsx(qe.Fragment,{children:n},t++));break}let o=n.slice(0,r),s=n.slice(r+2),a=s.indexOf("**");if(a===-1){e.push(jsx(qe.Fragment,{children:n},t++));break}o&&e.push(jsx(qe.Fragment,{children:o},t++)),e.push(jsx("strong",{children:s.slice(0,a)},t++)),n=s.slice(a+2);}return e.length===1?e[0]:jsx(Fragment,{children:e})}function Yt({content:i,isUser:e}){if(e)return jsx(Fragment,{children:i});let t=typeof i=="string"?i:"";if(!t.trim())return jsx(Fragment,{children:"\xA0"});let n=t.split(/\n/),r=[],o=[],s=()=>{o.length>0&&(r.push(jsx("ul",{className:"navsi-chatbot-message-list",children:o.map((a,c)=>jsx("li",{className:"navsi-chatbot-message-list-item",children:ft(a)},c))},r.length)),o=[]);};for(let a=0;a<n.length;a++){let u=n[a].trim(),h=u.match(/^[*-]\s+(.*)$/);h?(s(),o.push(h[1].trim())):(s(),u&&r.push(jsx("p",{className:"navsi-chatbot-message-paragraph",children:ft(u)},r.length)));}return s(),r.length===0?jsx(Fragment,{children:t}):jsx("div",{className:"navsi-chatbot-message-content",children:r})}function Jt({className:i,windowClassName:e$1,buttonClassName:t}){ht();let[n,r]=useState(""),o=useRef(null),s=useRef(null),a=useRef(null),c$1=useRef(false),u=useRef(false),{messages:h,sendMessage:E,isConnected:S,mode:D,setMode:pe,isExecuting:R,error:p,clearError:me,clearMessages:J,isWidgetOpen:V,setWidgetOpen:te,stopExecution:Pe,widgetConfig:$,voiceLanguage:be,setVoiceLanguage:A}=c(),Q=be??$?.voiceLanguage??(typeof navigator<"u"?navigator.language:void 0)??"en-US",{progress:O}=d(),{isReconnecting:G}=e(),$e=useCallback(g=>{u.current=true,E(g),r("");},[E]),y=f({lang:Q,onTranscript:$e,silenceMs:1200,autoSpeak:true});useEffect(()=>{h.length>0&&s.current&&V&&requestAnimationFrame(()=>{s.current&&s.current.scrollTo({top:s.current.scrollHeight,behavior:"smooth"});});},[h,V]),useEffect(()=>{if(!c$1.current){let g=[...h].reverse().find(T=>T.role==="assistant");a.current=g?.id??null,c$1.current=true;}},[]),useEffect(()=>{if(!c$1.current||!u.current||y.isListening)return;let g=h.length>0?h[h.length-1]:void 0;if(!g||g.role!=="assistant"||g.id===a.current)return;let T=g.content?.trim();T&&(y.speak(T),a.current=g.id,u.current=false);},[h,y]);let ve=()=>{n.trim()&&(u.current=false,E(n.trim()),r(""));},We=g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),ve());};function F(g,T){return g&&(/^#[0-9a-fA-F]{3,8}$/.test(g)||/^rgba?\(\s*[\d.,\s%]+\)$/.test(g)||/^hsla?\(\s*[\d.,\s%]+\)$/.test(g)||/^[a-zA-Z]{2,30}$/.test(g))?g:T}function j(g,T){if(!g)return T;let W=g.replace(/[^a-zA-Z0-9\s,'_-]/g,"").trim();return W.length>0&&W.length<=200?W:T}useEffect(()=>{let g=$?.theme,T="navsi-chatbot-theme-vars",W=document.getElementById(T);W||(W=document.createElement("style"),W.id=T,document.head.appendChild(W));let ye=F(g?.primaryColor,"#2563eb"),xe=F(g?.secondaryColor,"#1d4ed8"),Ee=F(g?.backgroundColor,"#ffffff"),Se=F(g?.textColor,"#1f2937"),we=j(g?.fontFamily,"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"),se=Math.min(50,Math.max(0,Number(g?.borderRadius)||12)),Ce=Math.min(800,Math.max(280,Number(g?.windowWidth)||360)),Re=Math.min(1e3,Math.max(300,Number(g?.windowHeight)||520)),Ae=Math.min(120,Math.max(32,Number(g?.buttonSize)||56)),ee=["bottom-right","bottom-left","top-right","top-left"].includes(g?.position??"")?g?.position??"bottom-right":"bottom-right",l=ee==="bottom-right"||ee==="top-right",f=ee==="bottom-right"||ee==="bottom-left";W.textContent=`
531
+ .navsi-chatbot-container {
532
+ --navsi-primary: ${ye};
533
+ --navsi-primary-hover: ${xe};
534
+ --navsi-bg: ${Ee};
535
+ --navsi-text: ${Se};
536
+ --navsi-font: ${we};
537
+ --navsi-radius: ${se}px;
538
+ --navsi-radius-sm: ${Math.max(4,Math.round(se*.5))}px;
539
+ --navsi-radius-full: 9999px;
540
+ --navsi-window-width: ${Ce}px;
541
+ --navsi-window-height: ${Re}px;
542
+ --navsi-button-size: ${Ae}px;
543
+ font-family: var(--navsi-font);
544
+ ${f?"bottom: 24px; top: auto;":"top: 24px; bottom: auto;"}
545
+ ${l?"right: 24px; left: auto;":"left: 24px; right: auto;"}
546
+ }
547
+ `;},[$?.theme]);let ne={position:"fixed",zIndex:9999},K=$?.headerTitle??"AI Assistant",Z=$?.welcomeMessage??"How can I help you today?",re=$?.subtitle??"Type a message to get started",oe=$?.askPlaceholder??"Ask a question...",ie=$?.navigatePlaceholder??"What should I do? Try: Go to cart, Add product 1 to cart",Be=$?.supportedLanguages??[{code:"en-US",label:"EN"},{code:"hi-IN",label:"\u0939\u093F\u0902\u0926\u0940"}];return jsxs("div",{style:ne,className:`navsi-chatbot-container ${i||""}`,children:[V&&jsxs("div",{className:`navsi-chatbot-window ${e$1||""}`,children:[jsxs("div",{className:"navsi-chatbot-header",children:[jsx("div",{className:"navsi-chatbot-header-left",children:jsxs("div",{children:[jsx("div",{className:"navsi-chatbot-title",children:K}),jsx("div",{className:"navsi-chatbot-status",children:S?"Connected":G?"Reconnecting":"Disconnected"}),y.isListening&&jsxs("div",{className:"navsi-chatbot-voice-indicator","aria-live":"polite",children:[jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Listening\u2026"]})]})}),jsxs("div",{className:"navsi-chatbot-mode-toggle",children:[jsx("button",{className:`navsi-chatbot-mode-button ${D==="ask"?"navsi-chatbot-mode-active":""}`,onClick:()=>pe("ask"),children:"Ask"}),jsx("button",{className:`navsi-chatbot-mode-button ${D==="navigate"?"navsi-chatbot-mode-active":""}`,onClick:()=>pe("navigate"),children:"Action"})]}),jsx("div",{className:"navsi-chatbot-lang-toggle",role:"group","aria-label":"Voice and response language",children:Be.map(g=>jsx("button",{type:"button",className:`navsi-chatbot-lang-button ${Q.startsWith(g.code.split("-")[0])?"navsi-chatbot-lang-active":""}`,onClick:()=>A(g.code),title:g.label,"aria-pressed":Q.startsWith(g.code.split("-")[0]),children:g.label},g.code))}),h.length>0&&jsx("button",{type:"button",onClick:()=>J(),className:"navsi-chatbot-clear",title:"Clear chat","aria-label":"Clear chat",children:"Clear"})]}),R&&jsxs("div",{className:"navsi-chatbot-banner",children:[jsx("span",{children:"\u26A1 Executing actions\u2026"}),O&&jsxs(Fragment,{children:[jsxs("span",{className:"navsi-chatbot-pill",children:[O.current+1,"/",O.total]}),O.description&&jsx("span",{className:"navsi-chatbot-step",children:O.description})]})]}),O&&jsx("div",{className:"navsi-chatbot-progress-container",children:jsx("div",{className:"navsi-chatbot-progress-bar",children:jsx("div",{className:"navsi-chatbot-progress-fill",style:{width:`${O.percentage??0}%`}})})}),p&&jsxs("div",{className:"navsi-chatbot-error",children:[jsx("span",{children:p.message}),jsx("button",{className:"navsi-chatbot-error-close",onClick:me,children:"\u2715"})]}),y.error&&jsx("div",{className:"navsi-chatbot-voice-error",role:"alert",children:y.error}),jsxs("div",{ref:s,className:"navsi-chatbot-messages",role:"log","aria-live":"polite","aria-label":"Chat messages",children:[h.length===0&&jsxs("div",{className:"navsi-chatbot-welcome",children:[jsx("div",{className:"navsi-chatbot-welcome-icon",children:"\u{1F44B}"}),jsx("div",{className:"navsi-chatbot-welcome-text",children:Z}),jsx("div",{className:"navsi-chatbot-welcome-hint",children:re})]}),h.map(g=>jsx("div",{className:`navsi-chatbot-message ${g.role==="user"?"navsi-chatbot-message-user":"navsi-chatbot-message-assistant"}`,children:jsx(Yt,{content:g.content,isUser:g.role==="user"})},g.id)),jsx("div",{ref:o})]}),jsxs("div",{className:"navsi-chatbot-input-area",children:[jsx("input",{type:"text",value:n,onChange:g=>r(g.target.value),onKeyDown:We,placeholder:D==="ask"?oe:ie,className:"navsi-chatbot-input",maxLength:8e3,"aria-label":D==="ask"?oe:ie}),jsx("button",{className:`navsi-chatbot-voice-button ${y.isListening?"navsi-chatbot-voice-button-active":""}`,onClick:()=>{y.isListening?y.stop():y.start();},disabled:!S||!y.isSupported,"aria-label":y.isSupported?y.isListening?"Stop voice input":"Start voice input":"Voice input not supported in this browser","aria-pressed":y.isListening,title:y.isSupported?y.isListening?"Click to stop and send":"Click to start listening":"Voice input is not available in this browser",type:"button",children:y.isListening?jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor",children:jsx("circle",{cx:"12",cy:"12",r:"8"})}):jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})}),R?jsx("button",{className:"navsi-chatbot-stop-button",onClick:Pe,"aria-label":"Stop",title:"Stop current action",children:jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor",children:jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1"})})}):jsx("button",{className:"navsi-chatbot-send-button",onClick:ve,disabled:!S,children:jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor",children:jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})})})]}),y.transcript&&jsx("div",{className:"navsi-chatbot-voice-transcript","aria-live":"polite",children:y.transcript})]}),jsx("button",{className:`navsi-chatbot-toggle ${t||""}`,onClick:()=>te(!V),"aria-label":V?"Close chat":"Open chat",children:V?jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",children:jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})}):jsx("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"currentColor",children:jsx("path",{d:"M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"})})})]})}export{ce as a,en as b,Ze as c,le as d,on as e,Kt as f,Jt as g};//# sourceMappingURL=chunk-BIWJ47RP.js.map
548
+ //# sourceMappingURL=chunk-BIWJ47RP.js.map