@marketrix.ai/widget 3.8.480 → 3.8.481

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.
Files changed (2) hide show
  1. package/dist/widget.mjs +3 -3
  2. package/package.json +1 -1
package/dist/widget.mjs CHANGED
@@ -15,7 +15,7 @@ return y(e,{...p,ref:u,className:d,style:{color:ua[n?"inherit":i],...s&&{fontSiz
15
15
  return b(Hi,{toast:e,className:"mtx-toast",render:/* @__PURE__ */y(Aa,{align:"center",gap:"md",rounded:"pill",paddingPreset:"toast",elevation:"panel",style:{backgroundColor:t.background,border:t.border}}),children:[
16
16
  /* @__PURE__ */y(Ca,{src:ca,alt:"",size:28,rounded:"full"}),
17
17
  /* @__PURE__ */b(Na,{grow:!0,minWidth:"0",children:[/* @__PURE__ */y(Zi,{render:/* @__PURE__ */y(Ba,{as:"span",block:!0,inheritColor:!0,weight:"medium",style:{fontSize:"13px",color:t.titleColor,whiteSpace:e.actionProps?"normal":"nowrap",overflow:"hidden",textOverflow:"ellipsis"}})}),null!=e.description&&/* @__PURE__ */y(Ji,{render:/* @__PURE__ */y(Ba,{as:"span",block:!0,inheritColor:!0,style:{fontSize:"12px",color:t.bodyColor,opacity:.8,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}})})]}),e.actionProps&&/* @__PURE__ */y(is,{render:/* @__PURE__ */y(Ma,{type:"button",variant:"ghost",shape:"pill",size:"sm",style:{color:t.titleColor,backgroundColor:t.actionBackground,border:t.border}})}),
18
- /* @__PURE__ */y(os,{render:/* @__PURE__ */y(La,{label:"Dismiss",size:"xs",tone:"inherit",style:{color:t.closeColor,padding:"2px"}}),children:/* @__PURE__ */y(Pa,{name:"closeSmall",size:12})})]},e.id)})},Ua=({children:e,container:t,offsetBottom:n=20})=>/* @__PURE__ */b(ai,{children:[e,/* @__PURE__ */y(ys,{container:t??void 0,children:/* @__PURE__ */y(Oi,{className:"mtx-toast-viewport",style:{zIndex:2147483004,bottom:`${n}px`},children:/* @__PURE__ */y(Wa,{})})})]}),Ha=aa,ja=({error:e,onClearError:t,onRetry:n,greeting:r,greetingBody:o,onGreetingDismiss:i})=>{const{add:s,close:c}=Ha();return a(()=>{if(null!=e)return s({id:"error",type:"error",title:e,timeout:0,priority:"high",onClose:t,...n&&{actionProps:{children:"Retry",onClick:n}}}),()=>c("error")},[e,n,s,c,t]),a(()=>{if(r)return s({id:"greeting",type:"info",title:r,description:o,timeout:8e3,onClose:i}),()=>c("greeting")},[r,o,s,c,i]),null};function qa(e){const t=[...e.parts],n=e.content.trim();return 0===t.length&&n&&t.push({type:"text",content:n}),{...e,timestamp:new Date(e.timestamp),parts:t}}function Va({videoStream:e,...t}){const n=t.timestamp.toISOString();if(!e)return{...t,timestamp:n};const r="Screenshare ended";return{...t,timestamp:n,content:r,isSystemMessage:!0,parts:[{type:"text",content:r}]}}var Ya=new class{restore(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=De.getContext();return{...o,messages:r.map(qa)}}persist(e){De.updateContext({...e,messages:e.messages.map(Va)})}};function Ka(e,t,n,r={}){return{id:`${e}-${Date.now()}`,content:n,sender:t,timestamp:/* @__PURE__ */new Date,parts:n?[{type:"text",content:n}]:[],...r}}var Xa=(e,t,n="user-message")=>Ka(n,"user",e.trim(),{mode:t}),Ga=e=>Ka("agent-message","agent",e.trim()),Ja=(e,t,n,r)=>Ka(r,n,e,{mode:t,isSystemMessage:!0}),Za={show:"Show",tell:"Tell",do:"Do"},Qa=e=>Za[e];function ec(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}function tc({messages:e,isTaskRunning:t,currentMode:n}){const r=e=>"agent"===e.sender&&!e.isSystemMessage&&!e.isScreenAccessRequest,o=e=>e.isPlaceholder&&void 0===e.mode||e.mode===n,i=[];!t||"show"!==n&&"do"!==n||i.push(e=>r(e)&&o(e)&&!!e.isPlaceholder,e=>r(e)&&o(e)),i.push(e=>r(e)&&!!e.isPlaceholder,r);for(const s of i){const t=ec(e,s);if(t>=0)return{index:t,message:e[t]}}return console.warn("[MessageFinder] No message found for progress update",{totalMessages:e.length,isTaskRunning:t,currentMode:n}),null}var nc=/* @__PURE__ */new Set(["click_element","type_text","select_dropdown_option","send_keys"]),rc=e=>e.replace(/\(?cancelled by cleanup\)?/gi,"").trim();function oc(e,t,n){if(t<0)return e;const r=[...e.parts];return r[t]={...r[t],...n},{...e,parts:r}}var ic=(e,t)=>e.parts.findIndex(e=>(e=>"progress"===e.type&&"in_progress"===e.status)(e)&&e.browserToolName===t),sc=/* @__PURE__ */new Map([["navigate","Navigating"],["search","Searching"],["click_element","Clicking element"],["type_text","Typing text"],["scroll","Scrolling"],["scroll_to_text","Scrolling to text"],["send_keys","Pressing key"],["extract","Extracting content"],["get_dropdown_options","Reading dropdown options"],["select_dropdown_option","Selecting option"],["go_back","Going back"],["wait","Waiting"],["close_tab","Closing tab"],["done","Done"],["get_html","Reading the page"],["get_screenshot","Taking screenshot"]]),ac=/* @__PURE__ */new Set(["button","link","textbox","checkbox","radio","switch","tab","menuitem"]);function*cc(e){let t=e;for(;t;){yield t;const e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}}function lc(e){if(!(e instanceof Element))return!1;try{if(!function(e){const t=e.tagName.toLowerCase();return"button"===t||"input"===t||"textarea"===t||"select"===t||"a"===t&&e.hasAttribute("href")||ac.has(e.getAttribute("role")??"")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||parseInt(e.getAttribute("tabindex")??"-1",10)>=0}(e))return!1;if(!0===e.disabled)return!1;if("true"===e.getAttribute("aria-disabled"))return!1;for(const r of cc(e))if(r instanceof HTMLElement&&r.inert)return!1;const t=window.getComputedStyle(e);if("none"===t.display||"none"===t.pointerEvents)return!1;const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return!1;for(const r of cc(e))if(r!==e){const e=window.getComputedStyle(r).overflow;if("hidden"===e||"clip"===e){const e=r.getBoundingClientRect();if(n.right<e.left||n.left>e.right||n.bottom<e.top||n.top>e.bottom)return!1}if(r===document.body)break}for(let r=e.getRootNode();r instanceof ShadowRoot;r=r.host.getRootNode()){const e=r.host.getBoundingClientRect();if(e.width<=0||e.height<=0)return!1}return!0}catch(t){return console.error("[isInteractable] Unexpected error:",t),!1}}var dc=["id","type","role","aria-label","name","href"],uc=new class{index=/* @__PURE__ */new Map;elementToSequence=/* @__PURE__ */new WeakMap;generateAnchoredSelector(e){const t=[];let n=e;for(;n!==document.body;){const e=n.id?`#${CSS.escape(n.id)}`:"";if(e&&1===document.querySelectorAll(e).length)return t.unshift(e),t.join(" > ");const r=n.parentElement;if(!r)break;const o=n.tagName,i=Array.from(r.children).filter(e=>e.tagName===o),s=i.length>1?`:nth-of-type(${i.indexOf(n)+1})`:"";t.unshift(o.toLowerCase()+s),n=r}return["body",...t].join(" > ")}staleReason(e){return document.contains(e.element)?dc.some((t,n)=>e.element.getAttribute(t)!==e.identity[n])?"has changed":null:"no longer exists"}indexInteractableElements(){this.clearIndex();const e=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{if(e instanceof HTMLElement&&null===e.offsetParent&&"BODY"!==e.tagName){const t=window.getComputedStyle(e),n="fixed"===t.position||"sticky"===t.position;if("none"===t.display)return NodeFilter.FILTER_REJECT;if(!n){let t=e.parentElement,n=!1;for(;t&&t!==document.body;){const e=window.getComputedStyle(t);if("fixed"===e.position||"sticky"===e.position){n=!0;break}t=t.parentElement}if(!n)return NodeFilter.FILTER_REJECT}}return NodeFilter.FILTER_ACCEPT}});let t=e.nextNode(),n=0;for(;t;){const r=t instanceof HTMLElement?t:null;if(r){const e=r.matches('a[href], button, input, textarea, select, [role="button"]'),t=r.classList.contains("cursor-pointer")||r.classList.contains("clickable"),o="function"==typeof r.onclick;(e||t||o||lc(r))&&(this.index.set(n,{element:r,selector:this.generateAnchoredSelector(r),identity:dc.map(e=>r.getAttribute(e))}),this.elementToSequence.set(r,n),n++)}t=e.nextNode()}}reindexAndSnapshot(){this.indexInteractableElements();const e=document.documentElement.cloneNode(!0);for(const[n,{selector:r}]of this.index.entries())try{e.querySelector(r)?.setAttribute("data-id",n.toString())}catch(t){console.warn(`[DomService] Failed to tag index ${n}:`,t)}return e.outerHTML}getSequenceForElement(e){return this.elementToSequence.get(e)}clearIndex(){this.index.clear(),this.elementToSequence=/* @__PURE__ */new WeakMap}checkElementInteractable(e,t){if(!document.body.contains(e))return`ELEMENT_NOT_INTERACTABLE: Element ${t} is not in the DOM`;const n=window.getComputedStyle(e);if("none"===n.display)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has display:none`;if("hidden"===n.visibility)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has visibility:hidden`;if(0===parseFloat(n.opacity))return`ELEMENT_NOT_INTERACTABLE: Element ${t} has opacity:0`;const r=e.getBoundingClientRect();if(0===r.width||0===r.height)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has zero dimensions`;const o=r.left+r.width/2,i=r.top+r.height/2,s=document.elementFromPoint(o,i);if(s&&s!==e&&!e.contains(s)&&!s.closest("#marketrix-show-highlight, #marketrix-show-popup, .marketrix-widget-container")){const e=s.tagName.toLowerCase();return`ELEMENT_OBSCURED: Element ${t} is covered by ${s.className?`${e}.${s.className.split(" ")[0]}`:e}. The obscuring element may be a modal or overlay that needs to be dismissed first.`}return null}getValidatedElement(e){const t=this.index.get(e);if(!t)return{element:null,error:`Element ${e} not found`};const n=this.staleReason(t);if(n)return{element:null,error:`DOM_CHANGED: Element at index ${e} ${n}. Call get_html to get updated indices.`};const r=this.checkElementInteractable(t.element,e);return r?{element:null,error:r}:{element:t.element}}},hc=null;function pc(){return hc?.active&&"live"===hc.getVideoTracks()[0]?.readyState?hc:(hc=null,null)}async function fc(){if(!1===De.getContext().config?.use_screenshare)throw new Error("Screen sharing is disabled for this widget");const e=pc();if(e)return e;const t=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});if(!t||0===t.getVideoTracks().length)throw new Error("Screen sharing permission denied or no video track available");return hc=t,t.getVideoTracks()[0].addEventListener("ended",()=>{hc=null}),t}var mc=["scroll","resize","touchmove","wheel"],gc=new class{currentPopup=null;currentHighlight=null;currentElement=null;currentOptions=null;currentPromise=null;resolvePromise=null;rejectPromise=null;clickHandler=null;scrollHandler=null;visibilityCheckInterval=null;async showToolAction(e){const{element:t,explanation:n,isClickAction:r=!1,browserToolName:o}=e;return this.currentOptions?.element===t&&this.currentOptions.explanation===n&&this.currentOptions.browserToolName===o&&this.currentPromise||(this.cleanup(),this.currentOptions=e,this.currentElement=t,t.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),this.createHighlight(t),this.createPopup(n,r),this.setupPositionUpdates(),this.setupVisibilityMonitoring(),r&&this.setupClickHandler(),this.currentPromise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})),this.currentPromise}cleanup(){if(this.takeSettlers().reject?.(/* @__PURE__ */new Error("Cancelled by cleanup")),this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler){for(const e of mc)window.removeEventListener(e,this.scrollHandler,{capture:!0});this.scrollHandler=null}this.visibilityCheckInterval&&(clearInterval(this.visibilityCheckInterval),this.visibilityCheckInterval=null),this.currentPopup?.remove(),this.currentHighlight?.remove(),document.getElementById("marketrix-show-popup")?.remove(),document.getElementById("marketrix-show-highlight")?.remove(),this.currentPopup=null,this.currentHighlight=null,this.currentElement=null,this.currentOptions=null,this.currentPromise=null}completeAction(){this.takeSettlers().resolve?.(),this.cleanup()}takeSettlers(){const e={resolve:this.resolvePromise,reject:this.rejectPromise};return this.resolvePromise=null,this.rejectPromise=null,e}createHighlight(e){const t=e.getBoundingClientRect(),n=document.createElement("div");n.id="marketrix-show-highlight",n.style.cssText=`position:fixed;top:${t.top}px;left:${t.left}px;width:${t.width}px;height:${t.height}px;border:3px solid #3b82f6;border-radius:4px;box-shadow:0 0 0 4px rgba(59,130,246,0.2),0 0 20px rgba(59,130,246,0.4);z-index:2147483645;pointer-events:none;transition:none;`,document.body.appendChild(n),this.currentHighlight=n}createPopup(e,t){const n=document.createElement("div");n.id="marketrix-show-popup",n.innerHTML=t?`<div style="font-weight: 500; color: #1f2937; font-size: 12px;">${this.escapeHtml(e)}</div>`:`<div style="margin-bottom:12px;font-weight:500;color:#1f2937;font-size:12px;">${this.escapeHtml(e)}</div><div style="display:flex;gap:8px;justify-content:flex-end;"><button id="marketrix-show-continue" style="background:#3b82f6;color:white;border:none;border-radius:6px;padding:8px 16px;font-size:12px;font-weight:500;cursor:pointer;">Continue</button></div>`,n.style.cssText="position: fixed; width: 320px; background: white; border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); z-index: 2147483646; padding: 16px;",document.body.appendChild(n),this.currentPopup=n,t||this.setupContinueButton(n),this.updatePopupPosition()}setupPositionUpdates(){this.scrollHandler=()=>{if(!this.currentElement||!this.currentHighlight)return;const e=this.currentElement.getBoundingClientRect();Object.assign(this.currentHighlight.style,{top:`${e.top}px`,left:`${e.left}px`,width:`${e.width}px`,height:`${e.height}px`}),this.updatePopupPosition()};for(const e of mc)window.addEventListener(e,this.scrollHandler,{capture:!0,passive:!0})}updatePopupPosition(){if(!this.currentPopup||!this.currentElement)return;const e=this.currentElement.getBoundingClientRect(),t=10,n=e.left+e.width/2,r=e.top+e.height/2,o=[{left:e.right+20,top:r-60},{left:e.left-320-20,top:r-60},{left:n-160,top:e.top-120-20},{left:n-160,top:e.bottom+20}];let i=o[0];for(const s of o)if(s.left>=t&&s.left+320<=window.innerWidth-t&&s.top>=t&&s.top+120<=window.innerHeight-t){i=s;break}this.currentPopup.style.left=`${Math.max(t,Math.min(i.left,window.innerWidth-320-t))}px`,this.currentPopup.style.top=`${Math.max(t,Math.min(i.top,window.innerHeight-120-t))}px`}setupClickHandler(){this.clickHandler=e=>{this.currentElement&&this.resolvePromise&&e.composedPath().includes(this.currentElement)&&(e.preventDefault(),e.stopPropagation(),this.completeAction())},document.addEventListener("click",this.clickHandler,{capture:!0})}setupContinueButton(e){window.requestAnimationFrame(()=>{e.querySelector("#marketrix-show-continue")?.addEventListener("click",e=>{e.stopPropagation(),this.completeAction()})})}setupVisibilityMonitoring(){this.visibilityCheckInterval=setInterval(()=>{const e=this.currentElement;if(!e)return;const t=e.getBoundingClientRect();if(t.bottom<0||t.top>window.innerHeight||t.right<0||t.left>window.innerWidth)return void this.failShowAction("ELEMENT_OFF_SCREEN: The highlighted element scrolled out of view");const n=uc.getSequenceForElement(e)??-1,r=uc.checkElementInteractable(e,n);r&&this.failShowAction(r)},200)}failShowAction(e){this.takeSettlers().reject?.(new Error(e)),this.cleanup()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}},yc=e=>({success:!0,data:{text:e}}),bc=e=>({success:!0,data:e}),vc=e=>({success:!1,data:{text:""},error:e}),wc=e=>({success:!1,data:{options:[]},error:e}),xc=new class{async executeTool(e,t,n="do",r=""){const o=t;try{if("show"===n&&nc.has(e)){const t=o.index;if(void 0!==t){const{element:n,error:o}=uc.getValidatedElement(t);if(!n)return vc(o||`Element ${t} not found`);await gc.showToolAction({element:n,explanation:r||`Execute ${e}`,browserToolName:e,isClickAction:"click_element"===e})}}switch(e){case"navigate":return this.navigate(o);case"search":return this.search(o);case"click_element":return await this.clickElement(o);case"type_text":return this.typeText(o);case"scroll":return this.scroll(o);case"scroll_to_text":return this.scrollToText(o);case"extract":return this.extract(o);case"go_back":return this.goBack();case"wait":return await this.wait(o);case"select_dropdown_option":return this.selectDropdownOption(o);case"get_dropdown_options":return this.getDropdownOptions(o);case"send_keys":return this.sendKeys(o);case"close_tab":return this.closeTab();case"done":return this.done(o);case"get_html":return this.getHtml();case"get_screenshot":return await this.getScreenshot();default:return vc(`Unknown tool: ${e}`)}}catch(i){return vc(i instanceof Error?i.message:String(i))}}navigate(e){if(!e.url)return vc("URL is required");if(e.new_tab)return window.open(e.url,"_blank")?yc(`Opened ${e.url} in new tab`):vc("The browser blocked opening a new tab");const t=e.url;return{...yc(`Navigating to ${t}`),afterResponseAttempt:()=>{window.location.href=t}}}search(e){if(!e.query)return vc("Query is required");const t=e.engine||"duckduckgo",n=encodeURIComponent(e.query);let r=`https://duckduckgo.com/?q=${n}`;return"google"===t&&(r=`https://www.google.com/search?q=${n}`),"bing"===t&&(r=`https://www.bing.com/search?q=${n}`),{...yc(`Searching for "${e.query}" on ${t}`),afterResponseAttempt:()=>{window.location.href=r}}}async clickElement(e){if(void 0===e.index)return vc("Index required");const{element:t,error:n}=uc.getValidatedElement(e.index);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),{...yc(`Clicked element ${e.index}`),afterResponseAttempt:()=>t.click()}):vc(n||`Element ${e.index} not found`)}typeText(e){if(void 0===e.index||void 0===e.text)return vc("Index and text required");const t=!1!==e.clear,{element:n,error:r}=uc.getValidatedElement(e.index);if(!n)return vc(r||`Element ${e.index} not found`);if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)n.focus(),this.setNativeValue(n,t?e.text:n.value+e.text),n.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e.text})),n.dispatchEvent(new Event("change",{bubbles:!0})),n.dispatchEvent(new Event("blur",{bubbles:!0}));else if(n.isContentEditable){n.focus();const r=window.getSelection();if(t?r?.selectAllChildren(n):r?.collapse(n,n.childNodes.length),!document.execCommand("insertText",!1,e.text))return vc(`Could not insert text into element ${e.index}`)}else if("value"in n)try{n.value=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))}catch(o){return vc(`Failed to set value on element: ${o instanceof Error?o.message:String(o)}`)}else try{n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0}))}catch(o){return vc(`Failed to set textContent: ${o instanceof Error?o.message:String(o)}`)}return yc(`Typed text into element ${e.index}`)}scroll(e){const t=.8*window.innerHeight;switch(e.direction){case"down":window.scrollBy({top:t,behavior:"smooth"});break;case"up":window.scrollBy({top:-t,behavior:"smooth"});break;case"left":window.scrollBy({left:-t,behavior:"smooth"});break;case"right":window.scrollBy({left:t,behavior:"smooth"});break;default:return vc("Invalid direction")}return yc(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return vc("Text required");const t=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);let n;for(;n=t.nextNode();)if(n.textContent?.includes(e.text)&&n.parentElement)return n.parentElement.scrollIntoView({behavior:"smooth",block:"center"}),yc(`Scrolled to "${e.text}"`);return vc(`Text "${e.text}" not found`)}extract(e){const t=!1!==e.extract_links,n={title:document.title,url:window.location.href,text:document.body.innerText.slice(0,1e4),links:t?Array.from(document.querySelectorAll("a[href]")).slice(0,100).map(e=>({text:e.textContent?.trim()||"",href:e.getAttribute("href")})):[]};return bc(n)}goBack(){return window.history.length<=1?vc("No history"):{...yc("Navigated back"),afterResponseAttempt:()=>window.history.back()}}async wait({seconds:e}){return void 0===e?vc("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),yc(`Waited ${e}s`))}selectDropdownOption(e){if(void 0===e.index||!e.option)return vc("Index/Option required");const{element:t,error:n}=uc.getValidatedElement(e.index);if(!t)return vc(n||`Select ${e.index} not found`);if(!(t instanceof HTMLSelectElement))return vc(`Element ${e.index} is not a select element`);const r=Array.from(t.options).find(t=>t.value===e.option||t.text===e.option);return r?(t.value=r.value,t.dispatchEvent(new Event("change",{bubbles:!0})),yc(`Selected ${e.option}`)):vc(`Option ${e.option} not found`)}getDropdownOptions(e){const t=e.index;if(void 0===t)return wc("Index required");const{element:n,error:r}=uc.getValidatedElement(t);if(!n)return wc(r||`Select ${t} not found`);if(!(n instanceof HTMLSelectElement))return wc(`Element ${t} is not a select element`);const o=Array.from(n.options).map(e=>({value:e.value,text:e.text}));return bc({options:o})}sendKeys(e){if(void 0===e.index||!e.keys)return vc("Index/Keys required");const{element:t,error:n}=uc.getValidatedElement(e.index);if(!t)return vc(n||`Element ${e.index} not found`);t.focus(),t.dispatchEvent(new KeyboardEvent("keydown",{key:e.keys,bubbles:!0,cancelable:!0})),t.dispatchEvent(new KeyboardEvent("keyup",{key:e.keys,bubbles:!0,cancelable:!0}));const r=this.simulateKeyAction(t,e.keys);return yc(r||`Sent keys ${e.keys}`)}simulateKeyAction(e,t){switch(t){case"Tab":case"Shift+Tab":{const n="Tab"===t?1:-1,r=Array.from(document.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent),o=r.indexOf(e),i=-1===o?void 0:r[o+n];return i?(i.focus(),`${t}: moved focus to ${i.tagName.toLowerCase()}${i.id?`#${i.id}`:""}`):`${t}: no ${n>0?"next":"previous"} focusable element`}case"Enter":if(e instanceof HTMLButtonElement||"button"===e.getAttribute("role"))return e.click(),"Enter: clicked button";if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.closest("form");if(t){const e=t.querySelector('button[type="submit"], input[type="submit"]');return e?(e.click(),"Enter: clicked form submit button"):(t.requestSubmit(),"Enter: submitted form")}}return e instanceof HTMLAnchorElement?(e.click(),"Enter: clicked link"):"Enter: dispatched event";case"Escape":return e.blur(),document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0,cancelable:!0})),"Escape: blurred element and dispatched to document";case" ":case"Space":return e instanceof HTMLInputElement&&("checkbox"===e.type||"radio"===e.type)?(e.click(),`Space: toggled ${e.type}`):e instanceof HTMLButtonElement||"button"===e.getAttribute("role")?(e.click(),"Space: clicked button"):"Space: dispatched event";case"ArrowDown":if(e instanceof HTMLSelectElement){const t=e.selectedIndex;return t<e.options.length-1?(e.selectedIndex=t+1,e.dispatchEvent(new Event("change",{bubbles:!0})),`ArrowDown: selected "${e.options[e.selectedIndex].text}"`):"ArrowDown: already at last option"}return"ArrowDown: dispatched event";case"ArrowUp":if(e instanceof HTMLSelectElement){const t=e.selectedIndex;return t>0?(e.selectedIndex=t-1,e.dispatchEvent(new Event("change",{bubbles:!0})),`ArrowUp: selected "${e.options[e.selectedIndex].text}"`):"ArrowUp: already at first option"}return"ArrowUp: dispatched event";case"Home":return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?(e.setSelectionRange(0,0),"Home: moved cursor to start"):"Home: dispatched event";case"End":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.value.length;return e.setSelectionRange(t,t),"End: moved cursor to end"}return"End: dispatched event";case"Backspace":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.value;if(!t||0===t.length)return"Backspace: input is empty, nothing to delete";const n=e.selectionStart??t.length,r=e.selectionEnd??t.length;let o,i;if(n===r&&n>0)o=t.slice(0,n-1)+t.slice(r),i=n-1;else{if(n===r)return"Backspace: cursor at start, nothing to delete";o=t.slice(0,n)+t.slice(r),i=n}return this.setValueAndCaret(e,o,i),`Backspace: deleted character, value is now "${o}"`}return"Backspace: dispatched event";case"Delete":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.selectionStart||0,n=e.selectionEnd||0,r=e.value;let o;if(t===n&&t<r.length)o=r.slice(0,t)+r.slice(n+1);else{if(t===n)return"Delete: cursor at end, nothing to delete";o=r.slice(0,t)+r.slice(n)}return this.setValueAndCaret(e,o,t),`Delete: deleted character, value is now "${o}"`}return"Delete: dispatched event";default:return null}}setNativeValue(e,t){const n=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;n?n.call(e,t):e.value=t}setValueAndCaret(e,t,n){this.setNativeValue(e,t),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(n,n)}closeTab(){return window.close(),window.closed?yc("Tab closed"):vc("The browser refused to close a tab this script did not open")}done(e){return yc(e.message||"Task ended")}getHtml(){try{const e=uc.reindexAndSnapshot();return yc(e)}catch(e){return vc(String(e))}}async getScreenshot(){const e=document.createElement("video");try{e.srcObject=await fc(),e.autoplay=!0,e.style.display="none",document.body.appendChild(e),await function(e){return new Promise((t,n)=>{const r=setTimeout(()=>n(/* @__PURE__ */new Error("Screen capture produced no frame")),5e3);e.onloadeddata=()=>{clearTimeout(r),t()},e.onerror=()=>{clearTimeout(r),n(/* @__PURE__ */new Error("Screen capture failed"))}})}(e);const t=document.createElement("canvas");return t.width=e.videoWidth,t.height=e.videoHeight,t.getContext("2d")?.drawImage(e,0,0),yc(t.toDataURL("image/jpeg",.75))}catch(t){return vc(String(t))}finally{e.remove()}}},Sc=e=>({state:e,effects:[]});function kc(e,t,n,r,o,i,s){const a=tc({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;if("failed"===i?c=function(e,t,n){const r=ic(e,t);if(r<0)return e;const o=rc(e.parts[r].content),i=rc(n);return oc(e,r,{status:"failed",content:i?`${o} (${i})`:o})}(c,r,s||""):"done"!==r&&(c="in_progress"===i?function(e,t,n){const r=rc(n),o=ic(e,t);return o>=0?oc(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||(e=>sc.get(e)??e)(r)):((e,t)=>oc(e,ic(e,t),{status:"completed"}))(c,r)),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&nc.has(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const l=[...e];return l[a.index]=c,l}var Cc=e=>({...e,isPlaceholder:!1});function Ec(e,t,n){const r=tc({messages:e.messages,isTaskRunning:e.task.isTaskRunning,currentMode:t}),o=[...e.messages];return r&&(o[r.index]=Cc(n(r.message))),{messages:o,task:{isTaskRunning:!1}}}var Ic={completed:"done",failed:"failed",stopped:"stopped"};function Mc(e,t,n,r){const o=e.messages.map(e=>{if(e.id!==t)return e;const o=[...e.parts],i=o[o.length-1],s="text"===i?.type&&!0===i.streaming,a=r&&s?i.content+n:n,c={type:"text",content:a,...r&&{streaming:!0}};return s?o[o.length-1]=c:o.push(c),{...e,content:a,isPlaceholder:!1,placeholderState:void 0,parts:o}});return{...e,messages:o}}var Tc=(e,t)=>({...e,content:t,parts:[...e.parts,{type:"text",content:t}]}),Rc=(e,t)=>({...Cc(Tc(e,t)),placeholderState:void 0});function Oc(e,t,n){const r=e.messages.map(e=>e.id===t?Rc(e,n):e);return{...e,messages:r}}var Ac=n(void 0),_c=({children:e})=>{const[t,n]=h({isOpen:!1,activeView:"home",currentMode:"tell"}),r=d(()=>({setActiveView:e=>n(t=>({...t,activeView:e})),toggleWidget:()=>n(e=>({...e,isOpen:!e.isOpen})),closeWidget:()=>n(e=>({...e,isOpen:!1})),setMode:e=>n(t=>({...t,currentMode:e})),setError:e=>n(t=>({...t,error:e})),applyState:e=>n(t=>({...t,...e}))}),[]);/* @__PURE__ */
18
+ /* @__PURE__ */y(os,{render:/* @__PURE__ */y(La,{label:"Dismiss",size:"xs",tone:"inherit",style:{color:t.closeColor,padding:"2px"}}),children:/* @__PURE__ */y(Pa,{name:"closeSmall",size:12})})]},e.id)})},Ua=({children:e,container:t,offsetBottom:n=20})=>/* @__PURE__ */b(ai,{children:[e,/* @__PURE__ */y(ys,{container:t??void 0,children:/* @__PURE__ */y(Oi,{className:"mtx-toast-viewport",style:{zIndex:2147483004,bottom:`${n}px`},children:/* @__PURE__ */y(Wa,{})})})]}),Ha=aa,ja=({error:e,onClearError:t,onRetry:n,greeting:r,greetingBody:o,onGreetingDismiss:i})=>{const{add:s,close:c}=Ha();return a(()=>{if(null!=e)return s({id:"error",type:"error",title:e,timeout:0,priority:"high",onClose:t,...n&&{actionProps:{children:"Retry",onClick:n}}}),()=>c("error")},[e,n,s,c,t]),a(()=>{if(r)return s({id:"greeting",type:"info",title:r,description:o,timeout:8e3,onClose:i}),()=>c("greeting")},[r,o,s,c,i]),null};function qa(e){const t=[...e.parts],n=e.content.trim();return 0===t.length&&n&&t.push({type:"text",content:n}),{...e,timestamp:new Date(e.timestamp),parts:t}}function Va({videoStream:e,...t}){const n=t.timestamp.toISOString();if(!e)return{...t,timestamp:n};const r="Screenshare ended";return{...t,timestamp:n,content:r,isSystemMessage:!0,parts:[{type:"text",content:r}]}}var Ya=new class{restore(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=De.getContext();return{...o,messages:r.map(qa)}}persist(e){De.updateContext({...e,messages:e.messages.map(Va)})}};function Ka(e,t,n,r={}){return{id:`${e}-${Date.now()}`,content:n,sender:t,timestamp:/* @__PURE__ */new Date,parts:n?[{type:"text",content:n}]:[],...r}}var Xa=(e,t,n="user-message")=>Ka(n,"user",e.trim(),{mode:t}),Ga=e=>Ka("agent-message","agent",e.trim()),Ja=(e,t,n,r)=>Ka(r,n,e,{mode:t,isSystemMessage:!0}),Za={show:"Show",tell:"Tell",do:"Do"},Qa=e=>Za[e];function ec(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}function tc({messages:e,isTaskRunning:t,currentMode:n}){const r=e=>"agent"===e.sender&&!e.isSystemMessage&&!e.isScreenAccessRequest,o=e=>e.isPlaceholder&&void 0===e.mode||e.mode===n,i=[];!t||"show"!==n&&"do"!==n||i.push(e=>r(e)&&o(e)&&!!e.isPlaceholder,e=>r(e)&&o(e)),i.push(e=>r(e)&&!!e.isPlaceholder,r);for(const s of i){const t=ec(e,s);if(t>=0)return{index:t,message:e[t]}}return console.warn("[MessageFinder] No message found for progress update",{totalMessages:e.length,isTaskRunning:t,currentMode:n}),null}var nc=/* @__PURE__ */new Set(["click_element","type_text","select_dropdown_option","send_keys"]),rc=e=>e.replace(/\(?cancelled by cleanup\)?/gi,"").trim();function oc(e,t,n){if(t<0)return e;const r=[...e.parts];return r[t]={...r[t],...n},{...e,parts:r}}var ic=(e,t)=>e.parts.findIndex(e=>(e=>"progress"===e.type&&"in_progress"===e.status)(e)&&e.browserToolName===t),sc=/* @__PURE__ */new Map([["navigate","Navigating"],["search","Searching"],["click_element","Clicking element"],["type_text","Typing text"],["scroll","Scrolling"],["scroll_to_text","Scrolling to text"],["send_keys","Pressing key"],["extract","Extracting content"],["get_dropdown_options","Reading dropdown options"],["select_dropdown_option","Selecting option"],["go_back","Going back"],["wait","Waiting"],["close_tab","Closing tab"],["done","Done"],["get_html","Reading the page"],["get_screenshot","Taking screenshot"]]),ac=/* @__PURE__ */new Set(["button","link","textbox","checkbox","radio","switch","tab","menuitem"]);function*cc(e){let t=e;for(;t;){yield t;const e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}}function lc(e){if(!(e instanceof Element))return!1;try{if(!function(e){const t=e.tagName.toLowerCase();return"button"===t||"input"===t||"textarea"===t||"select"===t||"a"===t&&e.hasAttribute("href")||ac.has(e.getAttribute("role")??"")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||parseInt(e.getAttribute("tabindex")??"-1",10)>=0}(e))return!1;if(!0===e.disabled)return!1;if("true"===e.getAttribute("aria-disabled"))return!1;for(const r of cc(e))if(r instanceof HTMLElement&&r.inert)return!1;const t=window.getComputedStyle(e);if("none"===t.display||"none"===t.pointerEvents)return!1;const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return!1;for(const r of cc(e))if(r!==e){const e=window.getComputedStyle(r).overflow;if("hidden"===e||"clip"===e){const e=r.getBoundingClientRect();if(n.right<e.left||n.left>e.right||n.bottom<e.top||n.top>e.bottom)return!1}if(r===document.body)break}for(let r=e.getRootNode();r instanceof ShadowRoot;r=r.host.getRootNode()){const e=r.host.getBoundingClientRect();if(e.width<=0||e.height<=0)return!1}return!0}catch(t){return console.error("[isInteractable] Unexpected error:",t),!1}}var dc=["id","type","role","aria-label","name","href"],uc=new class{index=/* @__PURE__ */new Map;elementToSequence=/* @__PURE__ */new WeakMap;generateAnchoredSelector(e){const t=[];let n=e;for(;n!==document.body;){const e=n.id?`#${CSS.escape(n.id)}`:"";if(e&&1===document.querySelectorAll(e).length)return t.unshift(e),t.join(" > ");const r=n.parentElement;if(!r)break;const o=n.tagName,i=Array.from(r.children).filter(e=>e.tagName===o),s=i.length>1?`:nth-of-type(${i.indexOf(n)+1})`:"";t.unshift(o.toLowerCase()+s),n=r}return["body",...t].join(" > ")}staleReason(e){return document.contains(e.element)?dc.some((t,n)=>e.element.getAttribute(t)!==e.identity[n])?"has changed":null:"no longer exists"}indexInteractableElements(){this.clearIndex();const e=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{if(e instanceof HTMLElement&&null===e.offsetParent&&"BODY"!==e.tagName){const t=window.getComputedStyle(e),n="fixed"===t.position||"sticky"===t.position;if("none"===t.display)return NodeFilter.FILTER_REJECT;if(!n){let t=e.parentElement,n=!1;for(;t&&t!==document.body;){const e=window.getComputedStyle(t);if("fixed"===e.position||"sticky"===e.position){n=!0;break}t=t.parentElement}if(!n)return NodeFilter.FILTER_REJECT}}return NodeFilter.FILTER_ACCEPT}});let t=e.nextNode(),n=0;for(;t;){const r=t instanceof HTMLElement?t:null;if(r){const e=r.matches('a[href], button, input, textarea, select, [role="button"]'),t=r.classList.contains("cursor-pointer")||r.classList.contains("clickable"),o="function"==typeof r.onclick;(e||t||o||lc(r))&&(this.index.set(n,{element:r,selector:this.generateAnchoredSelector(r),identity:dc.map(e=>r.getAttribute(e))}),this.elementToSequence.set(r,n),n++)}t=e.nextNode()}}reindexAndSnapshot(){this.indexInteractableElements();const e=document.documentElement.cloneNode(!0);for(const[n,{selector:r}]of this.index.entries())try{e.querySelector(r)?.setAttribute("data-id",n.toString())}catch(t){console.warn(`[DomService] Failed to tag index ${n}:`,t)}return e.outerHTML}getSequenceForElement(e){return this.elementToSequence.get(e)}clearIndex(){this.index.clear(),this.elementToSequence=/* @__PURE__ */new WeakMap}checkElementInteractable(e,t){if(!document.body.contains(e))return`ELEMENT_NOT_INTERACTABLE: Element ${t} is not in the DOM`;const n=window.getComputedStyle(e);if("none"===n.display)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has display:none`;if("hidden"===n.visibility)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has visibility:hidden`;if(0===parseFloat(n.opacity))return`ELEMENT_NOT_INTERACTABLE: Element ${t} has opacity:0`;const r=e.getBoundingClientRect();if(0===r.width||0===r.height)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has zero dimensions`;const o=r.left+r.width/2,i=r.top+r.height/2,s=document.elementFromPoint(o,i);if(s&&s!==e&&!e.contains(s)&&!s.closest("#marketrix-show-highlight, #marketrix-show-popup, .marketrix-widget-container")){const e=s.tagName.toLowerCase();return`ELEMENT_OBSCURED: Element ${t} is covered by ${s.className?`${e}.${s.className.split(" ")[0]}`:e}. The obscuring element may be a modal or overlay that needs to be dismissed first.`}return null}getValidatedElement(e){const t=this.index.get(e);if(!t)return{element:null,error:`Element ${e} not found`};const n=this.staleReason(t);if(n)return{element:null,error:`DOM_CHANGED: Element at index ${e} ${n}. Call get_html to get updated indices.`};const r=this.checkElementInteractable(t.element,e);return r?{element:null,error:r}:{element:t.element}}},hc=null;function pc(){return hc?.active&&"live"===hc.getVideoTracks()[0]?.readyState?hc:(hc=null,null)}async function fc(){if(!1===De.getContext().config?.use_screenshare)throw new Error("Screen sharing is disabled for this widget");const e=pc();if(e)return e;const t=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});if(!t||0===t.getVideoTracks().length)throw new Error("Screen sharing permission denied or no video track available");return hc=t,t.getVideoTracks()[0].addEventListener("ended",()=>{hc=null}),t}var mc=["scroll","resize","touchmove","wheel"],gc=new class{currentPopup=null;currentHighlight=null;currentElement=null;currentOptions=null;currentPromise=null;resolvePromise=null;rejectPromise=null;clickHandler=null;scrollHandler=null;visibilityCheckInterval=null;async showToolAction(e){const{element:t,explanation:n,isClickAction:r=!1,browserToolName:o}=e;return this.currentOptions?.element===t&&this.currentOptions.explanation===n&&this.currentOptions.browserToolName===o&&this.currentPromise||(this.cleanup(),this.currentOptions=e,this.currentElement=t,t.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),this.createHighlight(t),this.createPopup(n,r),this.setupPositionUpdates(),this.setupVisibilityMonitoring(),r&&this.setupClickHandler(),this.currentPromise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})),this.currentPromise}cleanup(){if(this.takeSettlers().reject?.(/* @__PURE__ */new Error("Cancelled by cleanup")),this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler){for(const e of mc)window.removeEventListener(e,this.scrollHandler,{capture:!0});this.scrollHandler=null}this.visibilityCheckInterval&&(clearInterval(this.visibilityCheckInterval),this.visibilityCheckInterval=null),this.currentPopup?.remove(),this.currentHighlight?.remove(),document.getElementById("marketrix-show-popup")?.remove(),document.getElementById("marketrix-show-highlight")?.remove(),this.currentPopup=null,this.currentHighlight=null,this.currentElement=null,this.currentOptions=null,this.currentPromise=null}completeAction(){this.takeSettlers().resolve?.(),this.cleanup()}takeSettlers(){const e={resolve:this.resolvePromise,reject:this.rejectPromise};return this.resolvePromise=null,this.rejectPromise=null,e}createHighlight(e){const t=e.getBoundingClientRect(),n=document.createElement("div");n.id="marketrix-show-highlight",n.style.cssText=`position:fixed;top:${t.top}px;left:${t.left}px;width:${t.width}px;height:${t.height}px;border:3px solid #3b82f6;border-radius:4px;box-shadow:0 0 0 4px rgba(59,130,246,0.2),0 0 20px rgba(59,130,246,0.4);z-index:2147483645;pointer-events:none;transition:none;`,document.body.appendChild(n),this.currentHighlight=n}createPopup(e,t){const n=document.createElement("div");n.id="marketrix-show-popup",n.innerHTML=t?`<div style="font-weight: 500; color: #1f2937; font-size: 12px;">${this.escapeHtml(e)}</div>`:`<div style="margin-bottom:12px;font-weight:500;color:#1f2937;font-size:12px;">${this.escapeHtml(e)}</div><div style="display:flex;gap:8px;justify-content:flex-end;"><button id="marketrix-show-continue" style="background:#3b82f6;color:white;border:none;border-radius:6px;padding:8px 16px;font-size:12px;font-weight:500;cursor:pointer;">Continue</button></div>`,n.style.cssText="position: fixed; width: 320px; background: white; border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); z-index: 2147483646; padding: 16px;",document.body.appendChild(n),this.currentPopup=n,t||this.setupContinueButton(n),this.updatePopupPosition()}setupPositionUpdates(){this.scrollHandler=()=>{if(!this.currentElement||!this.currentHighlight)return;const e=this.currentElement.getBoundingClientRect();Object.assign(this.currentHighlight.style,{top:`${e.top}px`,left:`${e.left}px`,width:`${e.width}px`,height:`${e.height}px`}),this.updatePopupPosition()};for(const e of mc)window.addEventListener(e,this.scrollHandler,{capture:!0,passive:!0})}updatePopupPosition(){if(!this.currentPopup||!this.currentElement)return;const e=this.currentElement.getBoundingClientRect(),t=10,n=e.left+e.width/2,r=e.top+e.height/2,o=[{left:e.right+20,top:r-60},{left:e.left-320-20,top:r-60},{left:n-160,top:e.top-120-20},{left:n-160,top:e.bottom+20}];let i=o[0];for(const s of o)if(s.left>=t&&s.left+320<=window.innerWidth-t&&s.top>=t&&s.top+120<=window.innerHeight-t){i=s;break}this.currentPopup.style.left=`${Math.max(t,Math.min(i.left,window.innerWidth-320-t))}px`,this.currentPopup.style.top=`${Math.max(t,Math.min(i.top,window.innerHeight-120-t))}px`}setupClickHandler(){this.clickHandler=e=>{this.currentElement&&this.resolvePromise&&e.composedPath().includes(this.currentElement)&&(e.preventDefault(),e.stopPropagation(),this.completeAction())},document.addEventListener("click",this.clickHandler,{capture:!0})}setupContinueButton(e){window.requestAnimationFrame(()=>{e.querySelector("#marketrix-show-continue")?.addEventListener("click",e=>{e.stopPropagation(),this.completeAction()})})}setupVisibilityMonitoring(){this.visibilityCheckInterval=setInterval(()=>{const e=this.currentElement;if(!e)return;const t=e.getBoundingClientRect();if(t.bottom<0||t.top>window.innerHeight||t.right<0||t.left>window.innerWidth)return void this.failShowAction("ELEMENT_OFF_SCREEN: The highlighted element scrolled out of view");const n=uc.getSequenceForElement(e)??-1,r=uc.checkElementInteractable(e,n);r&&this.failShowAction(r)},200)}failShowAction(e){this.takeSettlers().reject?.(new Error(e)),this.cleanup()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}},yc=e=>({success:!0,data:{text:e}}),bc=e=>({success:!0,data:e}),vc=e=>({success:!1,data:{text:""},error:e}),wc=e=>({success:!1,data:{options:[]},error:e}),xc=new class{async executeTool(e,t,n="do",r=""){const o=t;try{if("show"===n&&nc.has(e)){const t=o.index;if(void 0!==t){const{element:n,error:o}=uc.getValidatedElement(t);if(!n)return vc(o||`Element ${t} not found`);await gc.showToolAction({element:n,explanation:r||`Execute ${e}`,browserToolName:e,isClickAction:"click_element"===e})}}switch(e){case"navigate":return this.navigate(o);case"search":return this.search(o);case"click_element":return await this.clickElement(o);case"type_text":return this.typeText(o);case"scroll":return this.scroll(o);case"scroll_to_text":return this.scrollToText(o);case"extract":return this.extract(o);case"go_back":return this.goBack();case"wait":return await this.wait(o);case"select_dropdown_option":return this.selectDropdownOption(o);case"get_dropdown_options":return this.getDropdownOptions(o);case"send_keys":return this.sendKeys(o);case"close_tab":return this.closeTab();case"done":return this.done(o);case"get_html":return this.getHtml();case"get_screenshot":return await this.getScreenshot();default:return vc(`Unknown tool: ${e}`)}}catch(i){return vc(i instanceof Error?i.message:String(i))}}navigate(e){if(!e.url)return vc("URL is required");if(e.new_tab)return window.open(e.url,"_blank")?yc(`Opened ${e.url} in new tab`):vc("The browser blocked opening a new tab");const t=e.url;return{...yc(`Navigating to ${t}`),afterResponseAttempt:()=>{window.location.href=t}}}search(e){if(!e.query)return vc("Query is required");const t=e.engine||"duckduckgo",n=encodeURIComponent(e.query);let r=`https://duckduckgo.com/?q=${n}`;return"google"===t&&(r=`https://www.google.com/search?q=${n}`),"bing"===t&&(r=`https://www.bing.com/search?q=${n}`),{...yc(`Searching for "${e.query}" on ${t}`),afterResponseAttempt:()=>{window.location.href=r}}}async clickElement(e){if(void 0===e.index)return vc("Index required");const{element:t,error:n}=uc.getValidatedElement(e.index);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),{...yc(`Clicked element ${e.index}`),afterResponseAttempt:()=>t.click()}):vc(n||`Element ${e.index} not found`)}typeText(e){if(void 0===e.index||void 0===e.text)return vc("Index and text required");const t=!1!==e.clear,{element:n,error:r}=uc.getValidatedElement(e.index);if(!n)return vc(r||`Element ${e.index} not found`);if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)n.focus(),this.setNativeValue(n,t?e.text:n.value+e.text),n.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e.text})),n.dispatchEvent(new Event("change",{bubbles:!0})),n.dispatchEvent(new Event("blur",{bubbles:!0}));else if(n.isContentEditable){n.focus();const r=window.getSelection();if(t?r?.selectAllChildren(n):r?.collapse(n,n.childNodes.length),!document.execCommand("insertText",!1,e.text))return vc(`Could not insert text into element ${e.index}`)}else if("value"in n)try{n.value=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))}catch(o){return vc(`Failed to set value on element: ${o instanceof Error?o.message:String(o)}`)}else try{n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0}))}catch(o){return vc(`Failed to set textContent: ${o instanceof Error?o.message:String(o)}`)}return yc(`Typed text into element ${e.index}`)}scroll(e){const t=.8*window.innerHeight;switch(e.direction){case"down":window.scrollBy({top:t,behavior:"smooth"});break;case"up":window.scrollBy({top:-t,behavior:"smooth"});break;case"left":window.scrollBy({left:-t,behavior:"smooth"});break;case"right":window.scrollBy({left:t,behavior:"smooth"});break;default:return vc("Invalid direction")}return yc(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return vc("Text required");const t=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);let n;for(;n=t.nextNode();)if(n.textContent?.includes(e.text)&&n.parentElement)return n.parentElement.scrollIntoView({behavior:"smooth",block:"center"}),yc(`Scrolled to "${e.text}"`);return vc(`Text "${e.text}" not found`)}extract(e){const t=!1!==e.extract_links,n={title:document.title,url:window.location.href,text:document.body.innerText.slice(0,1e4),links:t?Array.from(document.querySelectorAll("a[href]")).slice(0,100).map(e=>({text:e.textContent?.trim()||"",href:e.getAttribute("href")})):[]};return bc(n)}goBack(){return window.history.length<=1?vc("No history"):{...yc("Navigated back"),afterResponseAttempt:()=>window.history.back()}}async wait({seconds:e}){return void 0===e?vc("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),yc(`Waited ${e}s`))}selectDropdownOption(e){if(void 0===e.index||!e.option)return vc("Index/Option required");const{element:t,error:n}=uc.getValidatedElement(e.index);if(!t)return vc(n||`Select ${e.index} not found`);if(!(t instanceof HTMLSelectElement))return vc(`Element ${e.index} is not a select element`);const r=Array.from(t.options).find(t=>t.value===e.option||t.text===e.option);return r?(t.value=r.value,t.dispatchEvent(new Event("change",{bubbles:!0})),yc(`Selected ${e.option}`)):vc(`Option ${e.option} not found`)}getDropdownOptions(e){const t=e.index;if(void 0===t)return wc("Index required");const{element:n,error:r}=uc.getValidatedElement(t);if(!n)return wc(r||`Select ${t} not found`);if(!(n instanceof HTMLSelectElement))return wc(`Element ${t} is not a select element`);const o=Array.from(n.options).map(e=>({value:e.value,text:e.text}));return bc({options:o})}sendKeys(e){if(void 0===e.index||!e.keys)return vc("Index/Keys required");const{element:t,error:n}=uc.getValidatedElement(e.index);if(!t)return vc(n||`Element ${e.index} not found`);t.focus(),t.dispatchEvent(new KeyboardEvent("keydown",{key:e.keys,bubbles:!0,cancelable:!0})),t.dispatchEvent(new KeyboardEvent("keyup",{key:e.keys,bubbles:!0,cancelable:!0}));const r=this.simulateKeyAction(t,e.keys);return yc(r||`Sent keys ${e.keys}`)}simulateKeyAction(e,t){switch(t){case"Tab":case"Shift+Tab":{const n="Tab"===t?1:-1,r=Array.from(document.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent),o=r.indexOf(e),i=-1===o?void 0:r[o+n];return i?(i.focus(),`${t}: moved focus to ${i.tagName.toLowerCase()}${i.id?`#${i.id}`:""}`):`${t}: no ${n>0?"next":"previous"} focusable element`}case"Enter":if(e instanceof HTMLButtonElement||"button"===e.getAttribute("role"))return e.click(),"Enter: clicked button";if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.closest("form");if(t){const e=t.querySelector('button[type="submit"], input[type="submit"]');return e?(e.click(),"Enter: clicked form submit button"):(t.requestSubmit(),"Enter: submitted form")}}return e instanceof HTMLAnchorElement?(e.click(),"Enter: clicked link"):"Enter: dispatched event";case"Escape":return e.blur(),document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0,cancelable:!0})),"Escape: blurred element and dispatched to document";case" ":case"Space":return e instanceof HTMLInputElement&&("checkbox"===e.type||"radio"===e.type)?(e.click(),`Space: toggled ${e.type}`):e instanceof HTMLButtonElement||"button"===e.getAttribute("role")?(e.click(),"Space: clicked button"):"Space: dispatched event";case"ArrowDown":if(e instanceof HTMLSelectElement){const t=e.selectedIndex;return t<e.options.length-1?(e.selectedIndex=t+1,e.dispatchEvent(new Event("change",{bubbles:!0})),`ArrowDown: selected "${e.options[e.selectedIndex].text}"`):"ArrowDown: already at last option"}return"ArrowDown: dispatched event";case"ArrowUp":if(e instanceof HTMLSelectElement){const t=e.selectedIndex;return t>0?(e.selectedIndex=t-1,e.dispatchEvent(new Event("change",{bubbles:!0})),`ArrowUp: selected "${e.options[e.selectedIndex].text}"`):"ArrowUp: already at first option"}return"ArrowUp: dispatched event";case"Home":return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?(e.setSelectionRange(0,0),"Home: moved cursor to start"):"Home: dispatched event";case"End":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.value.length;return e.setSelectionRange(t,t),"End: moved cursor to end"}return"End: dispatched event";case"Backspace":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.value;if(!t||0===t.length)return"Backspace: input is empty, nothing to delete";const n=e.selectionStart??t.length,r=e.selectionEnd??t.length;let o,i;if(n===r&&n>0)o=t.slice(0,n-1)+t.slice(r),i=n-1;else{if(n===r)return"Backspace: cursor at start, nothing to delete";o=t.slice(0,n)+t.slice(r),i=n}return this.setValueAndCaret(e,o,i),`Backspace: deleted character, value is now "${o}"`}return"Backspace: dispatched event";case"Delete":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.selectionStart||0,n=e.selectionEnd||0,r=e.value;let o;if(t===n&&t<r.length)o=r.slice(0,t)+r.slice(n+1);else{if(t===n)return"Delete: cursor at end, nothing to delete";o=r.slice(0,t)+r.slice(n)}return this.setValueAndCaret(e,o,t),`Delete: deleted character, value is now "${o}"`}return"Delete: dispatched event";default:return null}}setNativeValue(e,t){const n=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;n?n.call(e,t):e.value=t}setValueAndCaret(e,t,n){this.setNativeValue(e,t),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(n,n)}closeTab(){return window.close(),window.closed?yc("Tab closed"):vc("The browser refused to close a tab this script did not open")}done(e){return yc(e.message||"Task ended")}getHtml(){try{const e=uc.reindexAndSnapshot();return yc(e)}catch(e){return vc(String(e))}}async getScreenshot(){const e=document.createElement("video");try{e.srcObject=await fc(),e.autoplay=!0,e.style.display="none",document.body.appendChild(e),await function(e){return new Promise((t,n)=>{const r=setTimeout(()=>n(/* @__PURE__ */new Error("Screen capture produced no frame")),5e3);e.onloadeddata=()=>{clearTimeout(r),t()},e.onerror=()=>{clearTimeout(r),n(/* @__PURE__ */new Error("Screen capture failed"))}})}(e);const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;const n=t.getContext("2d");return n?(n.drawImage(e,0,0),yc(t.toDataURL("image/jpeg",.75))):vc("Could not read the shared screen: the browser refused a 2d canvas context.")}catch(t){return vc(String(t))}finally{e.remove()}}},Sc=e=>({state:e,effects:[]});function kc(e,t,n,r,o,i,s){const a=tc({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;if("failed"===i?c=function(e,t,n){const r=ic(e,t);if(r<0)return e;const o=rc(e.parts[r].content),i=rc(n);return oc(e,r,{status:"failed",content:i?`${o} (${i})`:o})}(c,r,s||""):"done"!==r&&(c="in_progress"===i?function(e,t,n){const r=rc(n),o=ic(e,t);return o>=0?oc(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||(e=>sc.get(e)??e)(r)):((e,t)=>oc(e,ic(e,t),{status:"completed"}))(c,r)),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&nc.has(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const l=[...e];return l[a.index]=c,l}var Cc=e=>({...e,isPlaceholder:!1});function Ec(e,t,n){const r=tc({messages:e.messages,isTaskRunning:e.task.isTaskRunning,currentMode:t}),o=[...e.messages];return r&&(o[r.index]=Cc(n(r.message))),{messages:o,task:{isTaskRunning:!1}}}var Ic={completed:"done",failed:"failed",stopped:"stopped"};function Mc(e,t,n,r){const o=e.messages.map(e=>{if(e.id!==t)return e;const o=[...e.parts],i=o[o.length-1],s="text"===i?.type&&!0===i.streaming,a=r&&s?i.content+n:n,c={type:"text",content:a,...r&&{streaming:!0}};return s?o[o.length-1]=c:o.push(c),{...e,content:a,isPlaceholder:!1,placeholderState:void 0,parts:o}});return{...e,messages:o}}var Tc=(e,t)=>({...e,content:t,parts:[...e.parts,{type:"text",content:t}]}),Rc=(e,t)=>({...Cc(Tc(e,t)),placeholderState:void 0});function Oc(e,t,n){const r=e.messages.map(e=>e.id===t?Rc(e,n):e);return{...e,messages:r}}var Ac=n(void 0),_c=({children:e})=>{const[t,n]=h({isOpen:!1,activeView:"home",currentMode:"tell"}),r=d(()=>({setActiveView:e=>n(t=>({...t,activeView:e})),toggleWidget:()=>n(e=>({...e,isOpen:!e.isOpen})),closeWidget:()=>n(e=>({...e,isOpen:!1})),setMode:e=>n(t=>({...t,currentMode:e})),setError:e=>n(t=>({...t,error:e})),applyState:e=>n(t=>({...t,...e}))}),[]);/* @__PURE__ */
19
19
  return y(Ac.Provider,{value:{uiState:t,uiActions:r},children:e})},Dc=()=>{const e=s(Ac);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},Pc=n(void 0),Lc=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=Dc(),[o,s]=h(()=>({messages:[],task:{isTaskRunning:!1}})),c=u(o),l=u(n.currentMode);l.current=n.currentMode;const p=u(/* @__PURE__ */new Set),f=i(e=>{const t=c.current,n=e(t);n===t||n.messages===t.messages&&n.task===t.task||(c.current=n,s(n))},[]),m=i(e=>{f(t=>({...t,messages:[...t.messages,e]}))},[f]),g=i((e,t)=>{f(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)}))},[f]),b=i(e=>{f(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[f]),v=i(e=>{f(t=>({...t,messages:e}))},[f]),w=i(()=>{f(e=>({...e,messages:[]}))},[f]),x=i(e=>{f(t=>({...t,task:{isTaskRunning:e}}))},[f]),S=o.messages.filter(e=>e.isPlaceholder).map(e=>e.id).join(" ");a(()=>{const e=S.split(" ").filter(Boolean).map(e=>setTimeout(()=>f(t=>function(e,t){return e.task.isTaskRunning?e:e.messages.find(e=>e.id===t)?.isPlaceholder?Oc(e,t,"This is taking longer than expected. Please try again."):e}(t,e)),12e4));return()=>e.forEach(clearTimeout)},[S,f]);const k=i(async(e,n,r)=>{const o=n??l.current;if(t)return r||m(Xa(e,o)),void m(Ga("This is a preview. In production, I'll respond to your messages here."));const i=De.getCredentialedConfig();if(!i)return console.error("Config not loaded or incomplete"),void m(Ga("Configuration error: Missing API credentials. Please check your widget settings."));r||m(Xa(e,o));const s=`temp-${globalThis.crypto.randomUUID()}`;m({id:s,content:"",sender:"agent",timestamp:/* @__PURE__ */new Date,mode:o,isPlaceholder:!0,placeholderState:"thinking",parts:[]});try{await async function(e,t,n,r){const o=await Pe.getOrCreateChatId();!function(e,t,n){const r={question:t,mode:n,chat_id:De.getChatId(),timestamp:/* @__PURE__ */(new Date).toISOString(),marketrix_id:e.mtxId,marketrix_key:e.mtxKey};e.userId&&(r.user_id=e.userId),Me.activityLogCreate({type:"widget_question",metadata:r}).catch(e=>console.warn("[API Service] Failed to log widget question:",e))}(e,t,n);const i={type:`chat/${n}`,request_id:r,content:t},s=sr.getInstance();await s.ready(o),await s.send(i)}(i,e,o,s)}catch(a){console.error("Failed to send message:",a),f(e=>Oc(e,s,"I'm sorry, I encountered an error processing your request. Please try again."))}},[t,m,f]);a(()=>{if(t)return;const e=sr.getInstance(),n=async t=>{const{toolCallId:n,tool:r,args:o,mode:i,explanation:s}=t,a=await xc.executeTool(r,o,i,s),c=a.success?void 0:a.error??"Tool execution failed";f(e=>function(e,t,n,r,o,i){return{...e,messages:kc(e.messages,e.task.isTaskRunning,o,t,n,r,i)}}(e,r,s,c?"failed":"completed",l.current,c)),c||"done"!==r||f(e=>function(e,t){return Ec(e,t,e=>({...e,taskStatus:"done"}))}(e,l.current)),await e.send({type:"tool/response",tool_call_id:n,success:a.success,data:JSON.stringify(a.data),error:c}).catch(e=>console.error("Failed to send tool response:",e)),a.afterResponseAttempt?.()},o={onMessage:e=>{if("tool/call"===e.type){const t=e.tool_call_id;if(p.current.has(t))return;p.current.add(t),p.current.size>1e3&&(p.current=new Set([...p.current].slice(-500)))}else"task/status"===e.type&&e.status in Ic&&p.current.clear();let t=[];f(n=>{const r=function(e,t,n){switch(t.type){case"tool/call":{const r=e.task.isTaskRunning?e.task:{isTaskRunning:!0},o=t.explanation||"";return{state:{messages:kc(e.messages,r.isTaskRunning,n,t.browser_tool,o,"in_progress"),task:r},effects:[{type:"executeTool",toolCallId:t.tool_call_id,tool:t.browser_tool,args:t.args,mode:t.mode||n,explanation:o}]}}case"task/status":{if("running"===t.status)return Sc(e);const r=t.status,o=e=>t.message?Tc(e,t.message):e;return{state:Ec(e,n,"has_question"===r?e=>({...o(e),placeholderState:"waiting-for-user"}):e=>({...o(e),taskStatus:Ic[r]})),effects:[]}}case"chat/delta":return{state:Mc(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:Mc(e,t.request_id,t.text,!1),effects:[]};case"chat/error":return{state:Oc(e,t.request_id,`Error: ${t.error}`),effects:[]};default:return Sc(e)}}(n,e,l.current);return t=r.effects,r.state});for(const r of t)n(r).catch(e=>console.error("[Widget] Tool call failed:",e))},onError:e=>{r.setError(e.message),e instanceof ir&&f(t=>function(e,t){return{messages:e.messages.map(e=>e.isPlaceholder?Rc(e,t):e),task:{isTaskRunning:!1}}}(t,e.message))}};return e.addCallbacks(o),()=>{e.removeCallbacks(o)}},[t,f,r]);const C=i(async()=>{f(e=>function(e,t){return Ec(e,t,e=>({...e,taskStatus:"stopped"}))}(e,l.current)),t||sr.getInstance().send({type:"chat/stop"}).catch(e=>{console.error("Failed to stop task remotely:",e),r.setError("Could not stop the assistant — it may still be working.")})},[t,f,r]),E=d(()=>({addMessage:m,updateMessage:g,removeMessage:b,setMessages:v,clearMessages:w,messageDispatch:k}),[m,g,b,v,w,k]),I=d(()=>({setTaskState:x,stopTask:C}),[x,C]);/* @__PURE__ */
20
20
  return y(Pc.Provider,{value:{messages:o.messages,chatActions:E,taskState:o.task,taskActions:I},children:e})},Nc=()=>{const e=s(Pc);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},Fc=n(null),zc=()=>{const{uiState:e}=Dc(),{messages:t}=Nc();return a(()=>{const{currentMode:n,isOpen:r}=e;Ya.persist({messages:t,currentMode:n,isOpen:r})},[t,e]),null},$c=({children:e,previewMode:t})=>{const{uiActions:n}=Dc(),{chatActions:r}=Nc(),[o,i]=h(!1);return a(()=>{if(t)return;let e=!1;return(async()=>{const t=await Pe.getOrCreateChatId();if(e)return;const{messages:o,...s}=Ya.restore();n.applyState(s),r.setMessages(o),i(!0),sr.getInstance().connect(t).catch(e=>console.error("Initial stream connection failed:",e))})().catch(t=>{e||(console.error("Widget initialization failed:",t),n.setError("Widget failed to initialise — please refresh the page."))}),()=>{e=!0}},[]),/* @__PURE__ */b(g,{children:[e,o&&/* @__PURE__ */y(zc,{})]})},Bc=({children:e,previewMode:t=!1})=>/* @__PURE__ */y(_c,{children:/* @__PURE__ */y(Lc,{previewMode:t,children:/* @__PURE__ */y($c,{previewMode:t,children:e})})});function Wc(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:null}function Uc(e,t){if(e.startsWith("rgba")||e.startsWith("rgb")){const n=e.match(/(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(n)return`rgba(${n[1]}, ${n[2]}, ${n[3]}, ${t})`}const n=Wc(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}var Hc={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"};function jc(e={}){const t=Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e));return function(e){return{color:{background:e.widget_background_color,foreground:e.widget_text_color,foregroundMuted:Uc(e.widget_text_color,.6),foregroundFaint:Uc(e.widget_text_color,.4),border:e.widget_border_color,primary:e.widget_accent_color,primaryForeground:(t=e.widget_accent_color,function(e){const t=Wc(e);if(!t)return.5;const[n,r,o]=[t.r/255,t.g/255,t.b/255].map(e=>e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4));return.2126*n+.7152*r+.0722*o}(t)>.5?"#000000":"#ffffff"),primaryHover:Uc(e.widget_accent_color,.85),secondary:e.widget_secondary_color,secondaryForeground:"#ffffff",secondaryBg:Uc(e.widget_secondary_color,.2),secondaryHover:Uc(e.widget_secondary_color,.3)},radius:"12px",motion:{durationAnimation:"300ms",durationFade:"200ms"}};var t}({...Hc,...t})}var qc=n(null),Vc=()=>{const e=s(qc);if(!e)throw new Error("useWidgetConfig must be used within WidgetRoot");return e},Yc=()=>{const{uiState:e,uiActions:t}=Dc(),{messages:n,chatActions:r,taskState:o,taskActions:s}=Nc(),a=d(()=>({...e,...o,messages:n,isAwaitingReply:n.some(e=>e.isPlaceholder)}),[e,n,o]),c=i(()=>{r.clearMessages(),s.setTaskState(!1),t.setError(void 0)},[r,s,t]);return{state:a,actions:d(()=>({...t,...s,...r,clearChatHistory:c}),[t,s,r,c])}},Kc={bottom_right:{vertical:"bottom",horizontal:"right"},bottom_left:{vertical:"bottom",horizontal:"left"},top_right:{vertical:"top",horizontal:"right"},top_left:{vertical:"top",horizontal:"left"}},Xc=Object.keys(Kc),Gc=e=>Kc[e],Jc=e=>{const{vertical:t,horizontal:n}=Gc(e);return{[t]:"20px",[n]:"20px"}},Zc=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=Gc(e);return{x:"left"===s?20:t-20-r,y:"top"===i?20:n-20-o}},Qc=class extends t.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`${this.props.label} Error Boundary caught error:`,e,t)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}},el="cubic-bezier(0.16, 1, 0.3, 1)",tl=({onPositionCommit:e})=>{const{isPreviewMode:n=!1,widget_accent_color:r,widget_background_color:o,widget_position:s,widget_position_z_index:a}=Vc(),{state:c,actions:d}=Yc(),p=c.isOpen,f=c.isTaskRunning,m=!!c.error,g=!p&&(c.isAwaitingReply||f),v=!p&&f,w=m?"marketrix-widget-button-error-glow":"marketrix-widget-button-processing-glow",x=m?"marketrix-widget-button-error-activity-ring":"marketrix-widget-button-processing-activity-ring",S=u(null),{isDragging:k,pixelPositionStyle:C,onPointerDown:E,onPointerMove:I,onPointerUp:M,onPointerCancel:T,suppressUntilRef:R}=function({position:e,onPositionCommit:n,isPreviewMode:r=!1,wrapperRef:o}){const[s,a]=h(!1),[c,d]=h({w:56,h:56}),[,p]=h(0),f=u(null),m=u(null),g=u(null),y=u(0),b=u([]),v=u(0),w=()=>{null!==g.current&&window.cancelAnimationFrame(g.current),g.current=null};t.useEffect(()=>w,[]),t.useEffect(()=>{if(r)return;const e=()=>p(e=>e+1);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[r]);const x=i(()=>{if(!o.current||"undefined"==typeof window)return;const e=o.current.getBoundingClientRect();d(t=>t.w===e.width&&t.h===e.height?t:{w:e.width,h:e.height})},[o]);l(()=>{x();const e="undefined"!=typeof window&&o.current?new ResizeObserver(x):null;return e&&o.current&&e.observe(o.current),()=>e?.disconnect()},[x,e,o]);const S="undefined"!=typeof window?window.innerWidth:0,k="undefined"!=typeof window?window.innerHeight:0,C=Zc(e,S,k,c.w,c.h),E=!r&&S>0&&k>0?{left:C.x,top:C.y}:void 0,I=(e,t=.999)=>e/1e3*t/(1-t),M=()=>{w(),o.current&&(o.current.style.transform="",o.current.style.willChange="",o.current.style.transition="")},T=i((e,t)=>{if(f.current)return;let r=!1;const i=()=>{r||(r=!0,f.current=null,t.style.transition="none",t.style.willChange="",n(e),a(!1),requestAnimationFrame(()=>{o.current&&(o.current.style.transition="")}))};f.current=i;const s=window.setTimeout(i,650);t.addEventListener("transitionend",function e(n){n.target===t&&"left"===n.propertyName&&(window.clearTimeout(s),t.removeEventListener("transitionend",e),i())})},[n,o]),R=i((t,r,i)=>{if(!o.current||!E)return M(),n(t),void a(!1);w();const s=o.current,l=Zc(e,S,k,c.w,c.h),d=Zc(t,S,k,c.w,c.h);s.style.transition="none",s.style.transform="none",s.style.willChange="left, top",s.style.left=`${l.x+r}px`,s.style.top=`${l.y+i}px`,requestAnimationFrame(()=>{s.style.transition=`left 600ms ${el}, top 600ms ${el}`,s.style.left=`${d.x}px`,s.style.top=`${d.y}px`}),T(t,s)},[T,n,E,e,S,k,c.w,c.h,o]),O=e=>{M(),m.current=null,a(!1),e.currentTarget.releasePointerCapture(e.pointerId)};return{isDragging:s,pixelPositionStyle:E,onPointerDown:e=>{m.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,dragging:!1,lastX:0,lastY:0},e.currentTarget.setPointerCapture(e.pointerId)},onPointerMove:e=>{const t=m.current;if(t?.pointerId!==e.pointerId)return;const n=e.clientX-t.startX,r=e.clientY-t.startY;if(!t.dragging&&Math.hypot(n,r)>5&&(t.dragging=!0,a(!0),b.current=[],v.current=0,o.current&&(o.current.style.willChange="transform",o.current.style.transition="none")),!t.dragging)return;t.lastX=n,t.lastY=r;const i=Date.now();i-v.current>=10&&(v.current=i,b.current=[...b.current.slice(-5),{x:e.clientX,y:e.clientY,t:i}]),null===g.current&&(g.current=window.requestAnimationFrame(()=>{g.current=null;const e=m.current,t=o.current;t&&e&&(t.style.transform=`translate3d(${e.lastX}px, ${e.lastY}px, 0)`)}))},onPointerUp:t=>{const n=m.current;if(n?.pointerId===t.pointerId){if(n.dragging){const r=(()=>{const e=b.current;if(e.length<2)return{x:0,y:0};const t=e[e.length-1].t-e[0].t;return t<=0?{x:0,y:0}:{x:(e[e.length-1].x-e[0].x)/t*1e3,y:(e[e.length-1].y-e[0].y)/t*1e3}})(),i=I(r.x),s=I(r.y),a={dx:n.lastX+i,dy:n.lastY+s},c=o.current?.getBoundingClientRect(),l=c?((e,t,n,r,o,i)=>{const s=Zc(t,n,r,o,i),a=s.x+e.dx,c=s.y+e.dy;let l=t,d=1/0;for(const u of Xc){const e=Zc(u,n,r,o,i),t=Math.hypot(a-e.x,c-e.y);t<d&&(d=t,l=u)}return l})(a,e,window.innerWidth,window.innerHeight,c.width,c.height):e;return R(l,n.lastX,n.lastY),y.current=Date.now()+600,m.current=null,void t.currentTarget.releasePointerCapture(t.pointerId)}O(t)}},onPointerCancel:e=>{m.current?.pointerId===e.pointerId&&O(e)},suppressUntilRef:y}}({position:s,onPositionCommit:e,isPreviewMode:n,wrapperRef:S});/* @__PURE__ */
21
21
  return y(Oa,{ref:S,className:"mtx-fab-anchor","data-animated":k?"false":"true","data-preview":n?"true":"false",style:{zIndex:a,pointerEvents:p?"none":"auto",...Jc(s),...C},children:/* @__PURE__ */b(Oa,{className:"mtx-fab","data-open":p?"true":"false",children:[g&&/* @__PURE__ */y(Oa,{className:w,"aria-hidden":!0}),v&&!k&&/* @__PURE__ */y(Ma,{type:"button",variant:"secondary",size:"sm",className:"mtx-fab-stop","data-side":s.includes("left")?"left":"right",onClick:e=>{e.preventDefault(),e.stopPropagation(),d.stopTask()},children:"Stop"}),
@@ -48,14 +48,14 @@ return b(Na,{style:{marginTop:"10px"},role:"article","aria-roledescription":"mes
48
48
  /* @__PURE__ */y(Oa,{ref:e},"scroll-anchor")]},"message-list-container"),l&&/* @__PURE__ */y(Aa,{position:"absolute",justify:"center",style:{top:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */y(La,{variant:"secondary",size:"sm",label:"Scroll to top",onClick:()=>{g.current?.scrollTo({top:0,behavior:"smooth"})},style:xd,children:/* @__PURE__ */y(Pa,{name:"arrowUp",size:10,style:{color:r.widget_accent_color}})})}),f&&/* @__PURE__ */y(Aa,{position:"absolute",justify:"center",style:{bottom:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */y(La,{variant:"secondary",size:"sm",label:"Scroll to bottom",onClick:()=>{e.current&&!c&&e.current.scrollIntoView({behavior:"smooth"})},style:xd,children:/* @__PURE__ */y(Pa,{name:"arrowDown",size:10,style:{color:r.widget_accent_color}})})})]})},kd=[{id:"tell",icon:"chatBubble",flag:"widget_feature_tell"},{id:"show",icon:"mousePointerClick",flag:"widget_feature_show"},{id:"do",icon:"ticktick",flag:"widget_feature_do"}],Cd=({onScreenSharingChange:e,startScreenShareRef:t,stopScreenShareRef:n,messageInputRef:r})=>{const o=Vc(),{state:i,actions:s}=Yc(),{currentMode:l,isTaskRunning:d,isAwaitingReply:p}=i,[f,m]=h(""),g=u(null),[v,w]=h(null),{isScreenSharing:x,isAwaitingScreenAccess:S,showScreenAccessDialog:k,handleScreenAccessDialogAllow:C,handleScreenAccessDialogDismiss:E,handleScreenAccessRequestAllow:I,handleScreenAccessRequestDeny:M,requestScreenAccess:T}=function({onScreenSharingChange:e,startScreenShareRef:t,stopScreenShareRef:n,onAddMessage:r,onUpdateMessage:o,onRemoveMessage:i,onSendMessage:s,pendingMessage:l,setPendingMessage:d}){const[u,p]=h(!1),[f,m]=h(null),[g,y]=h(null),[b,v]=h(!1),w=Wl(u),x=Wl(f),S=Wl(e),k=e=>{e&&i?.(e),r(Ja("Stopped screenshare","show","user","stopped-sharing")),m(null)},C=Wl(k);a(()=>{const e=()=>{const e=null!==pc(),t=w.current,n=x.current;e!==t&&(w.current=e,p(e),S.current?.(e)),t&&!e&&n&&C.current(n)};e();const t=setInterval(e,1e3);return()=>clearInterval(t)},[]);const E=()=>{v(!0)},I=()=>{if(!l)return;const e=l;d(null),s(e.content,e.mode,e.alreadyAdded)},M=e=>{g&&(o(g,{screenShareStatus:e}),y(null))},T=async()=>{try{const t=await fc();p(!0),e?.(!0),M("allowed"),r(Ja("Started screenshare","show","user","started-screenshare"));const n=((e,t="show")=>Ka("screenshare","user","",{mode:t,videoStream:e}))(t,"show");m(n.id),r(n)}catch(t){console.error("Failed to start screen sharing:",t),p(!1),e?.(!1),M("denied")}I()},R=T,O=()=>{hc&&(hc.getTracks().forEach(e=>e.stop()),hc=null),p(!1),e?.(!1),k(f)};return c(t,()=>E),c(n,()=>O),{isScreenSharing:u,isAwaitingScreenAccess:null!==g,showScreenAccessDialog:b,handleScreenAccessDialogAllow:async()=>{v(!1),await T()},handleScreenAccessDialogDismiss:()=>{v(!1)},handleScreenAccessRequestAllow:R,handleScreenAccessRequestDeny:()=>{M("denied"),I()},requestScreenAccess:e=>{if(g)return;const t=(e=>Ka("screen-access-request","agent","Can I take a look at your screen?",{mode:e,isScreenAccessRequest:!0}))(e);y(t.id),r(t)}}}({onScreenSharingChange:e,startScreenShareRef:t,stopScreenShareRef:n,onAddMessage:s.addMessage,onUpdateMessage:s.updateMessage,onRemoveMessage:s.removeMessage,onSendMessage:s.messageDispatch,pendingMessage:v,setPendingMessage:w}),R=S||p;/* @__PURE__ */
49
49
  return b(Na,{height:"full",children:[k&&/* @__PURE__ */y(dd,{open:k,onClose:E,title:"Can I take a look at your screen?",description:"By allowing screen access, Marketrix can understand your current context to guide you better and complete tasks on your behalf.",onConfirm:C,confirmLabel:"Yes",cancelLabel:"No",finalFocusRef:r}),
50
50
  /* @__PURE__ */y(Oa,{grow:!0,overflow:"hidden",paddingY:"2xs",style:{display:"flex",flexDirection:"column",minHeight:0},children:/* @__PURE__ */y(Qc,{label:"Chat",fallback:/* @__PURE__ */y(Ba,{as:"div",size:"xs",align:"center",variant:"muted",style:{padding:"16px"},children:"Something went wrong displaying messages. Please refresh."}),children:/* @__PURE__ */y(Sd,{messagesEndRef:g,onScreenAccessAllow:I,onScreenAccessDeny:M})})}),
51
- /* @__PURE__ */y(Oa,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px",marginTop:"auto"},children:/* @__PURE__ */y(Hl,{ref:r,value:f,onChange:m,onSubmit:()=>{if(!f.trim()||R)return;const e=f.trim();m(""),s.addMessage(Xa(e,l)),!1===o.use_screenshare||"show"!==l&&"do"!==l||x?s.messageDispatch(e,l,!0):(w({content:e,mode:l,alreadyAdded:!0}),T(l))},modes:kd.filter(({flag:e})=>o[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:Qa(e)})),activeMode:l,onModeChange:e=>{e!==l&&(s.addMessage(Ja(`Switched to ${Qa(e)} mode`,e,"agent","mode-change")),s.setMode(e))},disabled:R,taskRunning:d,onStop:()=>{gc.cleanup(),s.stopTask()}})})]})},Ed=[{id:"show-add-product",text:"Show me how to add a new product",type:"show"},{id:"show-login",text:"Show me how to login",type:"show"},{id:"do-login",text:"Do the login process for me",type:"do"},{id:"show-revenue",text:"Show me the revenue metrics",type:"show"},{id:"tell-conversion-rate",text:"What does my conversion rate mean and how can I improve it?",type:"tell"}],Id=({actions:e,onActionClick:t})=>{const n=Vc();return 0===e.length?null:/* @__PURE__ */y(Na,{gap:"sm",children:e.map((e,r)=>/* @__PURE__ */y(Ma,{elevation:"card",shape:"theme",size:"sm",variant:"chip",full:!0,onClick:n=>t(e,n),style:{color:n.widget_text_color,paddingTop:"8px",paddingBottom:"8px"},children:/* @__PURE__ */y(Ba,{as:"span",weight:"normal",leading:"tight",children:"show"===e.type?/* @__PURE__ */b(g,{children:["Show me ",e.text.replace(/^Show me\s*/i,"")]}):"do"===e.type?/* @__PURE__ */b(g,{children:["Do ",e.text.replace(/^Do\s*/i,"")]}):e.text})},`welcome-chip-${e.id}-${r}`))})},Md=({onNavigateToChat:e,onChipClick:t})=>{const n=Vc(),{messages:r}=Yc().state,o=function(e){const t=e.widget_chips;return t?.length?t.map((e,t)=>({id:`chip-${e.chip_text.replace(/\s+/g,"-").toLowerCase()}-${t}`,text:e.chip_text,type:e.chip_mode})):Ed}(n);/* @__PURE__ */
51
+ /* @__PURE__ */y(Oa,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px",marginTop:"auto"},children:/* @__PURE__ */y(Hl,{ref:r,value:f,onChange:m,onSubmit:()=>{if(!f.trim()||R)return;const e=f.trim();m(""),s.addMessage(Xa(e,l)),!1===o.use_screenshare||"show"!==l&&"do"!==l||x?s.messageDispatch(e,l,!0):(w({content:e,mode:l,alreadyAdded:!0}),T(l))},modes:kd.filter(({flag:e})=>o[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:Qa(e)})),activeMode:l,onModeChange:e=>{e!==l&&(s.addMessage(Ja(`Switched to ${Qa(e)} mode`,e,"agent","mode-change")),s.setMode(e))},disabled:R,taskRunning:d,onStop:()=>{gc.cleanup(),s.stopTask()}})})]})},Ed=[{id:"show-add-product",text:"Show me how to add a new product",type:"show"},{id:"show-login",text:"Show me how to login",type:"show"},{id:"do-login",text:"Do the login process for me",type:"do"},{id:"show-revenue",text:"Show me the revenue metrics",type:"show"},{id:"tell-conversion-rate",text:"What does my conversion rate mean and how can I improve it?",type:"tell"}],Id=({actions:e,onActionClick:t})=>{const n=Vc();return 0===e.length?null:/* @__PURE__ */y(Na,{gap:"sm",children:e.map((e,r)=>/* @__PURE__ */y(Ma,{elevation:"card",shape:"theme",size:"sm",variant:"chip",full:!0,onClick:n=>t(e,n),style:{color:n.widget_text_color,paddingTop:"8px",paddingBottom:"8px"},children:/* @__PURE__ */y(Ba,{as:"span",weight:"normal",leading:"tight",children:"show"===e.type?/* @__PURE__ */b(g,{children:["Show me ",e.text.replace(/^Show me\s+/i,"")]}):"do"===e.type?/* @__PURE__ */b(g,{children:["Do ",e.text.replace(/^Do\s+/i,"")]}):e.text})},`welcome-chip-${e.id}-${r}`))})},Md=({onNavigateToChat:e,onChipClick:t})=>{const n=Vc(),{messages:r}=Yc().state,o=function(e){const t=e.widget_chips;return t?.length?t.map((e,t)=>({id:`chip-${e.chip_text.replace(/\s+/g,"-").toLowerCase()}-${t}`,text:e.chip_text,type:e.chip_mode})):Ed}(n);/* @__PURE__ */
52
52
  return b(Na,{height:"full",overflow:"hidden",children:[/* @__PURE__ */b(Na,{grow:!0,overflowY:"auto",padding:"lg",children:[/* @__PURE__ */b(Oa,{style:{textAlign:"center",paddingTop:"8px",paddingBottom:"16px"},children:[/* @__PURE__ */y(Ba,{as:"h2",size:"lg",weight:"semibold",children:n.widget_greeting}),/* @__PURE__ */y(Ba,{as:"p",variant:"muted",size:"sm",style:{marginTop:"2px"},children:n.widget_body})]}),/* @__PURE__ */b(Na,{gap:"sm",children:[/* @__PURE__ */b(Ma,{type:"button",variant:"primary",full:!0,onClick:e,"aria-label":"Ask a question",style:{paddingTop:"10px",paddingBottom:"10px"},children:[/* @__PURE__ */y(Pa,{name:"chat",size:16}),"Ask a question"]}),/* @__PURE__ */y(Id,{actions:o,onActionClick:async(n,r)=>{r.preventDefault(),r.stopPropagation(),e(),t(n)}})]})]}),r.length>0&&/* @__PURE__ */b(Oa,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px"},children:[
53
53
  /* @__PURE__ */y(Ba,{as:"p",size:"xs",weight:"semibold",style:{marginBottom:"2px"},children:"Recent conversation"}),
54
54
  /* @__PURE__ */y(Ba,{as:"p",size:"xs",variant:"muted",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:r[r.length-1].content||"Message"}),
55
55
  /* @__PURE__ */y(Ba,{as:"p",size:"xs",variant:"muted",onClick:e,style:{marginTop:"4px",cursor:"pointer"},children:"Continue conversation →"})]})]})};function Td(e){const t=e.startsWith("top"),n=e.endsWith("left");return{position:"absolute",width:"20px",height:"20px",padding:"4px",touchAction:"none",zIndex:10,display:"flex",alignItems:t?"flex-start":"flex-end",justifyContent:n?"flex-start":"flex-end",cursor:$l[e].cursor,top:t?0:void 0,bottom:t?void 0:0,left:n?0:void 0,right:n?void 0:0}}var Rd=({onResizeStart:e})=>/* @__PURE__ */y(g,{children:Object.keys($l).map(t=>/* @__PURE__ */y("div",{role:"separator","aria-label":`Resize widget from ${t.replace("-"," ")}`,title:"Drag to resize",style:Td(t),onMouseDown:e(t)},t))}),Od=[{id:"home",icon:"home",label:"Home"},{id:"chat",icon:"chat",label:"Chat"}],Ad=()=>/* @__PURE__ */y(Dl,{render:/* @__PURE__ */y(Aa,{align:"center",justify:"around",shrink:!1,border:"top"}),style:{height:48},children:Od.map(e=>/* @__PURE__ */b(bl,{value:e.id,render:/* @__PURE__ */y(Ma,{stacked:!0,variant:"tab"}),children:[
56
56
  /* @__PURE__ */y("span",{className:"mtx-tab-underline"}),
57
57
  /* @__PURE__ */y(Ba,{as:"span",inheritColor:!0,"aria-hidden":"true",children:/* @__PURE__ */y(Pa,{name:e.icon,size:20})}),
58
- /* @__PURE__ */y(Ba,{as:"span",size:"xs",align:"center",inheritColor:!0,truncate:!0,block:!0,children:e.label})]},e.id))}),_d=()=>{const e=Vc(),{state:t,actions:n}=Yc(),{isOpen:r,activeView:o}=t,s=e.isPreviewMode??!1,{widthPx:c,heightPx:l,onResizeStart:d,containerRef:p}=function(e,t,n,r){const o=`marketrix_widget_size_${n}`,s=u(null),[a,c]=h(()=>function(e){try{const t=JSON.parse(Oe(e)??"null");return"number"!=typeof t?.width||"number"!=typeof t?.height?null:Fl({width:t.width,height:t.height})}catch(t){return console.warn("[useResize] Ignoring an unparseable stored size:",t),null}}(o)??Fl({width:zl(e,360),height:zl(t,450)})),l=u(a);l.current=a;const d=i(e=>t=>{if(t.preventDefault(),t.stopPropagation(),r)return;const n=t.clientX,i=t.clientY,a=l.current.width,d=l.current.height,{growX:u,growY:h,cursor:p}=$l[e];s.current&&(s.current.dataset.resizing="true");const f=e=>{const t=Fl({width:a+(e.clientX-n)*u,height:d+(e.clientY-i)*h});l.current=t,s.current&&(s.current.style.width=`${t.width}px`,s.current.style.height=`${t.height}px`)},m=()=>{if(document.removeEventListener("mousemove",f),document.removeEventListener("mouseup",m),document.body.style.cursor="",document.body.style.userSelect="",s.current&&delete s.current.dataset.resizing,c({...l.current}),!r){const{width:e,height:t}=l.current;Ae(o,JSON.stringify({width:e,height:t}))}};document.body.style.cursor=p,document.body.style.userSelect="none",document.addEventListener("mousemove",f),document.addEventListener("mouseup",m)},[r,o]);return{widthPx:`${a.width}px`,heightPx:`${a.height}px`,onResizeStart:d,containerRef:s}}(e.widget_width,e.widget_height,gr(e),s),f=u(null),m="chat"===o?"forward":"back";!function(e,t,n){const r=u(!1),o=u(null),s=i(()=>{const t=e.current;if(!t)return;const r=n?.focusTargetRef?.current;if(r)return void r.focus({preventScroll:!0});const o=Ll(t);o[0]&&o[0].focus({preventScroll:!0})},[e,n?.focusTargetRef]);a(()=>{if(!t)return r.current&&(o.current?.focus({preventScroll:!0}),o.current=null),void(r.current=!1);const i=e.current;if(!i)return;r.current||(o.current=Pl(i)),r.current=!0,s();const a=e=>{if("Escape"===e.key)return void n?.onEscape?.();if("Tab"!==e.key)return;const t=Ll(i);if(0===t.length)return;const r=Pl(i),o=r?t.indexOf(r):-1;-1!==o&&(e.shiftKey?0===o&&(e.preventDefault(),t[t.length-1].focus()):o===t.length-1&&(e.preventDefault(),t[0].focus()))};return document.addEventListener("keydown",a,!0),()=>document.removeEventListener("keydown",a,!0)},[t,e,s,n?.onEscape])}(p,r,{onEscape:n.closeWidget,focusTargetRef:"chat"===o?f:void 0});const g=Jc(e.widget_position),[v,w]=h(!1),x=u(null),S=u(null);if(!r)return null;const k=e.widget_background_color.includes("gradient")?e.widget_background_color:`linear-gradient(135deg, ${e.widget_background_color} 0%, ${e.widget_background_color} 100%)`,{vertical:C,horizontal:E}=Gc(e.widget_position),I="chat"===o&&!1!==e.use_screenshare?()=>{v?S.current?.():x.current?.()}:void 0;/* @__PURE__ */
58
+ /* @__PURE__ */y(Ba,{as:"span",size:"xs",align:"center",inheritColor:!0,truncate:!0,block:!0,children:e.label})]},e.id))}),_d=()=>{const e=Vc(),{state:t,actions:n}=Yc(),{isOpen:r,activeView:o}=t,s=e.isPreviewMode??!1,{widthPx:c,heightPx:l,onResizeStart:d,containerRef:p}=function(e,t,n,r){const o=`marketrix_widget_size_${n}`,s=u(null),[a,c]=h(()=>function(e){try{const t=JSON.parse(Oe(e)??"null");return"number"!=typeof t?.width||"number"!=typeof t?.height?null:Fl({width:t.width,height:t.height})}catch(t){return console.warn("[useResize] Ignoring an unparseable stored size:",t),null}}(o)??Fl({width:zl(e,360),height:zl(t,450)})),l=u(a);l.current=a;const d=i(e=>t=>{if(t.preventDefault(),t.stopPropagation(),r)return;const n=t.clientX,i=t.clientY,a=l.current.width,d=l.current.height,{growX:u,growY:h,cursor:p}=$l[e];s.current&&(s.current.dataset.resizing="true");const f=e=>{const t=Fl({width:a+(e.clientX-n)*u,height:d+(e.clientY-i)*h});l.current=t,s.current&&(s.current.style.width=`${t.width}px`,s.current.style.height=`${t.height}px`)},m=()=>{if(document.removeEventListener("mousemove",f),document.removeEventListener("mouseup",m),document.body.style.cursor="",document.body.style.userSelect="",s.current&&delete s.current.dataset.resizing,c({...l.current}),!r){const{width:e,height:t}=l.current;Ae(o,JSON.stringify({width:e,height:t}))}};document.body.style.cursor=p,document.body.style.userSelect="none",document.addEventListener("mousemove",f),document.addEventListener("mouseup",m)},[r,o]);return{widthPx:`${a.width}px`,heightPx:`${a.height}px`,onResizeStart:d,containerRef:s}}(e.widget_width,e.widget_height,gr(e),s),f=u(null),m="chat"===o?"forward":"back";!function(e,t,n){const r=u(!1),o=u(null),s=i(()=>{const t=e.current;if(!t)return;const r=n?.focusTargetRef?.current;if(r)return void r.focus({preventScroll:!0});const o=Ll(t);o[0]&&o[0].focus({preventScroll:!0})},[e,n?.focusTargetRef]);a(()=>{if(!t)return r.current&&(o.current?.focus({preventScroll:!0}),o.current=null),void(r.current=!1);const i=e.current;if(!i)return;r.current||(o.current=Pl(i)),r.current=!0,s();const a=e=>{const t=Pl(i);if(!t||!i.contains(t))return;if("Escape"===e.key)return void n?.onEscape?.();if("Tab"!==e.key)return;const r=Ll(i);if(0===r.length)return;const o=r.indexOf(t);-1!==o&&(e.shiftKey?0===o&&(e.preventDefault(),r[r.length-1].focus()):o===r.length-1&&(e.preventDefault(),r[0].focus()))};return document.addEventListener("keydown",a,!0),()=>document.removeEventListener("keydown",a,!0)},[t,e,s,n?.onEscape])}(p,r,{onEscape:n.closeWidget,focusTargetRef:"chat"===o?f:void 0});const g=Jc(e.widget_position),[v,w]=h(!1),x=u(null),S=u(null);if(!r)return null;const k=e.widget_background_color.includes("gradient")?e.widget_background_color:`linear-gradient(135deg, ${e.widget_background_color} 0%, ${e.widget_background_color} 100%)`,{vertical:C,horizontal:E}=Gc(e.widget_position),I="chat"===o&&!1!==e.use_screenshare?()=>{v?S.current?.():x.current?.()}:void 0;/* @__PURE__ */
59
59
  return b(Na,{ref:p,position:s?"absolute":"fixed",rounded:"theme",border:!0,overflow:"hidden",style:{zIndex:e.widget_position_z_index,backgroundImage:k,transformOrigin:`${C} ${E}`,width:c,height:l,fontSize:"14px",...g,pointerEvents:"auto",scrollbarWidth:"thin",animation:"messenger-entrance 300ms cubic-bezier(0, 1.2, 1, 1)",boxShadow:la.panel},children:[
60
60
  /* @__PURE__ */y(Bl,{title:e.widget_header,subtitle:e.widget_body,onClose:n.closeWidget,controls:I&&/* @__PURE__ */b(La,{variant:"ghost",size:"sm",label:v?"Stop screen sharing":"Start screen sharing",onClick:I,children:[v&&/* @__PURE__ */b("span",{className:"mtx-screenshare-dot",children:[/* @__PURE__ */y("span",{className:"mtx-screenshare-dot-ping"}),/* @__PURE__ */y("span",{className:"mtx-screenshare-dot-core"})]}),/* @__PURE__ */y(Pa,{name:"screenShare",size:16})]})}),
61
61
  /* @__PURE__ */b(ul,{value:o,onValueChange:e=>n.setActiveView(e),style:{display:"flex",flexDirection:"column",flex:"1 1 0%",minHeight:0},children:[/* @__PURE__ */b(Oa,{grow:!0,overflow:"hidden",style:{display:"flex",flexDirection:"column",minHeight:0},children:[/* @__PURE__ */y(wl,{value:"home","data-view-transition":!0,"data-direction":m,style:{width:"100%",height:"100%"},children:/* @__PURE__ */y(Md,{onNavigateToChat:()=>{n.setActiveView("chat")},onChipClick:e=>{n.addMessage(Xa(e.text,e.type,"chip-message")),n.setMode(e.type),n.messageDispatch(e.text,e.type,!0)}})}),/* @__PURE__ */y(wl,{value:"chat","data-view-transition":!0,"data-direction":m,style:{width:"100%",height:"100%"},children:/* @__PURE__ */y(Cd,{onScreenSharingChange:w,startScreenShareRef:x,stopScreenShareRef:S,messageInputRef:f})})]}),/* @__PURE__ */y(Ad,{})]}),!s&&/* @__PURE__ */y(Rd,{onResizeStart:d})]})},Dd=({config:e})=>{const[t,n]=h(!1),[r,o]=h(null),{state:i,actions:s}=Yc(),c=sr.getInstance(),l=e.isPreviewMode??!1,d=pr(e);var u;u=i.isOpen,a(()=>{if(!u)return;if(!window.matchMedia("(max-width: 767px)").matches)return;const e=document.documentElement,t=document.body,n=e.style.overflow,r=t.style.overflow;return e.style.overflow="hidden",t.style.overflow="hidden",()=>{e.style.overflow=n,t.style.overflow=r}},[u]);const[p,f]=h(e.widget_position??"bottom_right"),m=`marketrix_widget_position_${gr(e)}`;a(()=>{const t=l?null:Oe(m);(e=>Xc.includes(e))(t)?f(t):f(e.widget_position??"bottom_right")},[l,m,e.widget_position]),a(()=>{if(i.isOpen||l||"default"!==e.widget_appearance||!e.widget_greeting_toast)return void n(!1);const t=setTimeout(()=>n(!0),2e3);return()=>clearTimeout(t)},[i.isOpen,l,e.widget_appearance,e.widget_greeting_toast]);const g=d.invalidFields?fr(d.invalidFields):null;if(a(()=>{g&&console.error(`Marketrix Widget: ${g}`)},[g]),g)return null;const v=!e.widget_enabled||!1===e.show_widget||"hidden"===e.widget_appearance;if(!l&&v)return null;const w=Math.max(e.widget_position_z_index??0,2147483002),x={...e,widget_position:p,widget_position_z_index:w},S=i.isAwaitingReply||i.isTaskRunning,k={"--background":(C=jc(e)).color.background,"--foreground":C.color.foreground,"--card":C.color.background,"--card-foreground":C.color.foreground,"--primary":C.color.primary,"--foreground-muted":C.color.foregroundMuted,"--foreground-faint":C.color.foregroundFaint,"--primary-foreground":C.color.primaryForeground,"--primary-hover":C.color.primaryHover,"--secondary":C.color.secondary,"--secondary-foreground":C.color.secondaryForeground,"--secondary-bg":C.color.secondaryBg,"--secondary-hover":C.color.secondaryHover,"--border":C.color.border,"--ring":C.color.primary,"--radius":C.radius,"--duration-animation":C.motion.durationAnimation,"--duration-fade":C.motion.durationFade};var C;/* @__PURE__ */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marketrix.ai/widget",
3
- "version": "3.8.480",
3
+ "version": "3.8.481",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/widget.mjs",