@marketrix.ai/widget 3.8.491 → 3.8.492
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/src/components/chat/VideoStreamDisplay.d.ts +1 -1
- package/dist/src/context/UIStateContext.d.ts +1 -2
- package/dist/src/context/sseReducer.d.ts +1 -0
- package/dist/src/hooks/useWidget.d.ts +1 -1
- package/dist/src/index.d.ts +4 -4
- package/dist/src/services/BrowserToolService.d.ts +8 -4
- package/dist/src/types/index.d.ts +1 -2
- package/dist/src/utils/chat.d.ts +1 -1
- package/dist/widget.mjs +8 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -131,7 +131,7 @@ import {
|
|
|
131
131
|
unmountWidget,
|
|
132
132
|
updateMarketrixConfig,
|
|
133
133
|
getCurrentConfig,
|
|
134
|
-
|
|
134
|
+
MarketrixWidgetPreview,
|
|
135
135
|
} from '@marketrix.ai/widget';
|
|
136
136
|
```
|
|
137
137
|
|
|
@@ -182,16 +182,16 @@ When recording is enabled, **every input value is masked** — recordings captur
|
|
|
182
182
|
|
|
183
183
|
Both the `mtx-` and rrweb's native `rr-` prefixes are honoured, so existing `rr-block` / `rr-mask` markup keeps working.
|
|
184
184
|
|
|
185
|
-
### `
|
|
185
|
+
### `MarketrixWidgetPreview` — React component
|
|
186
186
|
|
|
187
187
|
For previewing appearance inside a React app (e.g. a settings/configuration screen). Renders into its own Shadow DOM and makes no network calls.
|
|
188
188
|
|
|
189
189
|
```tsx
|
|
190
|
-
import {
|
|
190
|
+
import { MarketrixWidgetPreview } from '@marketrix.ai/widget';
|
|
191
191
|
|
|
192
192
|
function Preview() {
|
|
193
193
|
return (
|
|
194
|
-
<
|
|
194
|
+
<MarketrixWidgetPreview
|
|
195
195
|
settings={{ widget_enabled: true, widget_position: 'bottom_right' /* ...WidgetSettingsData */ }}
|
|
196
196
|
mtxApiHost='https://api.marketrix.ai'
|
|
197
197
|
/>
|
|
@@ -217,7 +217,7 @@ TypeScript types are bundled with the package:
|
|
|
217
217
|
|
|
218
218
|
- `MarketrixConfig` — full config for `initWidget` / `updateMarketrixConfig` (`mtxId`, `mtxKey`, `mtxApiHost`, `userId`, `show_widget`, `use_screenshare`, plus all widget appearance settings, optional).
|
|
219
219
|
- `AddWidgetConfig` — discriminated config for `mountWidget` (production / preview variants + common options).
|
|
220
|
-
- `
|
|
220
|
+
- `MarketrixWidgetPreviewProps` — props for the `MarketrixWidgetPreview` component.
|
|
221
221
|
- `ChatMessage`, `WidgetState`, `InstructionType` (`'tell' | 'show' | 'do'`).
|
|
222
222
|
|
|
223
223
|
---
|
|
@@ -5,14 +5,13 @@ export interface UIState {
|
|
|
5
5
|
activeView: WidgetView;
|
|
6
6
|
currentMode: InstructionType;
|
|
7
7
|
error?: string;
|
|
8
|
-
errorRetryable?: boolean;
|
|
9
8
|
}
|
|
10
9
|
export interface UIStateActions {
|
|
11
10
|
setActiveView: (view: WidgetView) => void;
|
|
12
11
|
toggleWidget: () => void;
|
|
13
12
|
closeWidget: () => void;
|
|
14
13
|
setMode: (mode: InstructionType) => void;
|
|
15
|
-
setError: (error: string | undefined
|
|
14
|
+
setError: (error: string | undefined) => void;
|
|
16
15
|
applyState: (payload: Partial<UIState>) => void;
|
|
17
16
|
}
|
|
18
17
|
interface UIStateContextType {
|
|
@@ -18,7 +18,7 @@ export declare const useWidget: () => {
|
|
|
18
18
|
toggleWidget: () => void;
|
|
19
19
|
closeWidget: () => void;
|
|
20
20
|
setMode: (mode: import("..").InstructionType) => void;
|
|
21
|
-
setError: (error: string | undefined
|
|
21
|
+
setError: (error: string | undefined) => void;
|
|
22
22
|
applyState: (payload: Partial<import("../context/UIStateContext").UIState>) => void;
|
|
23
23
|
};
|
|
24
24
|
};
|
package/dist/src/index.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ declare global {
|
|
|
6
6
|
}
|
|
7
7
|
}
|
|
8
8
|
import React from 'react';
|
|
9
|
-
import type { AddWidgetConfig, ClientOwnedConfig, MarketrixConfig,
|
|
9
|
+
import type { AddWidgetConfig, ClientOwnedConfig, MarketrixConfig, MarketrixWidgetPreviewProps, ValidWidgetConfig } from './types';
|
|
10
10
|
import { getCurrentConfig } from './utils/bootstrap';
|
|
11
11
|
export declare const initWidget: (config: MarketrixConfig, container?: HTMLElement) => Promise<void>;
|
|
12
12
|
export declare const unmountWidget: () => void;
|
|
@@ -15,12 +15,12 @@ export declare const updateMarketrixConfig: (newConfig: ClientOwnedConfig & {
|
|
|
15
15
|
mtxKey?: string;
|
|
16
16
|
}) => Promise<void>;
|
|
17
17
|
export { getCurrentConfig };
|
|
18
|
-
export declare const
|
|
18
|
+
export declare const MarketrixWidgetPreview: React.FC<MarketrixWidgetPreviewProps>;
|
|
19
19
|
export declare const mountWidget: (config: AddWidgetConfig) => Promise<void>;
|
|
20
20
|
export type { InstructionType } from './sdk';
|
|
21
|
-
export type { AddWidgetConfig, ChatMessage, ClientOwnedConfig, MarketrixConfig,
|
|
21
|
+
export type { AddWidgetConfig, ChatMessage, ClientOwnedConfig, MarketrixConfig, MarketrixWidgetPreviewProps, WidgetState, } from './types';
|
|
22
22
|
declare const _default: {
|
|
23
|
-
|
|
23
|
+
MarketrixWidgetPreview: React.FC<MarketrixWidgetPreviewProps>;
|
|
24
24
|
mountWidget: (config: AddWidgetConfig) => Promise<void>;
|
|
25
25
|
initWidget: (config: MarketrixConfig, container?: HTMLElement) => Promise<void>;
|
|
26
26
|
unmountWidget: () => void;
|
|
@@ -17,12 +17,15 @@ export interface DropdownOptionsData {
|
|
|
17
17
|
text: string;
|
|
18
18
|
}>;
|
|
19
19
|
}
|
|
20
|
-
|
|
21
|
-
success:
|
|
20
|
+
type ToolFailure = {
|
|
21
|
+
success: false;
|
|
22
|
+
error: string;
|
|
23
|
+
};
|
|
24
|
+
export type ToolExecutionResult<T = TextData> = {
|
|
25
|
+
success: true;
|
|
22
26
|
data: T;
|
|
23
|
-
error?: string;
|
|
24
27
|
afterResponseAttempt?: () => void;
|
|
25
|
-
}
|
|
28
|
+
} | ToolFailure;
|
|
26
29
|
export declare class BrowserToolService {
|
|
27
30
|
executeTool(browserToolName: string, args: Record<string, unknown>, mode: InstructionType, explanation?: string): Promise<ToolExecutionResult<unknown>>;
|
|
28
31
|
private navigate;
|
|
@@ -48,3 +51,4 @@ export declare class BrowserToolService {
|
|
|
48
51
|
private getScreenshot;
|
|
49
52
|
}
|
|
50
53
|
export declare const browserToolService: BrowserToolService;
|
|
54
|
+
export {};
|
|
@@ -53,7 +53,6 @@ export interface WidgetState {
|
|
|
53
53
|
messages: ChatMessage[];
|
|
54
54
|
currentMode: InstructionType;
|
|
55
55
|
error?: string;
|
|
56
|
-
errorRetryable?: boolean;
|
|
57
56
|
isTaskRunning: boolean;
|
|
58
57
|
activeView: WidgetView;
|
|
59
58
|
}
|
|
@@ -69,7 +68,7 @@ export type AddWidgetConfig = ({
|
|
|
69
68
|
}) & ClientOwnedConfig & {
|
|
70
69
|
container?: HTMLElement;
|
|
71
70
|
};
|
|
72
|
-
export interface
|
|
71
|
+
export interface MarketrixWidgetPreviewProps {
|
|
73
72
|
settings: WidgetSettingsData;
|
|
74
73
|
container?: HTMLElement;
|
|
75
74
|
}
|
package/dist/src/utils/chat.d.ts
CHANGED
|
@@ -20,6 +20,6 @@ export declare const TOOL_LABELS: Map<string, string>;
|
|
|
20
20
|
export declare const getFriendlyToolName: (browserToolName: string) => string;
|
|
21
21
|
export declare const createUserMessage: (content: string, mode?: InstructionType, idPrefix?: string) => ChatMessage;
|
|
22
22
|
export declare const createAgentMessage: (content: string) => ChatMessage;
|
|
23
|
-
export declare const createSystemMessage: (content: string,
|
|
23
|
+
export declare const createSystemMessage: (content: string, idPrefix: string) => ChatMessage;
|
|
24
24
|
export declare const createScreenAccessRequestMessage: (mode: InstructionType | undefined, pendingContent?: string) => ChatMessage;
|
|
25
25
|
export declare const createScreenshareMessage: (stream: MediaStream, mode?: InstructionType) => ChatMessage;
|
package/dist/widget.mjs
CHANGED
|
@@ -15,8 +15,8 @@ return b(e,{...h,ref:u,className:d,style:{color:va[n?"inherit":i],...s&&{fontSiz
|
|
|
15
15
|
return v(Ji,{toast:e,className:"mtx-toast",render:/* @__PURE__ */b($a,{align:"center",gap:"md",rounded:"pill",paddingPreset:"toast",elevation:"panel",style:{backgroundColor:t.background,border:t.border}}),children:[
|
|
16
16
|
/* @__PURE__ */b(_a,{src:ga,alt:"",size:28,rounded:"pill"}),
|
|
17
17
|
/* @__PURE__ */v(ja,{grow:!0,minWidth:"0",children:[/* @__PURE__ */b(ss,{render:/* @__PURE__ */b(Ka,{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__ */b(is,{render:/* @__PURE__ */b(Ka,{as:"span",block:!0,inheritColor:!0,style:{fontSize:"12px",color:t.bodyColor,opacity:.8,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}})})]}),e.actionProps&&/* @__PURE__ */b(hs,{render:/* @__PURE__ */b(Na,{type:"button",variant:"ghost",shape:"pill",size:"sm",style:{color:t.titleColor,backgroundColor:t.actionBackground,border:t.border}})}),
|
|
18
|
-
/* @__PURE__ */b(ps,{render:/* @__PURE__ */b(Ha,{label:"Dismiss",size:"xs",tone:"inherit",style:{color:t.closeColor,padding:"2px"}}),children:/* @__PURE__ */b(Ua,{name:"closeSmall",size:12})})]},e.id)})},Ga=({children:e,container:t,offsetBottom:n=20})=>/* @__PURE__ */v(mi,{children:[e,/* @__PURE__ */b(Es,{container:t??void 0,children:/* @__PURE__ */b(zi,{className:"mtx-toast-viewport",style:{zIndex:2147483004,bottom:`${n}px`},children:/* @__PURE__ */b(Xa,{})})})]}),Ja=ma,Za=({error:e,onClearError:t,onRetry:n,greeting:r,greetingBody:o,onGreetingDismiss:i})=>{const{add:s,close:c}=Ja();return a(()=>{null!=e?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(()=>{r?s({id:"greeting",type:"info",title:r,description:o,timeout:8e3,onClose:i}):c("greeting")},[r,o,s,c,i]),null},Qa={show:"Show",tell:"Tell",do:"Do"},ec=e=>Qa[e];function tc(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}function nc({messages:e,isTaskRunning:t,currentMode:n}){const r=e=>"agent"===e.sender&&!e.isSystemMessage&&!e.isScreenAccessRequest&&!e.taskStatus,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);const s=tc(e,e=>"agent"===e.sender&&!!e.taskStatus)+1,a=e.slice(s);for(const c of i){const e=tc(a,c);if(e>=0)return{index:s+e,message:a[e]}}return console.warn("[MessageFinder] No message found for progress update",{totalMessages:e.length,isTaskRunning:t,currentMode:n}),null}var rc=/* @__PURE__ */new Set(["click_element","type_text","select_dropdown_option","send_keys"]),oc=e=>e.replace(/\(?cancelled by cleanup\)?/gi,"").trim();function ic(e,t,n){if(t<0)return e;const r=[...e.parts];return r[t]={...r[t],...n},{...e,parts:r}}var sc=(e,t)=>e.parts.findIndex(e=>(e=>"progress"===e.type&&"in_progress"===e.status)(e)&&e.browserToolName===t),ac=/* @__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"]]);function cc(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 lc=(e,t,n="user-message")=>cc(n,"user",e.trim(),{mode:t}),dc=e=>cc("agent-message","agent",e.trim()),uc=(e,t,n,r)=>cc(r,n,e,{mode:t,isSystemMessage:!0}),pc=/* @__PURE__ */new Set(["button","link","textbox","checkbox","radio","switch","tab","menuitem"]);function*hc(e){let t=e;for(;t;){yield t;const e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}}function fc(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")||pc.has(e.getAttribute("role")??"")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||parseInt(e.getAttribute("tabindex")??"-1",10)>=0}(e))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 hc(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("[isIndexable] Unexpected error:",t),!1}}var mc=["id","type","role","aria-label","name","href"],gc=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)?mc.some((t,n)=>e.element.getAttribute(t)!==e.identity[n])?"has changed":null:"no longer exists"}indexElements(){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||fc(r))&&(this.index.set(n,{element:r,selector:this.generateAnchoredSelector(r),identity:mc.map(e=>r.getAttribute(e))}),this.elementToSequence.set(r,n),n++)}t=e.nextNode()}}reindexAndSnapshot(){this.indexElements();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}notInteractableReason(e,t){if(!document.body.contains(e))return`ELEMENT_NOT_INTERACTABLE: Element ${t} is not in the DOM`;const n=function(e){if(!0===e.disabled)return"is a disabled control";if("true"===e.getAttribute("aria-disabled"))return"is aria-disabled";for(const t of hc(e))if(t.hasAttribute("inert"))return"is inside an inert subtree";return null}(e);if(n)return`ELEMENT_NOT_INTERACTABLE: Element ${t} ${n}`;const r=window.getComputedStyle(e);if("none"===r.display)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has display:none`;if("hidden"===r.visibility)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has visibility:hidden`;if(0===parseFloat(r.opacity))return`ELEMENT_NOT_INTERACTABLE: Element ${t} has opacity:0`;const o=e.getBoundingClientRect();if(0===o.width||0===o.height)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has zero dimensions`;const i=o.left+o.width/2,s=o.top+o.height/2,a=document.elementFromPoint(i,s);if(a&&a!==e&&!e.contains(a)&&!a.closest("#marketrix-show-highlight, #marketrix-show-popup, .marketrix-widget-container")){const e=a.tagName.toLowerCase();return`ELEMENT_OBSCURED: Element ${t} is covered by ${a.className?`${e}.${a.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.notInteractableReason(t.element,e);return r?{element:null,error:r}:{element:t.element}}},yc=["scroll","resize","touchmove","wheel"],bc=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 yc)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 yc)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=gc.getSequenceForElement(e)??-1,r=gc.notInteractableReason(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}},vc=e=>({success:!0,data:{text:e}}),wc=e=>({success:!0,data:e}),xc=e=>({success:!1,data:{text:""},error:e}),Sc=e=>({success:!1,data:{options:[]},error:e}),kc=(e,t)=>({success:!0,data:{text:e},afterResponseAttempt:t}),Cc=new class{async executeTool(e,t,n,r=""){const o=t;try{if("show"===n&&rc.has(e)){const t=o.index;if(void 0!==t){const{element:n,error:o}=gc.getValidatedElement(t);if(!n)return xc(o||`Element ${t} not found`);await bc.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 xc(`Unknown tool: ${e}`)}}catch(i){return xc(i instanceof Error?i.message:String(i))}}navigate(e){const t=(e=>{if(!e)return null;try{const t=new URL(e,window.location.href);return"http:"===t.protocol||"https:"===t.protocol?t.href:null}catch{return null}})(e.url);return t?e.new_tab?window.open(t,"_blank")?vc(`Opened ${t} in new tab`):xc("The browser blocked opening a new tab"):kc(`Navigating to ${t}`,()=>{window.location.href=t}):xc("An http(s) URL is required")}search(e){if(!e.query)return xc("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}`),kc(`Searching for "${e.query}" on ${t}`,()=>{window.location.href=r})}async clickElement(e){if(void 0===e.index)return xc("Index required");const{element:t,error:n}=gc.getValidatedElement(e.index);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),kc(`Clicking element ${e.index}`,()=>t.click())):xc(n||`Element ${e.index} not found`)}typeText(e){if(void 0===e.index||void 0===e.text)return xc("Index and text required");const t=!1!==e.clear,{element:n,error:r}=gc.getValidatedElement(e.index);if(!n)return xc(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 xc(`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 xc(`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 xc(`Failed to set textContent: ${o instanceof Error?o.message:String(o)}`)}return vc(`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 xc("Invalid direction")}return vc(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return xc("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"}),vc(`Scrolled to "${e.text}"`);return xc(`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 wc(n)}goBack(){return window.history.length<=1?xc("No history"):kc("Going back",()=>window.history.back())}async wait({seconds:e}){return void 0===e?xc("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),vc(`Waited ${e}s`))}selectDropdownOption(e){if(void 0===e.index||!e.option)return xc("Index/Option required");const{element:t,error:n}=gc.getValidatedElement(e.index);if(!t)return xc(n||`Select ${e.index} not found`);if(!(t instanceof HTMLSelectElement))return xc(`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})),vc(`Selected ${e.option}`)):xc(`Option ${e.option} not found`)}getDropdownOptions(e){const t=e.index;if(void 0===t)return Sc("Index required");const{element:n,error:r}=gc.getValidatedElement(t);if(!n)return Sc(r||`Select ${t} not found`);if(!(n instanceof HTMLSelectElement))return Sc(`Element ${t} is not a select element`);const o=Array.from(n.options).map(e=>({value:e.value,text:e.text}));return wc({options:o})}sendKeys(e){if(void 0===e.index||!e.keys)return xc("Index/Keys required");const{element:t,error:n}=gc.getValidatedElement(e.index);if(!t)return xc(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 vc(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?vc("Tab closed"):xc("The browser refused to close a tab this script did not open")}done(e){return vc(e.message||"Task ended")}getHtml(){try{const e=gc.reindexAndSnapshot();return vc(e)}catch(e){return xc(String(e))}}async getScreenshot(){const e=fr();if(!e)return xc("The visitor is not sharing their screen.");const t=document.createElement("video");try{t.srcObject=e,t.autoplay=!0,t.style.display="none",document.body.appendChild(t),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"))}})}(t);const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight;const r=n.getContext("2d");return r?(r.drawImage(t,0,0),vc(n.toDataURL("image/jpeg",.75))):xc("Could not read the shared screen: the browser refused a 2d canvas context.")}catch(n){return xc(String(n))}finally{t.remove()}}},Ec=e=>e.filter(e=>"text"===e.type).map(e=>e.content).join("\n"),Ic=e=>({state:e,effects:[]});function Mc(e,t,n,r,o,i,s){const a=nc({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;if("failed"===i?c=function(e,t,n){const r=sc(e,t);if(r<0)return e;const o=oc(e.parts[r].content),i=oc(n);return ic(e,r,{status:"failed",content:i?`${o} (${i})`:o})}(c,r,s||""):"done"!==r&&(c="in_progress"===i?function(e,t,n){const r=oc(n),o=sc(e,t);return o>=0?ic(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||(e=>ac.get(e)??e)(r)):((e,t)=>ic(e,sc(e,t),{status:"completed"}))(c,r)),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&rc.has(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const l=[...e];return l[a.index]=c,l}var Tc=e=>({...e,isPlaceholder:!1}),Rc=e=>"stopped"===e.phase?e:{phase:"idle"};function Oc(e,t,n){const r=nc({messages:e.messages,isTaskRunning:"running"===e.task.phase,currentMode:t}),o=[...e.messages];return r&&(o[r.index]=Tc(n(r.message))),{messages:o,task:Rc(e.task)}}var Ac={completed:"done",failed:"failed",stopped:"stopped"};function _c(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={type:"text",content:r&&s?i.content+n:n,...r&&{streaming:!0}};return s?o[o.length-1]=a:o.push(a),{...e,content:Ec(o),isPlaceholder:!1,placeholderState:void 0,parts:o}});return{...e,messages:o}}var Dc=(e,t)=>{const n=[...e.parts,{type:"text",content:t}];return{...e,content:Ec(n),parts:n}},Pc=(e,t)=>({...Tc(Dc(e,t)),placeholderState:void 0,taskStatus:"failed"});function Nc(e,t,n){const r=e.messages.map(e=>e.id===t?Pc(e,n):e);return{...e,messages:r}}var Lc=n(void 0),Fc=({children:e})=>{const[t,n]=p({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,t)=>n(n=>({...n,error:e,errorRetryable:t})),applyState:e=>n(t=>({...t,...e}))}),[]);/* @__PURE__ */
|
|
19
|
-
return b(Lc.Provider,{value:{uiState:t,uiActions:r},children:e})},zc=()=>{const e=s(Lc);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},$c=n(void 0),Bc=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=zc(),[o,s]=p(()=>({messages:[],task:{phase:"idle"}})),c=u(o),l=u(n.currentMode);l.current=n.currentMode;const h=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]),y=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(()=>{f(e=>({...e,task:{phase:"idle"}}))},[f]),S=o.messages.filter(e=>e.isPlaceholder).map(e=>`${e.id}:${e.parts.length}`).join(" ");a(()=>{const e=S.split(" ").filter(Boolean).map(e=>e.split(":")[0]).map(e=>setTimeout(()=>f(t=>function(e,t){const n=e.messages.find(e=>e.id===t);return n?.isPlaceholder&&"waiting-for-user"!==n.placeholderState?Nc(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(lc(e,o)),void m(dc("This is a preview. In production, I'll respond to your messages here."));const i=Ne.getCredentialedConfig();if(!i)return console.error("Config not loaded or incomplete"),void m(dc("Configuration error: Missing API credentials. Please check your widget settings."));r||m(lc(e,o));const s=`temp-${globalThis.crypto.randomUUID()}`,a={id:s,content:"",sender:"agent",timestamp:/* @__PURE__ */new Date,mode:o,isPlaceholder:!0,placeholderState:"thinking",parts:[]};f(e=>function(e,t){return{messages:[...e.messages,t],task:{phase:"idle"}}}(e,a));try{await async function(e,t,n,r){const o=await $e.getOrCreateChatId();!function(e,t,n){const r={question:t,mode:n,chat_id:Ne.getChatId(),timestamp:/* @__PURE__ */(new Date).toISOString(),marketrix_id:e.mtxId,marketrix_key:e.mtxKey};e.userId&&(r.user_id=e.userId),Te.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=ur.getInstance();await s.ready(o),await s.send(i)}(i,e,o,s)}catch(c){console.error("Failed to send message:",c),f(e=>Nc(e,s,"I'm sorry, I encountered an error processing your request. Please try again."))}},[t,m,f]);a(()=>{if(t)return;const e=ur.getInstance(),n=async t=>{const{toolCallId:n,tool:r,args:o,mode:i,explanation:s}=t,a=await
|
|
18
|
+
/* @__PURE__ */b(ps,{render:/* @__PURE__ */b(Ha,{label:"Dismiss",size:"xs",tone:"inherit",style:{color:t.closeColor,padding:"2px"}}),children:/* @__PURE__ */b(Ua,{name:"closeSmall",size:12})})]},e.id)})},Ga=({children:e,container:t,offsetBottom:n=20})=>/* @__PURE__ */v(mi,{children:[e,/* @__PURE__ */b(Es,{container:t??void 0,children:/* @__PURE__ */b(zi,{className:"mtx-toast-viewport",style:{zIndex:2147483004,bottom:`${n}px`},children:/* @__PURE__ */b(Xa,{})})})]}),Ja=ma,Za=({error:e,onClearError:t,onRetry:n,greeting:r,greetingBody:o,onGreetingDismiss:i})=>{const{add:s,close:c}=Ja();return a(()=>{null!=e?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(()=>{r?s({id:"greeting",type:"info",title:r,description:o,timeout:8e3,onClose:i}):c("greeting")},[r,o,s,c,i]),null},Qa={show:"Show",tell:"Tell",do:"Do"},ec=e=>Qa[e];function tc(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}function nc({messages:e,isTaskRunning:t,currentMode:n}){const r=e=>"agent"===e.sender&&!e.isSystemMessage&&!e.isScreenAccessRequest&&!e.taskStatus,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);const s=tc(e,e=>"agent"===e.sender&&!!e.taskStatus)+1,a=e.slice(s);for(const c of i){const e=tc(a,c);if(e>=0)return{index:s+e,message:a[e]}}return console.warn("[MessageFinder] No message found for progress update",{totalMessages:e.length,isTaskRunning:t,currentMode:n}),null}var rc=/* @__PURE__ */new Set(["click_element","type_text","select_dropdown_option","send_keys"]),oc=e=>e.replace(/\(?cancelled by cleanup\)?/gi,"").trim();function ic(e,t,n){if(t<0)return e;const r=[...e.parts];return r[t]={...r[t],...n},{...e,parts:r}}var sc=(e,t)=>e.parts.findIndex(e=>(e=>"progress"===e.type&&"in_progress"===e.status)(e)&&e.browserToolName===t),ac=/* @__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"]]);function cc(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 lc=(e,t,n="user-message")=>cc(n,"user",e.trim(),{mode:t}),dc=e=>cc("agent-message","agent",e.trim()),uc=(e,t)=>cc(t,"agent",e,{isSystemMessage:!0}),pc=/* @__PURE__ */new Set(["button","link","textbox","checkbox","radio","switch","tab","menuitem"]);function*hc(e){let t=e;for(;t;){yield t;const e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}}function fc(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")||pc.has(e.getAttribute("role")??"")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||parseInt(e.getAttribute("tabindex")??"-1",10)>=0}(e))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 hc(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("[isIndexable] Unexpected error:",t),!1}}var mc=["id","type","role","aria-label","name","href"],gc=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)?mc.some((t,n)=>e.element.getAttribute(t)!==e.identity[n])?"has changed":null:"no longer exists"}indexElements(){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||fc(r))&&(this.index.set(n,{element:r,selector:this.generateAnchoredSelector(r),identity:mc.map(e=>r.getAttribute(e))}),this.elementToSequence.set(r,n),n++)}t=e.nextNode()}}reindexAndSnapshot(){this.indexElements();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}notInteractableReason(e,t){if(!document.body.contains(e))return`ELEMENT_NOT_INTERACTABLE: Element ${t} is not in the DOM`;const n=function(e){if(!0===e.disabled)return"is a disabled control";if("true"===e.getAttribute("aria-disabled"))return"is aria-disabled";for(const t of hc(e))if(t.hasAttribute("inert"))return"is inside an inert subtree";return null}(e);if(n)return`ELEMENT_NOT_INTERACTABLE: Element ${t} ${n}`;const r=window.getComputedStyle(e);if("none"===r.display)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has display:none`;if("hidden"===r.visibility)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has visibility:hidden`;if(0===parseFloat(r.opacity))return`ELEMENT_NOT_INTERACTABLE: Element ${t} has opacity:0`;const o=e.getBoundingClientRect();if(0===o.width||0===o.height)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has zero dimensions`;const i=o.left+o.width/2,s=o.top+o.height/2,a=document.elementFromPoint(i,s);if(a&&a!==e&&!e.contains(a)&&!a.closest("#marketrix-show-highlight, #marketrix-show-popup, .marketrix-widget-container")){const e=a.tagName.toLowerCase();return`ELEMENT_OBSCURED: Element ${t} is covered by ${a.className?`${e}.${a.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.notInteractableReason(t.element,e);return r?{element:null,error:r}:{element:t.element}}},yc=["scroll","resize","touchmove","wheel"],bc=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 yc)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 yc)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=gc.getSequenceForElement(e)??-1,r=gc.notInteractableReason(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}},vc=e=>({success:!0,data:{text:e}}),wc=e=>({success:!0,data:e}),xc=e=>({success:!1,error:e}),Sc=(e,t)=>({success:!0,data:{text:e},afterResponseAttempt:t}),kc=new class{async executeTool(e,t,n,r=""){const o=t;try{if("show"===n&&rc.has(e)){const t=o.index;if(void 0!==t){const{element:n,error:o}=gc.getValidatedElement(t);if(!n)return xc(o||`Element ${t} not found`);await bc.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 xc(`Unknown tool: ${e}`)}}catch(i){return xc(i instanceof Error?i.message:String(i))}}navigate(e){const t=(e=>{if(!e)return null;try{const t=new URL(e,window.location.href);return"http:"===t.protocol||"https:"===t.protocol?t.href:null}catch{return null}})(e.url);return t?e.new_tab?window.open(t,"_blank")?vc(`Opened ${t} in new tab`):xc("The browser blocked opening a new tab"):Sc(`Navigating to ${t}`,()=>{window.location.href=t}):xc("An http(s) URL is required")}search(e){if(!e.query)return xc("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}`),Sc(`Searching for "${e.query}" on ${t}`,()=>{window.location.href=r})}async clickElement(e){if(void 0===e.index)return xc("Index required");const{element:t,error:n}=gc.getValidatedElement(e.index);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),Sc(`Clicking element ${e.index}`,()=>t.click())):xc(n||`Element ${e.index} not found`)}typeText(e){if(void 0===e.index||void 0===e.text)return xc("Index and text required");const t=!1!==e.clear,{element:n,error:r}=gc.getValidatedElement(e.index);if(!n)return xc(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 xc(`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 xc(`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 xc(`Failed to set textContent: ${o instanceof Error?o.message:String(o)}`)}return vc(`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 xc("Invalid direction")}return vc(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return xc("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"}),vc(`Scrolled to "${e.text}"`);return xc(`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 wc(n)}goBack(){return window.history.length<=1?xc("No history"):Sc("Going back",()=>window.history.back())}async wait({seconds:e}){return void 0===e?xc("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),vc(`Waited ${e}s`))}selectDropdownOption(e){if(void 0===e.index||!e.option)return xc("Index/Option required");const{element:t,error:n}=gc.getValidatedElement(e.index);if(!t)return xc(n||`Select ${e.index} not found`);if(!(t instanceof HTMLSelectElement))return xc(`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})),vc(`Selected ${e.option}`)):xc(`Option ${e.option} not found`)}getDropdownOptions(e){const t=e.index;if(void 0===t)return xc("Index required");const{element:n,error:r}=gc.getValidatedElement(t);if(!n)return xc(r||`Select ${t} not found`);if(!(n instanceof HTMLSelectElement))return xc(`Element ${t} is not a select element`);const o=Array.from(n.options).map(e=>({value:e.value,text:e.text}));return wc({options:o})}sendKeys(e){if(void 0===e.index||!e.keys)return xc("Index/Keys required");const{element:t,error:n}=gc.getValidatedElement(e.index);if(!t)return xc(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 vc(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?vc("Tab closed"):xc("The browser refused to close a tab this script did not open")}done(e){return vc(e.message||"Task ended")}getHtml(){try{const e=gc.reindexAndSnapshot();return vc(e)}catch(e){return xc(String(e))}}async getScreenshot(){const e=fr();if(!e)return xc("The visitor is not sharing their screen.");const t=document.createElement("video");try{t.srcObject=e,t.autoplay=!0,t.style.display="none",document.body.appendChild(t),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"))}})}(t);const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight;const r=n.getContext("2d");return r?(r.drawImage(t,0,0),vc(n.toDataURL("image/jpeg",.75))):xc("Could not read the shared screen: the browser refused a 2d canvas context.")}catch(n){return xc(String(n))}finally{t.remove()}}},Cc=e=>e.filter(e=>"text"===e.type).map(e=>e.content).join("\n"),Ec=e=>({state:e,effects:[]});function Ic(e,t,n,r,o,i,s){const a=nc({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;if("failed"===i?c=function(e,t,n){const r=sc(e,t);if(r<0)return e;const o=oc(e.parts[r].content),i=oc(n);return ic(e,r,{status:"failed",content:i?`${o} (${i})`:o})}(c,r,s||""):"done"!==r&&(c="in_progress"===i?function(e,t,n){const r=oc(n),o=sc(e,t);return o>=0?ic(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||(e=>ac.get(e)??e)(r)):((e,t)=>ic(e,sc(e,t),{status:"completed"}))(c,r)),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&rc.has(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const l=[...e];return l[a.index]=c,l}var Mc=(e,t)=>"running"===e.task.phase?e.task.mode??t:t,Tc=e=>({...e,isPlaceholder:!1}),Rc=e=>"stopped"===e.phase?e:{phase:"idle"};function Oc(e,t,n){const r=nc({messages:e.messages,isTaskRunning:"running"===e.task.phase,currentMode:Mc(e,t)}),o=[...e.messages];return r&&(o[r.index]=Tc(n(r.message))),{messages:o,task:Rc(e.task)}}var Ac={completed:"done",failed:"failed",stopped:"stopped"};function _c(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={type:"text",content:r&&s?i.content+n:n,...r&&{streaming:!0}};return s?o[o.length-1]=a:o.push(a),{...e,content:Cc(o),isPlaceholder:!1,placeholderState:void 0,parts:o}});return{...e,messages:o}}var Dc=(e,t)=>{const n=[...e.parts,{type:"text",content:t}];return{...e,content:Cc(n),parts:n}},Pc=(e,t)=>({...Tc(Dc(e,t)),placeholderState:void 0,taskStatus:"failed"});function Nc(e,t,n){const r=e.messages.map(e=>e.id===t?Pc(e,n):e);return{...e,messages:r}}var Lc=n(void 0),Fc=({children:e})=>{const[t,n]=p({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
|
+
return b(Lc.Provider,{value:{uiState:t,uiActions:r},children:e})},zc=()=>{const e=s(Lc);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},$c=n(void 0),Bc=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=zc(),[o,s]=p(()=>({messages:[],task:{phase:"idle"}})),c=u(o),l=u(n.currentMode);l.current=n.currentMode;const h=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]),y=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(()=>{f(e=>({...e,task:{phase:"idle"}}))},[f]),S=o.messages.filter(e=>e.isPlaceholder).map(e=>`${e.id}:${e.parts.length}`).join(" ");a(()=>{const e=S.split(" ").filter(Boolean).map(e=>e.split(":")[0]).map(e=>setTimeout(()=>f(t=>function(e,t){const n=e.messages.find(e=>e.id===t);return n?.isPlaceholder&&"waiting-for-user"!==n.placeholderState?Nc(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(lc(e,o)),void m(dc("This is a preview. In production, I'll respond to your messages here."));const i=Ne.getCredentialedConfig();if(!i)return console.error("Config not loaded or incomplete"),void m(dc("Configuration error: Missing API credentials. Please check your widget settings."));r||m(lc(e,o));const s=`temp-${globalThis.crypto.randomUUID()}`,a={id:s,content:"",sender:"agent",timestamp:/* @__PURE__ */new Date,mode:o,isPlaceholder:!0,placeholderState:"thinking",parts:[]};f(e=>function(e,t){return{messages:[...e.messages,t],task:{phase:"idle"}}}(e,a));try{await async function(e,t,n,r){const o=await $e.getOrCreateChatId();!function(e,t,n){const r={question:t,mode:n,chat_id:Ne.getChatId(),timestamp:/* @__PURE__ */(new Date).toISOString(),marketrix_id:e.mtxId,marketrix_key:e.mtxKey};e.userId&&(r.user_id=e.userId),Te.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=ur.getInstance();await s.ready(o),await s.send(i)}(i,e,o,s)}catch(c){console.error("Failed to send message:",c),f(e=>Nc(e,s,"I'm sorry, I encountered an error processing your request. Please try again."))}},[t,m,f]);a(()=>{if(t)return;const e=ur.getInstance(),n=async t=>{const{toolCallId:n,tool:r,args:o,mode:i,explanation:s}=t,a=await kc.executeTool(r,o,i,s),c=a.success?void 0:a.error;f(e=>function(e,t,n,r,o,i){return{...e,messages:Ic(e.messages,"running"===e.task.phase,Mc(e,o),t,n,r,i)}}(e,r,s,c?"failed":"completed",l.current,c)),c||"done"!==r||f(e=>function(e,t){return Oc(e,t,e=>({...e,taskStatus:"done"}))}(e,l.current)),await e.send({type:"tool/response",tool_call_id:n,success:a.success,...a.success&&{data:JSON.stringify(a.data)},error:c}).catch(e=>console.error("Failed to send tool response:",e)),a.success&&a.afterResponseAttempt?.()},o={onMessage:e=>{if("tool/call"===e.type){const t=e.tool_call_id;if(h.current.has(t))return;h.current.add(t),h.current.size>1e3&&(h.current=new Set([...h.current].slice(-500)))}else"task/status"===e.type&&e.status in Ac&&h.current.clear();let t=[];f(n=>{const r=function(e,t,n){switch(t.type){case"tool/call":{if("stopped"===e.task.phase)return Ec(e);const r="running"===e.task.phase?e.task:{phase:"running",mode:t.mode||n},o=t.explanation||"";return{state:{messages:Ic(e.messages,!0,r.mode??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 Ec(e);const r=t.status,o=e=>t.message?Dc(e,t.message):e;return{state:Oc(e,n,"has_question"===r?e=>({...o(e),placeholderState:"waiting-for-user"}):e=>({...o(e),taskStatus:Ac[r]})),effects:[]}}case"chat/delta":return{state:_c(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:_c(e,t.request_id,t.text,!1),effects:[]};case"chat/error":return{state:Nc(e,t.request_id,`Error: ${t.error}`),effects:[]};default:return Ec(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 dr&&f(t=>function(e,t){return{messages:e.messages.map(e=>e.isPlaceholder?Pc(e,t):e),task:Rc(e.task)}}(t,e.message))}};return e.addCallbacks(o),()=>{e.removeCallbacks(o)}},[t,f,r]);const C=i(async()=>{f(e=>function(e,t){return{...Oc(e,t,e=>({...e,taskStatus:"stopped"})),task:{phase:"stopped"}}}(e,l.current)),t||ur.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:y,setMessages:v,clearMessages:w,messageDispatch:k}),[m,g,y,v,w,k]),I=d(()=>({resetTask:x,stopTask:C}),[x,C]);/* @__PURE__ */
|
|
20
20
|
return b($c.Provider,{value:{messages:o.messages,chatActions:E,taskState:o.task,taskActions:I},children:e})},Wc=()=>{const e=s($c);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},Uc=n(null),Hc=()=>{const{uiState:e}=zc(),{messages:t}=Wc();return a(()=>{const{currentMode:n,isOpen:r}=e;var o;o={messages:t,currentMode:n,isOpen:r},Ne.updateContext({...o,messages:o.messages.map(Fe)})},[t,e]),null},jc=({children:e,previewMode:t})=>{const{uiActions:n}=zc(),{chatActions:r}=Wc(),[o,i]=p(!1);return a(()=>{if(t)return;let e=!1;return(async()=>{const{messages:t,...o}=function(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=Ne.getContext();return{...o,messages:r.map(Le)}}();n.applyState(o),r.setMessages(t),i(!0);const s=await $e.getOrCreateChatId();e||ur.getInstance().connect(s).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__ */v(y,{children:[e,o&&/* @__PURE__ */b(Hc,{})]})},qc=({children:e,previewMode:t=!1})=>/* @__PURE__ */b(Fc,{children:/* @__PURE__ */b(Bc,{previewMode:t,children:/* @__PURE__ */b(jc,{previewMode:t,children:e})})}),Vc=/^#?([a-f\d]{3}|[a-f\d]{6})$/i,Yc=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i;function Kc(e){const t=Vc.exec(e.trim());if(t){const e=t[1],[n,r,o]=(3===e.length?[e[0]+e[0],e[1]+e[1],e[2]+e[2]]:[e.slice(0,2),e.slice(2,4),e.slice(4,6)]).map(e=>parseInt(e,16));return{r:n,g:r,b:o}}const n=Yc.exec(e.trim());if(!n)return null;const[r,o,i]=[n[1],n[2],n[3]].map(Number);return r>255||o>255||i>255?null:{r:r,g:o,b:i}}function Xc(e){const t=function(e){const t=Kc(e);if(!t)return null;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}(e);return null===t||t>.5?"#000000":"#ffffff"}function Gc(e,t){const n=Kc(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}var Jc={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"};function Zc(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:Gc(e.widget_text_color,.6),foregroundFaint:Gc(e.widget_text_color,.4),border:e.widget_border_color,primary:e.widget_accent_color,primaryForeground:Xc(e.widget_accent_color),primaryHover:Gc(e.widget_accent_color,.85),secondary:e.widget_secondary_color,secondaryForeground:"#ffffff",secondaryBg:Gc(e.widget_secondary_color,.2),secondaryHover:Gc(e.widget_secondary_color,.3)},radius:"12px",motion:{durationAnimation:"300ms",durationFade:"200ms"}}}({...Jc,...t})}var Qc=n(null),el=()=>{const e=s(Qc);if(!e)throw new Error("useWidgetConfig must be used within WidgetRoot");return e},tl=()=>{const{uiState:e,uiActions:t}=zc(),{messages:n,chatActions:r,taskState:o,taskActions:s}=Wc(),a=d(()=>({...e,messages:n,isTaskRunning:"running"===o.phase,isAwaitingReply:n.some(e=>e.isPlaceholder)}),[e,n,o]),c=i(()=>{r.clearMessages(),s.resetTask(),t.setError(void 0)},[r,s,t]);return{state:a,actions:d(()=>({...t,...s,...r,clearChatHistory:c}),[t,s,r,c])}},nl={bottom_right:{vertical:"bottom",horizontal:"right"},bottom_left:{vertical:"bottom",horizontal:"left"},top_right:{vertical:"top",horizontal:"right"},top_left:{vertical:"top",horizontal:"left"}},rl=Object.keys(nl),ol=e=>nl[e],il=e=>{const{vertical:t,horizontal:n}=ol(e);return{[t]:"20px",[n]:"20px"}},sl={top:"bottom",bottom:"top",left:"right",right:"left"},al=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=ol(e);return{x:"left"===s?20:t-20-r,y:"top"===i?20:n-20-o}},cl=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}},ll="cubic-bezier(0.16, 1, 0.3, 1)",dl=({onPositionCommit:e})=>{const{isPreviewMode:n=!1,widget_accent_color:r,widget_background_color:o,widget_position:s,widget_position_z_index:a}=el(),{state:c,actions:d}=tl(),h=c.isOpen,f=c.isTaskRunning,m=!!c.error,g=!h&&(c.isAwaitingReply||f),y=!h&&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]=p(!1),[c,d]=p({w:56,h:56}),[,h]=p(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=()=>h(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=al(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)=>{f.current?.();let r=!1;const i=()=>{r||(r=!0,window.clearTimeout(s),t.removeEventListener("transitionend",c),f.current=null,t.style.transition="none",t.style.willChange="",n(e),a(!1),requestAnimationFrame(()=>{o.current&&(o.current.style.transition="")}))},s=window.setTimeout(i,650),c=e=>{e.target===t&&"left"===e.propertyName&&i()};t.addEventListener("transitionend",c),f.current=()=>{r=!0,window.clearTimeout(s),t.removeEventListener("transitionend",c),f.current=null}},[n,o]),R=i((t,r,i)=>{if(!o.current||!E)return M(),n(t),void a(!1);w();const s=o.current,l=al(e,S,k,c.w,c.h),d=al(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 ${ll}, top 600ms ${ll}`,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=al(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 rl){const e=al(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 b(za,{ref:S,className:"mtx-fab-anchor","data-animated":k?"false":"true","data-preview":n?"true":"false",style:{zIndex:a,pointerEvents:h?"none":"auto",...il(s),...C},children:/* @__PURE__ */v(za,{className:"mtx-fab","data-open":h?"true":"false",children:[g&&/* @__PURE__ */b(za,{className:w,"aria-hidden":!0}),y&&!k&&/* @__PURE__ */b(Na,{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"}),
|
|
22
22
|
/* @__PURE__ */b(Na,{type:"button",variant:"bare",onClick:()=>{Date.now()<R.current||d.toggleWidget()},onDragStart:e=>e.preventDefault(),onPointerDown:E,onPointerMove:I,onPointerUp:M,onPointerCancel:T,className:"mtx-fab-trigger",style:{touchAction:"none",cursor:k?"grabbing":"grab",userSelect:"none",WebkitUserSelect:"none"},"aria-label":h?"Close":"Open","aria-live":"polite",children:/* @__PURE__ */b($a,{className:"mtx-fab-center",children:/* @__PURE__ */v(za,{className:"mtx-fab-badge",style:{borderRadius:"12px",backgroundColor:h?o:r,boxShadow:ya.fab},children:[g&&/* @__PURE__ */b("svg",{className:x,viewBox:"0 0 54 54",fill:"none","aria-hidden":!0,children:/* @__PURE__ */b("rect",{x:"1.25",y:"1.25",width:"51.5",height:"51.5",rx:13,ry:13})}),
|
|
@@ -37,18 +37,18 @@ return b(gd,{open:e,onOpenChange:(e,n)=>{e||"none"===n.reason||t()},children:/*
|
|
|
37
37
|
/* @__PURE__ */b(yd,{className:"mtx-dialog-title",children:n}),null!=r&&/* @__PURE__ */b(td,{className:"mtx-dialog-description",children:r}),
|
|
38
38
|
/* @__PURE__ */v($a,{gap:"md",justify:"end",children:[/* @__PURE__ */b(Na,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),t()},children:a}),/* @__PURE__ */b(Na,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),o?.()},children:i})]})]})]})})},vd={sm:{width:"14px",height:"14px",borderWidth:"1.5px"},md:{width:"20px",height:"20px",borderWidth:"2px"},lg:{width:"24px",height:"24px",borderWidth:"2px"}};function wd({size:e="md",style:t,ref:n}){/* @__PURE__ */
|
|
39
39
|
return v("div",{ref:n,"data-size":e,role:"status",style:{display:"inline-flex",alignItems:"center",gap:"6px",...t},children:[/* @__PURE__ */b("div",{"aria-hidden":"true",className:"mtx-spinner-ring",style:vd[e]}),/* @__PURE__ */b("span",{className:"mtx-visually-hidden",children:"Loading"})]})}var xd=({isWaitingForUser:e})=>/* @__PURE__ */v($a,{align:"center",gap:"sm",paddingY:"2xs",children:[/* @__PURE__ */b(wd,{size:"sm"}),/* @__PURE__ */b(Ka,{as:"span",size:"xs",weight:"normal",variant:"faint",children:e?"Waiting for you to complete the action":"Thinking"})]}),Sd=({message:e,isLastMessage:t})=>{const{isTaskRunning:n}=tl().state,r="waiting-for-user"===e.placeholderState,o=n&&t&&("show"===e.mode||"do"===e.mode);return e.parts.length>0?/* @__PURE__ */v(ja,{gap:"sm",children:[e.parts.map((e,t)=>"text"===e.type?e.content?/* @__PURE__ */b(Ka,{as:"div",size:"sm",weight:"medium",style:{wordBreak:"break-word",whiteSpace:"pre-wrap",marginBottom:"4px"},children:e.content},`part-${t}`):null:"progress"===e.type?/* @__PURE__ */b($a,{align:"start",gap:"md",children:/* @__PURE__ */b(Ka,{as:"span",size:"xs",weight:"medium",style:{flex:1,whiteSpace:"pre-wrap"},children:e.content})},`part-${t}`):null),(e.isPlaceholder&&!e.parts.some(e=>"text"===e.type)||o)&&/* @__PURE__ */b(xd,{isWaitingForUser:r})]}):e.isPlaceholder||n&&t&&("show"===e.mode||"do"===e.mode)?/* @__PURE__ */b(xd,{isWaitingForUser:r}):/* @__PURE__ */b(za,{})},kd={done:{name:"checkCircle",opacity:1},failed:{name:"exclamationCircle",opacity:.75},stopped:{name:"circle",opacity:.5}},Cd=({status:e})=>{const{name:t,opacity:n}=kd[e];/* @__PURE__ */
|
|
40
|
-
return b(Ua,{name:t,size:14,style:{color:Gc(el().widget_accent_color,n),flexShrink:0}})},Ed="8px 8px 0 0",Id=({label:e,children:t})=>/* @__PURE__ */b($a,{position:"absolute",inset:"0",align:"center",justify:"center",style:{backgroundColor:"#111827",borderRadius:Ed,zIndex:10},children:/* @__PURE__ */v($a,{direction:"column",align:"center",gap:"md",style:{textAlign:"center",padding:"0 16px"},children:[t,/* @__PURE__ */b(Ka,{as:"span",size:"xs",weight:"medium",style:{color:"rgba(255,255,255,0.7)"},children:e})]})}),Md=({stream:e})=>{const t=u(null),n
|
|
41
|
-
/* @__PURE__ */b("video",{ref:t,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"auto",maxHeight:"192px",objectFit:"contain",borderRadius:Ed,transition:"opacity 500ms",opacity:
|
|
42
|
-
/* @__PURE__ */b($a,{position:"absolute",inset:"0",align:"center",justify:"center",style:{borderRadius:Ed,backgroundColor:"rgba(0,0,0,0)",zIndex:30,pointerEvents:"none"},children:/* @__PURE__ */b(za,{rounded:"lg",style:{padding:"4px 12px",backgroundColor:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:/* @__PURE__ */b(Ka,{as:"div",size:"xs",weight:"medium",style:{color:"white"},children:"Screen Sharing Active"})})})]})
|
|
40
|
+
return b(Ua,{name:t,size:14,style:{color:Gc(el().widget_accent_color,n),flexShrink:0}})},Ed="8px 8px 0 0",Id=({label:e,children:t})=>/* @__PURE__ */b($a,{position:"absolute",inset:"0",align:"center",justify:"center",style:{backgroundColor:"#111827",borderRadius:Ed,zIndex:10},children:/* @__PURE__ */v($a,{direction:"column",align:"center",gap:"md",style:{textAlign:"center",padding:"0 16px"},children:[t,/* @__PURE__ */b(Ka,{as:"span",size:"xs",weight:"medium",style:{color:"rgba(255,255,255,0.7)"},children:e})]})}),Md=({stream:e})=>{const t=u(null),[n,r]=p(!1),[o,i]=p(!1);return a(()=>{const n=t.current;if(!n)return;r(!1),i(!1),n.srcObject=e;const o=()=>{r(!0)},s=()=>{i(!0),r(!1)};return n.addEventListener("loadedmetadata",o),n.addEventListener("error",s),n.play().catch(e=>{e instanceof Error&&"AbortError"!==e.name&&(console.error("Error playing video stream:",e),i(!0))}),()=>{n.removeEventListener("loadedmetadata",o),n.removeEventListener("error",s),n.srcObject=null}},[e]),/* @__PURE__ */v(za,{width:"full",overflow:"hidden",position:"relative",style:{marginBottom:"4px",borderRadius:Ed,backgroundColor:"#000000",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06)"},children:[!n&&!o&&/* @__PURE__ */b(Id,{label:"Loading stream...",children:/* @__PURE__ */b(wd,{size:"lg",style:{color:"white"}})}),o&&/* @__PURE__ */b(Id,{label:"Failed to load stream",children:/* @__PURE__ */b(Ua,{name:"alertCircle",size:32,style:{color:"#9ca3af"}})}),
|
|
41
|
+
/* @__PURE__ */b("video",{ref:t,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"auto",maxHeight:"192px",objectFit:"contain",borderRadius:Ed,transition:"opacity 500ms",opacity:n?1:0,minHeight:"120px",background:"linear-gradient(135deg, #111827 0%, #374151 100%)"}}),n&&!o&&/* @__PURE__ */v($a,{position:"absolute",align:"center",gap:"sm",animate:"fadeIn",style:{top:"8px",right:"8px",padding:"4px 8px",borderRadius:"9999px",backgroundColor:"rgba(55,65,81,0.9)",backdropFilter:"blur(4px)",zIndex:20,boxShadow:"0 2px 8px rgba(31, 41, 55, 0.4)"},children:[/* @__PURE__ */v($a,{position:"relative",align:"center",justify:"center",children:[/* @__PURE__ */b(za,{position:"absolute",rounded:"pill",animate:"ping",style:{width:"8px",height:"8px",backgroundColor:"white",opacity:.75}}),/* @__PURE__ */b(za,{position:"relative",rounded:"pill",style:{width:"6px",height:"6px",backgroundColor:"white"}})]}),/* @__PURE__ */b(Ka,{as:"span",size:"xs",weight:"semibold",style:{color:"white",textTransform:"uppercase",letterSpacing:"0.05em",fontSize:"10px"},children:"Live"})]}),
|
|
42
|
+
/* @__PURE__ */b($a,{position:"absolute",inset:"0",align:"center",justify:"center",style:{borderRadius:Ed,backgroundColor:"rgba(0,0,0,0)",zIndex:30,pointerEvents:"none"},children:/* @__PURE__ */b(za,{rounded:"lg",style:{padding:"4px 12px",backgroundColor:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:/* @__PURE__ */b(Ka,{as:"div",size:"xs",weight:"medium",style:{color:"white"},children:"Screen Sharing Active"})})})]})},Td=({message:e,index:t,isLastMessage:n,onScreenAccessAllow:r,onScreenAccessDeny:o})=>{if(e.isSystemMessage)/* @__PURE__ */return b($a,{justify:"center",align:"center",children:/* @__PURE__ */b(Ka,{as:"span",variant:"faint",weight:"normal",style:{fontSize:"10px"},children:e.content})},`message-${e.id}-${t}`);const i="user"===e.sender,s=i?"show"===e.mode||"do"===e.mode?"mousePointerClick":void 0:e.isScreenAccessRequest||"waiting-for-user"===e.placeholderState?"checkCircle":void 0;/* @__PURE__ */
|
|
43
43
|
return v(ja,{style:{marginTop:"10px"},role:"article","aria-roledescription":"message","aria-label":i?"You said…":"Agent says…",animate:n?"fadeIn":void 0,children:[/* @__PURE__ */v($a,{align:"start",gap:"sm",width:"full",children:[
|
|
44
44
|
/* @__PURE__ */b($a,{shrink:!1,style:{width:"20px",height:"20px",marginTop:"6px"},children:!i&&/* @__PURE__ */b(_a,{src:"data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20viewBox='0%200%20361%20360'%3e%3cdefs%3e%3cstyle%3e%20.st0%20{%20display:%20none;%20fill:%20none;%20stroke:%20%23cdc9c2;%20stroke-width:%201.3px;%20}%20.st1%20{%20fill:%20%23fff;%20}%20.st2,%20.st3%20{%20fill:%20%237cffa6;%20}%20.st3%20{%20stroke:%20%237cffa6;%20stroke-width:%20.38px;%20}%20.st4%20{%20fill:%20%23101828;%20}%20%3c/style%3e%3c/defs%3e%3crect%20class='st4'%20x='.5'%20width='360'%20height='360'/%3e%3cpath%20class='st2'%20d='M83.37,209.58c15.35,0,27.8-12.45,27.8-27.8s-12.44-27.79-27.8-27.79-27.8,12.44-27.8,27.79,12.44,27.8,27.8,27.8Z'/%3e%3cpath%20class='st1'%20d='M85.86,68.28l152.45,223.44h67.29l-70.62-113.77,68.13-109.67h-67.29l-41.12,65.31-41.54-65.31h-67.29Z'/%3e%3cpath%20class='st3'%20d='M176.61,249.83l-35.08-51-57.82,92.71h66.85l26.05-41.7Z'/%3e%3crect%20class='st0'%20x='1.25'%20y='.65'%20width='358.7'%20height='358.7'%20rx='43.35'%20ry='43.35'/%3e%3c/svg%3e",alt:"Marketrix AI",size:20,fit:"cover",rounded:"lg",style:{border:"none",outline:"none",display:"block",backgroundColor:"transparent"}})}),
|
|
45
45
|
/* @__PURE__ */v(ja,{grow:!0,position:"relative",rounded:"lg",elevation:"card",style:{padding:e.videoStream?"0":"8px 10px",border:"1px solid transparent",backgroundColor:i?"var(--primary)":void 0,color:i?"var(--primary-foreground)":"var(--foreground)"},children:[e.videoStream&&/* @__PURE__ */b(Md,{stream:e.videoStream}),!e.videoStream&&(s?/* @__PURE__ */v($a,{align:"start",gap:"sm",children:[/* @__PURE__ */b($a,{shrink:!1,style:{marginTop:"3px"},children:/* @__PURE__ */b(Ua,{name:s,size:13})}),/* @__PURE__ */b(ja,{grow:!0,children:/* @__PURE__ */b(Sd,{message:e,isLastMessage:n})})]}):/* @__PURE__ */b(Sd,{message:e,isLastMessage:n})),e.isScreenAccessRequest&&!e.screenShareStatus&&/* @__PURE__ */v($a,{align:"center",gap:"sm",style:{marginTop:"6px"},children:[/* @__PURE__ */b(Na,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:()=>r?.(),children:"Yes"}),/* @__PURE__ */b(Na,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:()=>o?.(),children:"No"})]}),e.isScreenAccessRequest&&e.screenShareStatus&&/* @__PURE__ */b(Ka,{as:"div",variant:"faint",size:"xs",italic:!0,style:{marginTop:"2px"},children:"allowed"===e.screenShareStatus?"Sure":"No"}),!i&&e.taskStatus&&/* @__PURE__ */b($a,{position:"absolute",align:"center",justify:"center",style:{bottom:"4px",right:"4px"},children:/* @__PURE__ */b(Cd,{status:e.taskStatus})})]}),
|
|
46
46
|
/* @__PURE__ */b($a,{shrink:!1,style:{width:"20px"}})]}),!e.isPlaceholder&&/* @__PURE__ */b(Ka,{as:"div",variant:"faint",size:"xxs",align:"right",style:{marginTop:"2px",marginRight:"26px"},children:(a=e.timestamp,(a??/* @__PURE__ */new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}))})]},`message-${e.id}-${t}`);var a},Rd={boxShadow:ya.button,backgroundColor:"var(--card)",border:"1px solid var(--border)",pointerEvents:"auto"},Od=({messagesEndRef:e,onScreenAccessAllow:t,onScreenAccessDeny:n})=>{const r=el(),{state:o,actions:i}=tl(),{messages:s}=o,c=r.isPreviewMode??!1,[l,h]=p(!1),[f,m]=p(!1),g=u(null),y=d(()=>({id:"welcome",content:r.widget_body,sender:"agent",timestamp:/* @__PURE__ */new Date,isPlaceholder:!1,parts:[{type:"text",content:r.widget_body}]}),[r.widget_body]),w=d(()=>[y,...s],[y,s]),x=()=>{if(g.current){const{scrollTop:e,scrollHeight:t,clientHeight:n}=g.current;h(e>200);const r=Math.abs(t-e-n)<50;m(!r&&t>n)}};a(()=>{window.requestAnimationFrame(()=>{e.current&&(!c&&e.current.scrollIntoView({behavior:"auto"}),!c&&x())})},[s.length,c]);const S=s[s.length-1]?.content?.length??0;return a(()=>{const t=g.current;t&&!c&&t.scrollHeight-t.scrollTop-t.clientHeight<120&&window.requestAnimationFrame(()=>e.current?.scrollIntoView({behavior:"auto"}))},[S,c,e]),/* @__PURE__ */v(za,{position:"relative",height:"full",children:[
|
|
47
47
|
/* @__PURE__ */v(za,{ref:g,onScroll:x,role:"log","aria-relevant":"additions",height:"full",overflowY:"auto",paddingX:"lg",paddingY:"sm",style:{backgroundColor:r.widget_background_color.includes("gradient")?"transparent":r.widget_background_color,backgroundImage:r.widget_background_color.includes("gradient")?r.widget_background_color:`linear-gradient(135deg, ${r.widget_background_color} 0%, ${r.widget_background_color} 100%)`,scrollbarColor:`${Gc(r.widget_border_color,.3)} ${Gc(r.widget_border_color,.1)}`,scrollbarWidth:"thin"},children:[w.map((e,r)=>/* @__PURE__ */b(Td,{message:e,index:r,isLastMessage:r===w.length-1,onScreenAccessAllow:t,onScreenAccessDeny:n},`message-${e.id}-${r}`)),s.length>0&&/* @__PURE__ */b($a,{justify:"center",style:{marginTop:"12px",marginBottom:"4px"},children:/* @__PURE__ */b(Na,{type:"button",variant:"bare",onClick:i.clearChatHistory,children:/* @__PURE__ */b(Ka,{size:"xs",variant:"muted",style:{cursor:"pointer"},children:"Clear conversation"})})}),
|
|
48
|
-
/* @__PURE__ */b(za,{ref:e},"scroll-anchor")]},"message-list-container"),l&&/* @__PURE__ */b($a,{position:"absolute",justify:"center",style:{top:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */b(Ha,{variant:"secondary",size:"sm",label:"Scroll to top",onClick:()=>{g.current?.scrollTo({top:0,behavior:"smooth"})},style:Rd,children:/* @__PURE__ */b(Ua,{name:"arrowUp",size:10,style:{color:r.widget_accent_color}})})}),f&&/* @__PURE__ */b($a,{position:"absolute",justify:"center",style:{bottom:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */b(Ha,{variant:"secondary",size:"sm",label:"Scroll to bottom",onClick:()=>{e.current&&!c&&e.current.scrollIntoView({behavior:"smooth"})},style:Rd,children:/* @__PURE__ */b(Ua,{name:"arrowDown",size:10,style:{color:r.widget_accent_color}})})})]})},Ad=[{id:"tell",icon:"chatBubble",flag:"widget_feature_tell"},{id:"show",icon:"mousePointerClick",flag:"widget_feature_show"},{id:"do",icon:"ticktick",flag:"widget_feature_do"}],_d=({onScreenSharingChange:e,toggleScreenShareRef:t,messageInputRef:n})=>{const r=el(),{state:o,actions:i}=tl(),{currentMode:s,isTaskRunning:l,isAwaitingReply:d}=o,[h,f]=p(""),m=u(null),{isScreenSharing:g,isAwaitingScreenAccess:y,showScreenAccessDialog:w,handleScreenAccessDialogAllow:x,handleScreenAccessDialogDismiss:S,handleScreenAccessRequestAllow:k,handleScreenAccessRequestDeny:C,requestScreenAccess:E}=function({onScreenSharingChange:e,toggleScreenShareRef:t,onAddMessage:n,onUpdateMessage:r,onRemoveMessage:o,onSendMessage:i,messages:s}){const[l,d]=p(!1),[u,h]=p(null),[f,m]=p(!1),g=Xl(l),y=Xl(u),b=Xl(e),v=e=>{e&&o?.(e),n(uc("Stopped screenshare","
|
|
48
|
+
/* @__PURE__ */b(za,{ref:e},"scroll-anchor")]},"message-list-container"),l&&/* @__PURE__ */b($a,{position:"absolute",justify:"center",style:{top:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */b(Ha,{variant:"secondary",size:"sm",label:"Scroll to top",onClick:()=>{g.current?.scrollTo({top:0,behavior:"smooth"})},style:Rd,children:/* @__PURE__ */b(Ua,{name:"arrowUp",size:10,style:{color:r.widget_accent_color}})})}),f&&/* @__PURE__ */b($a,{position:"absolute",justify:"center",style:{bottom:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */b(Ha,{variant:"secondary",size:"sm",label:"Scroll to bottom",onClick:()=>{e.current&&!c&&e.current.scrollIntoView({behavior:"smooth"})},style:Rd,children:/* @__PURE__ */b(Ua,{name:"arrowDown",size:10,style:{color:r.widget_accent_color}})})})]})},Ad=[{id:"tell",icon:"chatBubble",flag:"widget_feature_tell"},{id:"show",icon:"mousePointerClick",flag:"widget_feature_show"},{id:"do",icon:"ticktick",flag:"widget_feature_do"}],_d=({onScreenSharingChange:e,toggleScreenShareRef:t,messageInputRef:n})=>{const r=el(),{state:o,actions:i}=tl(),{currentMode:s,isTaskRunning:l,isAwaitingReply:d}=o,[h,f]=p(""),m=u(null),{isScreenSharing:g,isAwaitingScreenAccess:y,showScreenAccessDialog:w,handleScreenAccessDialogAllow:x,handleScreenAccessDialogDismiss:S,handleScreenAccessRequestAllow:k,handleScreenAccessRequestDeny:C,requestScreenAccess:E}=function({onScreenSharingChange:e,toggleScreenShareRef:t,onAddMessage:n,onUpdateMessage:r,onRemoveMessage:o,onSendMessage:i,messages:s}){const[l,d]=p(!1),[u,h]=p(null),[f,m]=p(!1),g=Xl(l),y=Xl(u),b=Xl(e),v=e=>{e&&o?.(e),n(uc("Stopped screenshare","stopped-sharing")),h(null)},w=Xl(v);a(()=>{const e=()=>{const e=null!==fr(),t=g.current,n=y.current;e!==t&&(g.current=e,d(e),b.current?.(e)),t&&!e&&n&&w.current(n)};e();const t=setInterval(e,1e3);return()=>clearInterval(t)},[]);const x=s[tc(s,e=>!!e.isScreenAccessRequest&&!e.screenShareStatus)]??null,S=()=>{x?.pendingContent&&i(x.pendingContent,x.mode,!0)},k=e=>{x&&r(x.id,{screenShareStatus:e})},C=async()=>{try{const t=await async function(){if(!1===Ne.getContext().config?.use_screenshare)throw new Error("Screen sharing is disabled for this widget");const e=fr();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 hr=t,t.getVideoTracks()[0].addEventListener("ended",()=>{hr=null}),t}();d(!0),e?.(!0),k("allowed"),n(uc("Started screenshare","started-screenshare"));const r=((e,t="show")=>cc("screenshare","user","",{mode:t,videoStream:e}))(t,"show");h(r.id),n(r)}catch(t){console.error("Failed to start screen sharing:",t),d(!1),e?.(!1),k("denied")}S()},E=C;return c(t,()=>()=>{l?(mr(),d(!1),e?.(!1),v(u)):m(!0)}),{isScreenSharing:l,isAwaitingScreenAccess:null!==x,showScreenAccessDialog:f,handleScreenAccessDialogAllow:async()=>{m(!1),await C()},handleScreenAccessDialogDismiss:()=>{m(!1)},handleScreenAccessRequestAllow:E,handleScreenAccessRequestDeny:()=>{k("denied"),S()},requestScreenAccess:(e,t)=>{x||n(((e,t)=>cc("screen-access-request","agent","Can I take a look at your screen?",{mode:e,isScreenAccessRequest:!0,pendingContent:t}))(e,t))}}}({onScreenSharingChange:e,toggleScreenShareRef:t,onAddMessage:i.addMessage,onUpdateMessage:i.updateMessage,onRemoveMessage:i.removeMessage,onSendMessage:i.messageDispatch,messages:o.messages}),I=y||d;/* @__PURE__ */
|
|
49
49
|
return v(ja,{height:"full",children:[w&&/* @__PURE__ */b(bd,{open:w,onClose:S,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:x,confirmLabel:"Yes",cancelLabel:"No",finalFocusRef:n}),
|
|
50
50
|
/* @__PURE__ */b(za,{grow:!0,overflow:"hidden",paddingY:"2xs",style:{display:"flex",flexDirection:"column",minHeight:0},children:/* @__PURE__ */b(cl,{label:"Chat",fallback:/* @__PURE__ */b(Ka,{as:"div",size:"xs",align:"center",variant:"muted",style:{padding:"16px"},children:"Something went wrong displaying messages. Please refresh."}),children:/* @__PURE__ */b(Od,{messagesEndRef:m,onScreenAccessAllow:k,onScreenAccessDeny:C})})}),
|
|
51
|
-
/* @__PURE__ */b(za,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px",marginTop:"auto"},children:/* @__PURE__ */b(Jl,{ref:n,value:h,onChange:f,onSubmit:()=>{if(!h.trim()||I)return;const e=h.trim();f(""),i.addMessage(lc(e,s)),!1===r.use_screenshare||"show"!==s&&"do"!==s||g?i.messageDispatch(e,s,!0):E(s,e)},modes:Ad.filter(({flag:e})=>r[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:ec(e)})),activeMode:s,onModeChange:e=>{e!==s&&(i.addMessage(uc(`Switched to ${ec(e)} mode`,
|
|
51
|
+
/* @__PURE__ */b(za,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px",marginTop:"auto"},children:/* @__PURE__ */b(Jl,{ref:n,value:h,onChange:f,onSubmit:()=>{if(!h.trim()||I)return;const e=h.trim();f(""),i.addMessage(lc(e,s)),!1===r.use_screenshare||"show"!==s&&"do"!==s||g?i.messageDispatch(e,s,!0):E(s,e)},modes:Ad.filter(({flag:e})=>r[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:ec(e)})),activeMode:s,onModeChange:e=>{e!==s&&(i.addMessage(uc(`Switched to ${ec(e)} mode`,"mode-change")),i.setMode(e))},disabled:I,taskRunning:l,onStop:()=>{bc.cleanup(),i.stopTask()}})})]})},Dd=[{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"}],Pd=({actions:e,onActionClick:t})=>{const n=el();return 0===e.length?null:/* @__PURE__ */b(ja,{gap:"sm",children:e.map((e,r)=>/* @__PURE__ */b(Na,{elevation:"card",size:"sm",variant:"chip",full:!0,onClick:n=>t(e,n),style:{color:n.widget_text_color,paddingTop:"8px",paddingBottom:"8px"},children:/* @__PURE__ */b(Ka,{as:"span",weight:"normal",leading:"tight",children:e.text})},`welcome-chip-${e.id}-${r}`))})},Nd=({onNavigateToChat:e,onChipClick:t})=>{const n=el(),{messages:r}=tl().state,o=function(e){const t=e.widget_chips;return t?.length?t.map((e,t)=>{return{id:`chip-${e.chip_text.replace(/\s+/g,"-").toLowerCase()}-${t}`,text:(n=e.chip_text,r=e.chip_mode,"show"===r?`Show me ${n.replace(/^Show me\s+/i,"")}`:"do"===r?`Do ${n.replace(/^Do\s+/i,"")}`:n),type:e.chip_mode};var n,r}):Dd}(n);/* @__PURE__ */
|
|
52
52
|
return v(ja,{height:"full",overflow:"hidden",children:[/* @__PURE__ */v(ja,{grow:!0,overflowY:"auto",padding:"lg",children:[/* @__PURE__ */v(za,{style:{textAlign:"center",paddingTop:"8px",paddingBottom:"16px"},children:[/* @__PURE__ */b(Ka,{as:"h2",size:"lg",weight:"semibold",children:n.widget_greeting}),/* @__PURE__ */b(Ka,{as:"p",variant:"muted",size:"sm",style:{marginTop:"2px"},children:n.widget_body})]}),/* @__PURE__ */v(ja,{gap:"sm",children:[/* @__PURE__ */v(Na,{type:"button",variant:"primary",full:!0,onClick:e,"aria-label":"Ask a question",style:{paddingTop:"10px",paddingBottom:"10px"},children:[/* @__PURE__ */b(Ua,{name:"chat",size:16}),"Ask a question"]}),/* @__PURE__ */b(Pd,{actions:o,onActionClick:async(n,r)=>{r.preventDefault(),r.stopPropagation(),e(),t(n)}})]})]}),r.length>0&&/* @__PURE__ */v(za,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px"},children:[
|
|
53
53
|
/* @__PURE__ */b(Ka,{as:"p",size:"xs",weight:"semibold",style:{marginBottom:"2px"},children:"Recent conversation"}),
|
|
54
54
|
/* @__PURE__ */b(Ka,{as:"p",size:"xs",variant:"muted",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:r[r.length-1].content||"Message"}),
|
|
@@ -62,4 +62,4 @@ return v(ja,{ref:m,position:s?"absolute":"fixed",rounded:"lg",border:!0,overflow
|
|
|
62
62
|
return b(Qc,{value:y,children:/* @__PURE__ */b(za,{ref:o,"data-marketrix-widget":!0,position:"relative",style:{...x,...l&&{width:"100%",height:"100%"}},children:/* @__PURE__ */b(Uc,{value:r,children:/* @__PURE__ */v(Ga,{container:r,offsetBottom:"top"===ol(u).vertical?20:90,children:[w&&/* @__PURE__ */b(za,{"data-screen-edge-glow":!0,position:"fixed",inset:"0",style:{boxShadow:`inset 0 0 22px 2px ${Gc(y.widget_accent_color,.72)}, inset 0 0 46px 10px ${Gc(y.widget_accent_color,.28)}`,pointerEvents:"none",zIndex:2147483001}}),
|
|
63
63
|
/* @__PURE__ */b(cl,{label:"Widget",children:/* @__PURE__ */b($d,{})}),
|
|
64
64
|
/* @__PURE__ */b(dl,{onPositionCommit:e=>{h(e),l||De(f,e)}}),
|
|
65
|
-
/* @__PURE__ */b(Za,{error:i.error,onClearError:()=>s.setError(void 0),...i.errorRetryable&&{onRetry:()=>{s.setError(void 0),c.reconnectNow()}},greeting:t&&!i.error?e.widget_greeting:void 0,greetingBody:e.widget_body,onGreetingDismiss:()=>n(!1)})]})})})})},Wd={mount:null},Ud=null,Hd=(e,t)=>{const n=e.attachShadow({mode:"closed"}),r=document.createElement("style");r.textContent=':root,:host{--background:oklch(100% 0 0);--foreground:oklch(14.5% 0 0);--card:oklch(100% 0 0);--card-foreground:oklch(14.5% 0 0);--primary:oklch(20.5% 0 0);--primary-foreground:oklch(98.5% 0 0);--secondary:oklch(97% 0 0);--secondary-foreground:oklch(20.5% 0 0);--border:oklch(92.2% 0 0);--ring:oklch(70.8% 0 0);--foreground-muted:#1f293799;--foreground-faint:#1f293766;--primary-hover:#3b82f6d9;--secondary-bg:#6b728033;--secondary-hover:#6b72804d;--font-sans:"Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--radius:.625rem;--shadow-sm:0 1px 3px 0px #0000001a, 0 1px 2px -1px #0000001a;--shadow-lg:0 1px 3px 0px #0000001a, 0 4px 6px -1px #0000001a;--duration-animation:.3s;--duration-fade:.2s}*,:before,:after{box-sizing:border-box;border:0 solid var(--border);margin:0;padding:0}:host,[data-marketrix-widget]{font-family:var(--font-sans);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;line-height:1.5}:where([data-marketrix-widget]) :where(h1,h2,h3){font-size:inherit;font-weight:inherit}:where([data-marketrix-widget]) :where(img,svg,video,canvas){vertical-align:middle;display:block}:where([data-marketrix-widget]) :where(img,video){max-width:100%;height:auto}:where([data-marketrix-widget]) :where(button,input,textarea){font:inherit;color:inherit;background:0 0;border-radius:0}:where([data-marketrix-widget]) :where(button){appearance:button}:where([data-marketrix-widget]) :where(textarea){resize:vertical}[data-marketrix-widget] [hidden]{display:none!important}[data-marketrix-widget],[data-marketrix-widget] *{pointer-events:auto;transition:color .2s ease-in-out,background-color .2s ease-in-out,border-color .2s ease-in-out,opacity .2s ease-in-out,box-shadow .2s ease-in-out,transform .2s ease-in-out}[data-resizing=true],[data-resizing=true] *{transition:none!important}@media (prefers-reduced-motion:reduce){[data-marketrix-widget]{--duration-animation:0s!important;--duration-fade:0s!important}}.mtx-button{cursor:pointer;border:1px solid #0000;justify-content:center;align-items:center;gap:8px;font-weight:500;transition:all .2s ease-in-out;display:inline-flex}.mtx-button:focus-visible{outline:2px solid var(--ring);outline-offset:2px}.mtx-button[data-size=sm]{min-height:28px;padding:4px 8px;font-size:.75rem}.mtx-button[data-size=md]{min-height:36px;padding:8px 16px;font-size:.875rem}.mtx-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-button[data-variant=primary]:hover{background:color-mix(in oklab, var(--primary) 90%, transparent)}.mtx-button[data-variant=secondary]{background:var(--secondary);color:var(--secondary-foreground)}.mtx-button[data-variant=secondary]:hover{background:color-mix(in oklab, var(--secondary) 80%, transparent)}.mtx-button[data-variant=ghost]{color:var(--foreground);border-color:var(--border);background:0 0}.mtx-button[data-variant=ghost]:hover{background:var(--border)}.mtx-button[data-variant=chip]{background:var(--secondary-bg);color:var(--foreground)}.mtx-button[data-variant=chip]:hover{background:var(--primary);color:var(--primary-foreground);border-color:var(--primary)}.mtx-button[data-variant=bare],.mtx-button[data-variant=tab]{background:0 0;border-color:#0000;min-height:0;padding:0}.mtx-button[data-variant=bare]{color:inherit}.mtx-button[data-variant=tab]{color:var(--foreground-muted);flex:1;min-width:0;height:100%;position:relative}.mtx-button[data-variant=tab]:hover{color:var(--foreground)}.mtx-button[data-variant=tab][aria-selected=true]{color:var(--primary);font-weight:600}.mtx-button[data-stacked=true]{flex-direction:column;gap:2px}.mtx-button[data-full=true]{width:100%}.mtx-button[data-disabled=true]{opacity:.5;cursor:not-allowed;pointer-events:none}.mtx-icon-button{cursor:pointer;border:none;border-radius:9999px;flex-shrink:0;justify-content:center;align-items:center;transition:all .2s ease-in-out;display:inline-flex}.mtx-icon-button[data-size=xs]{width:20px;min-width:20px;height:20px}.mtx-icon-button[data-size=sm]{width:28px;min-width:28px;height:28px}.mtx-icon-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-icon-button[data-variant=primary]:hover{background:var(--primary-hover)}.mtx-icon-button[data-variant=secondary]{background:var(--secondary-bg);color:var(--foreground)}.mtx-icon-button[data-variant=secondary]:hover{background:var(--secondary-hover)}.mtx-icon-button[data-variant=ghost]{color:var(--foreground);opacity:.6;background:0 0}.mtx-icon-button[data-variant=ghost]:hover{opacity:1}.mtx-icon-button[data-disabled=true]{opacity:.5;cursor:not-allowed;pointer-events:none}.mtx-icon{flex-shrink:0;display:inline-block}.mtx-avatar{flex-shrink:0}.mtx-spinner-ring{border-style:solid;border-color:#0000 currentColor currentColor;border-radius:9999px;flex-shrink:0;animation:1s linear infinite mtx-spin}.mtx-visually-hidden{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.mtx-composer:focus-within{border-color:var(--foreground-faint)}.mtx-composer-input{resize:none;width:100%;min-height:0;color:var(--foreground);background:0 0;border:none;padding-left:12px;padding-right:12px;font-size:.875rem;display:block}.mtx-composer-input::placeholder{color:var(--foreground-faint)}.mtx-composer-input:focus{outline:none}.mtx-composer-input:disabled{cursor:not-allowed;opacity:.5}.mtx-mode-chip{cursor:pointer;background:var(--secondary-bg);color:var(--foreground-muted);border:none;border-radius:9999px;align-items:center;gap:2px;padding:2px 8px;font-size:11px;font-weight:500;transition:all .2s ease-in-out;display:inline-flex}.mtx-mode-chip[data-active=true]{background:var(--primary);color:var(--primary-foreground);box-shadow:var(--shadow-sm)}.mtx-toast-viewport{flex-direction:column;gap:8px;max-width:420px;display:flex;position:fixed;left:50%;transform:translate(-50%)}.mtx-toast{animation:mtx-fade-in var(--duration-animation) ease-out}.mtx-toast[data-ending-style]{opacity:0;transition:opacity var(--duration-animation) ease-out}.mtx-dialog-backdrop{animation:mtx-dialog-overlay-in var(--duration-fade) ease-out;background:#0003;position:fixed;inset:0}.mtx-dialog-popup{border-radius:var(--radius);background:var(--card);width:100%;max-width:24rem;max-height:85vh;animation:mtx-dialog-content-in var(--duration-animation) ease-out;flex-direction:column;padding:16px;display:flex;position:fixed;top:50%;left:50%;overflow:auto;transform:translate(-50%,-50%)}.mtx-dialog-title{color:var(--foreground);margin-bottom:4px;font-size:1rem;font-weight:600}.mtx-dialog-description{color:var(--foreground-muted);margin-bottom:16px;font-size:.875rem;line-height:1.625}.mtx-fab-anchor{position:fixed}.mtx-fab-anchor[data-preview=true]{position:absolute}.mtx-fab-anchor[data-animated=true]{transition:transform var(--duration-animation) ease-in-out}.mtx-fab{width:56px;height:56px;transition:all var(--duration-animation) ease-in-out;position:relative;overflow:visible}.mtx-fab[data-open=false]:hover{transform:scale(1.1)}.mtx-fab[data-open=true]{opacity:0;pointer-events:none;transform:scale(0)}.mtx-fab-trigger{z-index:10;width:56px;min-width:56px;height:56px;position:relative}.mtx-fab-center{justify-content:center;align-items:center;width:100%;height:100%;position:relative}.mtx-fab-badge{width:48px;height:48px;transition:transform .167s cubic-bezier(.33,0,0,1),opacity .167s cubic-bezier(.33,0,0,1),background-color .167s cubic-bezier(.33,0,0,1);animation:.25s ease-out forwards mtx-launcher-entrance;position:relative;overflow:hidden}.mtx-fab-badge:hover{transition-duration:.25s;transform:scale(1.1)}.mtx-fab-badge:active{transition-duration:.134s;transition-timing-function:cubic-bezier(.45,0,.2,1);transform:scale(.85)}.mtx-fab-icon-layer{justify-content:center;align-items:center;position:absolute;inset:0}.mtx-fab-avatar{z-index:10;object-fit:contain;width:100%;height:100%;position:relative}.mtx-fab-chevron{z-index:10;color:var(--foreground);pointer-events:none;position:relative}.mtx-fab-stop{z-index:20;text-transform:uppercase;letter-spacing:.025em;color:#fff;box-shadow:var(--shadow-lg);opacity:0;pointer-events:none;background:#111827;border:1px solid #ffffff40;border-radius:9999px;padding:4px 10px;font-size:11px;font-weight:600;transition:opacity .15s ease-in-out;position:absolute;top:50%;transform:translateY(-50%)}.mtx-fab-stop[data-side=left]{margin-left:8px;left:100%}.mtx-fab-stop[data-side=right]{margin-right:8px;right:100%}.mtx-fab:hover .mtx-fab-stop,.mtx-fab:focus-within .mtx-fab-stop{opacity:1;pointer-events:auto}.mtx-tab-underline{background:var(--primary);opacity:0;border-radius:9999px;height:2px;position:absolute;top:0;left:25%;right:25%}[aria-selected=true]>.mtx-tab-underline{opacity:1}.mtx-screenshare-dot{width:6px;height:6px;display:inline-flex;position:absolute;top:2px;right:2px}.mtx-screenshare-dot-ping{opacity:.75;background:currentColor;border-radius:9999px;width:100%;height:100%;animation:1s cubic-bezier(0,0,.2,1) infinite mtx-ping;display:inline-flex;position:absolute}.mtx-screenshare-dot-core{background:currentColor;border-radius:9999px;width:6px;height:6px;display:inline-flex;position:relative}.marketrix-widget-button-processing-glow,.marketrix-widget-button-error-glow{pointer-events:none;filter:blur(14px);will-change:transform, opacity;border-radius:50%;width:140%;height:140%;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}.marketrix-widget-button-processing-activity-ring,.marketrix-widget-button-error-activity-ring{pointer-events:none;z-index:0;position:absolute;inset:-3px;overflow:visible}.marketrix-widget-button-processing-activity-ring rect,.marketrix-widget-button-error-activity-ring rect{fill:none;stroke-width:2.5px;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:40 120;animation:1.9s cubic-bezier(.4,0,.2,1) infinite widget-activity-dash-travel}.marketrix-widget-button-processing-activity-ring rect{stroke:#31d06d;filter:drop-shadow(0 0 3px #31d06db3)}.marketrix-widget-button-error-activity-ring rect{stroke:#d0342c;filter:drop-shadow(0 0 3px #d0342cb3)}.marketrix-widget-button-processing-glow{animation:2s ease-in-out infinite widget-glow-green}.marketrix-widget-button-error-glow{animation:1.5s ease-in-out infinite widget-glow-red}[data-screen-edge-glow]{animation:1.6s ease-in-out infinite marketrix-screen-edge-pulse}[data-view-transition][data-direction=forward]{animation:.3s both viewSlideForward}[data-view-transition][data-direction=back]{animation:.3s both viewSlideBack}@keyframes mtx-spin{to{transform:rotate(360deg)}}@keyframes mtx-ping{75%,to{opacity:0;transform:scale(2)}}@keyframes mtx-pulse{50%{opacity:.5}}@keyframes mtx-dialog-overlay-in{0%{opacity:0}to{opacity:1}}@keyframes mtx-dialog-content-in{0%{opacity:0;scale:.96}to{opacity:1;scale:1}}@keyframes mtx-fade-in{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes mtx-launcher-entrance{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes marketrix-screen-edge-pulse{0%,to{opacity:.55}50%{opacity:1}}@keyframes widget-activity-dash-travel{0%{stroke-dashoffset:0;opacity:.5}18%{stroke-dashoffset:-112px;opacity:1}35%{stroke-dashoffset:-160px;opacity:.65}60%{stroke-dashoffset:-160px;opacity:.45}82%{stroke-dashoffset:-272px;opacity:1}to{stroke-dashoffset:-320px;opacity:.6}}@keyframes widget-glow-green{0%,to{opacity:.72;background:radial-gradient(circle,#31d06d00 38%,#31d06d61 58%,#31d06d3d 68%,#0000 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:1;background:radial-gradient(circle,#31d06d00 34%,#31d06d8c 56%,#31d06d54 68%,#0000 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes widget-glow-red{0%,to{opacity:.65;background:radial-gradient(circle,#d0342c00 38%,#d0342c57 58%,#d0342c38 68%,#0000 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:.95;background:radial-gradient(circle,#d0342c00 34%,#d0342c80 56%,#d0342c4d 68%,#0000 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes viewSlideForward{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes viewSlideBack{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}',n.appendChild(r);const o=document.createElement("div");return o.id=t,n.appendChild(o),{shadowRoot:n,mountEl:o}},jd=e=>{const t=e??document.body,n=document.createElement("div");n.className="marketrix-widget-container",n.style.pointerEvents="auto",e&&Object.assign(n.style,{width:"100%",height:"100%",position:"relative",overflow:"visible"}),t.appendChild(n);const{shadowRoot:r,mountEl:o}=Hd(n,"marketrix-widget-root");return Object.assign(o.style,{pointerEvents:"auto",width:"100%",height:"100%",position:"relative"}),{container:n,shadowRoot:r,mountEl:o}},qd=(e,n,r=!1)=>{const o=m(e);return o.render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(qc,{previewMode:r,children:/* @__PURE__ */b(Bd,{config:n})})})),o},Vd=()=>null!==Wd.mount,Yd=()=>Wd.mount?.config??null,Kd=(e,n="neutral")=>{if("undefined"==typeof window||"undefined"==typeof document)return;Xd();const r=document.createElement("div");r.id="marketrix-widget-notice-container",r.className="marketrix-widget-notice-container",document.body.appendChild(r);const{mountEl:o}=Hd(r,"marketrix-widget-notice-root");(Ud=m(o)).render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(Ga,{container:o,children:/* @__PURE__ */b(Za,{error:"error"===n?e:void 0,onClearError:Xd,greeting:"error"===n?void 0:e,onGreetingDismiss:Xd})})}))},Xd=()=>{Ud?.unmount(),Ud=null,document.getElementById("marketrix-widget-notice-container")?.remove()},Gd=null,Jd=0,Zd=null;function Qd(e,t,n=!1){const{container:r,mountEl:o}=jd(t),i=qd(o,e,n);Wd.mount={instance:i,config:e,container:r,host:t,previewMode:n}}var eu=(e,t)=>{if(Gd)return Gd;if(window.__mtx?.state)return Promise.resolve();if(Vd())return console.warn("Marketrix Widget: already initialized"),Promise.resolve();const n=async function(e,t,n){let r;window.__mtx={state:"initializing"},Kd("Loading widget settings...");try{(e=>{if(!e?.trim())throw new Error("API URL is required for SDK configuration");e!==Ie&&(Ie=e,Me=Ee(e))})(e.mtxApiHost??""),r=await async function(e){const{mtxId:t,mtxKey:n}=e;if(!t||!n)throw new Error("Please provide mtxId + mtxKey");let r;try{({items:r}=await Te.widgetSearch({marketrix_id:t,marketrix_key:n}))}catch(a){throw function(e,t){const n=Er(e);return n.includes("Failed to fetch")||n.includes("ERR_CONNECTION_REFUSED")||n.includes("NetworkError")||n.includes("Network request failed")?Ir(`Cannot connect to API server. Please ensure the API server is running at ${t.mtxApiHost||"configured API server"}. Error: ${n}`,e):Ir(`Widget validation failed: ${n}`,e)}(a,e)}if(!r.length)throw new Error("Widget not found or invalid credentials");const o=r.find(e=>"active"===e.status);if(!o){const e=r.map(e=>e.status).join(", ");throw new Error(`Found widget(s) but none are active. Current status(es): ${e}. Please activate the widget in the dashboard.`)}if(!o.application_id)throw new Error("Widget missing application_id");try{await Te.applicationGet({application_id:o.application_id})}catch(a){throw Ir(`Failed to validate application: ${Er(a)}`,a)}let i;try{i=await Te.widgetDefaultGet({type:"widget"})}catch(a){throw Ir(`Failed to fetch widget settings from API: ${Er(a)}`,a)}const s=Sr({...i,...o.settings});if(s.invalidFields)throw new Error(kr(s.invalidFields));return{...Cr(s.settings,e),mtxId:t,mtxKey:n,mtxApp:o.application_id}}(e)}catch(o){if(n!==Jd)return;return console.error("Marketrix Widget initialization failed:",o),Kd(o instanceof Error?o.message:"Failed to initialize widget","error"),void(window.__mtx=void 0)}n===Jd&&(Xd(),r.widget_enabled?(Ne.setConfig(r),Qd(r,t),window.__mtx={state:"active"},r.widget_recording&&r.mtxApp&&(async()=>{try{const e=await $e.getOrCreateChatId();if(n!==Jd)return;const t=new pr(e,r.mtxApp);Zd=t,await t.start(),n!==Jd&&(t.stop(),Zd===t&&(Zd=null))}catch(o){n===Jd&&console.error("Failed to start session recording:",o)}})()):window.__mtx=void 0)}(e,t,++Jd);return Gd=n,n.then(()=>{Gd===n&&(Gd=null)},()=>{Gd===n&&(Gd=null)}),n},tu=()=>{Jd++,ur.getInstance().disconnect(),Zd?.stop(),Zd=null,mr();const e=Wd.mount;Wd.mount=null,e&&(e.instance.unmount(),e.container.remove()),Gd=null,window.__mtx=void 0,Xd()},nu=async e=>{const t=Wd.mount;if(!t)return;const{config:n,host:r,previewMode:o}=t,i={...n,...e};tu(),o?Qd(i,r,!0):await eu(i,r)},ru=({settings:e,container:t})=>{const n=u(null),r=u(null),o=u(null);return a(()=>{const i=t??n.current??document.body;if(!(i&&(s=i,s instanceof HTMLElement)))return void console.error("MarketrixWidget: Invalid container");var s;const a=Sr(e);if(a.invalidFields)return void console.error(`Marketrix Widget: ${kr(a.invalidFields)}`);const{container:c,mountEl:l}=jd(i);return o.current=c,r.current=qd(l,{...Cr(a.settings),isPreviewMode:!0},!0),()=>{r.current&&(r.current.unmount(),r.current=null),o.current&&(o.current.remove(),o.current=null)}},[e,t]),t?null:/* @__PURE__ */b("div",{ref:n,style:{width:"100%",height:"100%",position:"relative"}})},ou=async e=>{const t=e.container;if(void 0!==e.settings){const n=Sr(e.settings);if(n.invalidFields)return void console.error(`Marketrix Widget: ${kr(n.invalidFields)}`);tu();const{settings:r,container:o,...i}=e;Qd({...Cr(n.settings,i),isPreviewMode:!0},t,!0)}else{if(void 0===e.mtxId||void 0===e.mtxKey)throw new Error("Invalid configuration: provide either settings (preview) or mtxId+mtxKey (production)");{const{container:n,...r}=e;await eu(r,t)}}};"undefined"!=typeof window&&setTimeout(()=>{try{(e=>{if("undefined"==typeof window||"undefined"==typeof document)return;if(window.__mtx?.state)return;const t=document.querySelectorAll("script[mtx-id]"),n=t[t.length-1];if(!(n&&(r=n,r instanceof HTMLScriptElement)))return;var r;const o=n.getAttribute("mtx-id"),i=n.getAttribute("mtx-key"),s=n.getAttribute("mtx-api-host");if(!o||!i||!s){if(Vd())return;return console.error("[AutoInit] Missing required attributes:",{hasMtxId:!!o,hasMtxKey:!!i,hasMtxApiHost:!!s}),void Kd("Please configure mtx-id, mtx-key and mtx-api-host","error")}const a={mtxId:o,mtxKey:i,mtxApiHost:s};"false"===n.getAttribute("mtx-use-screenshare")&&(a.use_screenshare=!1),e(a).catch(e=>console.error("[AutoInit] Failed to initialize widget:",e))})(eu)}catch(e){console.error("Marketrix Widget: Auto-init registration failed",e)}},0);var iu={MarketrixWidget:ru,mountWidget:ou,initWidget:eu,unmountWidget:tu,updateMarketrixConfig:nu,getCurrentConfig:Yd};export{ru as MarketrixWidget,iu as default,Yd as getCurrentConfig,eu as initWidget,ou as mountWidget,tu as unmountWidget,nu as updateMarketrixConfig};
|
|
65
|
+
/* @__PURE__ */b(Za,{error:i.error,onClearError:()=>s.setError(void 0),...c.canReconnect()&&{onRetry:()=>{s.setError(void 0),c.reconnectNow()}},greeting:t&&!i.error?e.widget_greeting:void 0,greetingBody:e.widget_body,onGreetingDismiss:()=>n(!1)})]})})})})},Wd={mount:null},Ud=null,Hd=(e,t)=>{const n=e.attachShadow({mode:"closed"}),r=document.createElement("style");r.textContent=':root,:host{--background:oklch(100% 0 0);--foreground:oklch(14.5% 0 0);--card:oklch(100% 0 0);--card-foreground:oklch(14.5% 0 0);--primary:oklch(20.5% 0 0);--primary-foreground:oklch(98.5% 0 0);--secondary:oklch(97% 0 0);--secondary-foreground:oklch(20.5% 0 0);--border:oklch(92.2% 0 0);--ring:oklch(70.8% 0 0);--foreground-muted:#1f293799;--foreground-faint:#1f293766;--primary-hover:#3b82f6d9;--secondary-bg:#6b728033;--secondary-hover:#6b72804d;--font-sans:"Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--radius:.625rem;--shadow-sm:0 1px 3px 0px #0000001a, 0 1px 2px -1px #0000001a;--shadow-lg:0 1px 3px 0px #0000001a, 0 4px 6px -1px #0000001a;--duration-animation:.3s;--duration-fade:.2s}*,:before,:after{box-sizing:border-box;border:0 solid var(--border);margin:0;padding:0}:host,[data-marketrix-widget]{font-family:var(--font-sans);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;line-height:1.5}:where([data-marketrix-widget]) :where(h1,h2,h3){font-size:inherit;font-weight:inherit}:where([data-marketrix-widget]) :where(img,svg,video,canvas){vertical-align:middle;display:block}:where([data-marketrix-widget]) :where(img,video){max-width:100%;height:auto}:where([data-marketrix-widget]) :where(button,input,textarea){font:inherit;color:inherit;background:0 0;border-radius:0}:where([data-marketrix-widget]) :where(button){appearance:button}:where([data-marketrix-widget]) :where(textarea){resize:vertical}[data-marketrix-widget] [hidden]{display:none!important}[data-marketrix-widget],[data-marketrix-widget] *{pointer-events:auto;transition:color .2s ease-in-out,background-color .2s ease-in-out,border-color .2s ease-in-out,opacity .2s ease-in-out,box-shadow .2s ease-in-out,transform .2s ease-in-out}[data-resizing=true],[data-resizing=true] *{transition:none!important}@media (prefers-reduced-motion:reduce){[data-marketrix-widget]{--duration-animation:0s!important;--duration-fade:0s!important}}.mtx-button{cursor:pointer;border:1px solid #0000;justify-content:center;align-items:center;gap:8px;font-weight:500;transition:all .2s ease-in-out;display:inline-flex}.mtx-button:focus-visible{outline:2px solid var(--ring);outline-offset:2px}.mtx-button[data-size=sm]{min-height:28px;padding:4px 8px;font-size:.75rem}.mtx-button[data-size=md]{min-height:36px;padding:8px 16px;font-size:.875rem}.mtx-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-button[data-variant=primary]:hover{background:color-mix(in oklab, var(--primary) 90%, transparent)}.mtx-button[data-variant=secondary]{background:var(--secondary);color:var(--secondary-foreground)}.mtx-button[data-variant=secondary]:hover{background:color-mix(in oklab, var(--secondary) 80%, transparent)}.mtx-button[data-variant=ghost]{color:var(--foreground);border-color:var(--border);background:0 0}.mtx-button[data-variant=ghost]:hover{background:var(--border)}.mtx-button[data-variant=chip]{background:var(--secondary-bg);color:var(--foreground)}.mtx-button[data-variant=chip]:hover{background:var(--primary);color:var(--primary-foreground);border-color:var(--primary)}.mtx-button[data-variant=bare],.mtx-button[data-variant=tab]{background:0 0;border-color:#0000;min-height:0;padding:0}.mtx-button[data-variant=bare]{color:inherit}.mtx-button[data-variant=tab]{color:var(--foreground-muted);flex:1;min-width:0;height:100%;position:relative}.mtx-button[data-variant=tab]:hover{color:var(--foreground)}.mtx-button[data-variant=tab][aria-selected=true]{color:var(--primary);font-weight:600}.mtx-button[data-stacked=true]{flex-direction:column;gap:2px}.mtx-button[data-full=true]{width:100%}.mtx-button[data-disabled=true]{opacity:.5;cursor:not-allowed;pointer-events:none}.mtx-icon-button{cursor:pointer;border:none;border-radius:9999px;flex-shrink:0;justify-content:center;align-items:center;transition:all .2s ease-in-out;display:inline-flex}.mtx-icon-button[data-size=xs]{width:20px;min-width:20px;height:20px}.mtx-icon-button[data-size=sm]{width:28px;min-width:28px;height:28px}.mtx-icon-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-icon-button[data-variant=primary]:hover{background:var(--primary-hover)}.mtx-icon-button[data-variant=secondary]{background:var(--secondary-bg);color:var(--foreground)}.mtx-icon-button[data-variant=secondary]:hover{background:var(--secondary-hover)}.mtx-icon-button[data-variant=ghost]{color:var(--foreground);opacity:.6;background:0 0}.mtx-icon-button[data-variant=ghost]:hover{opacity:1}.mtx-icon-button[data-disabled=true]{opacity:.5;cursor:not-allowed;pointer-events:none}.mtx-icon{flex-shrink:0;display:inline-block}.mtx-avatar{flex-shrink:0}.mtx-spinner-ring{border-style:solid;border-color:#0000 currentColor currentColor;border-radius:9999px;flex-shrink:0;animation:1s linear infinite mtx-spin}.mtx-visually-hidden{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.mtx-composer:focus-within{border-color:var(--foreground-faint)}.mtx-composer-input{resize:none;width:100%;min-height:0;color:var(--foreground);background:0 0;border:none;padding-left:12px;padding-right:12px;font-size:.875rem;display:block}.mtx-composer-input::placeholder{color:var(--foreground-faint)}.mtx-composer-input:focus{outline:none}.mtx-composer-input:disabled{cursor:not-allowed;opacity:.5}.mtx-mode-chip{cursor:pointer;background:var(--secondary-bg);color:var(--foreground-muted);border:none;border-radius:9999px;align-items:center;gap:2px;padding:2px 8px;font-size:11px;font-weight:500;transition:all .2s ease-in-out;display:inline-flex}.mtx-mode-chip[data-active=true]{background:var(--primary);color:var(--primary-foreground);box-shadow:var(--shadow-sm)}.mtx-toast-viewport{flex-direction:column;gap:8px;max-width:420px;display:flex;position:fixed;left:50%;transform:translate(-50%)}.mtx-toast{animation:mtx-fade-in var(--duration-animation) ease-out}.mtx-toast[data-ending-style]{opacity:0;transition:opacity var(--duration-animation) ease-out}.mtx-dialog-backdrop{animation:mtx-dialog-overlay-in var(--duration-fade) ease-out;background:#0003;position:fixed;inset:0}.mtx-dialog-popup{border-radius:var(--radius);background:var(--card);width:100%;max-width:24rem;max-height:85vh;animation:mtx-dialog-content-in var(--duration-animation) ease-out;flex-direction:column;padding:16px;display:flex;position:fixed;top:50%;left:50%;overflow:auto;transform:translate(-50%,-50%)}.mtx-dialog-title{color:var(--foreground);margin-bottom:4px;font-size:1rem;font-weight:600}.mtx-dialog-description{color:var(--foreground-muted);margin-bottom:16px;font-size:.875rem;line-height:1.625}.mtx-fab-anchor{position:fixed}.mtx-fab-anchor[data-preview=true]{position:absolute}.mtx-fab-anchor[data-animated=true]{transition:transform var(--duration-animation) ease-in-out}.mtx-fab{width:56px;height:56px;transition:all var(--duration-animation) ease-in-out;position:relative;overflow:visible}.mtx-fab[data-open=false]:hover{transform:scale(1.1)}.mtx-fab[data-open=true]{opacity:0;pointer-events:none;transform:scale(0)}.mtx-fab-trigger{z-index:10;width:56px;min-width:56px;height:56px;position:relative}.mtx-fab-center{justify-content:center;align-items:center;width:100%;height:100%;position:relative}.mtx-fab-badge{width:48px;height:48px;transition:transform .167s cubic-bezier(.33,0,0,1),opacity .167s cubic-bezier(.33,0,0,1),background-color .167s cubic-bezier(.33,0,0,1);animation:.25s ease-out forwards mtx-launcher-entrance;position:relative;overflow:hidden}.mtx-fab-badge:hover{transition-duration:.25s;transform:scale(1.1)}.mtx-fab-badge:active{transition-duration:.134s;transition-timing-function:cubic-bezier(.45,0,.2,1);transform:scale(.85)}.mtx-fab-icon-layer{justify-content:center;align-items:center;position:absolute;inset:0}.mtx-fab-avatar{z-index:10;object-fit:contain;width:100%;height:100%;position:relative}.mtx-fab-chevron{z-index:10;color:var(--foreground);pointer-events:none;position:relative}.mtx-fab-stop{z-index:20;text-transform:uppercase;letter-spacing:.025em;color:#fff;box-shadow:var(--shadow-lg);opacity:0;pointer-events:none;background:#111827;border:1px solid #ffffff40;border-radius:9999px;padding:4px 10px;font-size:11px;font-weight:600;transition:opacity .15s ease-in-out;position:absolute;top:50%;transform:translateY(-50%)}.mtx-fab-stop[data-side=left]{margin-left:8px;left:100%}.mtx-fab-stop[data-side=right]{margin-right:8px;right:100%}.mtx-fab:hover .mtx-fab-stop,.mtx-fab:focus-within .mtx-fab-stop{opacity:1;pointer-events:auto}.mtx-tab-underline{background:var(--primary);opacity:0;border-radius:9999px;height:2px;position:absolute;top:0;left:25%;right:25%}[aria-selected=true]>.mtx-tab-underline{opacity:1}.mtx-screenshare-dot{width:6px;height:6px;display:inline-flex;position:absolute;top:2px;right:2px}.mtx-screenshare-dot-ping{opacity:.75;background:currentColor;border-radius:9999px;width:100%;height:100%;animation:1s cubic-bezier(0,0,.2,1) infinite mtx-ping;display:inline-flex;position:absolute}.mtx-screenshare-dot-core{background:currentColor;border-radius:9999px;width:6px;height:6px;display:inline-flex;position:relative}.marketrix-widget-button-processing-glow,.marketrix-widget-button-error-glow{pointer-events:none;filter:blur(14px);will-change:transform, opacity;border-radius:50%;width:140%;height:140%;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}.marketrix-widget-button-processing-activity-ring,.marketrix-widget-button-error-activity-ring{pointer-events:none;z-index:0;position:absolute;inset:-3px;overflow:visible}.marketrix-widget-button-processing-activity-ring rect,.marketrix-widget-button-error-activity-ring rect{fill:none;stroke-width:2.5px;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:40 120;animation:1.9s cubic-bezier(.4,0,.2,1) infinite widget-activity-dash-travel}.marketrix-widget-button-processing-activity-ring rect{stroke:#31d06d;filter:drop-shadow(0 0 3px #31d06db3)}.marketrix-widget-button-error-activity-ring rect{stroke:#d0342c;filter:drop-shadow(0 0 3px #d0342cb3)}.marketrix-widget-button-processing-glow{animation:2s ease-in-out infinite widget-glow-green}.marketrix-widget-button-error-glow{animation:1.5s ease-in-out infinite widget-glow-red}[data-screen-edge-glow]{animation:1.6s ease-in-out infinite marketrix-screen-edge-pulse}[data-view-transition][data-direction=forward]{animation:.3s both viewSlideForward}[data-view-transition][data-direction=back]{animation:.3s both viewSlideBack}@keyframes mtx-spin{to{transform:rotate(360deg)}}@keyframes mtx-ping{75%,to{opacity:0;transform:scale(2)}}@keyframes mtx-pulse{50%{opacity:.5}}@keyframes mtx-dialog-overlay-in{0%{opacity:0}to{opacity:1}}@keyframes mtx-dialog-content-in{0%{opacity:0;scale:.96}to{opacity:1;scale:1}}@keyframes mtx-fade-in{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes mtx-launcher-entrance{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes marketrix-screen-edge-pulse{0%,to{opacity:.55}50%{opacity:1}}@keyframes widget-activity-dash-travel{0%{stroke-dashoffset:0;opacity:.5}18%{stroke-dashoffset:-112px;opacity:1}35%{stroke-dashoffset:-160px;opacity:.65}60%{stroke-dashoffset:-160px;opacity:.45}82%{stroke-dashoffset:-272px;opacity:1}to{stroke-dashoffset:-320px;opacity:.6}}@keyframes widget-glow-green{0%,to{opacity:.72;background:radial-gradient(circle,#31d06d00 38%,#31d06d61 58%,#31d06d3d 68%,#0000 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:1;background:radial-gradient(circle,#31d06d00 34%,#31d06d8c 56%,#31d06d54 68%,#0000 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes widget-glow-red{0%,to{opacity:.65;background:radial-gradient(circle,#d0342c00 38%,#d0342c57 58%,#d0342c38 68%,#0000 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:.95;background:radial-gradient(circle,#d0342c00 34%,#d0342c80 56%,#d0342c4d 68%,#0000 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes viewSlideForward{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes viewSlideBack{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}',n.appendChild(r);const o=document.createElement("div");return o.id=t,n.appendChild(o),{shadowRoot:n,mountEl:o}},jd=e=>{const t=e??document.body,n=document.createElement("div");n.className="marketrix-widget-container",n.style.pointerEvents="auto",e&&Object.assign(n.style,{width:"100%",height:"100%",position:"relative",overflow:"visible"}),t.appendChild(n);const{shadowRoot:r,mountEl:o}=Hd(n,"marketrix-widget-root");return Object.assign(o.style,{pointerEvents:"auto",width:"100%",height:"100%",position:"relative"}),{container:n,shadowRoot:r,mountEl:o}},qd=(e,n,r=!1)=>{const o=m(e);return o.render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(qc,{previewMode:r,children:/* @__PURE__ */b(Bd,{config:n})})})),o},Vd=()=>null!==Wd.mount,Yd=()=>Wd.mount?.config??null,Kd=(e,n="neutral")=>{if("undefined"==typeof window||"undefined"==typeof document)return;Xd();const r=document.createElement("div");r.id="marketrix-widget-notice-container",r.className="marketrix-widget-notice-container",document.body.appendChild(r);const{mountEl:o}=Hd(r,"marketrix-widget-notice-root");(Ud=m(o)).render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(Ga,{container:o,children:/* @__PURE__ */b(Za,{error:"error"===n?e:void 0,onClearError:Xd,greeting:"error"===n?void 0:e,onGreetingDismiss:Xd})})}))},Xd=()=>{Ud?.unmount(),Ud=null,document.getElementById("marketrix-widget-notice-container")?.remove()},Gd=null,Jd=0,Zd=null;function Qd(e,t,n=!1){const{container:r,mountEl:o}=jd(t),i=qd(o,e,n);Wd.mount={instance:i,config:e,container:r,host:t,previewMode:n}}var eu=(e,t)=>{if(Gd)return Gd;if(window.__mtx?.state)return Promise.resolve();if(Vd())return console.warn("Marketrix Widget: already initialized"),Promise.resolve();const n=async function(e,t,n){let r;window.__mtx={state:"initializing"},Kd("Loading widget settings...");try{(e=>{if(!e?.trim())throw new Error("API URL is required for SDK configuration");e!==Ie&&(Ie=e,Me=Ee(e))})(e.mtxApiHost??""),r=await async function(e){const{mtxId:t,mtxKey:n}=e;if(!t||!n)throw new Error("Please provide mtxId + mtxKey");let r;try{({items:r}=await Te.widgetSearch({marketrix_id:t,marketrix_key:n}))}catch(a){throw function(e,t){const n=Er(e);return n.includes("Failed to fetch")||n.includes("ERR_CONNECTION_REFUSED")||n.includes("NetworkError")||n.includes("Network request failed")?Ir(`Cannot connect to API server. Please ensure the API server is running at ${t.mtxApiHost||"configured API server"}. Error: ${n}`,e):Ir(`Widget validation failed: ${n}`,e)}(a,e)}if(!r.length)throw new Error("Widget not found or invalid credentials");const o=r.find(e=>"active"===e.status);if(!o){const e=r.map(e=>e.status).join(", ");throw new Error(`Found widget(s) but none are active. Current status(es): ${e}. Please activate the widget in the dashboard.`)}if(!o.application_id)throw new Error("Widget missing application_id");try{await Te.applicationGet({application_id:o.application_id})}catch(a){throw Ir(`Failed to validate application: ${Er(a)}`,a)}let i;try{i=await Te.widgetDefaultGet({type:"widget"})}catch(a){throw Ir(`Failed to fetch widget settings from API: ${Er(a)}`,a)}const s=Sr({...i,...o.settings});if(s.invalidFields)throw new Error(kr(s.invalidFields));return{...Cr(s.settings,e),mtxId:t,mtxKey:n,mtxApp:o.application_id}}(e)}catch(o){if(n!==Jd)return;return console.error("Marketrix Widget initialization failed:",o),Kd(o instanceof Error?o.message:"Failed to initialize widget","error"),void(window.__mtx=void 0)}n===Jd&&(Xd(),r.widget_enabled?(Ne.setConfig(r),Qd(r,t),window.__mtx={state:"active"},r.widget_recording&&r.mtxApp&&(async()=>{try{const e=await $e.getOrCreateChatId();if(n!==Jd)return;const t=new pr(e,r.mtxApp);Zd=t,await t.start(),n!==Jd&&(t.stop(),Zd===t&&(Zd=null))}catch(o){n===Jd&&console.error("Failed to start session recording:",o)}})()):window.__mtx=void 0)}(e,t,++Jd);return Gd=n,n.then(()=>{Gd===n&&(Gd=null)},()=>{Gd===n&&(Gd=null)}),n},tu=()=>{Jd++,ur.getInstance().disconnect(),Zd?.stop(),Zd=null,mr();const e=Wd.mount;Wd.mount=null,e&&(e.instance.unmount(),e.container.remove()),Gd=null,window.__mtx=void 0,Xd()},nu=async e=>{const t=Wd.mount;if(!t)return;const{config:n,host:r,previewMode:o}=t,i={...n,...e};tu(),o?Qd(i,r,!0):await eu(i,r)},ru=({settings:e,container:t})=>{const n=u(null),r=u(null),o=u(null);return a(()=>{const i=t??n.current??document.body;if(!(i&&(s=i,s instanceof HTMLElement)))return void console.error("MarketrixWidgetPreview: Invalid container");var s;const a=Sr(e);if(a.invalidFields)return void console.error(`Marketrix Widget: ${kr(a.invalidFields)}`);const{container:c,mountEl:l}=jd(i);return o.current=c,r.current=qd(l,{...Cr(a.settings),isPreviewMode:!0},!0),()=>{r.current&&(r.current.unmount(),r.current=null),o.current&&(o.current.remove(),o.current=null)}},[e,t]),t?null:/* @__PURE__ */b("div",{ref:n,style:{width:"100%",height:"100%",position:"relative"}})},ou=async e=>{const t=e.container;if(void 0!==e.settings){const n=Sr(e.settings);if(n.invalidFields)return void console.error(`Marketrix Widget: ${kr(n.invalidFields)}`);tu();const{settings:r,container:o,...i}=e;Qd({...Cr(n.settings,i),isPreviewMode:!0},t,!0)}else{if(void 0===e.mtxId||void 0===e.mtxKey)throw new Error("Invalid configuration: provide either settings (preview) or mtxId+mtxKey (production)");{const{container:n,...r}=e;await eu(r,t)}}};"undefined"!=typeof window&&setTimeout(()=>{try{(e=>{if("undefined"==typeof window||"undefined"==typeof document)return;if(window.__mtx?.state)return;const t=document.querySelectorAll("script[mtx-id]"),n=t[t.length-1];if(!(n&&(r=n,r instanceof HTMLScriptElement)))return;var r;const o=n.getAttribute("mtx-id"),i=n.getAttribute("mtx-key"),s=n.getAttribute("mtx-api-host");if(!o||!i||!s){if(Vd())return;return console.error("[AutoInit] Missing required attributes:",{hasMtxId:!!o,hasMtxKey:!!i,hasMtxApiHost:!!s}),void Kd("Please configure mtx-id, mtx-key and mtx-api-host","error")}const a={mtxId:o,mtxKey:i,mtxApiHost:s};"false"===n.getAttribute("mtx-use-screenshare")&&(a.use_screenshare=!1),e(a).catch(e=>console.error("[AutoInit] Failed to initialize widget:",e))})(eu)}catch(e){console.error("Marketrix Widget: Auto-init registration failed",e)}},0);var iu={MarketrixWidgetPreview:ru,mountWidget:ou,initWidget:eu,unmountWidget:tu,updateMarketrixConfig:nu,getCurrentConfig:Yd};export{ru as MarketrixWidgetPreview,iu as default,Yd as getCurrentConfig,eu as initWidget,ou as mountWidget,tu as unmountWidget,nu as updateMarketrixConfig};
|