@marketrix.ai/widget 3.8.489 → 3.8.490

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/widget.mjs CHANGED
@@ -1,65 +1,65 @@
1
- import*as e from"react";import t,{createContext as n,createElement as r,forwardRef as o,useCallback as i,useContext as s,useEffect as a,useImperativeHandle as c,useLayoutEffect as l,useMemo as d,useRef as u,useState as p,useSyncExternalStore as h,useSyncExternalStore as f}from"react";import{createRoot as m}from"react-dom/client";import*as g from"react-dom";import{Fragment as y,jsx as b,jsxs as v}from"react/jsx-runtime";function w(e){return Array.isArray(e)?e:null==e?[]:[e]}var x="orpc",S=class extends Error{constructor(...e){super(...e),this.name="AbortError"}};function k(e){let t;return()=>{if(t)return t.result;const n=e();return t={result:n},n}}function C(){return globalThis["__@orpc/shared@1.15.0/otel/config__"]}function E(e,t={},n){return(C()?.tracer)?.startSpan(e,t,n)}function I(e,t,n={}){if(!e)return;const r=function(e){if(e instanceof Error){const t={message:e.message,name:e.name,stack:e.stack};return!("code"in e)||"string"!=typeof e.code&&"number"!=typeof e.code||(t.code=e.code),t}return{message:String(e)}}(t);e.recordException(r),n.signal?.aborted&&n.signal.reason===t||e.setStatus({code:2,message:r.message})}async function M({name:e,context:t,...n},r){const o=C()?.tracer;if(!o)return r();const i=async e=>{try{return await r(e)}catch(t){throw I(e,t,n),t}finally{e.end()}};return t?o.startActiveSpan(e,n,t,i):o.startActiveSpan(e,n,i)}async function T(e,t){const n=C();if(!e||!n)return t();const r=n.trace.setSpan(n.context.active(),e);return n.context.with(r,t)}function R(e){return!(!e||"object"!=typeof e)&&"next"in e&&"function"==typeof e.next&&Symbol.asyncIterator in e&&"function"==typeof e[Symbol.asyncIterator]}var O=Symbol.asyncDispose??Symbol.for("asyncDispose"),A=class{#e=!1;#t=!1;#n;#r;constructor(e,t){this.#n=t,this.#r=function(e){let t=Promise.resolve();return(...n)=>t=t.catch(()=>{}).then(()=>e(...n))}(async()=>{if(this.#e)return{done:!0,value:void 0};try{const t=await e();return t.done&&(this.#e=!0),t}catch(t){throw this.#e=!0,t}finally{this.#e&&!this.#t&&(this.#t=!0,await this.#n("next"))}})}next(){return this.#r()}async return(e){return this.#e=!0,this.#t||(this.#t=!0,await this.#n("return")),{done:!0,value:e}}async throw(e){throw this.#e=!0,this.#t||(this.#t=!0,await this.#n("throw")),e}async[O](){this.#e=!0,this.#t||(this.#t=!0,await this.#n("dispose"))}[Symbol.asyncIterator](){return this}};function _({name:e,...t},n){let r;return new A(async()=>{r??=E(e);try{const e=await T(r,()=>n.next());return r?.addEvent(e.done?"completed":"yielded"),e}catch(o){throw I(r,o,t),o}},async e=>{try{"next"!==e&&await T(r,()=>n.return?.())}catch(o){throw I(r,o,t),o}finally{r?.end()}})}function D(e,t,n){const r=(t,o)=>{const i=e[o];return i?i({...t,next:(e=t)=>r(e,o+1)}):n(t)};return r(t,0)}function P(e){if(e)return JSON.parse(e)}function N(e){return JSON.stringify(e)}function L(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||!t||!t.constructor}function F(e){return!!e&&("object"==typeof e||"function"==typeof e)}function z(e,...t){return"function"==typeof e?e(...t):e}function $(e){return new Proxy(e,{get(e,t,n){const r=Reflect.get(e,t,n);return"then"!==t||"function"!=typeof r?r:new Proxy(r,{apply(t,n,r){if(2!==r.length||r.some(e=>{return!("function"==typeof(t=e)&&W.test(t.toString()));var t}))return Reflect.apply(t,n,r);let o=!0;r[0].call(n,$(new Proxy(e,{get:(e,t,n)=>{if(!o||"then"!==t)return Reflect.get(e,t,n);o=!1}})))}})}})}var B,W=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/,U=/* @__PURE__ */new Set(["bind","valueOf","toString","toJSON"]),H={BAD_REQUEST:{status:400,message:"Bad Request"},UNAUTHORIZED:{status:401,message:"Unauthorized"},FORBIDDEN:{status:403,message:"Forbidden"},NOT_FOUND:{status:404,message:"Not Found"},METHOD_NOT_SUPPORTED:{status:405,message:"Method Not Supported"},NOT_ACCEPTABLE:{status:406,message:"Not Acceptable"},TIMEOUT:{status:408,message:"Request Timeout"},CONFLICT:{status:409,message:"Conflict"},PRECONDITION_FAILED:{status:412,message:"Precondition Failed"},PAYLOAD_TOO_LARGE:{status:413,message:"Payload Too Large"},UNSUPPORTED_MEDIA_TYPE:{status:415,message:"Unsupported Media Type"},UNPROCESSABLE_CONTENT:{status:422,message:"Unprocessable Content"},TOO_MANY_REQUESTS:{status:429,message:"Too Many Requests"},CLIENT_CLOSED_REQUEST:{status:499,message:"Client Closed Request"},INTERNAL_SERVER_ERROR:{status:500,message:"Internal Server Error"},NOT_IMPLEMENTED:{status:501,message:"Not Implemented"},BAD_GATEWAY:{status:502,message:"Bad Gateway"},SERVICE_UNAVAILABLE:{status:503,message:"Service Unavailable"},GATEWAY_TIMEOUT:{status:504,message:"Gateway Timeout"}},j=class e extends Error{defined;code;status;data;static{const t=Symbol.for("__@orpc/client@1.15.0/error/ORPC_ERROR_CONSTRUCTORS__");globalThis[t]??=/* @__PURE__ */new WeakSet,(B=globalThis[t]).add(e)}constructor(e,...t){const n=function(e){return e[0]??{}}(t);if(void 0!==n.status&&!q(n.status))throw new Error("[ORPCError] Invalid error status code.");const r=function(e,t){return t||H[e]?.message||e}(e,n.message);super(r,n),this.code=e,this.status=function(e,t){return t??H[e]?.status??500}(e,n.status),this.defined=n.defined??!1,this.data=n.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance](e){if(B.has(this)){const t=function(e){return F(e)?Object.getPrototypeOf(e)?.constructor:null}(e);if(t&&B.has(t))return!0}return super[Symbol.hasInstance](e)}};function q(e){return e<200||e>=400}function V(e){if(!L(e))return!1;const t=["defined","code","status","message","data"];return!Object.keys(e).some(e=>!t.includes(e))&&"defined"in e&&"boolean"==typeof e.defined&&"code"in e&&"string"==typeof e.code&&"status"in e&&"number"==typeof e.status&&q(e.status)&&"message"in e&&"string"==typeof e.message}function Y(e,t={}){return new j(e.code,{...t,...e})}var K=class extends TypeError{},X=class extends TypeError{},G=class extends Error{data;constructor(e){super(e?.message??"An error event was received",e),this.data=e?.data}},J=/\r\n|\r(?!\n)|\n/,Z=/(?:\r\n|\r(?!\n)|\n){2}/,Q=/(?:\r\n|\r(?!\n)|\n){2}/g;function ee(e){const t={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(const n of e.split(J)){if(""===n)continue;const e=n.indexOf(":"),r=-1===e?"":n.slice(32===n.charCodeAt(e+1)?e+2:e+1);if(0!==e)switch(-1===e?n:n.slice(0,e)){case"data":t.data=void 0===t.data?r:`${t.data}\n${r}`;break;case"event":t.event=r;break;case"id":t.id=r;break;case"retry":{const e=Number.parseInt(r,10);e>=0&&e.toString()===r&&(t.retry=e);break}}else t.comments.push(r)}return t}var te=class{constructor(e={}){this.options=e}pending=[];tail="";discardLeadingLF=!1;feed(e){if(""===e)return;if(this.discardLeadingLF&&(this.discardLeadingLF=!1,10===e.charCodeAt(0)&&""===(e=e.slice(1))))return;const t=this.tail+e;if(!Z.test(t))return this.pending.push(e),void(this.tail=t.slice(-3));this.pending.push(e);const n=1===this.pending.length?e:this.pending.join(""),r=n.length-t.length,o=[];let i=0;for(const a of t.matchAll(Q))o.push(n.slice(i,r+a.index)),i=r+a.index+a[0].length;const s=n.slice(i);this.pending.length=0,this.tail=s.slice(-3),""===s?this.discardLeadingLF=13===e.charCodeAt(e.length-1):this.pending.push(s);for(const a of o){const e=ee(a);this.options.onEvent&&this.options.onEvent(e)}}end(){if(0!==this.pending.length)throw new X("Event Iterator ended before complete")}},ne=class extends TransformStream{constructor(){let e;super({start(t){e=new te({onEvent:e=>{t.enqueue(e)}})},transform(t){e.feed(t)},flush(){e.end()}})}},re=/\r\n|[\n\r]/,oe=/\r\n|[\n\r]/g;function ie(e){return re.test(e)}function se(e){if(ie(e))throw new K("Event's id must not contain a carriage return or newline character")}function ae(e){if(!Number.isInteger(e)||e<0)throw new K("Event's retry must be a integer and >= 0")}function ce(e){if(ie(e))throw new K("Event's comment must not contain a carriage return or newline character")}function le(e){let t="";var n;return t+=function(e){let t="";for(const n of e??[])ce(n),t+=`: ${n}\n`;return t}(e.comments),void 0!==e.event&&(function(e){if(ie(e))throw new K("Event's event must not contain a carriage return or newline character")}(e.event),t+=`event: ${e.event}\n`),void 0!==e.retry&&(ae(e.retry),t+=`retry: ${e.retry}\n`),void 0!==e.id&&(se(e.id),t+=`id: ${e.id}\n`),t+=void 0===(n=e.data)?"":`data: ${n.replace(oe,"\ndata: ")}\n`,t+="\n",t}var de=Symbol("ORPC_EVENT_SOURCE_META");function ue(e,t){if(void 0===t.id&&void 0===t.retry&&!t.comments?.length)return e;if(void 0!==t.id&&se(t.id),void 0!==t.retry&&ae(t.retry),void 0!==t.comments)for(const n of t.comments)ce(n);return new Proxy(e,{get:(e,n,r)=>n===de?t:Reflect.get(e,n,r)})}function pe(e){return F(e)?Reflect.get(e,de):void 0}function he(e,t){const n=async e=>{let n=await t.error(e);if(n!==e){const t=pe(e);t&&F(n)&&(n=ue(n,t))}return n};return new A(async()=>{const{done:r,value:o}=await(async()=>{try{return await e.next()}catch(t){throw await n(t)}})();let i=await t.value(o,r);if(i!==o){const e=pe(o);e&&F(i)&&(i=ue(i,e))}return{done:r,value:i}},async()=>{try{await(e.return?.())}catch(t){throw await n(t)}})}function fe(e,t={}){const n=t.path??[];return $(new Proxy(async(...[t,r={}])=>await e.call(n,t,function(e){return{...e,context:e.context??{}}}(r)),{get:(r,o)=>"string"!=typeof o||U.has(o)?Reflect.get(r,o):fe(e,{...t,path:[...n,o]})}))}function me(e,t={}){return e.forEach((e,n)=>{Array.isArray(t[n])?t[n].push(e):void 0!==t[n]?t[n]=[t[n],e]:t[n]=e}),t}var ge=class{plugins;constructor(e=[]){this.plugins=[...e].sort((e,t)=>(e.order??0)-(t.order??0))}init(e){for(const t of this.plugins)t.init?.(e)}},ye=class{constructor(e,t,n={}){this.codec=e,this.sender=t,new ge(n.plugins).init(n),this.interceptors=w(n.interceptors),this.clientInterceptors=w(n.clientInterceptors)}interceptors;clientInterceptors;call(e,t,n){return M({name:`${x}.${e.join("/")}`,signal:n.signal},r=>(r?.setAttribute("rpc.system",x),r?.setAttribute("rpc.method",e.join(".")),R(t)&&(t=_({name:"consume_event_iterator_input",signal:n.signal},t)),D(this.interceptors,{...n,path:e,input:t},async({path:e,input:t,...n})=>{const o=C();let i;const s=o?.trace.getActiveSpan()??r;s&&o&&(i=o?.trace.setSpan(o.context.active(),s));const a=await M({name:"encode_request",context:i},()=>this.codec.encode(e,t,n)),c=await D(this.clientInterceptors,{...n,input:t,path:e,request:a},({input:e,path:t,request:n,...r})=>M({name:"send_request",signal:r.signal,context:i},()=>this.sender.call(n,r,t,e))),l=await M({name:"decode_response",context:i},()=>this.codec.decode(c,n,e,t));return R(l)?_({name:"consume_event_iterator_output",signal:n.signal},l):l})))}},be=class{customSerializers;constructor(e={}){if(this.customSerializers=e.customJsonSerializers??[],this.customSerializers.length!==new Set(this.customSerializers.map(e=>e.type)).size)throw new Error("Custom serializer type must be unique.")}serialize(e,t=[],n=[],r=[],o=[]){for(const i of this.customSerializers)if(i.condition(e)){const s=this.serialize(i.serialize(e),t,n,r,o);return n.push([i.type,...t]),s}if(e instanceof Blob)return r.push(t),o.push(e),[e,n,r,o];if("bigint"==typeof e)return n.push([0,...t]),[e.toString(),n,r,o];if(e instanceof Date)return n.push([1,...t]),Number.isNaN(e.getTime())?[null,n,r,o]:[e.toISOString(),n,r,o];if(Number.isNaN(e))return n.push([2,...t]),[null,n,r,o];if(e instanceof URL)return n.push([4,...t]),[e.toString(),n,r,o];if(e instanceof RegExp)return n.push([5,...t]),[e.toString(),n,r,o];if(e instanceof Set){const i=this.serialize(Array.from(e),t,n,r,o);return n.push([6,...t]),i}if(e instanceof Map){const i=this.serialize(Array.from(e.entries()),t,n,r,o);return n.push([7,...t]),i}if(Array.isArray(e))return[e.map((e,i)=>void 0===e?(n.push([3,...t,i]),null):this.serialize(e,[...t,i],n,r,o)[0]),n,r,o];if(L(e)){const i={};for(const s in e)"toJSON"===s&&"function"==typeof e[s]||(i[s]=this.serialize(e[s],[...t,s],n,r,o)[0]);return[i,n,r,o]}return[e,n,r,o]}deserialize(e,t,n,r){const o={data:e};n&&r&&n.forEach((e,t)=>{let n=o,i="data";e.forEach(e=>{if(n=n[i],i=e,!Object.hasOwn(n,i))throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${i}`)}),n[i]=r(t)});for(const i of t){const e=i[0];let t=o,n="data";for(let r=1;r<i.length;r++)if(t=t[n],n=i[r],!Object.hasOwn(t,n))throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${n}`);for(const r of this.customSerializers)if(r.type===e){t[n]=r.deserialize(t[n]);break}switch(e){case 0:t[n]=BigInt(t[n]);break;case 1:t[n]=new Date(t[n]??"Invalid Date");break;case 2:t[n]=NaN;break;case 3:t[n]=void 0;break;case 4:t[n]=new URL(t[n]);break;case 5:{const[,e,r]=t[n].match(/^\/(.*)\/([a-z]*)$/);t[n]=new RegExp(e,r);break}case 6:t[n]=new Set(t[n]);break;case 7:t[n]=new Map(t[n])}}return o.data}},ve=class{constructor(e,t){this.serializer=e,this.baseUrl=t.url,this.maxUrlLength=t.maxUrlLength??2083,this.fallbackMethod=t.fallbackMethod??"POST",this.expectedMethod=t.method??this.fallbackMethod,this.headers=t.headers??{}}baseUrl;maxUrlLength;fallbackMethod;expectedMethod;headers;async encode(e,t,n){let r=function(e){return"function"==typeof e.forEach?me(e):e}(await z(this.headers,n,e,t));void 0!==n.lastEventId&&(r=function(e,t){const n={...e};for(const r in t)Array.isArray(t[r])?n[r]=[...w(n[r]),...t[r]]:void 0!==t[r]&&(Array.isArray(n[r])?n[r]=[...n[r],t[r]]:void 0!==n[r]?n[r]=[n[r],t[r]]:n[r]=t[r]);return n}(r,{"last-event-id":n.lastEventId}));const o=await z(this.expectedMethod,n,e,t),i=await z(this.baseUrl,n,e,t),s=new URL(i);s.pathname=`${s.pathname.replace(/\/$/,"")}${function(e){return`/${e.map(encodeURIComponent).join("/")}`}(e)}`;const a=this.serializer.serialize(t);if(!("GET"!==o||a instanceof FormData||R(a))){const i=await z(this.maxUrlLength,n,e,t),c=new URL(s);if(c.searchParams.append("data",N(a)),c.toString().length<=i)return{body:void 0,method:o,headers:r,url:c,signal:n.signal}}return{url:s,method:"GET"===o?this.fallbackMethod:o,headers:r,body:a,signal:n.signal}}async decode(e){const t=!q(e.status),n=await(async()=>{let t=!1;try{const n=await e.body();return t=!0,this.serializer.deserialize(n)}catch(n){if(!t)throw new Error("Cannot parse response body, please check the response body and content-type.",{cause:n});throw new Error("Invalid RPC response format.",{cause:n})}})();if(!t){if(V(n))throw Y(n);throw new j((r=e.status,Object.entries(H).find(([,e])=>e.status===r)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"),{status:e.status,data:{...e,body:n}})}var r;return n}},we=class{constructor(e){this.jsonSerializer=e}serialize(e){return R(e)?he(e,{value:async e=>this.#o(e,!1),error:async e=>{return new G({data:this.#o((t=e,t instanceof j?t:new j("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:t})).toJSON(),!1),cause:e});var t}}):this.#o(e,!0)}#o(e,t){const[n,r,o,i]=this.jsonSerializer.serialize(e),s=0===r.length?void 0:r;if(!t||0===i.length)return{json:n,meta:s};const a=new FormData;return a.set("data",N({json:n,meta:s,maps:o})),i.forEach((e,t)=>{a.set(t.toString(),e)}),a}deserialize(e){return R(e)?he(e,{value:async e=>this.#i(e),error:async e=>{if(!(e instanceof G))return e;const t=this.#i(e.data);return V(t)?Y(t,{cause:e}):new G({data:t,cause:e})}}):this.#i(e)}#i(e){if(void 0===e)return;if(!(e instanceof FormData))return this.jsonSerializer.deserialize(e.json,e.meta??[]);const t=JSON.parse(e.get("data"));return this.jsonSerializer.deserialize(t.json,t.meta??[],t.maps,t=>e.get(t.toString()))}},xe=class extends ye{constructor(e,t){const n=new be(t),r=new we(n);super(new ve(r,t),e,t)}},Se=class extends ge{initRuntimeAdapter(e){for(const t of this.plugins)t.initRuntimeAdapter?.(e)}},ke=class{fetch;toFetchRequestOptions;adapterInterceptors;constructor(e){new Se(e.plugins).initRuntimeAdapter(e),this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=e,this.adapterInterceptors=w(e.adapterInterceptors)}async call(e,t,n,r){const o=function(e,t={}){const n=function(e,t=new Headers){for(const[n,r]of Object.entries(e))if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.append(n,r);return t}(e.headers),r=function(e,t,n={}){if(e instanceof ReadableStream)return e;const r=t.get("content-disposition");return t.delete("content-type"),t.delete("content-disposition"),void 0!==e?e instanceof Blob?(t.set("content-type",e.type),t.set("content-length",e.size.toString()),t.set("content-disposition",r??function(e,t="inline"){return`${t}; filename="${e.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,'\\"')}"; filename*=utf-8''${encodeURIComponent(e).replace(/['()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)))}`}(e instanceof File?e.name:"blob")),e):e instanceof FormData||e instanceof URLSearchParams?e:R(e)?(t.set("content-type","text/event-stream"),function(e,t={}){const n=t.eventIteratorKeepAliveEnabled??!0,r=t.eventIteratorKeepAliveInterval??5e3,o=t.eventIteratorKeepAliveComment??"",i=t.eventIteratorInitialCommentEnabled??!0,s=t.eventIteratorInitialComment??"";let a,c,l=!1;return new ReadableStream({start(e){c=E("stream_event_iterator"),i&&e.enqueue(le({comments:[s]}))},async pull(t){try{n&&(a=setInterval(()=>{t.enqueue(le({comments:[o]})),c?.addEvent("keepalive")},r));const i=await T(c,()=>e.next());if(clearInterval(a),l)return;const s=pe(i.value);if(!i.done||void 0!==i.value||void 0!==s){const e=i.done?"done":"message";t.enqueue(le({...s,event:e,data:N(i.value)})),c?.addEvent(e)}i.done&&(t.close(),c?.end())}catch(i){if(clearInterval(a),l)return;i instanceof G?(t.enqueue(le({...pe(i),event:"error",data:N(i.data)})),c?.addEvent("error"),t.close()):(I(c,i),t.error(i)),c?.end()}},async cancel(){try{l=!0,clearInterval(a),c?.addEvent("cancelled"),await T(c,()=>e.return?.())}catch(t){throw I(c,t),t}finally{c?.end()}}}).pipeThrough(new TextEncoderStream)}(e,n)):(t.set("content-type","application/json"),N(e)):void 0}(e.body,n,t);return new Request(e.url,{signal:e.signal,method:e.method,headers:n,body:r})}(e,this.toFetchRequestOptions);return function(e,t={}){return{body:k(()=>function(e,t={}){return M({name:"parse_standard_body",signal:t.signal},async()=>{const n=e.headers.get("content-disposition");if("string"==typeof n){const t=function(e){const t=e.match(/filename\*=(UTF-8'')?([^;]*)/i);if(t&&"string"==typeof t[2])return function(e){try{return decodeURIComponent(e)}catch{return e}}(t[2]);const n=e.match(/filename="((?:\\"|[^"])*)"/i);return n&&"string"==typeof n[1]?n[1].replace(/\\"/g,'"'):void 0}(n)??"blob",r=await e.blob();return new File([r],t,{type:r.type})}const r=e.headers.get("content-type");if(!r||r.startsWith("application/json"))return P(await e.text());if(r.startsWith("multipart/form-data"))return await e.formData();if(r.startsWith("application/x-www-form-urlencoded")){const t=await e.text();return new URLSearchParams(t)}if(r.startsWith("text/event-stream"))return function(e,t={}){const n=(e?.pipeThrough(new TextDecoderStream).pipeThrough(new ne))?.getReader();let r,o=!1;return new A(async()=>{r??=E("consume_event_iterator_stream");try{for(;;){if(void 0===n)return{done:!0,value:void 0};const{done:e,value:t}=await T(r,()=>n.read());if(e){if(o)throw new S("Stream was cancelled");return{done:!0,value:void 0}}switch(t.event){case"message":{let e=P(t.data);return F(e)&&(e=ue(e,t)),r?.addEvent("message"),{done:!1,value:e}}case"error":{let e=new G({data:P(t.data)});throw e=ue(e,t),r?.addEvent("error"),e}case"done":{let e=P(t.data);return F(e)&&(e=ue(e,t)),r?.addEvent("done"),{done:!0,value:e}}default:r?.addEvent("maybe_keepalive")}}}catch(e){throw e instanceof G||I(r,e,t),e}},async e=>{try{"next"!==e&&(o=!0,r?.addEvent("cancelled")),await T(r,()=>n?.cancel())}catch(i){throw I(r,i,t),i}finally{r?.end()}})}(e.body,t);if(r.startsWith("text/plain"))return await e.text();const o=await e.blob();return new File([o],"blob",{type:o.type})})}(e,t)),status:e.status,get headers(){const t=me(e.headers);return Object.defineProperty(this,"headers",{value:t,writable:!0}),t},set headers(e){Object.defineProperty(this,"headers",{value:e,writable:!0})}}}(await D(this.adapterInterceptors,{...t,request:o,path:n,input:r,init:{redirect:"manual"}},({request:e,path:t,input:n,init:r,...o})=>this.fetch(e,r,o,t,n)),{signal:o.signal})}},Ce=class extends xe{constructor(e){super(new ke(e),e)}};function Ee(e){return fe(new Ce({url:e}))}var Ie="",Me=Ee(""),Te=new Proxy({},{get:(e,t)=>Me[t]}),Re="marketrix_chat_context";function Oe(e){return e.mtxId??(null!=e.mtxApp?String(e.mtxApp):"default")}var Ae={chat_id:null,messages:[],currentMode:"tell",isOpen:!1,config:null,timestamp:0};function _e(e){try{return"undefined"==typeof localStorage?null:localStorage.getItem(e)}catch(t){return console.warn("[StorageService] localStorage is unreadable:",t),null}}function De(e,t){try{"undefined"!=typeof localStorage&&localStorage.setItem(e,t)}catch(n){console.warn("[StorageService] localStorage is unwritable:",n)}}function Pe(e){const t=_e(e);if(!t)return{...Ae};try{const e={...Ae,...JSON.parse(t)};if(Date.now()-e.timestamp<=6048e5)return e}catch(n){console.warn("[StorageService] Failed to parse the stored context:",n)}return{...Ae}}var Ne,Le=new class{key=Re;context=Pe(this.key);getContext(){return this.context}updateContext(e){this.context={...this.context,...e,timestamp:Date.now()},De(this.key,JSON.stringify(this.context))}getChatId(){return this.context.chat_id}setChatId(e){this.updateContext({chat_id:e})}getCredentialedConfig(){const{config:e}=this.context;return e?.mtxId&&e.mtxKey?e:null}setConfig(e){this.key=`${Re}_${Oe(e)}`,this.context=Pe(this.key),this.updateContext({config:e})}},Fe=new class{creation=null;async getOrCreateChatId(){return Le.getChatId()||(this.creation??=this.createChatId().finally(()=>{this.creation=null}),this.creation)}async createChatId(){const e=await Te.chatCreate(void 0);if(!e)throw new Error("API returned empty chat ID");return Le.setChatId(e),e}},ze=Object.defineProperty,$e=(e,t,n)=>((e,t,n)=>t in e?ze(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n),Be=/* @__PURE__ */(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e[e.Asset=7]="Asset",e))(Be||{}),We=/* @__PURE__ */(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(We||{}),Ue=/* @__PURE__ */(e=>(e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e))(Ue||{}),He=/* @__PURE__ */(e=>(e[e.Mouse=0]="Mouse",e[e.Pen=1]="Pen",e[e.Touch=2]="Touch",e))(He||{}),je=/* @__PURE__ */(e=>(e[e["2D"]=0]="2D",e[e.WebGL=1]="WebGL",e[e.WebGL2=2]="WebGL2",e))(je||{}),qe=/* @__PURE__ */(e=>(e[e.Play=0]="Play",e[e.Pause=1]="Pause",e[e.Seeked=2]="Seeked",e[e.VolumeChange=3]="VolumeChange",e[e.RateChange=4]="RateChange",e))(qe||{}),Ve=/* @__PURE__ */(e=>(e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e))(Ve||{}),Ye={Node:["childNodes","parentNode","parentElement","textContent","ownerDocument"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Ke={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Xe={},Ge={};function Je(e){if(Xe[e])return Xe[e];const t=globalThis[e],n=t.prototype,r=e in Ye?Ye[e]:void 0,o=Boolean(r&&r.every(e=>{var t,r;return Boolean(null==(r=null==(t=Object.getOwnPropertyDescriptor(n,e))?void 0:t.get)?void 0:r.toString().includes("[native code]"))})),i=e in Ke?Ke[e]:void 0,s=Boolean(i&&i.every(e=>{var t;return"function"==typeof n[e]&&(null==(t=n[e])?void 0:t.toString().includes("[native code]"))}));if(o&&s&&!globalThis.Zone)return Xe[e]=t.prototype,t.prototype;try{const r=document.createElement("iframe");r.style.display="none",document.body.appendChild(r);const o=r.contentWindow;if(!o)return t.prototype;const i=o[e].prototype;if(!i)return r.remove(),n;const s=navigator.userAgent;return s.includes("Safari")&&!s.includes("Chrome")?(r.classList.add("rr-block"),r.setAttribute("__rrwebUntaintedMutationObserver",""),Ge[e]=()=>r.remove()):r.remove(),Xe[e]=i}catch{return n}}var Ze={};function Qe(e,t,n){var r;const o=`${e}.${String(n)}`;if(Ze[o])return Ze[o].call(t);const i=Je(e),s=null==(r=Object.getOwnPropertyDescriptor(i,n))?void 0:r.get;return s?(Ze[o]=s,s.call(t)):t[n]}var et={};function tt(e,t,n){const r=`${e}.${String(n)}`;if(et[r])return et[r].bind(t);const o=Je(e)[n];return"function"!=typeof o?t[n]:(et[r]=o,o.bind(t))}var nt=Date.now;function rt(e,t,n){try{if(!(t in e))return()=>{};const r=e[t],o=n(r);return"function"==typeof o&&(o.prototype=o.prototype||{},Object.defineProperties(o,{__rrweb_original__:{enumerable:!1,value:r}})),e[t]=o,()=>{e[t]=r}}catch{return()=>{}}}/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())||(nt=()=>/* @__PURE__ */(new Date).getTime());var ot=function(e){return Qe("Node",e,"ownerDocument")},it=function(e){return Qe("Node",e,"childNodes")},st=function(e){return Qe("Node",e,"parentNode")},at=function(e){return Qe("Node",e,"parentElement")},ct=function(e){return Qe("Node",e,"textContent")},lt=function(e,t){return tt("Node",e,"contains")(t)},dt=function(e){return tt("Node",e,"getRootNode")()},ut=function(e){return e&&"host"in e?Qe("ShadowRoot",e,"host"):null},pt=function(e){return e&&"shadowRoot"in e?Qe("Element",e,"shadowRoot"):null};function ht(e){return e.nodeType===e.ELEMENT_NODE}function ft(e){const t=e&&"host"in e&&"mode"in e&&ut(e)||null;return Boolean(t&&"shadowRoot"in t&&pt(t)===e)}function mt(e){return"[object ShadowRoot]"===Object.prototype.toString.call(e)}function gt(e){try{const n=e.rules||e.cssRules;if(!n)return null;let r=e.href;return!r&&e.ownerNode&&(r=e.ownerNode.baseURI),(t=Array.from(n,e=>yt(e,r)).join("")).includes(" background-clip: text;")&&!t.includes(" -webkit-background-clip: text;")&&(t=t.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),t}catch(n){return null}var t}function yt(e,t){if(function(e){return"styleSheet"in e}(e)){let t;try{t=gt(e.styleSheet)||function(e){const{cssText:t}=e;if(t.split('"').length<3)return t;const n=["@import",`url(${JSON.stringify(e.href)})`];return""===e.layerName?n.push("layer"):e.layerName&&n.push(`layer(${e.layerName})`),e.supportsText&&n.push(`supports(${e.supportsText})`),e.media.length&&n.push(e.media.mediaText),n.join(" ")+";"}(e)}catch(n){t=e.cssText}return e.styleSheet.href?Tt(t,e.styleSheet.href):t}{let n=e.cssText;return function(e){return"selectorText"in e}(e)&&e.selectorText.includes(":")&&(n=n.replace(/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm,"$1\\$2")),t?Tt(n,t):n}}var bt=class{constructor(){$e(this,"idNodeMap",/* @__PURE__ */new Map),$e(this,"nodeMetaMap",/* @__PURE__ */new WeakMap)}getId(e){var t;return e?(null==(t=this.getMeta(e))?void 0:t.id)??-1:-1}getNode(e){return this.idNodeMap.get(e)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(e){return this.nodeMetaMap.get(e)||null}removeNodeFromMap(e){const t=this.getId(e);this.idNodeMap.delete(t),e.childNodes&&e.childNodes.forEach(e=>this.removeNodeFromMap(e))}has(e){return this.idNodeMap.has(e)}hasNode(e){return this.nodeMetaMap.has(e)}add(e,t){const n=t.id;this.idNodeMap.set(n,e),this.nodeMetaMap.set(e,t)}replace(e,t){const n=this.getNode(e);if(n){const e=this.nodeMetaMap.get(n);e&&this.nodeMetaMap.set(t,e)}this.idNodeMap.set(e,t)}reset(){this.idNodeMap=/* @__PURE__ */new Map,this.nodeMetaMap=/* @__PURE__ */new WeakMap}};function vt({element:e,maskInputOptions:t,tagName:n,type:r,value:o,maskInputFn:i}){let s=o||"";const a=r&&wt(r);return(t[n.toLowerCase()]||a&&t[a])&&(s=i?i(s,e):"*".repeat(s.length)),s}function wt(e){return e.toLowerCase()}var xt="__rrweb_original__";function St(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?wt(t):null}function kt(e,t){let n;try{n=new URL(e,t??window.location.href)}catch(o){return null}const r=n.pathname.match(/\.([0-9a-z]+)(?:$)/i);return(null==r?void 0:r[1])??null}var Ct=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,Et=/^(?:[a-z+]+:)?\/\//i,It=/^www\..*/i,Mt=/^(data:)([^,]*),(.*)/i;function Tt(e,t){return(e||"").replace(Ct,(e,n,r,o,i,s)=>{const a=r||i||s,c=n||o||"";if(!a)return e;if(Et.test(a)||It.test(a))return`url(${c}${a}${c})`;if(Mt.test(a))return`url(${c}${a}${c})`;if("/"===a[0])return`url(${c}${function(e){let t="";return t=e.indexOf("//")>-1?e.split("/").slice(0,3).join("/"):e.split("/")[0],t=t.split("?")[0],t}(t)+a}${c})`;const l=a.split("#")[0],d=a.substring(l.length),u=t.split("#")[0].split("/"),p=l.split("/");u.pop();for(const t of p)"."!==t&&(".."===t?u.pop():u.push(t));return`url(${c}${u.join("/")}${d}${c})`})}function Rt(e,t=!1){return t?e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,""):e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"").replace(/0px/g,"0")}var Ot,At,_t=1,Dt=/* @__PURE__ */new RegExp("[^a-z0-9-_:]");function Pt(){return _t++}var Nt=/^[^ \t\n\r\u000c]+/,Lt=/^[, \t\n\r\u000c]+/,Ft=/* @__PURE__ */new WeakMap;function zt(e,t){return t&&""!==t.trim()?$t(e,t):t}function $t(e,t){let n=Ft.get(e);if(n||(n=e.createElement("a"),Ft.set(e,n)),t){if(t.startsWith("blob:")||t.startsWith("data:"))return t}else t="";return n.setAttribute("href",t),n.href}function Bt(e,t,n,r){return r?"src"===n||"href"===n&&("use"!==t||"#"!==r[0])||"xlink:href"===n&&"#"!==r[0]||"background"===n&&["table","td","th"].includes(t)?zt(e,r):"srcset"===n?function(e,t){if(""===t.trim())return t;let n=0;function r(e){let r;const o=e.exec(t.substring(n));return o?(r=o[0],n+=r.length,r):""}const o=[];for(;r(Lt),!(n>=t.length);){let i=r(Nt);if(","===i.slice(-1))i=zt(e,i.substring(0,i.length-1)),o.push(i);else{let r="";i=zt(e,i);let s=!1;for(;;){const e=t.charAt(n);if(""===e){o.push((i+r).trim());break}if(s)")"===e&&(s=!1);else{if(","===e){n+=1,o.push((i+r).trim());break}"("===e&&(s=!0)}r+=e,n+=1}}}return o.join(", ")}(e,r):"style"===n?Tt(r,$t(e)):"object"===t&&"data"===n?zt(e,r):r:r}function Wt(e,t,n){return["video","audio"].includes(e)&&"autoplay"===t}function Ut(e,t,n){if(!e)return!1;if(e.nodeType!==e.ELEMENT_NODE)return!!n&&Ut(st(e),t,n);for(let r=e.classList.length;r--;){const n=e.classList[r];if(t.test(n))return!0}return!!n&&Ut(st(e),t,n)}function Ht(e,t,n,r){let o;if(ht(e)){if(o=e,!it(o).length)return!1}else{if(null===at(e))return!1;o=at(e)}try{if("string"==typeof t){if(r){if(o.closest(`.${t}`))return!0}else if(o.classList.contains(t))return!0}else if(Ut(o,t,r))return!0;if(n)if(r){if(o.closest(n))return!0}else if(o.matches(n))return!0}catch(i){}return!1}function jt(e){return null==e?"":e.toLowerCase()}function qt(e){return!0===e||"all"===e?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===e,headMetaDescKeywords:"all"===e,headTitleMutations:"all"===e}:e||{}}function Vt(e,t){const{doc:n,mirror:r,blockClass:o,blockSelector:i,maskTextClass:s,maskTextSelector:a,skipChild:c=!1,inlineStylesheet:l=!0,maskInputOptions:d={},maskTextFn:u,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f={},inlineImages:m=!1,recordCanvas:g=!1,onSerialize:y,onIframeLoad:b,iframeLoadTimeout:v=5e3,onStylesheetLoad:w,stylesheetLoadTimeout:x=5e3,keepIframeSrcFn:S=()=>!1,newlyAddedElement:k=!1,cssCaptured:C=!1}=t;let{needsMask:E}=t,{preserveWhiteSpace:I=!0}=t;E||(E=Ht(e,s,a,void 0===E));const M=function(e,t){const{doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:s,inlineStylesheet:a,maskInputOptions:c={},maskTextFn:l,maskInputFn:d,dataURLOptions:u={},inlineImages:p,recordCanvas:h,keepIframeSrcFn:f,newlyAddedElement:m=!1,cssCaptured:g=!1}=t,y=function(e,t){if(!t.hasNode(e))return;const n=t.getId(e);return 1===n?void 0:n}(n,r);switch(e.nodeType){case e.DOCUMENT_NODE:return"CSS1Compat"!==e.compatMode?{type:Ve.Document,childNodes:[],compatMode:e.compatMode}:{type:Ve.Document,childNodes:[]};case e.DOCUMENT_TYPE_NODE:return{type:Ve.DocumentType,name:e.name,publicId:e.publicId,systemId:e.systemId,rootId:y};case e.ELEMENT_NODE:return function(e,t){const{doc:n,blockClass:r,blockSelector:o,inlineStylesheet:i,maskInputOptions:s={},maskInputFn:a,dataURLOptions:c={},inlineImages:l,recordCanvas:d,keepIframeSrcFn:u,newlyAddedElement:p=!1,rootId:h}=t,f=function(e,t,n){try{if("string"==typeof t){if(e.classList.contains(t))return!0}else for(let n=e.classList.length;n--;){const r=e.classList[n];if(t.test(r))return!0}if(n)return e.matches(n)}catch(r){}return!1}(e,r,o),m=function(e){if(e instanceof HTMLFormElement)return"form";const t=wt(e.tagName);return Dt.test(t)?"div":t}(e);let g={};const y=e.attributes.length;for(let x=0;x<y;x++){const t=e.attributes[x];Wt(m,t.name,t.value)||(g[t.name]=Bt(n,m,wt(t.name),t.value))}if("link"===m&&i){const t=Array.from(n.styleSheets).find(t=>t.href===e.href);let r=null;t&&(r=gt(t)),r&&(delete g.rel,delete g.href,g._cssText=r)}if("style"===m&&e.sheet){let t=gt(e.sheet);t&&(e.childNodes.length>1&&(t=function(e,t){return function(e,t,n=!1){const r=Array.from(t.childNodes),o=[];let i=0;if(r.length>1&&e&&"string"==typeof e){let t=Rt(e,n);const s=t.length/e.length;for(let a=1;a<r.length;a++)if(r[a].textContent&&"string"==typeof r[a].textContent){const c=Rt(r[a].textContent,n),l=100;let d=3;for(;d<c.length&&(c[d].match(/[a-zA-Z0-9]/)||-1!==c.indexOf(c.substring(0,d),1));d++);for(;d<c.length;d++){let u=c.substring(0,d),p=t.split(u),h=-1;if(2===p.length)h=p[0].length;else if(p.length>2&&""===p[0]&&""!==r[a-1].textContent)h=t.indexOf(u,1);else if(1===p.length){if(u=u.substring(0,u.length-1),p=t.split(u),p.length<=1)return o.push(e),o;d=101}else d===c.length-1&&(h=t.indexOf(u));if(p.length>=2&&d>l){const e=r[a-1].textContent;if(e&&"string"==typeof e){const n=Rt(e).length;h=t.indexOf(u,n)}-1===h&&(h=p[0].length)}if(-1!==h){let a=Math.floor(h/s);for(;a>0&&a<e.length;){if(i+=1,i>50*r.length)return o.push(e),o;const c=Rt(e.substring(0,a),n);if(c.length===h){o.push(e.substring(0,a)),e=e.substring(a),t=t.substring(h);break}c.length<h?a+=Math.max(1,Math.floor((h-c.length)/s)):a-=Math.max(1,Math.floor((c.length-h)*s))}break}}}}return o.push(e),o}(e,t).join("/* rr_split */")}(t,e)),g._cssText=t)}if(["input","textarea","select"].includes(m)){const t=e.value,n=e.checked;"radio"!==g.type&&"checkbox"!==g.type&&"submit"!==g.type&&"button"!==g.type&&t?g.value=vt({element:e,type:St(e),tagName:m,value:t,maskInputOptions:s,maskInputFn:a}):n&&(g.checked=n)}if("option"===m&&(e.selected&&!s.select?g.selected=!0:delete g.selected),"dialog"===m&&e.open&&(g.rr_open_mode=e.matches("dialog:modal")?"modal":"non-modal"),"canvas"===m&&d)if("2d"===e.__context)(function(e){const t=e.getContext("2d");if(!t)return!0;for(let n=0;n<e.width;n+=50)for(let r=0;r<e.height;r+=50){const o=t.getImageData,i=xt in o?o[xt]:o;if(new Uint32Array(i.call(t,n,r,Math.min(50,e.width-n),Math.min(50,e.height-r)).data.buffer).some(e=>0!==e))return!1}return!0})(e)||(g.rr_dataURL=e.toDataURL(c.type,c.quality));else if(!("__context"in e)){const t=e.toDataURL(c.type,c.quality),r=n.createElement("canvas");r.width=e.width,r.height=e.height,t!==r.toDataURL(c.type,c.quality)&&(g.rr_dataURL=t)}if("img"===m&&l){Ot||(Ot=n.createElement("canvas"),At=Ot.getContext("2d"));const t=e,r=t.currentSrc||t.getAttribute("src")||"<unknown-src>",o=t.crossOrigin,i=()=>{t.removeEventListener("load",i);try{Ot.width=t.naturalWidth,Ot.height=t.naturalHeight,At.drawImage(t,0,0),g.rr_dataURL=Ot.toDataURL(c.type,c.quality)}catch(e){if("anonymous"!==t.crossOrigin)return t.crossOrigin="anonymous",void(t.complete&&0!==t.naturalWidth?i():t.addEventListener("load",i));console.warn(`Cannot inline img src=${r}! Error: ${e}`)}"anonymous"===t.crossOrigin&&(o?g.crossOrigin=o:t.removeAttribute("crossorigin"))};t.complete&&0!==t.naturalWidth?i():t.addEventListener("load",i)}if(["audio","video"].includes(m)){const t=g;t.rr_mediaState=e.paused?"paused":"played",t.rr_mediaCurrentTime=e.currentTime,t.rr_mediaPlaybackRate=e.playbackRate,t.rr_mediaMuted=e.muted,t.rr_mediaLoop=e.loop,t.rr_mediaVolume=e.volume}if(p||(e.scrollLeft&&(g.rr_scrollLeft=e.scrollLeft),e.scrollTop&&(g.rr_scrollTop=e.scrollTop)),f){const{width:t,height:n}=e.getBoundingClientRect();g={class:g.class,rr_width:`${t}px`,rr_height:`${n}px`}}let b;"iframe"!==m||u(g.src)||(e.contentDocument||(g.rr_src=g.src),delete g.src);try{customElements.get(m)&&(b=!0)}catch(w){}return{type:Ve.Element,tagName:m,attributes:g,childNodes:[],isSVG:(v=e,Boolean("svg"===v.tagName||v.ownerSVGElement)||void 0),needBlock:f,rootId:h,isCustom:b};var v}(e,{doc:n,blockClass:o,blockSelector:i,inlineStylesheet:a,maskInputOptions:c,maskInputFn:d,dataURLOptions:u,inlineImages:p,recordCanvas:h,keepIframeSrcFn:f,newlyAddedElement:m,rootId:y});case e.TEXT_NODE:return function(e,t){const{needsMask:n,maskTextFn:r,rootId:o,cssCaptured:i}=t,s=st(e),a=s&&s.tagName;let c="";const l="STYLE"===a||void 0,d="SCRIPT"===a||void 0;return d?c="SCRIPT_PLACEHOLDER":i||(c=ct(e),l&&c&&(c=Tt(c,$t(t.doc)))),!l&&!d&&c&&n&&(c=r?r(c,at(e)):c.replace(/[\S]/g,"*")),{type:Ve.Text,textContent:c||"",rootId:o}}(e,{doc:n,needsMask:s,maskTextFn:l,rootId:y,cssCaptured:g});case e.CDATA_SECTION_NODE:return{type:Ve.CDATA,textContent:"",rootId:y};case e.COMMENT_NODE:return{type:Ve.Comment,textContent:ct(e)||"",rootId:y};default:return!1}}(e,{doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:E,inlineStylesheet:l,maskInputOptions:d,maskTextFn:u,maskInputFn:p,dataURLOptions:f,inlineImages:m,recordCanvas:g,keepIframeSrcFn:S,newlyAddedElement:k,cssCaptured:C});if(!M)return console.warn(e,"not serialized"),null;let T;T=r.hasNode(e)?r.getId(e):function(e,t){if(t.comment&&e.type===Ve.Comment)return!0;if(e.type===Ve.Element){if(t.script&&("script"===e.tagName||"link"===e.tagName&&("preload"===e.attributes.rel&&"script"===e.attributes.as||"modulepreload"===e.attributes.rel)||"link"===e.tagName&&"prefetch"===e.attributes.rel&&"string"==typeof e.attributes.href&&"js"===kt(e.attributes.href)))return!0;if(t.headFavicon&&("link"===e.tagName&&"shortcut icon"===e.attributes.rel||"meta"===e.tagName&&(jt(e.attributes.name).match(/^msapplication-tile(image|color)$/)||"application-name"===jt(e.attributes.name)||"icon"===jt(e.attributes.rel)||"apple-touch-icon"===jt(e.attributes.rel)||"shortcut icon"===jt(e.attributes.rel))))return!0;if("meta"===e.tagName){if(t.headMetaDescKeywords&&jt(e.attributes.name).match(/^description|keywords$/))return!0;if(t.headMetaSocial&&(jt(e.attributes.property).match(/^(og|twitter|fb):/)||jt(e.attributes.name).match(/^(og|twitter):/)||"pinterest"===jt(e.attributes.name)))return!0;if(t.headMetaRobots&&("robots"===jt(e.attributes.name)||"googlebot"===jt(e.attributes.name)||"bingbot"===jt(e.attributes.name)))return!0;if(t.headMetaHttpEquiv&&void 0!==e.attributes["http-equiv"])return!0;if(t.headMetaAuthorship&&("author"===jt(e.attributes.name)||"generator"===jt(e.attributes.name)||"framework"===jt(e.attributes.name)||"publisher"===jt(e.attributes.name)||"progid"===jt(e.attributes.name)||jt(e.attributes.property).match(/^article:/)||jt(e.attributes.property).match(/^product:/)))return!0;if(t.headMetaVerification&&("google-site-verification"===jt(e.attributes.name)||"yandex-verification"===jt(e.attributes.name)||"csrf-token"===jt(e.attributes.name)||"p:domain_verify"===jt(e.attributes.name)||"verify-v1"===jt(e.attributes.name)||"verification"===jt(e.attributes.name)||"shopify-checkout-api-token"===jt(e.attributes.name)))return!0}}return!1}(M,h)||!I&&M.type===Ve.Text&&!M.textContent.replace(/^\s+|\s+$/gm,"").length?-2:Pt();const R=Object.assign(M,{id:T});if(r.add(e,R),-2===T)return null;y&&y(e);let O=!c;if(R.type===Ve.Element){O=O&&!R.needBlock,delete R.needBlock;const t=pt(e);t&&mt(t)&&(R.isShadowHost=!0)}if((R.type===Ve.Document||R.type===Ve.Element)&&O){h.headWhitespace&&R.type===Ve.Element&&"head"===R.tagName&&(I=!1);const t={doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:E,maskTextClass:s,maskTextSelector:a,skipChild:c,inlineStylesheet:l,maskInputOptions:d,maskTextFn:u,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:I,onSerialize:y,onIframeLoad:b,iframeLoadTimeout:v,onStylesheetLoad:w,stylesheetLoadTimeout:x,keepIframeSrcFn:S,cssCaptured:!1};if(R.type===Ve.Element&&"textarea"===R.tagName&&void 0!==R.attributes.value);else{R.type===Ve.Element&&void 0!==R.attributes._cssText&&"string"==typeof R.attributes._cssText&&(t.cssCaptured=!0);for(const n of Array.from(it(e))){const e=Vt(n,t);e&&R.childNodes.push(e)}}let k=null;if(ht(e)&&(k=pt(e)))for(const e of Array.from(it(k))){const n=Vt(e,t);n&&(mt(k)&&(n.isShadow=!0),R.childNodes.push(n))}}const A=st(e);return A&&ft(A)&&mt(A)&&(R.isShadow=!0),R.type===Ve.Element&&"iframe"===R.tagName&&function(e,t,n){const r=e.contentWindow;if(!r)return;let o,i=!1;try{o=r.document.readyState}catch(a){return}if("complete"!==o){const r=setTimeout(()=>{i||(t(),i=!0)},n);return void e.addEventListener("load",()=>{clearTimeout(r),i=!0,t()})}const s="about:blank";if(r.location.href!==s||e.src===s||""===e.src)return setTimeout(t,0),e.addEventListener("load",t);e.addEventListener("load",t)}(e,()=>{const t=e.contentDocument;if(t&&b){const n=Vt(t,{doc:t,mirror:r,blockClass:o,blockSelector:i,needsMask:E,maskTextClass:s,maskTextSelector:a,skipChild:!1,inlineStylesheet:l,maskInputOptions:d,maskTextFn:u,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:I,onSerialize:y,onIframeLoad:b,iframeLoadTimeout:v,onStylesheetLoad:w,stylesheetLoadTimeout:x,keepIframeSrcFn:S});n&&b(e,n)}},v),R.type===Ve.Element&&"link"===R.tagName&&"string"==typeof R.attributes.rel&&("stylesheet"===R.attributes.rel||"preload"===R.attributes.rel&&"string"==typeof R.attributes.href&&"css"===kt(R.attributes.href))&&function(e,t,n){let r,o=!1;try{r=e.sheet}catch(s){return}if(r)return;const i=setTimeout(()=>{o||(t(),o=!0)},n);e.addEventListener("load",()=>{clearTimeout(i),o=!0,t()})}(e,()=>{if(w){const t=Vt(e,{doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:E,maskTextClass:s,maskTextSelector:a,skipChild:!1,inlineStylesheet:l,maskInputOptions:d,maskTextFn:u,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:I,onSerialize:y,onIframeLoad:b,iframeLoadTimeout:v,onStylesheetLoad:w,stylesheetLoadTimeout:x,keepIframeSrcFn:S});t&&w(e,t)}},x),R}var Yt=class e{constructor(...e){$e(this,"parentElement",null),$e(this,"parentNode",null),$e(this,"ownerDocument"),$e(this,"firstChild",null),$e(this,"lastChild",null),$e(this,"previousSibling",null),$e(this,"nextSibling",null),$e(this,"ELEMENT_NODE",1),$e(this,"TEXT_NODE",3),$e(this,"nodeType"),$e(this,"nodeName"),$e(this,"RRNodeType")}get childNodes(){const e=[];let t=this.firstChild;for(;t;)e.push(t),t=t.nextSibling;return e}contains(t){if(!(t instanceof e))return!1;if(t.ownerDocument!==this.ownerDocument)return!1;if(t===this)return!0;for(;t.parentNode;){if(t.parentNode===this)return!0;t=t.parentNode}return!1}appendChild(e){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(e,t){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(e){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}};function Kt(e,t,n=document){const r={capture:!0,passive:!0};return n.addEventListener(e,t,r),()=>n.removeEventListener(e,t,r)}var Xt="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.",Gt={map:{},getId:()=>(console.error(Xt),-1),getNode:()=>(console.error(Xt),null),removeNodeFromMap(){console.error(Xt)},has:()=>(console.error(Xt),!1),reset(){console.error(Xt)}};function Jt(e,t,n={}){let r=null,o=0;return function(...i){const s=Date.now();o||!1!==n.leading||(o=s);const a=t-(s-o),c=this;a<=0||a>t?(r&&(clearTimeout(r),r=null),o=s,e.apply(c,i)):r||!1===n.trailing||(r=setTimeout(()=>{o=!1===n.leading?0:Date.now(),r=null,e.apply(c,i)},a))}}function Zt(e,t,n,r,o=window){const i=o.Object.getOwnPropertyDescriptor(e,t);return o.Object.defineProperty(e,t,r?n:{set(e){setTimeout(()=>{n.set.call(this,e)},0),i&&i.set&&i.set.call(this,e)}}),()=>Zt(e,t,i||{},!0)}function Qt(e){var t,n,r,o;const i=e.document;return{left:i.scrollingElement?i.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:i.documentElement.scrollLeft||(null==i?void 0:i.body)&&(null==(t=at(i.body))?void 0:t.scrollLeft)||(null==(n=null==i?void 0:i.body)?void 0:n.scrollLeft)||0,top:i.scrollingElement?i.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==i?void 0:i.documentElement.scrollTop)||(null==i?void 0:i.body)&&(null==(r=at(i.body))?void 0:r.scrollTop)||(null==(o=null==i?void 0:i.body)?void 0:o.scrollTop)||0}}function en(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function tn(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function nn(e){return e?e.nodeType===e.ELEMENT_NODE?e:at(e):null}function rn(e,t,n,r){if(!e)return!1;const o=nn(e);if(!o)return!1;try{if("string"==typeof t){if(o.classList.contains(t))return!0;if(r&&null!==o.closest("."+t))return!0}else if(Ut(o,t,r))return!0}catch(i){}if(n){if(o.matches(n))return!0;if(r&&null!==o.closest(n))return!0}return!1}function on(e,t,n){return!("TITLE"!==e.tagName||!n.headTitleMutations)||-2===t.getId(e)}function sn(e,t){if(ft(e))return!1;const n=t.getId(e);if(!t.has(n))return!0;const r=st(e);return(!r||r.nodeType!==e.DOCUMENT_NODE)&&(!r||sn(r,t))}function an(e){return Boolean(e.changedTouches)}function cn(e,t){return Boolean("IFRAME"===e.nodeName&&t.getMeta(e))}function ln(e,t){return Boolean("LINK"===e.nodeName&&e.nodeType===e.ELEMENT_NODE&&e.getAttribute&&"stylesheet"===e.getAttribute("rel")&&t.getMeta(e))}function dn(e){return!!e&&(e instanceof Yt&&"shadowRoot"in e?Boolean(e.shadowRoot):Boolean(pt(e)))}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(Gt=new Proxy(Gt,{get:(e,t,n)=>("map"===t&&console.error(Xt),Reflect.get(e,t,n))}));var un=class{constructor(){$e(this,"id",1),$e(this,"styleIDMap",/* @__PURE__ */new WeakMap),$e(this,"idStyleMap",/* @__PURE__ */new Map)}getId(e){return this.styleIDMap.get(e)??-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let n;return n=void 0===t?this.id++:t,this.styleIDMap.set(e,n),this.idStyleMap.set(n,e),n}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=/* @__PURE__ */new WeakMap,this.idStyleMap=/* @__PURE__ */new Map,this.id=1}generateId(){return this.id++}};function pn(e){var t;let n=null;return"getRootNode"in e&&(null==(t=dt(e))?void 0:t.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&ut(dt(e))&&(n=ut(dt(e))),n}function hn(e){const t=ot(e);return!!t&&(lt(t,e)||function(e){const t=ot(e);if(!t)return!1;const n=function(e){let t,n=e;for(;t=pn(n);)n=t;return n}(e);return lt(t,n)}(e))}function fn(e){return"__ln"in e}var mn,gn=class{constructor(){$e(this,"length",0),$e(this,"head",null),$e(this,"tail",null)}get(e){if(e>=this.length)throw new Error("Position outside of list range");let t=this.head;for(let n=0;n<e;n++)t=(null==t?void 0:t.next)||null;return t}addNode(e){const t={value:e,previous:null,next:null};if(e.__ln=t,e.previousSibling&&fn(e.previousSibling)){const n=e.previousSibling.__ln.next;t.next=n,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,n&&(n.previous=t)}else if(e.nextSibling&&fn(e.nextSibling)&&e.nextSibling.__ln.previous){const n=e.nextSibling.__ln.previous;t.previous=n,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,n&&(n.next=t)}else this.head&&(this.head.previous=t),t.next=this.head,this.head=t;null===t.next&&(this.tail=t),this.length++}removeNode(e){const t=e.__ln;this.head&&(t.previous?(t.previous.next=t.next,t.next?t.next.previous=t.previous:this.tail=t.previous):(this.head=t.next,this.head?this.head.previous=null:this.tail=null),e.__ln&&delete e.__ln,this.length--)}},yn=(e,t)=>`${e}@${t}`,bn=class{constructor(){$e(this,"frozen",!1),$e(this,"locked",!1),$e(this,"texts",[]),$e(this,"attributes",[]),$e(this,"attributeMap",/* @__PURE__ */new WeakMap),$e(this,"removes",[]),$e(this,"mapRemoves",[]),$e(this,"movedMap",{}),$e(this,"addedSet",/* @__PURE__ */new Set),$e(this,"movedSet",/* @__PURE__ */new Set),$e(this,"droppedSet",/* @__PURE__ */new Set),$e(this,"removesSubTreeCache",/* @__PURE__ */new Set),$e(this,"mutationCb"),$e(this,"blockClass"),$e(this,"blockSelector"),$e(this,"maskTextClass"),$e(this,"maskTextSelector"),$e(this,"inlineStylesheet"),$e(this,"maskInputOptions"),$e(this,"maskTextFn"),$e(this,"maskInputFn"),$e(this,"keepIframeSrcFn"),$e(this,"recordCanvas"),$e(this,"inlineImages"),$e(this,"slimDOMOptions"),$e(this,"dataURLOptions"),$e(this,"doc"),$e(this,"mirror"),$e(this,"iframeManager"),$e(this,"stylesheetManager"),$e(this,"shadowDomManager"),$e(this,"canvasManager"),$e(this,"processedNodeManager"),$e(this,"unattachedDoc"),$e(this,"processMutations",e=>{e.forEach(this.processMutation),this.emit()}),$e(this,"emit",()=>{if(this.frozen||this.locked)return;const e=[],t=/* @__PURE__ */new Set,n=new gn,r=e=>{let t=e,n=-2;for(;-2===n;)t=t&&t.nextSibling,n=t&&this.mirror.getId(t);return n},o=o=>{const i=st(o);if(!i||!hn(o))return;let s=!1;if(o.nodeType===Node.TEXT_NODE){const e=i.tagName;if("TEXTAREA"===e)return;"STYLE"===e&&this.addedSet.has(i)&&(s=!0)}const a=ft(i)?this.mirror.getId(pn(o)):this.mirror.getId(i),c=r(o);if(-1===a||-1===c)return n.addNode(o);const l=Vt(o,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:e=>{cn(e,this.mirror)&&this.iframeManager.addIframe(e),ln(e,this.mirror)&&this.stylesheetManager.trackLinkElement(e),dn(o)&&this.shadowDomManager.addShadowRoot(pt(o),this.doc)},onIframeLoad:(e,t)=>{this.iframeManager.attachIframe(e,t),this.shadowDomManager.observeAttachShadow(e)},onStylesheetLoad:(e,t)=>{this.stylesheetManager.attachLinkElement(e,t)},cssCaptured:s});l&&(e.push({parentId:a,nextId:c,node:l}),t.add(l.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const a of this.movedSet)wn(this.removesSubTreeCache,a,this.mirror)&&!this.movedSet.has(st(a))||o(a);for(const a of this.addedSet)xn(this.droppedSet,a)||wn(this.removesSubTreeCache,a,this.mirror)?xn(this.movedSet,a)?o(a):this.droppedSet.add(a):o(a);let i=null;for(;n.length;){let e=null;if(i){const t=this.mirror.getId(st(i.value)),n=r(i.value);-1!==t&&-1!==n&&(e=i)}if(!e){let t=n.tail;for(;t;){const n=t;if(t=t.previous,n){const t=this.mirror.getId(st(n.value));if(-1===r(n.value))continue;if(-1!==t){e=n;break}{const t=n.value,r=st(t);if(r&&r.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const t=ut(r);if(-1!==this.mirror.getId(t)){e=n;break}}}}}}if(!e){for(;n.head;)n.removeNode(n.head.value);break}i=e.previous,n.removeNode(e.value),o(e.value)}const s={texts:this.texts.map(e=>{const t=e.node,n=st(t);return n&&"TEXTAREA"===n.tagName&&this.genTextAreaValueMutation(n),{id:this.mirror.getId(t),value:e.value}}).filter(e=>!t.has(e.id)).filter(e=>this.mirror.has(e.id)),attributes:this.attributes.map(e=>{const{attributes:t}=e;if("string"==typeof t.style){const n=JSON.stringify(e.styleDiff),r=JSON.stringify(e._unchangedStyles);n.length<t.style.length&&(n+r).split("var(").length===t.style.split("var(").length&&(t.style=e.styleDiff)}return{id:this.mirror.getId(e.node),attributes:t}}).filter(e=>!t.has(e.id)).filter(e=>this.mirror.has(e.id)),removes:this.removes,adds:e};(s.texts.length||s.attributes.length||s.removes.length||s.adds.length)&&(this.texts=[],this.attributes=[],this.attributeMap=/* @__PURE__ */new WeakMap,this.removes=[],this.addedSet=/* @__PURE__ */new Set,this.movedSet=/* @__PURE__ */new Set,this.droppedSet=/* @__PURE__ */new Set,this.removesSubTreeCache=/* @__PURE__ */new Set,this.movedMap={},this.mutationCb(s))}),$e(this,"genTextAreaValueMutation",e=>{let t=this.attributeMap.get(e);t||(t={node:e,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(t),this.attributeMap.set(e,t));const n=Array.from(it(e),e=>ct(e)||"").join("");t.attributes.value=vt({element:e,maskInputOptions:this.maskInputOptions,tagName:e.tagName,type:St(e),value:n,maskInputFn:this.maskInputFn})}),$e(this,"processMutation",e=>{if(!on(e.target,this.mirror,this.slimDOMOptions))switch(e.type){case"characterData":{const t=ct(e.target);rn(e.target,this.blockClass,this.blockSelector,!1)||t===e.oldValue||this.texts.push({value:Ht(e.target,this.maskTextClass,this.maskTextSelector,!0)&&t?this.maskTextFn?this.maskTextFn(t,nn(e.target)):t.replace(/[\S]/g,"*"):t,node:e.target});break}case"attributes":{const n=e.target;let r=e.attributeName,o=e.target.getAttribute(r);if("value"===r){const e=St(n);o=vt({element:n,maskInputOptions:this.maskInputOptions,tagName:n.tagName,type:e,value:o,maskInputFn:this.maskInputFn})}if(rn(e.target,this.blockClass,this.blockSelector,!1)||o===e.oldValue)return;let i=this.attributeMap.get(e.target);if("IFRAME"===n.tagName&&"src"===r&&!this.keepIframeSrcFn(o)){if(n.contentDocument)return;r="rr_src"}if(i||(i={node:e.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(i),this.attributeMap.set(e.target,i)),"type"===r&&"INPUT"===n.tagName&&"password"===(e.oldValue||"").toLowerCase()&&n.setAttribute("data-rr-is-password","true"),!Wt(n.tagName,r))if(i.attributes[r]=Bt(this.doc,wt(n.tagName),wt(r),o),"style"===r){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(t){this.unattachedDoc=this.doc}const r=this.unattachedDoc.createElement("span");e.oldValue&&r.setAttribute("style",e.oldValue);for(const e of Array.from(n.style)){const t=n.style.getPropertyValue(e),o=n.style.getPropertyPriority(e);t!==r.style.getPropertyValue(e)||o!==r.style.getPropertyPriority(e)?i.styleDiff[e]=""===o?t:[t,o]:i._unchangedStyles[e]=[t,o]}for(const e of Array.from(r.style))""===n.style.getPropertyValue(e)&&(i.styleDiff[e]=!1)}else"open"===r&&"DIALOG"===n.tagName&&(n.matches("dialog:modal")?i.attributes.rr_open_mode="modal":i.attributes.rr_open_mode="non-modal");break}case"childList":if(rn(e.target,this.blockClass,this.blockSelector,!0))return;if("TEXTAREA"===e.target.tagName)return void this.genTextAreaValueMutation(e.target);e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{const n=this.mirror.getId(t),r=ft(e.target)?this.mirror.getId(ut(e.target)):this.mirror.getId(e.target);rn(e.target,this.blockClass,this.blockSelector,!1)||on(t,this.mirror,this.slimDOMOptions)||!function(e,t){return-1!==t.getId(e)}(t,this.mirror)||(this.addedSet.has(t)?(vn(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&-1===n||sn(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[yn(n,r)]?vn(this.movedSet,t):(this.removes.push({parentId:r,id:n,isShadow:!(!ft(e.target)||!mt(e.target))||void 0}),function(e,t){const n=[e];for(;n.length;){const e=n.pop();t.has(e)||(t.add(e),it(e).forEach(e=>n.push(e)))}}(t,this.removesSubTreeCache))),this.mapRemoves.push(t))})}}),$e(this,"genAdds",(e,t)=>{if(!this.processedNodeManager.inOtherBuffer(e,this)&&!this.addedSet.has(e)&&!this.movedSet.has(e)){if(this.mirror.hasNode(e)){if(on(e,this.mirror,this.slimDOMOptions))return;this.movedSet.add(e);let n=null;t&&this.mirror.hasNode(t)&&(n=this.mirror.getId(t)),n&&-1!==n&&(this.movedMap[yn(this.mirror.getId(e),n)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);rn(e,this.blockClass,this.blockSelector,!1)||(it(e).forEach(e=>this.genAdds(e)),dn(e)&&it(pt(e)).forEach(t=>{this.processedNodeManager.add(t,this),this.genAdds(t,e)}))}})}init(e){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}};function vn(e,t){e.delete(t),it(t).forEach(t=>vn(e,t))}function wn(e,t,n){return 0!==e.size&&function(e,t){const n=st(t);return!!n&&e.has(n)}(e,t)}function xn(e,t){return 0!==e.size&&Sn(e,t)}function Sn(e,t){const n=st(t);return!!n&&(!!e.has(n)||Sn(e,n))}var kn=e=>mn?(...t)=>{try{return e(...t)}catch(n){if(mn&&!0===mn(n))return;throw n}}:e,Cn=[];function En(e){try{if("composedPath"in e){const t=e.composedPath();if(t.length)return t[0]}else if("path"in e&&e.path.length)return e.path[0]}catch{}return e&&e.target}function In(e,t){const n=new bn;Cn.push(n),n.init(e);const[r,o]=[Je("MutationObserver").constructor,Ge.MutationObserver??(()=>{})],i=new r(kn(n.processMutations.bind(n)));return i.observe(t,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),[i,o]}function Mn({scrollCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,sampling:i}){return Kt("scroll",kn(Jt(kn(i=>{const s=En(i);if(!s||rn(s,r,o,!0))return;const a=n.getId(s);if(s===t&&t.defaultView){const n=Qt(t.defaultView);e({id:a,x:n.left,y:n.top})}else e({id:a,x:s.scrollLeft,y:s.scrollTop})}),i.scroll||100)),t)}var Tn=["INPUT","TEXTAREA","SELECT"],Rn=/* @__PURE__ */new WeakMap;function On(e){return function e(t,n){if(Pn("CSSGroupingRule")&&t.parentRule instanceof CSSGroupingRule||Pn("CSSMediaRule")&&t.parentRule instanceof CSSMediaRule||Pn("CSSSupportsRule")&&t.parentRule instanceof CSSSupportsRule||Pn("CSSConditionRule")&&t.parentRule instanceof CSSConditionRule){const r=Array.from(t.parentRule.cssRules).indexOf(t);return n.unshift(r),e(t.parentRule,n)}if(t.parentStyleSheet){const e=Array.from(t.parentStyleSheet.cssRules).indexOf(t);n.unshift(e)}return n}(e,[])}function An(e,t,n){let r,o;return e?(e.ownerNode?r=t.getId(e.ownerNode):o=n.getId(e),{styleId:o,id:r}):{}}function _n({mirror:e,stylesheetManager:t},n){var r,o,i;let s=null;s="#document"===n.nodeName?e.getId(n):e.getId(ut(n));const a="#document"===n.nodeName?null==(r=n.defaultView)?void 0:r.Document:null==(i=null==(o=n.ownerDocument)?void 0:o.defaultView)?void 0:i.ShadowRoot,c=(null==a?void 0:a.prototype)?Object.getOwnPropertyDescriptor(null==a?void 0:a.prototype,"adoptedStyleSheets"):void 0;return null!==s&&-1!==s&&a&&c?(Object.defineProperty(n,"adoptedStyleSheets",{configurable:c.configurable,enumerable:c.enumerable,get(){var e;return null==(e=c.get)?void 0:e.call(this)},set(e){var n;const r=null==(n=c.set)?void 0:n.call(this,e);if(null!==s&&-1!==s)try{t.adoptStyleSheets(e,s)}catch(o){}return r}}),kn(()=>{Object.defineProperty(n,"adoptedStyleSheets",{configurable:c.configurable,enumerable:c.enumerable,get:c.get,set:c.set})})):()=>{}}function Dn(e,t={}){const n=e.doc.defaultView;if(!n)return()=>{};let r;!function(e,t){const{mutationCb:n,mousemoveCb:r,mouseInteractionCb:o,scrollCb:i,viewportResizeCb:s,inputCb:a,mediaInteractionCb:c,styleSheetRuleCb:l,styleDeclarationCb:d,canvasMutationCb:u,fontCb:p,selectionCb:h,customElementCb:f}=e;e.mutationCb=(...e)=>{t.mutation&&t.mutation(...e),n(...e)},e.mousemoveCb=(...e)=>{t.mousemove&&t.mousemove(...e),r(...e)},e.mouseInteractionCb=(...e)=>{t.mouseInteraction&&t.mouseInteraction(...e),o(...e)},e.scrollCb=(...e)=>{t.scroll&&t.scroll(...e),i(...e)},e.viewportResizeCb=(...e)=>{t.viewportResize&&t.viewportResize(...e),s(...e)},e.inputCb=(...e)=>{t.input&&t.input(...e),a(...e)},e.mediaInteractionCb=(...e)=>{t.mediaInteaction&&t.mediaInteaction(...e),c(...e)},e.styleSheetRuleCb=(...e)=>{t.styleSheetRule&&t.styleSheetRule(...e),l(...e)},e.styleDeclarationCb=(...e)=>{t.styleDeclaration&&t.styleDeclaration(...e),d(...e)},e.canvasMutationCb=(...e)=>{t.canvasMutation&&t.canvasMutation(...e),u(...e)},e.fontCb=(...e)=>{t.font&&t.font(...e),p(...e)},e.selectionCb=(...e)=>{t.selection&&t.selection(...e),h(...e)},e.customElementCb=(...e)=>{t.customElement&&t.customElement(...e),f(...e)}}(e,t);let o=()=>{};e.recordDOM&&([r,o]=In(e,e.doc));const i=function({mousemoveCb:e,sampling:t,doc:n,mirror:r}){if(!1===t.mousemove)return()=>{};const o="number"==typeof t.mousemove?t.mousemove:50,i="number"==typeof t.mousemoveCallback?t.mousemoveCallback:500;let s,a=[];const c=Jt(kn(t=>{const n=Date.now()-s;e(a.map(e=>(e.timeOffset-=n,e)),t),a=[],s=null}),i),l=kn(Jt(kn(e=>{const t=En(e),{clientX:n,clientY:o}=an(e)?e.changedTouches[0]:e;s||(s=nt()),a.push({x:n,y:o,id:r.getId(t),timeOffset:nt()-s}),c("undefined"!=typeof DragEvent&&e instanceof DragEvent?We.Drag:e instanceof MouseEvent?We.MouseMove:We.TouchMove)}),o,{trailing:!1})),d=[Kt("mousemove",l,n),Kt("touchmove",l,n),Kt("drag",l,n)];return kn(()=>{d.forEach(e=>e())})}(e),s=function({mouseInteractionCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,sampling:i}){if(!1===i.mouseInteraction)return()=>{};const s=!0===i.mouseInteraction||void 0===i.mouseInteraction?{}:i.mouseInteraction,a=[];let c=null;return Object.keys(Ue).filter(e=>Number.isNaN(Number(e))&&!e.endsWith("_Departed")&&!1!==s[e]).forEach(i=>{let s=wt(i);const l=(t=>i=>{const s=En(i);if(rn(s,r,o,!0))return;let a=null,l=t;if("pointerType"in i){switch(i.pointerType){case"mouse":a=He.Mouse;break;case"touch":a=He.Touch;break;case"pen":a=He.Pen}a===He.Touch?Ue[t]===Ue.MouseDown?l="TouchStart":Ue[t]===Ue.MouseUp&&(l="TouchEnd"):He.Pen}else an(i)&&(a=He.Touch);null!==a?(c=a,(l.startsWith("Touch")&&a===He.Touch||l.startsWith("Mouse")&&a===He.Mouse)&&(a=null)):Ue[t]===Ue.Click&&(a=c,c=null);const d=an(i)?i.changedTouches[0]:i;if(!d)return;const u=n.getId(s),{clientX:p,clientY:h}=d;kn(e)({type:Ue[l],id:u,x:p,y:h,...null!==a&&{pointerType:a}})})(i);if(window.PointerEvent)switch(Ue[i]){case Ue.MouseDown:case Ue.MouseUp:s=s.replace("mouse","pointer");break;case Ue.TouchStart:case Ue.TouchEnd:return}a.push(Kt(s,l,t))}),kn(()=>{a.forEach(e=>e())})}(e),a=Mn(e),c=function({viewportResizeCb:e},{win:t}){let n=-1,r=-1;return Kt("resize",kn(Jt(kn(()=>{const t=en(),o=tn();n===t&&r===o||(e({width:Number(o),height:Number(t)}),n=t,r=o)}),200)),t)}(e,{win:n}),l=function({inputCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,ignoreClass:i,ignoreSelector:s,maskInputOptions:a,maskInputFn:c,sampling:l,userTriggeredOnInput:d}){function u(e){let n=En(e);const l=e.isTrusted,u=n&&n.tagName;if(n&&"OPTION"===u&&(n=at(n)),!n||!u||Tn.indexOf(u)<0||rn(n,r,o,!0))return;if(n.classList.contains(i)||s&&n.matches(s))return;let h=n.value,f=!1;const m=St(n)||"";"radio"===m||"checkbox"===m?f=n.checked:(a[u.toLowerCase()]||a[m])&&(h=vt({element:n,maskInputOptions:a,tagName:u,type:m,value:h,maskInputFn:c})),p(n,d?{text:h,isChecked:f,userTriggered:l}:{text:h,isChecked:f});const g=n.name;"radio"===m&&g&&f&&t.querySelectorAll(`input[type="radio"][name="${g}"]`).forEach(e=>{if(e!==n){const t=e.value;p(e,d?{text:t,isChecked:!f,userTriggered:!1}:{text:t,isChecked:!f})}})}function p(t,r){const o=Rn.get(t);if(!o||o.text!==r.text||o.isChecked!==r.isChecked){Rn.set(t,r);const o=n.getId(t);kn(e)({...r,id:o})}}const h=("last"===l.input?["change"]:["input","change"]).map(e=>Kt(e,kn(u),t)),f=t.defaultView;if(!f)return()=>{h.forEach(e=>e())};const m=f.Object.getOwnPropertyDescriptor(f.HTMLInputElement.prototype,"value"),g=[[f.HTMLInputElement.prototype,"value"],[f.HTMLInputElement.prototype,"checked"],[f.HTMLSelectElement.prototype,"value"],[f.HTMLTextAreaElement.prototype,"value"],[f.HTMLSelectElement.prototype,"selectedIndex"],[f.HTMLOptionElement.prototype,"selected"]];return m&&m.set&&h.push(...g.map(e=>Zt(e[0],e[1],{set(){kn(u)({target:this,isTrusted:!1})}},!1,f))),kn(()=>{h.forEach(e=>e())})}(e),d=function({mediaInteractionCb:e,blockClass:t,blockSelector:n,mirror:r,sampling:o,doc:i}){const s=kn(i=>Jt(kn(o=>{const s=En(o);if(!s||rn(s,t,n,!0))return;const{currentTime:a,volume:c,muted:l,playbackRate:d,loop:u}=s;e({type:i,id:r.getId(s),currentTime:a,volume:c,muted:l,playbackRate:d,loop:u})}),o.media||500)),a=[Kt("play",s(qe.Play),i),Kt("pause",s(qe.Pause),i),Kt("seeked",s(qe.Seeked),i),Kt("volumechange",s(qe.VolumeChange),i),Kt("ratechange",s(qe.RateChange),i)];return kn(()=>{a.forEach(e=>e())})}(e);let u=()=>{},p=()=>{},h=()=>{},f=()=>{};e.recordDOM&&(u=function({styleSheetRuleCb:e,mirror:t,stylesheetManager:n},{win:r}){if(!r.CSSStyleSheet||!r.CSSStyleSheet.prototype)return()=>{};const o=r.CSSStyleSheet.prototype.insertRule;r.CSSStyleSheet.prototype.insertRule=new Proxy(o,{apply:kn((r,o,i)=>{const[s,a]=i,{id:c,styleId:l}=An(o,t,n.styleMirror);return(c&&-1!==c||l&&-1!==l)&&e({id:c,styleId:l,adds:[{rule:s,index:a}]}),r.apply(o,i)})}),r.CSSStyleSheet.prototype.addRule=function(e,t,n=this.cssRules.length){const o=`${e} { ${t} }`;return r.CSSStyleSheet.prototype.insertRule.apply(this,[o,n])};const i=r.CSSStyleSheet.prototype.deleteRule;let s,a;r.CSSStyleSheet.prototype.deleteRule=new Proxy(i,{apply:kn((r,o,i)=>{const[s]=i,{id:a,styleId:c}=An(o,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,removes:[{index:s}]}),r.apply(o,i)})}),r.CSSStyleSheet.prototype.removeRule=function(e){return r.CSSStyleSheet.prototype.deleteRule.apply(this,[e])},r.CSSStyleSheet.prototype.replace&&(s=r.CSSStyleSheet.prototype.replace,r.CSSStyleSheet.prototype.replace=new Proxy(s,{apply:kn((r,o,i)=>{const[s]=i,{id:a,styleId:c}=An(o,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,replace:s}),r.apply(o,i)})})),r.CSSStyleSheet.prototype.replaceSync&&(a=r.CSSStyleSheet.prototype.replaceSync,r.CSSStyleSheet.prototype.replaceSync=new Proxy(a,{apply:kn((r,o,i)=>{const[s]=i,{id:a,styleId:c}=An(o,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,replaceSync:s}),r.apply(o,i)})}));const c={};Nn("CSSGroupingRule")?c.CSSGroupingRule=r.CSSGroupingRule:(Nn("CSSMediaRule")&&(c.CSSMediaRule=r.CSSMediaRule),Nn("CSSConditionRule")&&(c.CSSConditionRule=r.CSSConditionRule),Nn("CSSSupportsRule")&&(c.CSSSupportsRule=r.CSSSupportsRule));const l={};return Object.entries(c).forEach(([r,o])=>{l[r]={insertRule:o.prototype.insertRule,deleteRule:o.prototype.deleteRule},o.prototype.insertRule=new Proxy(l[r].insertRule,{apply:kn((r,o,i)=>{const[s,a]=i,{id:c,styleId:l}=An(o.parentStyleSheet,t,n.styleMirror);return(c&&-1!==c||l&&-1!==l)&&e({id:c,styleId:l,adds:[{rule:s,index:[...On(o),a||0]}]}),r.apply(o,i)})}),o.prototype.deleteRule=new Proxy(l[r].deleteRule,{apply:kn((r,o,i)=>{const[s]=i,{id:a,styleId:c}=An(o.parentStyleSheet,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,removes:[{index:[...On(o),s]}]}),r.apply(o,i)})})}),kn(()=>{r.CSSStyleSheet.prototype.insertRule=o,r.CSSStyleSheet.prototype.deleteRule=i,s&&(r.CSSStyleSheet.prototype.replace=s),a&&(r.CSSStyleSheet.prototype.replaceSync=a),Object.entries(c).forEach(([e,t])=>{t.prototype.insertRule=l[e].insertRule,t.prototype.deleteRule=l[e].deleteRule})})}(e,{win:n}),p=_n(e,e.doc),h=function({styleDeclarationCb:e,mirror:t,ignoreCSSAttributes:n,stylesheetManager:r},{win:o}){const i=o.CSSStyleDeclaration.prototype.setProperty;o.CSSStyleDeclaration.prototype.setProperty=new Proxy(i,{apply:kn((o,s,a)=>{var c;const[l,d,u]=a;if(n.has(l))return i.apply(s,[l,d,u]);const{id:p,styleId:h}=An(null==(c=s.parentRule)?void 0:c.parentStyleSheet,t,r.styleMirror);return(p&&-1!==p||h&&-1!==h)&&e({id:p,styleId:h,set:{property:l,value:d,priority:u},index:On(s.parentRule)}),o.apply(s,a)})});const s=o.CSSStyleDeclaration.prototype.removeProperty;return o.CSSStyleDeclaration.prototype.removeProperty=new Proxy(s,{apply:kn((o,i,a)=>{var c;const[l]=a;if(n.has(l))return s.apply(i,[l]);const{id:d,styleId:u}=An(null==(c=i.parentRule)?void 0:c.parentStyleSheet,t,r.styleMirror);return(d&&-1!==d||u&&-1!==u)&&e({id:d,styleId:u,remove:{property:l},index:On(i.parentRule)}),o.apply(i,a)})}),kn(()=>{o.CSSStyleDeclaration.prototype.setProperty=i,o.CSSStyleDeclaration.prototype.removeProperty=s})}(e,{win:n}),e.collectFonts&&(f=function({fontCb:e,doc:t}){const n=t.defaultView;if(!n)return()=>{};const r=[],o=/* @__PURE__ */new WeakMap,i=n.FontFace;n.FontFace=function(e,t,n){const r=new i(e,t,n);return o.set(r,{family:e,buffer:"string"!=typeof t,descriptors:n,fontSource:"string"==typeof t?t:JSON.stringify(Array.from(new Uint8Array(t)))}),r};const s=rt(t.fonts,"add",function(t){return function(n){return setTimeout(kn(()=>{const t=o.get(n);t&&(e(t),o.delete(n))}),0),t.apply(this,[n])}});return r.push(()=>{n.FontFace=i}),r.push(s),kn(()=>{r.forEach(e=>e())})}(e)));const m=function(e){const{doc:t,mirror:n,blockClass:r,blockSelector:o,selectionCb:i}=e;let s=!0;const a=kn(()=>{const e=t.getSelection();if(!e||s&&(null==e?void 0:e.isCollapsed))return;s=e.isCollapsed||!1;const a=[],c=e.rangeCount||0;for(let t=0;t<c;t++){const{startContainer:i,startOffset:s,endContainer:c,endOffset:l}=e.getRangeAt(t);rn(i,r,o,!0)||rn(c,r,o,!0)||a.push({start:n.getId(i),startOffset:s,end:n.getId(c),endOffset:l})}i({ranges:a})});return a(),Kt("selectionchange",a)}(e),g=function({doc:e,customElementCb:t}){const n=e.defaultView;return n&&n.customElements?rt(n.customElements,"define",function(e){return function(n,r,o){try{t({define:{name:n}})}catch(i){console.warn(`Custom element callback failed for ${n}`)}return e.apply(this,[n,r,o])}}):()=>{}}(e),y=[];for(const b of e.plugins)y.push(b.observer(b.callback,n,b.options));return kn(()=>{Cn.forEach(e=>e.reset()),r?.disconnect(),o(),i(),s(),a(),c(),l(),d(),u(),p(),h(),f(),m(),g(),y.forEach(e=>e())})}function Pn(e){return void 0!==window[e]}function Nn(e){return Boolean(void 0!==window[e]&&window[e].prototype&&"insertRule"in window[e].prototype&&"deleteRule"in window[e].prototype)}for(var Ln=class{constructor(e){$e(this,"iframeIdToRemoteIdMap",/* @__PURE__ */new WeakMap),$e(this,"iframeRemoteIdToIdMap",/* @__PURE__ */new WeakMap),this.generateIdFn=e}getId(e,t,n,r){const o=n||this.getIdToRemoteIdMap(e),i=r||this.getRemoteIdToIdMap(e);let s=o.get(t);return s||(s=this.generateIdFn(),o.set(t,s),i.set(s,t)),s}getIds(e,t){const n=this.getIdToRemoteIdMap(e),r=this.getRemoteIdToIdMap(e);return t.map(t=>this.getId(e,t,n,r))}getRemoteId(e,t,n){const r=n||this.getRemoteIdToIdMap(e);return"number"!=typeof t?t:r.get(t)||-1}getRemoteIds(e,t){const n=this.getRemoteIdToIdMap(e);return t.map(t=>this.getRemoteId(e,t,n))}reset(e){if(!e)return this.iframeIdToRemoteIdMap=/* @__PURE__ */new WeakMap,void(this.iframeRemoteIdToIdMap=/* @__PURE__ */new WeakMap);this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=/* @__PURE__ */new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=/* @__PURE__ */new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}},Fn=class{constructor(e){$e(this,"iframes",/* @__PURE__ */new WeakMap),$e(this,"crossOriginIframeMap",/* @__PURE__ */new WeakMap),$e(this,"crossOriginIframeMirror",new Ln(Pt)),$e(this,"crossOriginIframeStyleMirror"),$e(this,"crossOriginIframeRootIdMap",/* @__PURE__ */new WeakMap),$e(this,"mirror"),$e(this,"mutationCb"),$e(this,"wrappedEmit"),$e(this,"loadListener"),$e(this,"stylesheetManager"),$e(this,"recordCrossOriginIframes"),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new Ln(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var n,r;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&(null==(n=e.contentWindow)||n.addEventListener("message",this.handleMessage.bind(this))),null==(r=this.loadListener)||r.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){const t=e;if("rrweb"!==t.data.type||t.origin!==t.data.origin)return;if(!e.source)return;const n=this.crossOriginIframeMap.get(e.source);if(!n)return;const r=this.transformCrossOriginEvent(n,t.data.event);r&&this.wrappedEmit(r,t.data.isCheckout)}transformCrossOriginEvent(e,t){var n;switch(t.type){case Be.FullSnapshot:{this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e);const n=t.data.node.id;return this.crossOriginIframeRootIdMap.set(e,n),this.patchRootIdOnNode(t.data.node,n),{timestamp:t.timestamp,type:Be.IncrementalSnapshot,data:{source:We.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case Be.Meta:case Be.Load:case Be.DomContentLoaded:return!1;case Be.Plugin:return t;case Be.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case Be.IncrementalSnapshot:switch(t.data.source){case We.Mutation:return t.data.adds.forEach(t=>{this.replaceIds(t,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(t.node,e);const n=this.crossOriginIframeRootIdMap.get(e);n&&this.patchRootIdOnNode(t.node,n)}),t.data.removes.forEach(t=>{this.replaceIds(t,e,["parentId","id"])}),t.data.attributes.forEach(t=>{this.replaceIds(t,e,["id"])}),t.data.texts.forEach(t=>{this.replaceIds(t,e,["id"])}),t;case We.Drag:case We.TouchMove:case We.MouseMove:return t.data.positions.forEach(t=>{this.replaceIds(t,e,["id"])}),t;case We.ViewportResize:return!1;case We.MediaInteraction:case We.MouseInteraction:case We.Scroll:case We.CanvasMutation:case We.Input:return this.replaceIds(t.data,e,["id"]),t;case We.StyleSheetRule:case We.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case We.Font:return t;case We.Selection:return t.data.ranges.forEach(t=>{this.replaceIds(t,e,["start","end"])}),t;case We.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),null==(n=t.data.styles)||n.forEach(t=>{this.replaceStyleIds(t,e,["styleId"])}),t}}return!1}replace(e,t,n,r){for(const o of r)(Array.isArray(t[o])||"number"==typeof t[o])&&(Array.isArray(t[o])?t[o]=e.getIds(n,t[o]):t[o]=e.getId(n,t[o]));return t}replaceIds(e,t,n){return this.replace(this.crossOriginIframeMirror,e,t,n)}replaceStyleIds(e,t,n){return this.replace(this.crossOriginIframeStyleMirror,e,t,n)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id","rootId"]),"childNodes"in e&&e.childNodes.forEach(e=>{this.replaceIdOnNode(e,t)})}patchRootIdOnNode(e,t){e.type===Ve.Document||e.rootId||(e.rootId=t),"childNodes"in e&&e.childNodes.forEach(e=>{this.patchRootIdOnNode(e,t)})}},zn=class{constructor(e){$e(this,"shadowDoms",/* @__PURE__ */new WeakSet),$e(this,"mutationCb"),$e(this,"scrollCb"),$e(this,"bypassOptions"),$e(this,"mirror"),$e(this,"restoreHandlers",[]),this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(e,t){if(!mt(e))return;if(this.shadowDoms.has(e))return;this.shadowDoms.add(e);const[n]=In({...this.bypassOptions,doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},e);this.restoreHandlers.push(()=>n.disconnect()),this.restoreHandlers.push(Mn({...this.bypassOptions,scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(ut(e))),this.restoreHandlers.push(_n({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e))},0)}observeAttachShadow(e){e.contentWindow&&e.contentDocument&&this.patchAttachShadow(e.contentWindow.Element,e.contentDocument)}patchAttachShadow(e,t){const n=this;this.restoreHandlers.push(rt(e.prototype,"attachShadow",function(e){return function(r){const o=e.call(this,r),i=pt(this);return i&&hn(this)&&n.addShadowRoot(i,t),o}}))}reset(){this.restoreHandlers.forEach(e=>{try{e()}catch(t){}}),this.restoreHandlers=[],this.shadowDoms=/* @__PURE__ */new WeakSet}},$n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Bn="undefined"==typeof Uint8Array?[]:/* @__PURE__ */new Uint8Array(256),Wn=0;Wn<64;Wn++)Bn[$n.charCodeAt(Wn)]=Wn;var Un=function(e){var t,n=new Uint8Array(e),r=n.length,o="";for(t=0;t<r;t+=3)o+=$n[n[t]>>2],o+=$n[(3&n[t])<<4|n[t+1]>>4],o+=$n[(15&n[t+1])<<2|n[t+2]>>6],o+=$n[63&n[t+2]];return r%3==2?o=o.substring(0,o.length-1)+"=":r%3==1&&(o=o.substring(0,o.length-2)+"=="),o},Hn=/* @__PURE__ */new Map,jn=(e,t,n)=>{if(!e||!Yn(e,t)&&"object"!=typeof e)return;const r=function(e,t){let n=Hn.get(e);return n||(n=/* @__PURE__ */new Map,Hn.set(e,n)),n.has(t)||n.set(t,[]),n.get(t)}(n,e.constructor.name);let o=r.indexOf(e);return-1===o&&(o=r.length,r.push(e)),o};function qn(e,t,n){if(e instanceof Array)return e.map(e=>qn(e,t,n));if(null===e)return e;if(e instanceof Float32Array||e instanceof Float64Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Uint8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Int8Array||e instanceof Uint8ClampedArray)return{rr_type:e.constructor.name,args:[Object.values(e)]};if(e instanceof ArrayBuffer)return{rr_type:e.constructor.name,base64:Un(e)};if(e instanceof DataView)return{rr_type:e.constructor.name,args:[qn(e.buffer,t,n),e.byteOffset,e.byteLength]};if(e instanceof HTMLImageElement){const t=e.constructor.name,{src:n}=e;return{rr_type:t,src:n}}return e instanceof HTMLCanvasElement?{rr_type:"HTMLImageElement",src:e.toDataURL()}:e instanceof ImageData?{rr_type:e.constructor.name,args:[qn(e.data,t,n),e.width,e.height]}:Yn(e,t)||"object"==typeof e?{rr_type:e.constructor.name,index:jn(e,t,n)}:e}var Vn=(e,t,n)=>e.map(e=>qn(e,t,n)),Yn=(e,t)=>{const n=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(e=>"function"==typeof t[e]);return Boolean(n.find(n=>e instanceof t[n]))};function Kn(e,t,n,r){const o=[];try{const i=rt(e.HTMLCanvasElement.prototype,"getContext",function(e){return function(o,...i){if(!rn(this,t,n,!0)){const e=function(e){return"experimental-webgl"===e?"webgl":e}(o);if("__context"in this||(this.__context=e),r&&["webgl","webgl2"].includes(e))if(i[0]&&"object"==typeof i[0]){const e=i[0];e.preserveDrawingBuffer||(e.preserveDrawingBuffer=!0)}else i.splice(0,1,{preserveDrawingBuffer:!0})}return e.apply(this,[o,...i])}});o.push(i)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{o.forEach(e=>e())}}function Xn(e,t,n,r,o,i){const s=[],a=Object.getOwnPropertyNames(e);for(const c of a)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(c))try{if("function"!=typeof e[c])continue;const a=rt(e,c,function(e){return function(...s){const a=e.apply(this,s);if(jn(a,i,this),"tagName"in this.canvas&&!rn(this.canvas,r,o,!0)){const e=Vn(s,i,this),r={type:t,property:c,args:e};n(this.canvas,r)}return a}});s.push(a)}catch{const r=Zt(e,c,{set(e){n(this.canvas,{type:t,property:c,args:[e],setter:!0})}});s.push(r)}return s}var Gn='(function() {\n "use strict";\n var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\n var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);\n for (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n }\n var encode = function(arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = "";\n for (i2 = 0; i2 < len; i2 += 3) {\n base64 += chars[bytes[i2] >> 2];\n base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];\n base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];\n base64 += chars[bytes[i2 + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + "=";\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + "==";\n }\n return base64;\n };\n const lastBlobMap = /* @__PURE__ */ new Map();\n const transparentBlobMap = /* @__PURE__ */ new Map();\n async function getTransparentBlobFor(width, height, dataURLOptions) {\n const id = `${width}-${height}`;\n if ("OffscreenCanvas" in globalThis) {\n if (transparentBlobMap.has(id)) return transparentBlobMap.get(id);\n const offscreen = new OffscreenCanvas(width, height);\n offscreen.getContext("2d");\n const blob = await offscreen.convertToBlob(dataURLOptions);\n const arrayBuffer = await blob.arrayBuffer();\n const base64 = encode(arrayBuffer);\n transparentBlobMap.set(id, base64);\n return base64;\n } else {\n return "";\n }\n }\n const worker = self;\n worker.onmessage = async function(e) {\n if ("OffscreenCanvas" in globalThis) {\n const { id, bitmap, width, height, dataURLOptions } = e.data;\n const transparentBase64 = getTransparentBlobFor(\n width,\n height,\n dataURLOptions\n );\n const offscreen = new OffscreenCanvas(width, height);\n const ctx = offscreen.getContext("2d");\n ctx.drawImage(bitmap, 0, 0);\n bitmap.close();\n const blob = await offscreen.convertToBlob(dataURLOptions);\n const type = blob.type;\n const arrayBuffer = await blob.arrayBuffer();\n const base64 = encode(arrayBuffer);\n if (!lastBlobMap.has(id) && await transparentBase64 === base64) {\n lastBlobMap.set(id, base64);\n return worker.postMessage({ id });\n }\n if (lastBlobMap.get(id) === base64) return worker.postMessage({ id });\n worker.postMessage({\n id,\n type,\n base64,\n width,\n height\n });\n lastBlobMap.set(id, base64);\n } else {\n return worker.postMessage({ id: e.data.id });\n }\n };\n})();\n//# sourceMappingURL=image-bitmap-data-url-worker-IJpC7g_b.js.map\n',Jn="undefined"!=typeof self&&self.Blob&&new Blob([Gn],{type:"text/javascript;charset=utf-8"});function Zn(e){let t;try{if(t=Jn&&(self.URL||self.webkitURL).createObjectURL(Jn),!t)throw"";const n=new Worker(t,{name:null==e?void 0:e.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch(n){return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Gn),{name:null==e?void 0:e.name})}finally{t&&(self.URL||self.webkitURL).revokeObjectURL(t)}}var Qn,er,tr,nr=class{constructor(e){$e(this,"pendingCanvasMutations",/* @__PURE__ */new Map),$e(this,"rafStamps",{latestId:0,invokeId:null}),$e(this,"mirror"),$e(this,"mutationCb"),$e(this,"resetObservers"),$e(this,"frozen",!1),$e(this,"locked",!1),$e(this,"processMutation",(e,t)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(e)||this.pendingCanvasMutations.set(e,[]),this.pendingCanvasMutations.get(e).push(t)});const{sampling:t="all",win:n,blockClass:r,blockSelector:o,recordCanvas:i,dataURLOptions:s}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,i&&"all"===t&&this.initCanvasMutationObserver(n,r,o),i&&"number"==typeof t&&this.initCanvasFPSObserver(t,n,r,o,{dataURLOptions:s})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,n,r,o){const i=Kn(t,n,r,!0),s=/* @__PURE__ */new Map,a=new Zn;a.onmessage=e=>{const{id:t}=e.data;if(s.set(t,!1),!("base64"in e.data))return;const{base64:n,type:r,width:o,height:i}=e.data;this.mutationCb({id:t,type:je["2D"],commands:[{property:"clearRect",args:[0,0,o,i]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:n}],type:r}]},0,0]}]})};const c=1e3/e;let l,d=0;const u=e=>{d&&e-d<c||(d=e,(()=>{const e=[];return t.document.querySelectorAll("canvas").forEach(t=>{rn(t,n,r,!0)||e.push(t)}),e})().forEach(async e=>{var t;const n=this.mirror.getId(e);if(s.get(n))return;if(0===e.width||0===e.height)return;if(s.set(n,!0),["webgl","webgl2"].includes(e.__context)){const n=e.getContext(e.__context);!1===(null==(t=null==n?void 0:n.getContextAttributes())?void 0:t.preserveDrawingBuffer)&&n.clear(n.COLOR_BUFFER_BIT)}const r=await createImageBitmap(e);a.postMessage({id:n,bitmap:r,width:e.width,height:e.height,dataURLOptions:o.dataURLOptions},[r])})),l=requestAnimationFrame(u)};l=requestAnimationFrame(u),this.resetObservers=()=>{i(),cancelAnimationFrame(l)}}initCanvasMutationObserver(e,t,n){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const r=Kn(e,t,n,!1),o=function(e,t,n,r){const o=[],i=Object.getOwnPropertyNames(t.CanvasRenderingContext2D.prototype);for(const s of i)try{if("function"!=typeof t.CanvasRenderingContext2D.prototype[s])continue;const i=rt(t.CanvasRenderingContext2D.prototype,s,function(o){return function(...i){return rn(this.canvas,n,r,!0)||setTimeout(()=>{const n=Vn(i,t,this);e(this.canvas,{type:je["2D"],property:s,args:n})},0),o.apply(this,i)}});o.push(i)}catch{const n=Zt(t.CanvasRenderingContext2D.prototype,s,{set(t){e(this.canvas,{type:je["2D"],property:s,args:[t],setter:!0})}});o.push(n)}return()=>{o.forEach(e=>e())}}(this.processMutation.bind(this),e,t,n),i=function(e,t,n,r){const o=[];return void 0!==t.WebGLRenderingContext&&o.push(...Xn(t.WebGLRenderingContext.prototype,je.WebGL,e,n,r,t)),void 0!==t.WebGL2RenderingContext&&o.push(...Xn(t.WebGL2RenderingContext.prototype,je.WebGL2,e,n,r,t)),()=>{o.forEach(e=>e())}}(this.processMutation.bind(this),e,t,n);this.resetObservers=()=>{r(),o(),i()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{const n=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,n)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;const n=this.pendingCanvasMutations.get(e);if(!n||-1===t)return;const r=n.map(e=>{const{type:t,...n}=e;return n}),{type:o}=n[0];this.mutationCb({id:t,type:o,commands:r}),this.pendingCanvasMutations.delete(e)}},rr=class{constructor(e){$e(this,"trackedLinkElements",/* @__PURE__ */new WeakSet),$e(this,"mutationCb"),$e(this,"adoptedStyleSheetCb"),$e(this,"styleMirror",new un),this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(0===e.length)return;const n={id:t,styleIds:[]},r=[];for(const o of e){let e;this.styleMirror.has(o)?e=this.styleMirror.getId(o):(e=this.styleMirror.add(o),r.push({styleId:e,rules:Array.from(o.rules||CSSRule,(e,t)=>({rule:yt(e,o.href),index:t}))})),n.styleIds.push(e)}r.length>0&&(n.styles=r),this.adoptedStyleSheetCb(n)}reset(){this.styleMirror.reset(),this.trackedLinkElements=/* @__PURE__ */new WeakSet}trackStylesheetInLinkElement(e){}},or=class{constructor(){$e(this,"nodeMap",/* @__PURE__ */new WeakMap),$e(this,"active",!1)}inOtherBuffer(e,t){const n=this.nodeMap.get(e);return n&&Array.from(n).some(e=>e!==t)}add(e,t){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=/* @__PURE__ */new WeakMap,this.active=!1})),this.nodeMap.set(e,(this.nodeMap.get(e)||/* @__PURE__ */new Set).add(t))}destroy(){}},ir=!1;try{if(2!==Array.from([1],e=>2*e)[0]){const e=document.createElement("iframe");document.body.appendChild(e),Array.from=(null==(Ne=e.contentWindow)?void 0:Ne.Array.from)||Array.from,document.body.removeChild(e)}}catch(iu){}var sr=new bt;function ar(e={}){const{emit:t,checkoutEveryNms:n,checkoutEveryNth:r,blockClass:o="rr-block",blockSelector:i=null,ignoreClass:s="rr-ignore",ignoreSelector:a=null,maskTextClass:c="rr-mask",maskTextSelector:l=null,inlineStylesheet:d=!0,maskAllInputs:u,maskInputOptions:p,slimDOMOptions:h,maskInputFn:f,maskTextFn:m,hooks:g,packFn:y,sampling:b={},dataURLOptions:v={},mousemoveWait:w,recordDOM:x=!0,recordCanvas:S=!1,recordCrossOriginIframes:k=!1,recordAfter:C=("DOMContentLoaded"===e.recordAfter?e.recordAfter:"load"),userTriggeredOnInput:E=!1,collectFonts:I=!1,inlineImages:M=!1,plugins:T,keepIframeSrcFn:R=()=>!1,ignoreCSSAttributes:O=/* @__PURE__ */new Set([]),errorHandler:A}=e;mn=A;const _=!k||window.parent===window;let D=!1;if(!_)try{window.parent.document&&(D=!1)}catch(V){D=!0}if(_&&!t)throw new Error("emit function is required");if(!_&&!D)return()=>{};void 0!==w&&void 0===b.mousemove&&(b.mousemove=w),sr.reset();const P=!0===u?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:void 0!==p?p:{password:!0},N=qt(h);let L;!function(e=window){"NodeList"in e&&!e.NodeList.prototype.forEach&&(e.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in e&&!e.DOMTokenList.prototype.forEach&&(e.DOMTokenList.prototype.forEach=Array.prototype.forEach)}();let F=0;const z=e=>{for(const t of T||[])t.eventProcessor&&(e=t.eventProcessor(e));return y&&!D&&(e=y(e)),e};Qn=(e,o)=>{var i;const s=e;if(s.timestamp=nt(),!(null==(i=Cn[0])?void 0:i.isFrozen())||s.type===Be.FullSnapshot||s.type===Be.IncrementalSnapshot&&s.data.source===We.Mutation||Cn.forEach(e=>e.unfreeze()),_)t?.(z(s),o);else if(D){const e={type:"rrweb",event:z(s),origin:window.location.origin,isCheckout:o};window.parent.postMessage(e,"*")}if(s.type===Be.FullSnapshot)L=s,F=0;else if(s.type===Be.IncrementalSnapshot){if(s.data.source===We.Mutation&&s.data.isAttachIframe)return;F++;const e=r&&F>=r,t=n&&s.timestamp-L.timestamp>n;(e||t)&&er(!0)}};const $=e=>{Qn({type:Be.IncrementalSnapshot,data:{source:We.Mutation,...e}})},B=e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.Scroll,...e}}),W=e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.CanvasMutation,...e}}),U=new rr({mutationCb:$,adoptedStyleSheetCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.AdoptedStyleSheet,...e}})}),H=new Fn({mirror:sr,mutationCb:$,stylesheetManager:U,recordCrossOriginIframes:k,wrappedEmit:Qn});for(const K of T||[])K.getMirror&&K.getMirror({nodeMirror:sr,crossOriginIframeMirror:H.crossOriginIframeMirror,crossOriginIframeStyleMirror:H.crossOriginIframeStyleMirror});const j=new or;tr=new nr({recordCanvas:S,mutationCb:W,win:window,blockClass:o,blockSelector:i,mirror:sr,sampling:b.canvas,dataURLOptions:v});const q=new zn({mutationCb:$,scrollCb:B,bypassOptions:{blockClass:o,blockSelector:i,maskTextClass:c,maskTextSelector:l,inlineStylesheet:d,maskInputOptions:P,dataURLOptions:v,maskTextFn:m,maskInputFn:f,recordCanvas:S,inlineImages:M,sampling:b,slimDOMOptions:N,iframeManager:H,stylesheetManager:U,canvasManager:tr,keepIframeSrcFn:R,processedNodeManager:j},mirror:sr});er=(e=!1)=>{if(!x)return;Qn({type:Be.Meta,data:{href:window.location.href,width:tn(),height:en()}},e),U.reset(),q.init(),Cn.forEach(e=>e.lock());const t=function(e,t){const{mirror:n=new bt,blockClass:r="rr-block",blockSelector:o=null,maskTextClass:i="rr-mask",maskTextSelector:s=null,inlineStylesheet:a=!0,inlineImages:c=!1,recordCanvas:l=!1,maskAllInputs:d=!1,maskTextFn:u,maskInputFn:p,slimDOM:h=!1,dataURLOptions:f,preserveWhiteSpace:m,onSerialize:g,onIframeLoad:y,iframeLoadTimeout:b,onStylesheetLoad:v,stylesheetLoadTimeout:w,keepIframeSrcFn:x=()=>!1}=t;return Vt(e,{doc:e,mirror:n,blockClass:r,blockSelector:o,maskTextClass:i,maskTextSelector:s,skipChild:!1,inlineStylesheet:a,maskInputOptions:!0===d?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:!1===d?{password:!0}:d,maskTextFn:u,maskInputFn:p,slimDOMOptions:qt(h),dataURLOptions:f,inlineImages:c,recordCanvas:l,preserveWhiteSpace:m,onSerialize:g,onIframeLoad:y,iframeLoadTimeout:b,onStylesheetLoad:v,stylesheetLoadTimeout:w,keepIframeSrcFn:x,newlyAddedElement:!1})}(document,{mirror:sr,blockClass:o,blockSelector:i,maskTextClass:c,maskTextSelector:l,inlineStylesheet:d,maskAllInputs:P,maskTextFn:m,maskInputFn:f,slimDOM:N,dataURLOptions:v,recordCanvas:S,inlineImages:M,onSerialize:e=>{cn(e,sr)&&H.addIframe(e),ln(e,sr)&&U.trackLinkElement(e),dn(e)&&q.addShadowRoot(pt(e),document)},onIframeLoad:(e,t)=>{H.attachIframe(e,t),q.observeAttachShadow(e)},onStylesheetLoad:(e,t)=>{U.attachLinkElement(e,t)},keepIframeSrcFn:R});if(!t)return console.warn("Failed to snapshot the document");Qn({type:Be.FullSnapshot,data:{node:t,initialOffset:Qt(window)}},e),Cn.forEach(e=>e.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&U.adoptStyleSheets(document.adoptedStyleSheets,sr.getId(document))};try{const e=[],t=e=>{var t;return kn(Dn)({mutationCb:$,mousemoveCb:(e,t)=>Qn({type:Be.IncrementalSnapshot,data:{source:t,positions:e}}),mouseInteractionCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.MouseInteraction,...e}}),scrollCb:B,viewportResizeCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.ViewportResize,...e}}),inputCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.Input,...e}}),mediaInteractionCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.MediaInteraction,...e}}),styleSheetRuleCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.StyleSheetRule,...e}}),styleDeclarationCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.StyleDeclaration,...e}}),canvasMutationCb:W,fontCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.Font,...e}}),selectionCb:e=>{Qn({type:Be.IncrementalSnapshot,data:{source:We.Selection,...e}})},customElementCb:e=>{Qn({type:Be.IncrementalSnapshot,data:{source:We.CustomElement,...e}})},blockClass:o,ignoreClass:s,ignoreSelector:a,maskTextClass:c,maskTextSelector:l,maskInputOptions:P,inlineStylesheet:d,sampling:b,recordDOM:x,recordCanvas:S,inlineImages:M,userTriggeredOnInput:E,collectFonts:I,doc:e,maskInputFn:f,maskTextFn:m,keepIframeSrcFn:R,blockSelector:i,slimDOMOptions:N,dataURLOptions:v,mirror:sr,iframeManager:H,stylesheetManager:U,shadowDomManager:q,processedNodeManager:j,canvasManager:tr,ignoreCSSAttributes:O,plugins:(null==(t=null==T?void 0:T.filter(e=>e.observer))?void 0:t.map(e=>({observer:e.observer,options:e.options,callback:t=>Qn({type:Be.Plugin,data:{plugin:e.name,payload:t}})})))||[]},g)};H.addLoadListener(n=>{try{e.push(t(n.contentDocument))}catch(r){console.warn(r)}});const n=()=>{er(),e.push(t(document)),ir=!0};return["interactive","complete"].includes(document.readyState)?n():(e.push(Kt("DOMContentLoaded",()=>{Qn({type:Be.DomContentLoaded,data:{}}),"DOMContentLoaded"===C&&n()})),e.push(Kt("load",()=>{Qn({type:Be.Load,data:{}}),"load"===C&&n()},window))),()=>{e.forEach(e=>{try{e()}catch(t){String(t).toLowerCase().includes("cross-origin")||console.warn(t)}}),j.destroy(),ir=!1,mn=void 0}}catch(Y){console.warn(Y)}}ar.addCustomEvent=(e,t)=>{if(!ir)throw new Error("please add custom event after start recording");Qn({type:Be.Custom,data:{tag:e,payload:t}})},ar.freezePage=()=>{Cn.forEach(e=>e.freeze())},ar.takeFullSnapshot=e=>{if(!ir)throw new Error("please take full snapshot after start recording");er(e)},ar.mirror=sr;var cr=class extends Error{},lr=class e{static instance=null;abortController=null;chatId=null;status="disconnected";callbacks=/* @__PURE__ */new Set;tornDown=!1;credentialRejected=!1;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;maxReconnectDelay=3e4;reconnectTimer=null;connectionId=0;tabId=globalThis.crypto.randomUUID();registrationWaiters=/* @__PURE__ */new Set;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}addCallbacks(e){this.callbacks.add(e)}removeCallbacks(e){this.callbacks.delete(e)}isConnected(){return"registered"===this.status}reconnectSuppressed(){return this.tornDown||this.credentialRejected}canReconnect(){return null!==this.chatId&&!this.reconnectSuppressed()&&!this.isConnected()}reconnectNow(){this.canReconnect()&&null!==this.chatId&&(this.clearReconnectTimer(),this.reconnectAttempts=0,this.reconnectDelay=1e3,this.abortConnection(),this.connect(this.chatId).catch(console.error))}async ready(e){await this.connect(e),await this.waitUntilRegistered()}async waitUntilRegistered(){if(!this.isConnected()){if(this.credentialRejected)throw new cr("Chat is unavailable — the widget credentials were rejected.");await new Promise((e,t)=>this.registrationWaiters.add({resolve:e,reject:t}))}}async connect(e){if(this.credentialRejected)return;if(this.tornDown=!1,this.chatId===e&&("connecting"===this.status||"open"===this.status||"registered"===this.status))return;this.abortConnection(),this.chatId=e,this.status="connecting";const t=++this.connectionId;this.abortController=new AbortController;const n=this.abortController.signal;try{const r=Le.getCredentialedConfig(),o=await Te.widgetStream({chat_id:e,tab_id:this.tabId,...r&&{marketrix_id:r.mtxId,marketrix_key:r.mtxKey}},{signal:n});this.status="open",this.consumeEvents(o,t)}catch(r){n.aborted||(console.error("[StreamClient] Connection failed:",r),this.status="error",this.notifyError(/* @__PURE__ */new Error("Stream connection failed")),this.scheduleReconnect())}}async consumeEvents(e,t){let n=!1;try{for await(const r of e){if(this.connectionId!==t){n=!0;break}this.handleMessage(r)}}catch(r){this.connectionId!==t?n=!0:this.reconnectSuppressed()||(console.warn("[StreamClient] Stream error:",r),this.status="error")}finally{n||this.connectionId!==t||this.reconnectSuppressed()||(this.status="disconnected",this.scheduleReconnect())}}disconnect(){this.tornDown=!0,this.credentialRejected=!1,this.clearReconnectTimer(),this.abortConnection(),this.chatId=null,this.settleWaiters(/* @__PURE__ */new Error("Stream disconnected before registration"))}send(e){return this.chatId?Te.widgetMessagePost({chat_id:this.chatId,tab_id:this.tabId,command:e}).then(()=>{}).catch(e=>{throw this.notifyError(/* @__PURE__ */new Error(`Failed to send message: ${String(e)}`)),e}):Promise.reject(/* @__PURE__ */new Error("No active chat"))}notifyError(e){this.callbacks.forEach(t=>t.onError?.(e))}settleWaiters(e){for(const t of this.registrationWaiters)t.reject(e);this.registrationWaiters.clear()}giveUp(e){const t=new cr(e);this.notifyError(t),this.settleWaiters(t)}handleMessage(e){if(!this.reconnectSuppressed()&&"heartbeat"!==e.type){if("registered"===e.type&&e.chat_id===this.chatId){this.status="registered",this.reconnectAttempts=0,this.reconnectDelay=1e3;for(const e of this.registrationWaiters)e.resolve();this.registrationWaiters.clear()}"chat/error"===e.type&&"auth"===e.request_id&&(console.error("[StreamClient] Authentication failed — will not reconnect"),this.credentialRejected=!0,this.giveUp("Chat is unavailable — the widget credentials were rejected.")),this.callbacks.forEach(t=>t.onMessage?.(e))}}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.giveUp("Could not reconnect to the assistant. Try again.");this.clearReconnectTimer(),this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);this.reconnectTimer=setTimeout(()=>{!this.reconnectSuppressed()&&this.chatId&&this.connect(this.chatId).catch(console.error)},e)}abortConnection(){this.abortController?.abort(),this.abortController=null,this.status="disconnected"}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},dr=class{chatId;applicationId;events=[];sessionId=globalThis.crypto.randomUUID();stopRecording=null;flushTimer=null;flushPromise=Promise.resolve();stopped=!1;constructor(e,t){this.chatId=e,this.applicationId=t}async start(){this.stopRecording||this.stopped||(await lr.getInstance().ready(this.chatId),this.stopped||(await Te.widgetMessagePost({chat_id:this.chatId,command:{type:"rrweb/metadata",rrweb_session_id:this.sessionId,chat_id:this.chatId,application_id:this.applicationId,url:window.location.href,user_agent:navigator.userAgent,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}}}),this.stopped||(this.stopRecording=ar({emit:e=>this.buffer(e),maskAllInputs:!0,maskTextClass:/^(rr-mask|mtx-mask)$/,blockClass:/^(rr-block|mtx-block)$/}))))}stop(){this.stopped=!0,this.stopRecording?.(),this.stopRecording=null,this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null,this.flush()}buffer(e){this.events.push(e),this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flush()},500))}flush(){return this.flushPromise=this.flushPromise.then(async()=>{this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null;const e=this.events.splice(0);if(e.length)try{await Te.widgetMessagePost({chat_id:this.chatId,command:{type:"rrweb/events",rrweb_session_id:this.sessionId,events:e}})}catch(t){this.events=e.concat(this.events).slice(0,2e4),console.error("Failed to record session events:",t)}}),this.flushPromise}},ur=null;function pr(){return ur?.active&&"live"===ur.getVideoTracks()[0]?.readyState?ur:(ur=null,null)}function hr(){ur&&(ur.getTracks().forEach(e=>e.stop()),ur=null)}var fr=e=>"string"==typeof e,mr=e=>"boolean"==typeof e,gr=(...e)=>t=>"string"==typeof t&&e.includes(t),yr={widget_enabled:mr,widget_appearance:gr("default","hidden"),widget_position:gr("bottom_left","bottom_right","top_left","top_right"),widget_header:fr,widget_body:fr,widget_greeting:fr,widget_greeting_toast:mr,widget_recording:mr,widget_feature_tell:mr,widget_feature_show:mr,widget_feature_do:mr,widget_background_color:fr,widget_text_color:fr,widget_border_color:fr,widget_accent_color:fr,widget_secondary_color:fr,widget_border_radius:fr,widget_font_size:fr,widget_width:fr,widget_height:fr,widget_animation_duration:fr,widget_fade_duration:fr,widget_chips:e=>Array.isArray(e)&&e.every(e=>"object"==typeof e&&null!==e&&gr("tell","show","do")(e.chip_mode)&&fr(e.chip_text))},br=Object.keys(yr);function vr(e){if("object"!=typeof e||null===e)return{invalidFields:["settings"]};const t=e,n=br.filter(e=>!yr[e](t[e]));if(n.length>0)return{invalidFields:n};const r={};for(const o of br)r[o]=t[o];return{settings:r}}var wr=e=>`Widget settings are invalid: ${e.join(", ")}`;function xr(e,t={}){return{...t,...e}}function Sr(e){return e instanceof Error?e.message:"string"==typeof e?e:"Unknown error"}function kr(e,t){const n=new Error(e);return n.cause=t,n}function Cr(){}var Er=Object.freeze([]),Ir=Object.freeze({});function Mr(t){e.useEffect(t,Er)}var Tr={};function Rr(t,n){const r=e.useRef(Tr);return r.current===Tr&&(r.current=t(n)),r}var Or="undefined"!=typeof document?e.useLayoutEffect:()=>{},Ar=function(e,...t){const n=new URL("https://base-ui.com/production-error");return n.searchParams.set("code",e.toString()),t.forEach(e=>n.searchParams.append("args[]",e)),`Base UI error #${e}; visit ${n} for the full message.`},_r=/*#__PURE__*/e.createContext(void 0);function Dr(){const t=e.useContext(_r);if(!t)throw new Error(Ar(73));return t}var Pr=parseInt(e.version,10);function Nr(e){return Pr>=e}var Lr,Fr=Nr(19)?function(t,n,r,o,i){return function(t,n,r,o,i){const s=e.useCallback(()=>n(t.getSnapshot(),r,o,i),[t,n,r,o,i]);return f(t.subscribe,s,s)}(t,n,r,o,i)}:function(e,t,n,r,o){return function(e,t,n,r){const o=u(null),i=e=>{const t=o.current;if(t&&Object.is(t.snapshot,e))return t.selection;const n=r(e);return o.current={snapshot:e,selection:n},n};return h(e,()=>i(t()),n&&(()=>i(n())))}(e.subscribe,e.getSnapshot,e.getSnapshot,e=>t(e,n,r,o))};function zr(e,t,n,r,o){return Fr(e,t,n,r,o)}Lr={before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let n=0;n<e.syncHooks.length;n+=1){const r=e.syncHooks[n],o=r.selector(r.store.state,r.a1,r.a2,r.a3);Object.is(r.value,o)||(t=!0,r.value=o)}return t&&(e.syncTick+=1),e.syncTick})},after(e){e.syncHooks.length>0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{const n=/* @__PURE__ */new Set;for(const o of e.syncHooks)n.add(o.store);const r=[];for(const e of n)r.push(e.subscribe(t));return()=>{for(const e of r)e()}}),f(e.subscribe,e.getSnapshot,e.getSnapshot))}},[].push(Lr);var $r=class{constructor(e){this.state=e,this.listeners=/* @__PURE__ */new Set,this.updateTick=0}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.state;setState(e){if(this.state===e)return;this.state=e,this.updateTick+=1;const t=this.updateTick;for(const n of this.listeners){if(t!==this.updateTick)return;n(e)}}update(e){for(const t in e)if(!Object.is(this.state[t],e[t]))return void this.setState({...this.state,...e})}set(e,t){Object.is(this.state[e],t)||this.setState({...this.state,[e]:t})}notifyAll(){const e={...this.state};this.setState(e)}use(e,t,n,r){return zr(this,e,t,n,r)}},Br={...e},Wr=Br.useInsertionEffect,Ur=Wr&&Wr!==Br.useLayoutEffect?Wr:e=>e();function Hr(e){const t=Rr(jr).current;return t.next=e,Ur(t.effect),t.trampoline}function jr(){const e={next:void 0,callback:qr,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function qr(){}var Vr=class extends $r{constructor(e,t={},n){super(e),this.context=t,this.selectors=n}useSyncedValue(t,n){e.useDebugValue(t);const r=this;Or(()=>{r.state[t]!==n&&r.set(t,n)},[r,t,n])}useSyncedValueWithCleanup(e,t){const n=this;Or(()=>(n.state[e]!==t&&n.set(e,t),()=>{n.set(e,void 0)}),[n,e,t])}useSyncedValues(e){const t=this,n=Object.values(e);Or(()=>{t.update(e)},[t,...n])}useControlledProp(t,n){e.useDebugValue(t);const r=this,o=void 0!==n;Or(()=>{o&&!Object.is(r.state[t],n)&&r.setState({...r.state,[t]:n})},[r,t,n,o])}select(e,t,n,r){return(0,this.selectors[e])(this.state,t,n,r)}useState(t,n,r,o){return e.useDebugValue(t),zr(this,this.selectors[t],n,r,o)}useContextCallback(t,n){e.useDebugValue(t);const r=Hr(n??Cr);this.context[t]=r}useStateSetter(t){const n=e.useRef(void 0);return void 0===n.current&&(n.current=e=>{this.set(t,e)}),n.current}observe(e,t){let n;n="function"==typeof e?e:this.selectors[e];let r=n(this.state);return t(r,r,this),this.subscribe(e=>{const o=n(e);if(!Object.is(r,o)){const e=r;r=o,t(o,e,this)}})}};function Yr(){return"undefined"!=typeof window}function Kr(e){return Gr(e)?(e.nodeName||"").toLowerCase():"#document"}function Xr(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Gr(e){return!!Yr()&&(e instanceof Node||e instanceof Xr(e).Node)}function Jr(e){return!!Yr()&&(e instanceof Element||e instanceof Xr(e).Element)}function Zr(e){return!!Yr()&&(e instanceof HTMLElement||e instanceof Xr(e).HTMLElement)}function Qr(e){return!(!Yr()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Xr(e).ShadowRoot)}function eo(e){return/^(html|body|#document)$/.test(Kr(e))}function to(e){return Xr(e).getComputedStyle(e)}function no(e){if("html"===Kr(e))return e;const t=e.assignedSlot||e.parentNode||Qr(e)&&e.host||function(e){var t;return null==(t=(Gr(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}(e);return Qr(t)?t.host:t}function ro(...e){return()=>{for(let t=0;t<e.length;t+=1){const n=e[t];n&&n()}}}function oo(e){return e?.ownerDocument||document}function io(e,t,n,r){return e.addEventListener(t,n,r),()=>{e.removeEventListener(t,n,r)}}var so=null;globalThis.requestAnimationFrame;var ao=new class{callbacks=[];callbacksCount=0;nextId=1;startId=1;isScheduled=!1;tick=e=>{this.isScheduled=!1;const t=this.callbacks,n=this.callbacksCount;if(this.callbacks=[],this.callbacksCount=0,this.startId=this.nextId,n>0)for(let r=0;r<t.length;r+=1)t[r]?.(e)};request(e){const t=this.nextId;return this.nextId+=1,this.callbacks.push(e),this.callbacksCount+=1,this.isScheduled||(requestAnimationFrame(this.tick),this.isScheduled=!0),t}cancel(e){const t=e-this.startId;t<0||t>=this.callbacks.length||(this.callbacks[t]=null,this.callbacksCount-=1)}},co=class e{static create(){return new e}static request(e){return ao.request(e)}static cancel(e){return ao.cancel(e)}currentId=so;request(e){this.cancel(),this.currentId=ao.request(()=>{this.currentId=so,e()})}cancel=()=>{this.currentId!==so&&(ao.cancel(this.currentId),this.currentId=so)};disposeEffect=()=>this.cancel};function lo(){const e=Rr(co.create).current;return Mr(e.disposeEffect),e}var uo=class e{static create(){return new e}currentId=0;start(e,t){this.clear(),this.currentId=setTimeout(()=>{this.currentId=0,t()},e)}isStarted(){return 0!==this.currentId}clear=()=>{0!==this.currentId&&(clearTimeout(this.currentId),this.currentId=0)};disposeEffect=()=>this.clear};function po(){const e=Rr(uo.create).current;return Mr(e.disposeEffect),e}var ho=0;function fo(e,t){if("string"==typeof e)return{description:e};if("function"==typeof e){const n=e(t);return"string"==typeof n?{description:n}:n}return e}var{userAgent:mo,platform:go,maxTouchPoints:yo}="undefined"==typeof navigator?{userAgent:"",platform:"",maxTouchPoints:0}:{userAgent:navigator.userAgent,platform:navigator.platform??"",maxTouchPoints:navigator.maxTouchPoints??0},bo=mo.toLowerCase(),vo=go.toLowerCase(),wo=/^i(os$|p)/.test(vo)||"macintel"===vo&&yo>1,xo="android",So=vo===xo||bo.includes(xo),ko=!wo&&vo.startsWith("mac"),Co=(vo.startsWith("win"),!So&&/^(linux|chrome os)/.test(vo),ko||wo),Eo="undefined"!=typeof CSS&&!!CSS.supports?.("-webkit-backdrop-filter:none"),Io=(!Eo&&bo.includes("firefox"),!Eo&&bo.includes("chrom"),Co),Mo=/jsdom|happydom/.test(bo),To="data-base-ui-focusable";function Ro(e){let t=e.activeElement;for(;null!=t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t}function Oo(e,t){if(!e||!t)return!1;const n=t.getRootNode?.();if(e.contains(t))return!0;if(n&&Qr(n)){let n=t;for(;n;){if(e===n)return!0;n=n.parentNode||n.host}}return!1}function Ao(e){return"composedPath"in e?e.composedPath()[0]:e.target}function _o(e,t){if(null==t)return!1;if("composedPath"in e)return e.composedPath().includes(t);const n=e;return null!=n.target&&t.contains(n.target)}function Do(e){return Zr(e)&&e.matches("input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])")}function Po(e){return!!e&&"combobox"===e.getAttribute("role")&&Do(e)}function No(e){if(!e||Mo)return!0;try{return e.matches(":focus-visible")}catch(t){return!0}}function Lo(e){return e?e.hasAttribute("data-base-ui-focusable")?e:e.querySelector("[data-base-ui-focusable]")||e:null}function Fo(e,t,n=!0){return e.filter(e=>e.parentId===t).flatMap(t=>[...!n||t.context?.open?[t]:[],...Fo(e,t.id,n)])}function zo(e,t){let n=[],r=e.find(e=>e.id===t)?.parentId;for(;r;){const t=e.find(e=>e.id===r);r=t?.parentId,t&&(n=n.concat(t))}return n}function $o(e,t){return t<0||t>=e.length}function Bo(e,{startingIndex:t=-1,decrement:n=!1,disabledIndices:r,amount:o=1}={}){let i=t;do{i+=n?-o:o}while(i>=0&&i<=e.length-1&&Wo(e,i,r));return i}function Wo(e,t,n){if("function"==typeof n?n(t):n?.includes(t))return!0;const r=e[t];return!!r&&(!Uo(r)||!!r.matches(":disabled")||!n&&(r.hasAttribute("disabled")||"true"===r.getAttribute("aria-disabled")))}function Uo(e,t=(e?to(e):null)){return!(!(e&&e.isConnected&&t)||function(e){return"hidden"===e.visibility||"collapse"===e.visibility}(t))&&("function"==typeof e.checkVisibility?e.checkVisibility():"none"!==t.display&&"contents"!==t.display)}function Ho(e){const t=e.assignedSlot;if(t)return t;if(e.parentElement)return e.parentElement;const n=e.getRootNode();return Qr(n)?n.host:null}function jo(e){for(const t of Array.from(e.children))if("summary"===Kr(t))return t;return null}function qo(e,t){const n=jo(t);return!!n&&(e===n||Oo(n,e))}function Vo(e){const t=e?Kr(e):"";return null!=e&&e.matches('a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]')&&("summary"!==t||null!=e.parentElement&&"details"===Kr(e.parentElement)&&jo(e.parentElement)===e)&&("details"!==t||null==jo(e))&&("input"!==t||"hidden"!==e.type)}function Yo(e){if(!Vo(e)||!e.isConnected||e.matches(":disabled"))return!1;for(let t=e;t;t=Ho(t)){const n=t!==e,r="slot"===Kr(t);if(t.hasAttribute("inert"))return!1;if(n&&"details"===Kr(t)&&!t.open&&!qo(e,t)||t.hasAttribute("hidden")||!r&&!Ko(t,n))return!1}return!0}function Ko(e,t){const n=to(e);return t?"none"!==n.display:Uo(e,n)}function Xo(e){const t=e.tabIndex;if(t<0){const t=Kr(e);if("details"===t||"audio"===t||"video"===t||Zr(e)&&e.isContentEditable)return 0}return t}function Go(e){if("input"!==Kr(e))return null;const t=e;return"radio"===t.type&&""!==t.name?t:null}function Jo(e){if(Zr(e)&&"slot"===Kr(e)){const t=e.assignedElements({flatten:!0});if(t.length>0)return t}return Zr(e)&&e.shadowRoot?Array.from(e.shadowRoot.children):Array.from(e.children)}function Zo(e,t){Jo(e).forEach(e=>{Vo(e)&&t.push(e),Zo(e,t)})}function Qo(e,t,n){Jo(e).forEach(e=>{Zr(e)&&e.matches(t)&&n.push(e),Qo(e,t,n)})}function ei(e){return Yo(e)&&Xo(e)>=0}function ti(e){const t=[];return Zo(e,t),t.filter(Yo)}function ni(e){const t=ti(e);return t.filter(e=>Xo(e)>=0&&function(e,t){const n=Go(e);if(!n)return!0;const r=t.find(e=>{const t=Go(e);return t?.name===n.name&&t.form===n.form&&t.checked});return r?r===n:t.find(e=>{const t=Go(e);return t?.name===n.name&&t.form===n.form})===n}(e,t))}function ri(e,t){const n=ni(e),r=n.length;if(0===r)return;const o=Ro(oo(e)),i=n.indexOf(o);return n[-1===i?1===t?0:r-1:i+t]}function oi(e){return ri(oo(e).body,1)||e}function ii(e){return ri(oo(e).body,-1)||e}function si(e,t){const n=t||e.currentTarget,r=e.relatedTarget;return!r||!Oo(n,r)}function ai(e){const t=[];Qo(e,"[data-tabindex]",t),t.forEach(e=>{const t=e.dataset.tabindex;delete e.dataset.tabindex,t?e.setAttribute("tabindex",t):e.removeAttribute("tabindex")})}function ci(e){const t=/* @__PURE__ */new Map;let n=0,r=0;return e.forEach((e,o)=>{const i="ending"===e.transitionStatus;t.set(e.id,{value:e,domIndex:o,visibleIndex:i?-1:n,offsetY:r}),r+=e.height||0,i||(n+=1)}),t}function li(e,t){let n=0;return e.map(e=>{if("ending"===e.transitionStatus)return e;const r=n>=t;return n+=1,e.limited===r?e:{...e,limited:r}})}var di={toasts:e=>e.toasts,isEmpty:e=>0===e.toasts.length,toast:(e,t)=>e.toastMetadata.get(t)?.value,toastIndex:(e,t)=>e.toastMetadata.get(t)?.domIndex??-1,toastOffsetY:(e,t)=>e.toastMetadata.get(t)?.offsetY??0,toastVisibleIndex:(e,t)=>e.toastMetadata.get(t)?.visibleIndex??-1,focused:e=>e.focused,expanded:e=>e.hovering||e.focused,expandedOrOutOfFocus:e=>e.hovering||e.focused||!e.isWindowFocused,prevFocusElement:e=>e.prevFocusElement},ui=class extends Vr{timers=/* @__PURE__ */new Map;areTimersPaused=!1;constructor(e){super({...e,toastMetadata:ci(e.toasts)},{},di)}setViewport=e=>{this.set("viewport",e)};syncProviderProps(e,t){const n=this.state.limit!==t;if(this.state.timeout===e&&!n)return;const r={timeout:e,limit:t};if(n){const e=li(this.state.toasts,t);r.toasts=e,r.toastMetadata=ci(e)}this.update(r)}disposeEffect=()=>()=>{this.timers.forEach(e=>{e.timeout?.clear()}),this.timers.clear()};removeToast(e,t=!1){const n=di.toastIndex(this.state,e);if(-1===n)return;const r=this.state.toasts[n];t||r?.onRemove?.();const o=[...this.state.toasts];o.splice(n,1),this.setToasts(o)}addToast=e=>{const{timeout:t,limit:n}=this.state,r=e.id||(ho+=1,`toast-${Math.random().toString(36).slice(2,6)}-${ho}`);if(e.id){const t=di.toast(this.state,e.id);if(t){if("ending"!==t.transitionStatus){const{id:t,transitionStatus:n,...r}=e;return this.updateToastInternal(e.id,r,!0,!0),e.id}this.removeToast(e.id,!0)}}const o={...e,id:r,updateKey:0,transitionStatus:"starting"},i=[o,...this.state.toasts];this.setToasts(li(i,n));const s=o.timeout??t;return"loading"!==o.type&&s>0&&this.scheduleTimer(r,s,()=>this.closeToast(r)),di.expandedOrOutOfFocus(this.state)&&this.pauseTimers(),r};updateToast=(e,t)=>{this.updateToastInternal(e,t,!1,!0)};updateToastInternal=(e,t,n=!1,r=!1)=>{const{timeout:o,toasts:i}=this.state,s=di.toast(this.state,e);if(!s)return;if("ending"===s.transitionStatus)return;const a={...s,...t,...r&&{updateKey:s.updateKey+1}};this.setToasts(i.map(t=>t.id===e?a:t));const c=a.timeout??o,l=s.timeout??o,d=Object.hasOwn(t,"timeout"),u="ending"!==a.transitionStatus&&"loading"!==a.type&&c>0,p=this.timers.has(e),h=l!==c,f="loading"===s.type;u||!p?u&&(!p||h||d||f||n)&&(this.clearTimer(e),this.scheduleTimer(e,c,()=>this.closeToast(e)),di.expandedOrOutOfFocus(this.state)&&this.pauseTimers()):this.clearTimer(e)};closeToast=e=>{const t=void 0===e,{limit:n,toasts:r}=this.state;let o;if(t)o=r,this.clearTimers();else{const t=di.toast(this.state,e);if(!t)return;o=[t],this.clearTimer(e)}const i=li(r.map(n=>t||n.id===e?{...n,transitionStatus:"ending",height:0}:n),n);this.setToasts(i,!i.some(e=>"ending"!==e.transitionStatus)),o.forEach(e=>{"ending"!==e.transitionStatus&&e.onClose?.()}),this.handleFocusManagement(e)};promiseToast=(e,t)=>{const n=fo(t.loading),r=this.addToast({...n,type:"loading"}),o=e.then(e=>{const n=fo(t.success,e);return this.updateToast(r,{...n,type:"success",timeout:n.timeout}),e}).catch(e=>{const n=fo(t.error,e);return this.updateToast(r,{...n,type:"error",timeout:n.timeout}),Promise.reject(e)});return{}.hasOwnProperty.call(t,"setPromise")&&t.setPromise(o),o};pauseTimers(){this.areTimersPaused||(this.areTimersPaused=!0,this.timers.forEach(e=>{e.timeout&&(e.timeout.clear(),e.remaining=Math.max(e.remaining-(Date.now()-e.start),0))}))}resumeTimers(){this.areTimersPaused&&(this.areTimersPaused=!1,this.timers.forEach((e,t)=>{e.remaining=e.remaining>0?e.remaining:e.delay,e.timeout??=uo.create(),e.timeout.start(e.remaining,()=>{this.handleTimerFired(t),e.callback()}),e.start=Date.now()}))}restoreFocusToPrevElement(){this.state.prevFocusElement?.focus({preventScroll:!0})}handleDocumentPointerDown=e=>{if("touch"!==e.pointerType)return;const t=Ao(e);Oo(this.state.viewport,t)||(this.resumeTimers(),this.update({hovering:!1,focused:!1}))};scheduleTimer(e,t,n){const r=Date.now(),o=di.expandedOrOutOfFocus(this.state)?void 0:uo.create();o?.start(t,()=>{this.handleTimerFired(e),n()}),this.timers.set(e,{timeout:o,start:r,delay:t,remaining:t,callback:n})}clearTimers(){this.timers.forEach(e=>{e.timeout?.clear()}),this.timers.clear(),this.areTimersPaused=!1}clearTimer(e){this.timers.get(e)?.timeout?.clear(),this.timers.delete(e),this.resetPausedStateIfNoTimersRemain()}handleTimerFired(e){this.timers.delete(e),this.resetPausedStateIfNoTimersRemain()}resetPausedStateIfNoTimersRemain(){0===this.timers.size&&(this.areTimersPaused=!1)}setToasts(e,t=0===e.length){const n={toasts:e,toastMetadata:ci(e)};t&&(n.hovering=!1,n.focused=!1),this.update(n)}handleFocusManagement(e){const t=Ro(oo(this.state.viewport));if(!this.state.viewport||!Oo(this.state.viewport,t)||!No(t))return;if(void 0===e)return void this.restoreFocusToPrevElement();const n=di.toasts(this.state),r=di.toastIndex(this.state,e),o=(e,t)=>{for(let r=e;r>=0&&r<n.length;r+=t)if("ending"!==n[r].transitionStatus)return n[r];return null},i=o(r+1,1)??o(r-1,-1);i?i.ref?.current?.focus():this.restoreFocusToPrevElement()}},pi=function(t){const{children:n,timeout:r=5e3,limit:o=3,toastManager:i}=t,s=Rr(()=>new ui({timeout:r,limit:o,viewport:null,toasts:[],hovering:!1,focused:!1,isWindowFocused:!0,prevFocusElement:null})).current;return Mr(s.disposeEffect),e.useEffect(function(){if(i)return i[" subscribe"](({action:e,options:t})=>{const n=t.id;"promise"===e&&t.promise?s.promiseToast(t.promise,t):"update"===e&&n?s.updateToast(n,t):"close"===e?s.closeToast(n):s.addToast(t)})},[s,i]),/*#__PURE__*/v(_r.Provider,{value:s,children:[/*#__PURE__*/b(hi,{store:s,timeout:r,limit:o}),n]})};function hi(e){const{store:t,timeout:n,limit:r}=e;return Or(()=>{t.syncProviderProps(n,r)},[t,n,r]),null}var fi={clipPath:"inset(50%)",overflow:"hidden",whiteSpace:"nowrap",border:0,padding:0,width:1,height:1,margin:-1,position:"fixed",top:0,left:0},mi=/*#__PURE__*/e.forwardRef(function(t,n){const[r,o]=e.useState();return Or(()=>{Io&&Eo&&o("button")},[]),/*#__PURE__*/b("span",{...t,ref:n,style:fi,"aria-hidden":!r||void 0,tabIndex:0,role:r,"data-base-ui-focus-guard":""})});function gi(e,t,n,r){const o=Rr(yi).current;return function(e,t,n,r,o){return e.refs[0]!==t||e.refs[1]!==n||e.refs[2]!==r||e.refs[3]!==o}(o,e,t,n,r)&&bi(o,[e,t,n,r]),o.callback}function yi(){return{callback:null,cleanup:null,refs:[]}}function bi(e,t){e.refs=t,t.every(e=>null==e)?e.callback=null:e.callback=n=>{if(e.cleanup&&(e.cleanup(),e.cleanup=null),null!=n){const r=Array(t.length).fill(null);for(let e=0;e<t.length;e+=1){const o=t[e];if(null!=o)switch(typeof o){case"function":{const t=o(n);"function"==typeof t&&(r[e]=t);break}case"object":o.current=n}}e.cleanup=()=>{for(let e=0;e<t.length;e+=1){const n=t[e];if(null!=n)switch(typeof n){case"function":{const t=r[e];"function"==typeof t?t():n(null);break}case"object":n.current=null}}}}}}function vi(t){if(!/*#__PURE__*/e.isValidElement(t))return null;const n=t,r=n.props;return(Nr(19)?r?.ref:n.ref)??null}function wi(e,t){return e&&!t?e:!e&&t?t:e||t?{...e,...t}:void 0}var xi={};function Si(e,t,n,r,o){if(!(n||r||o||e))return ki(t);let i=ki(e);return t&&(i=Ci(i,t)),n&&(i=Ci(i,n)),r&&(i=Ci(i,r)),o&&(i=Ci(i,o)),i}function ki(e){return Ii(e)?{...Mi(e,xi)}:function(e){const t={...e};for(const n in t){const e=t[n];Ei(n,e)&&(t[n]=Ri(e))}return t}(e)}function Ci(e,t){return Ii(t)?Mi(t,e):function(e,t){if(!t)return e;for(const n in t){const r=t[n];switch(n){case"style":e[n]=wi(e.style,r);break;case"className":e[n]=Ai(e.className,r);break;default:Ei(n,r)?e[n]=Ti(e[n],r):e[n]=r}}return e}(e,t)}function Ei(e,t){const n=e.charCodeAt(0),r=e.charCodeAt(1),o=e.charCodeAt(2);return 111===n&&110===r&&o>=65&&o<=90&&("function"==typeof t||void 0===t)}function Ii(e){return"function"==typeof e}function Mi(e,t){return Ii(e)?e(t):e??xi}function Ti(e,t){return t?e?(...n)=>{const r=n[0];if(_i(r)){const o=r;Oi(o);const i=t(...n);return o.baseUIHandlerPrevented||e?.(...n),i}const o=t(...n);return e?.(...n),o}:Ri(t):e}function Ri(e){return e?(...t)=>{const n=t[0];return _i(n)&&Oi(n),e(...t)}:e}function Oi(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function Ai(e,t){return t?e?t+" "+e:t:e}function _i(e){return null!=e&&"object"==typeof e&&"nativeEvent"in e}function Di(t,n,o={}){const i=n.render,s=function(e,t={}){const{className:n,style:r,render:o}=e,{state:i=Ir,ref:s,props:a,stateAttributesMapping:c,enabled:l=!0}=t,d=l?function(e,t){return"function"==typeof e?e(t):e}(n,i):void 0,u=l?function(e,t){return"function"==typeof e?e(t):e}(r,i):void 0,p=l?function(e,t){const n={};for(const r in e){const o=e[r];if(t?.hasOwnProperty(r)){const e=t[r](o);null!=e&&Object.assign(n,e);continue}!0===o?n[`data-${r.toLowerCase()}`]="":o&&(n[`data-${r.toLowerCase()}`]=o.toString())}return n}(i,c):Ir,h=l&&a?function(e){return Array.isArray(e)?function(e){if(0===e.length)return xi;if(1===e.length)return ki(e[0]);let t=ki(e[0]);for(let n=1;n<e.length;n+=1)t=Ci(t,e[n]);return t}(e):Si(void 0,e)}(a):void 0,f=l?wi(p,h)??{}:Ir;return"undefined"!=typeof document&&(l?Array.isArray(s)?f.ref=function(e){const t=Rr(yi).current;return function(e,t){return e.refs.length!==t.length||e.refs.some((e,n)=>e!==t[n])}(t,e)&&bi(t,e),t.callback}([f.ref,vi(o),...s]):f.ref=gi(f.ref,vi(o),s):gi(null,null)),l?(void 0!==d&&(f.className=Ai(f.className,d)),void 0!==u&&(f.style=wi(f.style,u)),f):Ir}(n,o);return!1===o.enabled?null:function(t,n,o,i){if(n){if("function"==typeof n)return n(o,i);const t=Si(o,n.props);t.ref=o.ref;let r=n;return r?.$$typeof===Pi&&(r=e.Children.toArray(n)[0]),/*#__PURE__*/e.cloneElement(r,t)}if(t&&"string"==typeof t)return function(t,n){return"button"===t?/*#__PURE__*/r("button",{type:"button",...n,key:n.key}):"img"===t?/*#__PURE__*/r("img",{alt:"",...n,key:n.key}):/*#__PURE__*/e.createElement(t,n)}(t,o);throw new Error(Ar(8))}(t,i,s,o.state??Ir)}var Pi=Symbol.for("react.lazy"),Ni=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,children:s,...a}=t,c=Dr(),l=po(),d=e.useRef(!1),u=e.useRef(!1),p=e.useRef(!1),h=c.useState("isEmpty"),f=c.useState("toasts"),m=c.useState("focused"),g=c.useState("expanded"),y=c.useState("prevFocusElement"),w=f[0]?.height,x=f.some(e=>"ending"===e.transitionStatus),S=f.filter(e=>"high"===e.priority);function k(){c.state.toasts.some(e=>"ending"===e.transitionStatus)||p.current||!u.current||(c.state.isWindowFocused&&c.resumeTimers(),c.set("hovering",!1),u.current=!1)}function C(){c.pauseTimers(),c.set("hovering",!0),u.current=!1}function E(e){"touch"===e.pointerType&&(p.current=!1,k())}function I(){d.current?d.current=!1:m||No(Ro(oo(c.state.viewport)))&&(c.set("focused",!0),c.pauseTimers())}e.useEffect(()=>{const e=c.state.viewport;if(!e||h)return;const t=Xr(e),n=oo(e);return ro(io(t,"keydown",function(t){"F6"===t.key&&Ao(t)!==e&&(t.preventDefault(),c.set("prevFocusElement",Ro(n)),e?.focus({preventScroll:!0}),c.pauseTimers(),c.set("focused",!0))}),io(t,"blur",function(e){Ao(e)===t&&(c.set("isWindowFocused",!1),c.pauseTimers())},!0),io(t,"focus",function(n){if(n.relatedTarget)return;const r=Ao(n),o=Ro(oo(e));r!==t&&Oo(e,r)&&No(o)||c.resumeTimers(),l.start(0,()=>c.set("isWindowFocused",!0))},!0),io(n,"pointerdown",c.handleDocumentPointerDown,!0))},[c,l,h]),e.useEffect(k,[x,c]);const M={tabIndex:-1,role:"region","aria-live":"polite","aria-atomic":!1,"aria-relevant":"additions text","aria-label":"Notifications",onMouseEnter:C,onMouseMove:C,onMouseLeave:function(){u.current=!0,k()},onFocus:I,onBlur:function(e){m&&!Oo(c.state.viewport,e.relatedTarget)&&(c.set("focused",!1),c.state.isWindowFocused&&c.resumeTimers())},onKeyDown:function(e){"Tab"===e.key&&e.shiftKey&&Ao(e.nativeEvent)===c.state.viewport&&(e.preventDefault(),c.restoreFocusToPrevElement())},onClick:I,onPointerDown:function(e){"touch"===e.pointerType&&(p.current=!0)},onPointerUp:E,onPointerCancel:E,style:{"--toast-frontmost-height":w?`${w}px`:void 0}},T={expanded:g},R=!h&&y&&/*#__PURE__*/b(mi,{onFocus:function(e){d.current=!0;const t=e.relatedTarget===c.state.viewport?f.find(e=>"ending"!==e.transitionStatus&&!e.limited):void 0;t?t.ref?.current?.focus():c.restoreFocusToPrevElement()}}),O=Di("div",t,{ref:[n,c.setViewport],state:T,props:[M,a,{children:/*#__PURE__*/v(e.Fragment,{children:[R,s,R]})}]});/*#__PURE__*/
2
- return v(e.Fragment,{children:[R,O,!m&&S.length>0&&/*#__PURE__*/b("div",{style:fi,children:S.map(e=>/*#__PURE__*/v("div",{role:"alert","aria-atomic":!0,children:[/*#__PURE__*/b("div",{children:e.title}),/*#__PURE__*/b("div",{children:e.description})]},e.id))})]})});function Li(e){return Nr(19)?e:e?"true":void 0}var Fi=/*#__PURE__*/e.createContext(void 0);function zi(){const t=e.useContext(Fi);if(!t)throw new Error(Ar(66));return t}var $i=/*#__PURE__*/function(e){return e.startingStyle="data-starting-style",e.endingStyle="data-ending-style",e}({}),Bi={"data-starting-style":""},Wi={"data-ending-style":""},Ui={transitionStatus:e=>"starting"===e?Bi:"ending"===e?Wi:null};function Hi(e){return null==e?e:"current"in e?e.current:e}function ji(t){const{enabled:n=!0,open:r,ref:o,onComplete:i}=t,s=Hr(i),a=function(e,t=!1){const n=lo();return Hr((r,o=null)=>{n.cancel();const i=Hi(e);if(null==i)return;const s=i,a=()=>{g.flushSync(r)};if("function"!=typeof s.getAnimations||globalThis.BASE_UI_ANIMATIONS_DISABLED)r();else{if(t){const e="data-starting-style";if(!s.hasAttribute(e))return void n.request(c);const t=new MutationObserver(()=>{s.hasAttribute(e)||(t.disconnect(),c())});return t.observe(s,{attributes:!0,attributeFilter:[e]}),void o?.addEventListener("abort",()=>t.disconnect(),{once:!0})}n.request(c)}function c(){Promise.all(s.getAnimations().map(e=>e.finished)).then(()=>{o?.aborted||a()},()=>{o?.aborted||(s.getAnimations().some(e=>e.pending||"finished"!==e.playState)?c():a())})}})}(o,r);e.useEffect(()=>{if(!n)return;const e=new AbortController;return a(s,e.signal),()=>{e.abort()}},[n,r,s,a])}var qi={clipPath:"inset(50%)",position:"fixed",top:0,left:0};function Vi(e,t,n){switch(e){case"up":return-n;case"down":return n;case"left":return-t;case"right":return t;default:return 0}}var Yi={...Ui,swipeDirection:e=>e?{"data-swipe-direction":e}:null},Ki=/*#__PURE__*/e.forwardRef(function(t,n){const{toast:r,render:o,className:i,swipeDirection:s=["down","right"],style:a,...c}=t,l=void 0!==r.positionerProps?.anchor;let d=[];l||(d=Array.isArray(s)?s:[s]);const u=d.length>0,p=Dr(),[h,f]=e.useState(void 0),[m,y]=e.useState(!1),[v,w]=e.useState(!1),[x,S]=e.useState({x:0,y:0}),[k,C]=e.useState({x:0,y:0,scale:1}),[E,I]=e.useState(),[M,T]=e.useState(),[R,O]=e.useState(null),A=e.useRef(null),_=e.useRef(void 0),D=e.useRef({x:0,y:0}),P=e.useRef({x:0,y:0,scale:1}),N=e.useRef(void 0),L=e.useRef(0),F=e.useRef(!1),z=e.useRef({x:0,y:0}),$=e.useRef(!1),B=e.useRef({x:0,y:0}),W=e.useRef(null),U=e.useRef(null),H=p.useState("toastIndex",r.id),j=p.useState("toastVisibleIndex",r.id),q=p.useState("toastOffsetY",r.id),V=p.useState("focused"),Y=p.useState("expanded");ji({open:"ending"!==r.transitionStatus,ref:A,onComplete(){"ending"===r.transitionStatus&&p.removeToast(r.id)}});const K=Hr((e=!1)=>{const t=A.current;if(!t)return;const n=t.style.height;t.style.height="auto";const o=t.offsetHeight;function i(){p.updateToastInternal(r.id,{ref:A,height:o,transitionStatus:void 0})}t.style.height=n,e?g.flushSync(i):i()});function X(e){B.current=e,S(e)}Or(()=>{const e=_.current;"starting"!==r.transitionStatus&&e===r.id||(void 0!==e&&(f(void 0),C({x:0,y:0,scale:1}),X({x:0,y:0})),_.current=r.id,K())},[K,r.id,r.transitionStatus]),Or(()=>()=>{U.current?.abort()},[]);const G=Hr(e=>{if(e.pointerId!==W.current)return;W.current=null,U.current?.abort(),U.current=null,y(!1),w(!1),O(null);const t=P.current;if("pointercancel"===e.type||F.current)return X({x:t.x,y:t.y}),void f(void 0);const n=B.current,o=n.x-t.x,i=n.y-t.y;let s;for(const r of d)if(Vi(r,o,i)>40){s=r;break}s?(f(s),p.closeToast(r.id)):(X({x:t.x,y:t.y}),f(void 0))});e.useEffect(()=>{const e=A.current;if(u&&e)return io(e,"touchmove",function(t){null!==W.current&&Oo(e,Ao(t))&&t.preventDefault()},{passive:!1})},[u]);const J="high"===r.priority,Z={role:J?"alertdialog":"dialog",tabIndex:0,"aria-modal":!1,"aria-labelledby":E,"aria-describedby":M,"aria-hidden":!(!J||V)||void 0,onPointerDown:u?function(e){if(0!==e.button)return;if("touch"===e.pointerType&&p.pauseTimers(),Ao(e.nativeEvent)?.closest('button,a,input,textarea,[role="button"],[data-base-ui-swipe-ignore],[data-swipe-ignore]'))return;F.current=!1,N.current=void 0,L.current=0,W.current=e.pointerId,D.current={x:e.clientX,y:e.clientY},z.current=D.current;const t=e.currentTarget,n=function(e){const t=Xr(e).getComputedStyle(e).transform;let n=0,r=0,o=1;if(t&&"none"!==t){const e=t.match(/matrix(?:3d)?\(([^)]+)\)/);if(e){const t=e[1].split(", ").map(parseFloat);6===t.length?(n=t[4],r=t[5],o=Math.sqrt(t[0]*t[0]+t[1]*t[1])):16===t.length&&(n=t[12],r=t[13],o=t[0])}}return{x:n,y:r,scale:o}}(t);P.current=n,C(n),X({x:n.x,y:n.y}),p.set("hovering",!0),y(!0),w(!1),O(null),$.current=!0,U.current?.abort();const r=new AbortController;U.current=r;const o=oo(t);o.addEventListener("pointerup",G,{signal:r.signal}),o.addEventListener("pointercancel",G,{signal:r.signal}),t.setPointerCapture?.(e.pointerId)}:void 0,onPointerMove:u?function(e){if(e.pointerId!==W.current)return;e.preventDefault(),$.current&&(D.current={x:e.clientX,y:e.clientY},$.current=!1);const{clientY:t,clientX:n,movementX:r,movementY:o}=e;(o<0&&t>z.current.y||o>0&&t<z.current.y)&&(z.current={x:z.current.x,y:t}),(r<0&&n>z.current.x||r>0&&n<z.current.x)&&(z.current={x:n,y:z.current.y});const i=n-D.current.x,s=t-D.current.y,a=t-z.current.y,c=n-z.current.x;let l,u=R;if(!v&&Math.sqrt(i*i+s*s)>=1){w(!0);const e=d.includes("left")||d.includes("right"),t=d.includes("up")||d.includes("down");e&&t&&(u=Math.abs(i)>Math.abs(s)?"horizontal":"vertical",O(u))}if(N.current){const e=N.current,t=Vi(e,c,a);t>40?(F.current=!1,f(e)):d.includes("left")&&d.includes("right")||d.includes("up")&&d.includes("down")||!(L.current-t>=10)||(F.current=!0)}else"vertical"===u?s>0?l="down":s<0&&(l="up"):"horizontal"===u?i>0?l="right":i<0&&(l="left"):l=Math.abs(i)>=Math.abs(s)?i>0?"right":"left":s>0?"down":"up",l&&d.includes(l)&&(N.current=l,L.current=Vi(l,i,s),f(l));const p=function(e,t){const n=e=>e>0?e**.5:-(Math.abs(e)**.5),r=e>0&&!d.includes("right")||e<0&&!d.includes("left"),o=t>0&&!d.includes("down")||t<0&&!d.includes("up");return{x:r?n(e):e,y:o?n(t):t}}(i,s);let h=P.current.x,m=P.current.y;const g=d.includes("left")||d.includes("right"),y=d.includes("up")||d.includes("down");"vertical"!==u&&g&&(h+=p.x),"horizontal"!==u&&y&&(m+=p.y),X({x:h,y:m})}:void 0,onPointerUp:u?G:void 0,onPointerCancel:u?G:void 0,onKeyDown:function(e){if("Escape"===e.key){if(!A.current||!Oo(A.current,Ro(oo(A.current))))return;p.closeToast(r.id)}},inert:Li(r.limited),style:{...function(){const e=x.x-k.x,t=x.y-k.y;return{transition:m?"none":void 0,transform:m?`translateX(${x.x}px) translateY(${x.y}px) scale(${k.scale})`:void 0,"--toast-swipe-movement-x":`${e}px`,"--toast-swipe-movement-y":`${t}px`}}(),"--toast-index":"ending"===r.transitionStatus?H:j,"--toast-offset-y":`${q}px`,"--toast-height":r.height?`${r.height}px`:void 0}},Q=e.useMemo(()=>({toast:r,setTitleId:I,setDescriptionId:T,recalculateHeight:K,visibleIndex:j,expanded:Y}),[r,I,T,K,j,Y]),ee={transitionStatus:r.transitionStatus,expanded:Y,limited:r.limited||!1,type:r.type,swiping:m,swipeDirection:h},te=Di("div",t,{ref:[n,A],state:ee,stateAttributesMapping:Yi,props:[Z,c]});/*#__PURE__*/
3
- return b(Fi.Provider,{value:Q,children:te})}),Xi=0,Gi=Br.useId;function Ji(t,n){if(void 0!==Gi){const e=Gi();return t??(n?`${n}-${e}`:e)}return function(t,n="mui"){const[r,o]=e.useState(t),i=t||r;return e.useEffect(()=>{null==r&&o(`${n}-${Xi+=1}`)},[r,n]),i}(t,n)}function Zi(e){return null!=e&&"boolean"!=typeof e&&""!==e&&(!Array.isArray(e)||e.some(Zi))}function Qi(t){/*#__PURE__*/
4
- return e.isValidElement(t)&&Zi(t.props.children)}function es(e,t,n){const{toast:r,setTitleId:o,setDescriptionId:i}=zi(),s="title"===n?o:i,a=t??("title"===n?r.title:r.description);return{id:Ji(e),children:a,type:r.type,setId:s}}function ts(e,t,n){const r=Qi(e);return Or(()=>{if(r)return n(t),()=>{n(e=>e===t?void 0:e)}},[r,t,n]),r?e:null}var ns=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,children:s,...a}=e,{id:c,children:l,type:d,setId:u}=es(i,s,"description");return ts(Di("p",e,{ref:t,state:{type:d},props:{...a,id:c,children:l}}),c,u)}),rs=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,children:s,...a}=e,{id:c,children:l,type:d,setId:u}=es(i,s,"title");return ts(Di("h2",e,{ref:t,state:{type:d},props:{...a,id:c,children:l}}),c,u)}),os=/*#__PURE__*/e.createContext(void 0);function is(t=!1){const n=e.useContext(os);if(void 0===n&&!t)throw new Error(Ar(16));return n}function ss(e,t,{detail:n=0}={}){e.dispatchEvent(new(Xr(e).PointerEvent)("click",{bubbles:!0,cancelable:!0,composed:!0,detail:n,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,metaKey:t.metaKey}))}function as(t={}){const{disabled:n=!1,focusableWhenDisabled:r,tabIndex:o=0,native:i=!0,composite:s}=t,a=e.useRef(null),c=is(!0),l=s??void 0!==c,{props:d}=function(t){const{focusableWhenDisabled:n,disabled:r,composite:o=!1,tabIndex:i=0,isNativeButton:s}=t,a=o&&!1!==n,c=o&&!1===n;return{props:e.useMemo(()=>{const e={onKeyDown(e){r&&n&&"Tab"!==e.key&&e.preventDefault()}};return o||(e.tabIndex=i,!s&&r&&(e.tabIndex=n?i:-1)),(s&&(n||a)||!s&&r)&&(e["aria-disabled"]=r),!s||n&&!c||(e.disabled=r),e},[o,r,n,a,c,s,i])}}({focusableWhenDisabled:r,disabled:n,composite:l,tabIndex:o,isNativeButton:i}),u=e.useCallback(()=>{const e=a.current;cs(e)&&l&&n&&void 0===d.disabled&&e.disabled&&(e.disabled=!1)},[n,d.disabled,l]);return Or(u,[u]),{getButtonProps:e.useCallback((e={})=>{const{onClick:t,onMouseDown:r,onKeyUp:o,onKeyDown:s,onPointerDown:a,...c}=e;return Si({onClick(e){n?e.preventDefault():t?.(e)},onMouseDown(e){n||r?.(e)},onKeyDown(e){if(n)return;if(Oi(e),s?.(e),e.baseUIHandlerPrevented)return;const t=e.target===e.currentTarget,r=e.currentTarget,o=cs(r),a=!i&&Zr(c=r)&&"A"===c.tagName&&Boolean(c.href);var c;const d=t&&(i?o:!a),u="Enter"===e.key,p=" "===e.key,h=r.getAttribute("role"),f=h?.startsWith("menuitem")||"option"===h||"gridcell"===h;if(t&&l&&p){if(e.defaultPrevented&&f)return;return e.preventDefault(),void(i&&!o||(e.preventBaseUIHandler(),ss(r,e)))}d&&!i&&(p||u)?e.defaultPrevented||(e.preventDefault(),u&&(e.preventBaseUIHandler(),ss(r,e))):t&&a&&p&&e.preventDefault()},onKeyUp(e){n||(Oi(e),o?.(e),e.target===e.currentTarget&&i&&l&&cs(e.currentTarget)&&" "===e.key?e.preventDefault():e.baseUIHandlerPrevented||e.target!==e.currentTarget||i||l||e.defaultPrevented||" "!==e.key||(e.preventBaseUIHandler(),ss(e.currentTarget,e)))},onPointerDown(e){n?e.preventDefault():a?.(e)}},i?{type:"button"}:{role:"button"},d,c)},[n,d,l,i]),buttonRef:Hr(e=>{a.current=e,u()})}}function cs(e){return Zr(e)&&"BUTTON"===e.tagName}var ls=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,disabled:s,nativeButton:a=!0,...c}=t,l=Dr(),{toast:d,expanded:u}=zi(),[p,h]=e.useState(!1),{getButtonProps:f,buttonRef:m}=as({disabled:s,native:a});return Di("button",t,{ref:[n,m],state:{type:d.type},props:[{"aria-hidden":!u&&!p,onClick(){l.closeToast(d.id)},onFocus(){h(!0)},onBlur(){h(!1)}},c,f]})}),ds=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,disabled:i,nativeButton:s=!0,...a}=e,{toast:c}=zi(),l=c.actionProps?.children??a.children,{getButtonProps:d,buttonRef:u}=as({disabled:i,native:s}),p=Di("button",e,{ref:[t,u],state:{type:c.type},props:[a,c.actionProps,d,{children:l}]});return Qi(p)?p:null}),us="none",ps="missing",hs="initial";function fs(e,t,n,r){let o=!1,i=!1;const s=r??Ir;return{reason:e,event:t??new Event("base-ui"),cancel(){o=!0},allowPropagation(){i=!0},get isCanceled(){return o},get isPropagationAllowed(){return i},trigger:n,...s}}function ms(e){return`data-base-ui-${e}`}var gs=/*#__PURE__*/e.createContext(null),ys=()=>e.useContext(gs),bs=ms("portal");function vs(t={}){const{ref:n,container:r,componentProps:o=Ir,elementProps:i}=t,s=Ji(),a=ys()?.portalNode,[c,l]=e.useState(null),[d,u]=e.useState(null),p=Hr(e=>{null!==e&&u(e)}),h=e.useRef(null);Or(()=>{if(null===r)return void(h.current&&(h.current=null,u(null),l(null)));const e=(r&&(Gr(r)?r:r.current))??a??document.body;null!=e?h.current!==e&&(h.current=e,u(null),l(e)):h.current&&(h.current=null,u(null),l(null))},[r,a]);const f=Di("div",o,{ref:[n,p],props:[{id:s,[bs]:""},i]}),m=c&&f?/*#__PURE__*/g.createPortal(f,c):null;return{node:d,nodeId:/*#__PURE__*/e.isValidElement(f)?f.props.id:void 0,subtree:m}}var ws=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,children:s,container:a,...c}=t,{node:l,nodeId:d,subtree:u}=vs({container:a,ref:n,componentProps:t,elementProps:c}),p=e.useRef(null),h=e.useRef(null),f=e.useRef(null),m=e.useRef(null),[y,w]=e.useState(null),x=e.useRef(!1),S=y?.modal,k=y?.open,C=!!y&&!y.modal&&y.open&&!!l;e.useEffect(()=>{if(l&&!S)return ro(io(l,"focusin",e,!0),io(l,"focusout",e,!0));function e(e){l&&e.relatedTarget&&si(e)&&("focusin"===e.type?x.current&&(ai(l),x.current=!1):(function(e){ni(e).forEach(e=>{e.dataset.tabindex=e.getAttribute("tabindex")||"",e.setAttribute("tabindex","-1")})}(l),x.current=!0))}},[l,S]),Or(()=>{l&&!0===k&&x.current&&(ai(l),x.current=!1)},[k,l]);const E=e.useMemo(()=>({beforeOutsideRef:p,afterOutsideRef:h,beforeInsideRef:f,afterInsideRef:m,portalNode:l,setFocusManagerState:w}),[l]);/*#__PURE__*/
5
- return v(e.Fragment,{children:[u,/*#__PURE__*/v(gs.Provider,{value:E,children:[C&&l&&/*#__PURE__*/b(mi,{"data-type":"outside",ref:p,onFocus:e=>{if(si(e,l))f.current?.focus();else{const e=y?y.domReference:null;ii(e)?.focus()}}}),C&&l&&/*#__PURE__*/b("span",{"aria-owns":d,style:qi}),l&&/*#__PURE__*/g.createPortal(s,l),C&&l&&/*#__PURE__*/b(mi,{"data-type":"outside",ref:h,onFocus:e=>{if(si(e,l))m.current?.focus();else{const t=y?y.domReference:null;oi(t)?.focus(),y?.closeOnFocusOut&&y?.onOpenChange(!1,fs("focus-out",e.nativeEvent))}}})]})]})}),xs=/*#__PURE__*/e.forwardRef(function(t,n){const{children:r,container:o,className:i,render:s,style:a,...c}=t,{node:l,subtree:d}=vs({container:o,ref:n,componentProps:t,elementProps:c});return d||l?/*#__PURE__*/v(e.Fragment,{children:[d,l&&/*#__PURE__*/g.createPortal(r,l)]}):null}),Ss=/*#__PURE__*/e.forwardRef(function(e,t){/*#__PURE__*/
6
- return b(xs,{ref:t,...e})});function ks(e){const t=Rr(Cs,e).current;return t.next=e,Or(t.effect),t}function Cs(e){const t={current:e,next:e,effect:()=>{t.current=t.next}};return t}var Es=0;function Is(e,t={}){const{preventScroll:n=!1,sync:r=!1,shouldFocus:o}=t;function i(){o&&!o()||e?.focus({preventScroll:n})}if(cancelAnimationFrame(Es),r)return i(),Cr;const s=requestAnimationFrame(i);return Es=s,()=>{Es===s&&(cancelAnimationFrame(s),Es=0)}}var Ms={inert:/* @__PURE__ */new WeakMap,"aria-hidden":/* @__PURE__ */new WeakMap},Ts="data-base-ui-inert",Rs={inert:/* @__PURE__ */new WeakSet,"aria-hidden":/* @__PURE__ */new WeakSet},Os=/* @__PURE__ */new WeakMap,As=0;function _s(e){return e?Qr(e)?e.host:_s(e.parentNode):null}var Ds=(e,t)=>t.map(t=>{if(e.contains(t))return t;const n=_s(t);return e.contains(n)?n:null}).filter(e=>null!=e),Ps=e=>{const t=/* @__PURE__ */new Set;return e.forEach(e=>{let n=e;for(;n&&!t.has(n);)t.add(n),n=n.parentNode}),t},Ns=(e,t,n)=>{const r=[],o=e=>{e&&!n.has(e)&&Array.from(e.children).forEach(e=>{"script"!==Kr(e)&&(t.has(e)?o(e):r.push(e))})};return o(e),r};function Ls(e,t={}){const{ariaHidden:n=!1,inert:r=!1,mark:o=!0}=t;return function(e,t,n,r,{mark:o=!0}){let i=null;r?i="inert":n&&(i="aria-hidden");let s=null,a=null;const c=Ds(t,e),l=o?Ns(t,Ps(c),new Set(c)):[],d=[],u=[];if(i){const e=Ms[i],n=function(e){return Rs[e]}(i);a=n,s=e;const r=Ds(t,Array.from(t.querySelectorAll("[aria-live]"))),o=c.concat(r);Ns(t,Ps(o),new Set(o)).forEach(t=>{const r=t.getAttribute(i),o=null!==r&&"false"!==r,s=(e.get(t)||0)+1;e.set(t,s),d.push(t),1===s&&o&&n.add(t),o||t.setAttribute(i,"inert"===i?"":"true")})}return o&&l.forEach(e=>{const t=(Os.get(e)||0)+1;Os.set(e,t),u.push(e),1===t&&e.setAttribute(Ts,"")}),As+=1,()=>{s&&d.forEach(e=>{const t=(s.get(e)||0)-1;s.set(e,t),t||(!a?.has(e)&&i&&e.removeAttribute(i),a?.delete(e))}),o&&u.forEach(e=>{const t=(Os.get(e)||0)-1;Os.set(e,t),t||e.removeAttribute(Ts)}),(As-=1)||(Ms.inert=/* @__PURE__ */new WeakMap,Ms["aria-hidden"]=/* @__PURE__ */new WeakMap,Rs.inert=/* @__PURE__ */new WeakSet,Rs["aria-hidden"]=/* @__PURE__ */new WeakSet,Os=/* @__PURE__ */new WeakMap)}}(e,oo(e[0]).body,n,r,{mark:o})}function Fs(){const e=/* @__PURE__ */new Map;return{emit(t,n){e.get(t)?.forEach(e=>e(n))},on(t,n){e.has(t)||e.set(t,/* @__PURE__ */new Set),e.get(t).add(n)},off(t,n){e.get(t)?.delete(n)}}}var zs=/*#__PURE__*/e.createContext(null),$s=/*#__PURE__*/e.createContext(null),Bs=t=>{const n=e.useContext($s);return t??n},Ws=[];function Us(){Ws=Ws.filter(e=>e.deref()?.isConnected)}function Hs(e){Us(),e&&"body"!==Kr(e)&&(Ws.push(new WeakRef(e)),Ws.length>20&&(Ws=Ws.slice(-20)))}function js(){return Us(),Ws[Ws.length-1]?.deref()}function qs(e){if(e.hasAttribute("tabindex")&&!e.hasAttribute("data-tabindex"))return;if(!e.getAttribute("role")?.includes("dialog"))return;const t=ti(e).filter(e=>{const t=e.getAttribute("data-tabindex")||"";return ei(e)||e.hasAttribute("data-tabindex")&&!t.startsWith("-")}),n=e.getAttribute("tabindex");0===t.length?"0"!==n&&(e.setAttribute("tabindex","0"),e.setAttribute("data-tabindex","0")):("-1"!==n||e.hasAttribute("data-tabindex")&&"-1"!==e.getAttribute("data-tabindex"))&&(e.setAttribute("tabindex","-1"),e.setAttribute("data-tabindex","-1"))}function Vs(t){const{context:n,children:r,disabled:o=!1,initialFocus:i=!0,returnFocus:s=!0,restoreFocus:a=!1,modal:c=!0,closeOnFocusOut:l=!0,openInteractionType:d="",nextFocusableElement:u,previousFocusableElement:p,beforeContentFocusGuardRef:h,externalTree:f,getInsideElements:m}=t,g="rootStore"in n?n.rootStore:n,y=g.useState("open"),w=g.useState("domReferenceElement"),x=g.useState("floatingElement"),{events:S,dataRef:k}=g.context,C=Hr(()=>k.current.floatingContext?.nodeId),E=!1===i,I=Po(w)&&E,M=ks(i),T=ks(s),R=ks(d),O=ks(y),A=Bs(f),_=ys(),D=e.useRef(!1),P=e.useRef(!1),N=e.useRef(!1),L=e.useRef(null),F=e.useRef(""),z=e.useRef(""),$=e.useRef(null),B=e.useRef(null),W=gi($,h,_?.beforeInsideRef),U=gi(B,_?.afterInsideRef),H=po(),j=po(),q=lo(),V=null!=_,Y=Lo(x),K=Hr((e=Y)=>e?ni(e):[]),X=Hr(()=>m?.().filter(e=>null!=e)??[]);e.useEffect(()=>{if(!o&&c)return io(oo(Y),"keydown",function(e){"Tab"===e.key&&Oo(Y,Ro(oo(Y)))&&0===K().length&&!I&&function(e){e.preventDefault(),e.stopPropagation()}(e)})},[o,Y,c,I,K]),e.useEffect(()=>{if(o||!y)return;const e=oo(Y);function t(){N.current=!1}return ro(io(e,"pointerdown",function(e){const t=Ao(e),n=X(),r=Oo(x,t)||Oo(w,t)||Oo(_?.portalNode,t)||n.some(e=>e===t||Oo(e,t));N.current=!r,z.current=e.pointerType||"keyboard",t?.closest("[data-base-ui-click-trigger]")&&(P.current=!0,j.start(0,()=>{P.current=!1}))},!0),io(e,"pointerup",t,!0),io(e,"pointercancel",t,!0),io(e,"keydown",function(){z.current="keyboard"},!0),t)},[o,x,w,Y,y,_,j,X]),e.useEffect(()=>{if(o||!l)return;const e=oo(Y);function t(t){const n=t.relatedTarget,r=t.currentTarget,o=Ao(t);c&&null==n&&null!=o&&Oo(x,o)&&Hs(o),queueMicrotask(()=>{const i=C(),s=g.context.triggerElements,l=X(),d=n?.hasAttribute(ms("focus-guard"))&&[$.current,B.current,_?.beforeInsideRef.current,_?.afterInsideRef.current,_?.beforeOutsideRef.current,_?.afterOutsideRef.current,Hi(p),Hi(u)].includes(n),h=!(Oo(w,n)||Oo(x,n)||Oo(n,x)||Oo(_?.portalNode,n)||l.some(e=>e===n||Oo(e,n))||s.hasMatchingElement(e=>Oo(e,n))||d||A&&(Fo(A.nodesRef.current,i).find(e=>Oo(e.context?.elements.floating,n)||Oo(e.context?.elements.domReference,n))||zo(A.nodesRef.current,i).find(e=>[e.context?.elements.floating,Lo(e.context?.elements.floating)].includes(n)||e.context?.elements.domReference===n)));if(r===w&&Y&&qs(Y),a&&r!==w&&!Uo(o)&&Ro(e)===e.body){if(Zr(Y)&&(Y.focus(),"popup"===a))return void q.request(()=>{Y.focus()});const e=K(),t=L.current,n=(t&&e.includes(t)?t:null)||e[e.length-1]||Y;Zr(n)&&n.focus()}k.current.insideReactTree?k.current.insideReactTree=!1:!I&&c||!n||!h||P.current||!I&&n===js()||(D.current=!0,g.setOpen(!1,fs("focus-out",t)))})}const n=Zr(w)?w:null;return x||n?ro(n&&io(n,"focusout",t),n&&io(n,"pointerdown",function(){P.current=!0,j.start(0,()=>{P.current=!1})}),x&&io(x,"focusin",function(e){const t=Ao(e);ei(t)&&(L.current=t)}),x&&io(x,"focusout",t),x&&_&&io(x,"focusout",function(){N.current||(k.current.insideReactTree=!0,H.start(0,()=>{k.current.insideReactTree=!1}))},!0)):void 0},[o,w,x,Y,c,A,_,g,l,a,K,I,C,k,H,j,q,u,p,X]),e.useEffect(()=>{if(o||!x||!y)return;const e=Array.from(_?.portalNode?.querySelectorAll(`[${ms("portal")}]`)||[]),t=(A?zo(A.nodesRef.current,C()):[]).find(e=>Po(e.context?.elements.domReference||null))?.context?.elements.domReference,n=Ls([x,...e,$.current,B.current,_?.beforeOutsideRef.current,_?.afterOutsideRef.current,...X(),t,Hi(p),Hi(u),I?w:null].filter(e=>null!=e),{ariaHidden:c||I,mark:!1}),r=Ls([x,...e].filter(e=>null!=e));return()=>{r(),n()}},[y,o,w,x,c,_,I,A,C,u,p,X]),Or(()=>{if(!y||o||!Zr(Y))return;F.current="",z.current="";const e=oo(Y),t=Ro(e);queueMicrotask(()=>{const n=M.current,r="function"==typeof n?n(R.current||""):n;if(void 0===r||!1===r)return;if(Oo(Y,t))return;let o=null;const i=()=>(null==o&&(o=K(Y)),o[0]||Y);let s;s=!0===r||null===r?i():Hi(r),s=s||i();const a=Oo(Y,Ro(e));Is(s,{preventScroll:s===Y,shouldFocus(){if(!O.current)return!1;if(a)return!0;const t=Ro(e);return!(t!==s&&Oo(Y,t))}})})},[o,y,Y,K,M,R,O]),Or(()=>{if(o||!Y)return;const e=oo(Y),t=Ro(e),n=null==R.current;function r(e){var t;if(e.open||(F.current=function(e,t){const n=Xr(Ao(e));return e instanceof n.KeyboardEvent?"keyboard":e instanceof n.FocusEvent?t||"keyboard":"pointerType"in e?e.pointerType||"keyboard":"touches"in e?"touch":e instanceof n.MouseEvent?t||(0===e.detail?"keyboard":"mouse"):""}(e.nativeEvent,z.current)),"trigger-hover"===e.reason&&"mouseleave"===e.nativeEvent.type&&(D.current=!0),"outside-press"===e.reason)if(e.nested)D.current=!1;else if(""===(t=e.nativeEvent).pointerType&&t.isTrusted||(So&&t.pointerType?"click"===t.type&&1===t.buttons:0===t.detail&&!t.pointerType)||function(e){return!Mo&&(!So&&0===e.width&&0===e.height||So&&1===e.width&&1===e.height&&0===e.pressure&&0===e.detail&&"mouse"===e.pointerType||e.width<1&&e.height<1&&0===e.pressure&&0===e.detail&&"touch"===e.pointerType)}(e.nativeEvent))D.current=!1;else{let e=!1;oo(Y).createElement("div").focus({get preventScroll(){return e=!0,!1}}),D.current=!e}}return Hs(t),S.on("openchange",r),()=>{S.off("openchange",r);const o=Ro(e),i=X(),s=Oo(x,o)||i.some(e=>e===o||Oo(e,o))||A&&Fo(A.nodesRef.current,C(),!1).some(e=>Oo(e.context?.elements.floating,o)),a=T.current,c=F.current,l=function(e){const r=T.current;let o="function"==typeof r?r(e):r;if(void 0===o||!1===o)return null;null===o&&(o=!0);const i=w?.isConnected?w:null,s=t?.isConnected&&"body"!==Kr(t)?t:null;let a=n?s||i:i||s;return a||(a=js()||null),"boolean"==typeof o?a:Hi(o)||a||null}(c);queueMicrotask(()=>{const t=(n=l)?ei(n)?n:ni(n)[0]||n:null;var n;const r="boolean"!=typeof a;if(a&&!D.current&&Zr(t)&&(r||t===o||o===e.body||s)){const e={preventScroll:!0};"keyboard"===c&&(e.focusVisible=!0),t.focus(e)}D.current=!1})}},[o,x,Y,T,R,S,A,w,C,X]),Or(()=>{if(!Eo||y||!x)return;const e=Ro(oo(x));Zr(e)&&Do(e)&&Oo(x,e)&&e.blur()},[y,x]),Or(()=>{if(!o&&_)return _.setFocusManagerState({modal:c,closeOnFocusOut:l,open:y,onOpenChange:g.setOpen,domReference:w}),()=>{_.setFocusManagerState(null)}},[o,_,c,y,g,l,w]),Or(()=>{if(!o&&Y)return qs(Y),()=>{queueMicrotask(Us)}},[o,Y]);const G=!o&&(!c||!I)&&(V||c);/*#__PURE__*/
7
- return v(e.Fragment,{children:[G&&/*#__PURE__*/b(mi,{"data-type":"inside",ref:W,onFocus:e=>{if(c){const e=K();Is(e[e.length-1])}else _?.portalNode&&(D.current=!1,si(e,_.portalNode)?oi(w)?.focus():Hi(p??_.beforeOutsideRef)?.focus())}}),r,G&&/*#__PURE__*/b(mi,{"data-type":"inside",ref:U,onFocus:e=>{c?Is(K()[0]):_?.portalNode&&(l&&(D.current=!0),si(e,_.portalNode)?ii(w)?.focus():Hi(u??_.afterOutsideRef)?.focus())}})]})}function Ys(){return!1}var Ks={open:e=>e.open,transitionStatus:e=>e.transitionStatus,domReferenceElement:e=>e.domReferenceElement,referenceElement:e=>e.positionReference??e.referenceElement,floatingElement:e=>e.floatingElement,floatingId:e=>e.floatingId},Xs=class extends Vr{constructor(e){const{syncOnly:t,nested:n,onOpenChange:r,triggerElements:o,...i}=e;super({...i,positionReference:i.referenceElement,domReferenceElement:i.referenceElement},{onOpenChange:r,dataRef:{current:{}},events:Fs(),nested:n,triggerElements:o},Ks),this.syncOnly=t}syncOpenEvent=(e,t)=>{(!e||!this.state.open||null!=t&&function(e){const t=e.type;return"click"===t||"mousedown"===t||"keydown"===t||"keyup"===t}(t))&&(this.context.dataRef.current.openEvent=e?t:void 0)};dispatchOpenChange=(e,t)=>{this.syncOpenEvent(e,t.event);const n={open:e,reason:t.reason,nativeEvent:t.event,nested:this.context.nested,triggerElement:t.trigger};this.context.events.emit("openchange",n)};setOpen=(e,t)=>{this.syncOnly||this.dispatchOpenChange(e,t),this.context.onOpenChange?.(e,t)}};function Gs(t,n=!1,r=!1){const[o,i]=e.useState(t&&n?"idle":void 0),[s,a]=e.useState(t);return t&&!s&&(a(!0),i("starting")),t||!s||"ending"===o||r||i("ending"),t||s||"ending"!==o||i(void 0),Or(()=>{if(!t&&s&&"ending"!==o&&r){const e=co.request(()=>{i("ending")});return()=>{co.cancel(e)}}},[t,s,o,r]),Or(()=>{if(!t||n)return;const e=co.request(()=>{i(void 0)});return()=>{co.cancel(e)}},[n,t]),Or(()=>{if(!t||!n)return;t&&s&&"idle"!==o&&i("starting");const e=co.request(()=>{i("idle")});return()=>{co.cancel(e)}},[n,t,s,o]),{mounted:s,setMounted:a,transitionStatus:o}}var Js={tabIndex:-1,[To]:""};function Zs({handle:e,store:t}){return Or(()=>e.attachStore(t),[e,t]),null}var Qs=class{constructor(){this.idMap=/* @__PURE__ */new Map}add(e,t){this.idMap.set(e,t)}delete(e){this.idMap.delete(e)}hasElement(e){for(const t of this.idMap.values())if(t===e)return!0;return!1}hasMatchingElement(e){for(const t of this.idMap.values())if(e(t))return!0;return!1}getById(e){return this.idMap.get(e)}entries(){return this.idMap.entries()}elements(){return this.idMap.values()}get size(){return this.idMap.size}},ea=e=>e.triggerIdProp??e.activeTriggerId,ta=e=>e.openProp??e.open,na=e=>(e.popupElement?.id??e.floatingId)||void 0;function ra(e,t){return void 0!==t&&ta(e)&&ea(e)===t}var oa,ia={open:ta,mounted:e=>e.mounted,transitionStatus:e=>e.transitionStatus,floatingRootContext:e=>e.floatingRootContext,triggerCount:e=>e.triggerCount,preventUnmountingOnClose:e=>e.preventUnmountingOnClose,payload:e=>e.payload,activeTriggerId:ea,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:na,isTriggerActive:(e,t)=>void 0!==t&&ea(e)===t,isOpenedByTrigger:(e,t)=>ra(e,t),isMountedByTrigger:(e,t)=>void 0!==t&&ea(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>function(e,t){return!!ra(e,t)||void 0!==t&&ta(e)&&null==ea(e)&&1===e.triggerCount}(e,t)?na(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement},sa=/*#__PURE__*/e.createContext(void 0);(oa={}).open="data-open",oa.closed="data-closed",oa[oa.startingStyle=$i.startingStyle]="startingStyle",oa[oa.endingStyle=$i.endingStyle]="endingStyle",oa.anchorHidden="data-anchor-hidden",oa.side="data-side",oa.align="data-align";var aa={"data-open":""},ca={"data-closed":""},la={"data-anchor-hidden":""},da={open:e=>e?aa:ca,anchorHidden:e=>e?la:null},ua={...da,...Ui};function pa(){const t=Dr(),n=t.useState("toasts");return e.useMemo(()=>({toasts:n,add:t.addToast,close:t.closeToast,update:t.updateToast,promise:t.promiseToast}),[n,t])}var ha="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",fa={none:"none",card:"0 1px 4px rgba(0,0,0,0.1)",section:"0 2px 8px rgba(0,0,0,0.06)",panel:"0 12px 40px rgba(0,0,0,0.16), 0 4px 12px rgba(0,0,0,0.08)",fab:"0 2px 8px rgba(0,0,0,0.18), 0 0 0 1px rgba(0,0,0,0.04)",button:"0 4px 6px -1px rgba(0,0,0,0.1)"},ma={none:"0",sm:"calc(var(--radius) - 4px)",md:"calc(var(--radius) - 2px)",lg:"var(--radius)",xl:"calc(var(--radius) + 4px)",pill:"9999px"},ga={default:"var(--foreground)",muted:"var(--foreground-muted)",faint:"var(--foreground-faint)",primary:"var(--primary)",inherit:"inherit"},ya={tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625"},ba={info:{background:"#f0f9ff",border:"1px solid #bae6fd",titleColor:"#0c4a6e",bodyColor:"#0369a1",closeColor:"#7dd3fc",actionBackground:"#e0f2fe"},error:{background:"#fef2f2",border:"1px solid #fecaca",titleColor:"#b91c1c",bodyColor:"#b91c1c",closeColor:"#f87171",actionBackground:"#fee2e2"},neutral:{background:"rgba(255, 255, 255, 0.95)",border:"1px solid rgba(255, 255, 255, 0.2)",titleColor:"#1f2937",bodyColor:"#1f2937",closeColor:"#6b7280",actionBackground:"transparent"}};function va(e){if(e&&"none"!==e)return{boxShadow:fa[e]}}var wa=2147483003,xa={none:"0","2xs":"2px",xs:"4px",sm:"6px",md:"8px",lg:"12px",xl:"16px","2xl":"24px"},Sa={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch",baseline:"baseline"},ka={start:"flex-start",center:"center",end:"flex-end",between:"space-between",around:"space-around"},Ca={spin:"mtx-spin 1s linear infinite",ping:"mtx-ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"mtx-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",fadeIn:"mtx-fade-in 0.5s ease-out"},Ea={top:"borderTopWidth",bottom:"borderBottomWidth",left:"borderLeftWidth",right:"borderRightWidth"},Ia=/* @__PURE__ */new Set(["padding","paddingX","paddingY","paddingTop","paddingBottom","gap","align","justify","grow","shrink","position","inset","overflow","overflowY","width","height","minWidth","border","rounded","animate","hidden","as","style"]);function Ma(e){const t={};return void 0!==e.padding&&(t.padding=xa[e.padding]),void 0!==e.paddingX&&(t.paddingLeft=xa[e.paddingX],t.paddingRight=xa[e.paddingX]),void 0!==e.paddingY&&(t.paddingTop=xa[e.paddingY],t.paddingBottom=xa[e.paddingY]),void 0!==e.paddingTop&&(t.paddingTop=xa[e.paddingTop]),void 0!==e.paddingBottom&&(t.paddingBottom=xa[e.paddingBottom]),void 0!==e.gap&&(t.gap=xa[e.gap]),void 0!==e.align&&(t.alignItems=Sa[e.align]),void 0!==e.justify&&(t.justifyContent=ka[e.justify]),!0===e.grow&&(t.flex="1 1 0%"),!1===e.shrink&&(t.flexShrink=0),void 0!==e.position&&(t.position=e.position),void 0!==e.inset&&(t.inset="0"===e.inset?"0":xa[e.inset]),void 0!==e.overflow&&(t.overflow=e.overflow),void 0!==e.overflowY&&(t.overflowY=e.overflowY),void 0!==e.width&&(t.width="full"===e.width?"100%":"auto"),void 0!==e.height&&(t.height="full"===e.height?"100%":"auto"),"0"===e.minWidth&&(t.minWidth=0),void 0!==e.border&&!1!==e.border&&(t.borderColor="var(--border)",t.borderStyle="solid",!0===e.border?t.borderWidth="1px":t[Ea[e.border]]="1px"),void 0!==e.rounded&&!1!==e.rounded&&(!0===e.rounded?t.borderRadius=ma.lg:t.borderRadius=ma[e.rounded]),void 0!==e.animate&&"none"!==e.animate&&(t.animation=Ca[e.animate]),!0===e.hidden&&(t.display="none"),t}var Ta={sm:20,md:32,lg:48};function Ra(e){const{src:t,alt:n,elevation:r,fit:o="contain",size:i="md",rounded:s,className:a,style:c,ref:l,...d}=e,u="string"==typeof i?Ta[i]:i;/* @__PURE__ */
8
- return b("img",{...d,ref:l,alt:n,className:a?`mtx-avatar ${a}`:"mtx-avatar",src:t,style:{objectFit:o,width:u,height:u,...Ma({rounded:s}),...va(r),...c}})}var Oa=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,disabled:o=!1,focusableWhenDisabled:i=!1,nativeButton:s=!0,style:a,...c}=e,{getButtonProps:l,buttonRef:d}=as({disabled:o,focusableWhenDisabled:i,native:s});return Di("button",e,{state:{disabled:o},ref:[t,d],props:[c,l]})}),Aa={default:ma.lg,pill:ma.pill};function _a({className:e,disabled:t,elevation:n,full:r,shape:o="default",size:i="md",stacked:s=!1,type:a="button",variant:c="primary",style:l,ref:d,...u}){/* @__PURE__ */
9
- return b(Oa,{...u,ref:d,className:e?`mtx-button ${e}`:"mtx-button","data-disabled":t?"true":"false","data-full":r?"true":"false","data-size":i,"data-stacked":s?"true":"false","data-variant":c,disabled:t,style:{borderRadius:Aa[o],...va(n),...l},type:a})}var Da={default:{},card:{backgroundColor:"var(--card)",color:"var(--card-foreground)"}},Pa={none:{},card:{padding:"8px 12px"},toast:{padding:"8px 12px 8px 8px"}},Na=o(function(e,t){const{as:n="div",background:r="default",className:o,elevation:i,paddingPreset:s="none",style:a,...c}=e,l=function(e){const t={};for(const n in e)Ia.has(n)||(t[n]=e[n]);return t}(c);/* @__PURE__ */
10
- return b(n,{...l,ref:t,className:o,style:{...Da[r],...Pa[s],...va(i),...Ma(e),...a}})}),La=o(function(e,t){const{direction:n,hidden:r,style:o,...i}=e;/* @__PURE__ */
11
- return b(Na,{...i,ref:t,hidden:r,style:{display:!0===r?"none":"flex",..."column"===n&&{flexDirection:"column"},...o}})}),Fa=(e,t=2)=>({d:e,stroke:"currentColor",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round"}),za={checkCircle:{viewBox:"0 0 512 512",paths:[{d:"M504 256c0 136.967-111.033 248-248 248S8 392.967 8 256 119.033 8 256 8s248 111.033 248 248zM227.314 387.314l184-184c6.248-6.248 6.248-16.379 0-22.627l-22.627-22.627c-6.248-6.249-16.379-6.249-22.628 0L216 308.118l-70.059-70.059c-6.248-6.248-16.379-6.248-22.628 0l-22.627 22.627c-6.248 6.248-6.248 16.379 0 22.627l104 104c6.249 6.249 16.379 6.249 22.628.001z"}]},circle:{viewBox:"0 0 512 512",paths:[{d:"M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"}]},exclamationCircle:{viewBox:"0 0 512 512",paths:[{d:"M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"}]},arrowUp:{viewBox:"0 0 448 512",paths:[{d:"M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z"}]},arrowDown:{viewBox:"0 0 448 512",paths:[{d:"M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z"}]},chatBubble:{viewBox:"0 0 512 512",paths:[{d:"M87.48 380c1.2-4.38-1.43-10.47-3.94-14.86a42.63 42.63 0 0 0-2.54-3.8 199.81 199.81 0 0 1-33-110C47.64 139.09 140.72 48 255.82 48 356.2 48 440 117.54 459.57 209.85a199 199 0 0 1 4.43 41.64c0 112.41-89.49 204.93-204.59 204.93-18.31 0-43-4.6-56.47-8.37s-26.92-8.77-30.39-10.11a31.14 31.14 0 0 0-11.13-2.07 30.7 30.7 0 0 0-12.08 2.43L81.5 462.78a15.92 15.92 0 0 1-4.66 1.22 9.61 9.61 0 0 1-9.58-9.74 15.85 15.85 0 0 1 .6-3.29z",fill:"none",stroke:"currentColor",strokeWidth:32,strokeLinecap:"round"},{d:"M160 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0"},{d:"M256 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0"},{d:"M352 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0"}]},stop:{viewBox:"0 0 512 512",paths:[{d:"M392 432H120a40 40 0 0 1-40-40V120a40 40 0 0 1 40-40h272a40 40 0 0 1 40 40v272a40 40 0 0 1-40 40z"}]},mousePointerClick:{viewBox:"0 0 24 24",paths:[Fa("M14 4.1 12 6"),Fa("m5.1 8-2.9-.8"),Fa("m6 12-1.9 2"),Fa("M7.2 2.2 8 5.1"),Fa("M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z")]},ticktick:{viewBox:"0 0 24 24",paths:[{d:"M12 0C5.383 0 0 5.383 0 12s5.383 12 12 12 12-5.383 12-12h-2.7c0 5.128-4.172 9.3-9.3 9.3-5.128 0-9.3-4.172-9.3-9.3 0-5.128 4.172-9.3 9.3-9.3V0Zm7.4 2.583-7.505 9.371L8.388 9.08l-2.002 2.436 4.741 3.888a1.573 1.573 0 0 0 2.231-.233l8.504-10.617L19.4 2.583Z"}]},home:{viewBox:"0 0 24 24",paths:[Fa("M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6")]},chat:{viewBox:"0 0 24 24",paths:[Fa("M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z")]},send:{viewBox:"0 0 24 24",paths:[Fa("M5 12h14m-7-7l7 7-7 7")]},closeSmall:{viewBox:"0 0 12 12",paths:[Fa("M9 3L3 9M3 3l6 6",1.5)]},close:{viewBox:"0 0 20 20",paths:[{d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",fillRule:"evenodd",clipRule:"evenodd"}]},chevronDown:{viewBox:"0 0 24 24",paths:[Fa("M19 9l-7 7-7-7",2.5)]},screenShare:{viewBox:"0 0 24 24",paths:[Fa("M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z")]},alertCircle:{viewBox:"0 0 24 24",paths:[Fa("M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z")]}};function $a({name:e,size:t=16,className:n,ref:r,...o}){const i=za[e];return i?/* @__PURE__ */b("svg",{...o,ref:r,"aria-hidden":"true",className:n?`mtx-icon ${n}`:"mtx-icon",fill:"none",height:t,viewBox:i.viewBox,width:t,xmlns:"http://www.w3.org/2000/svg",children:i.paths.map((e,t)=>/* @__PURE__ */b("path",{clipRule:e.clipRule,d:e.d,fill:e.fill??(e.stroke?"none":"currentColor"),fillRule:e.fillRule,stroke:e.stroke,strokeLinecap:e.strokeLinecap,strokeLinejoin:e.strokeLinejoin,strokeMiterlimit:e.strokeMiterlimit,strokeWidth:e.strokeWidth},t))}):null}function Ba({variant:e="ghost",size:t="sm",tone:n,label:r,disabled:o,children:i,style:s,ref:a,...c}){/* @__PURE__ */
12
- return b("button",{...c,ref:a,type:"button",disabled:o,"aria-label":r,className:"mtx-icon-button","data-disabled":o?"true":"false","data-size":t,"data-variant":e,style:n?{color:ga[n],...s}:s,children:i})}var Wa=o(function(e,t){/* @__PURE__ */
13
- return b(La,{...e,ref:t,direction:"column"})}),Ua={xxs:"10px",xs:"0.75rem",sm:"0.875rem",lg:"1.125rem"},Ha={normal:400,medium:500,semibold:600},ja={overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function qa({as:e="span",block:t=!1,inheritColor:n=!1,italic:r=!1,leading:o,variant:i="default",size:s,weight:a,truncate:c,align:l,className:d,ref:u,style:p,...h}){/* @__PURE__ */
14
- return b(e,{...h,ref:u,className:d,style:{color:ga[n?"inherit":i],...s&&{fontSize:Ua[s]},...a&&{fontWeight:Ha[a]},...l&&{textAlign:l},...o&&{lineHeight:ya[o]},...t&&{display:"block"},...r&&{fontStyle:"italic"},...c&&ja,...p}})}var Va=()=>{const{toasts:e}=pa();return e.map(e=>{const t=ba[n=e.type,"error"===n||"info"===n?n:"neutral"];var n;/* @__PURE__ */
15
- return v(Ki,{toast:e,className:"mtx-toast",render:/* @__PURE__ */b(La,{align:"center",gap:"md",rounded:"pill",paddingPreset:"toast",elevation:"panel",style:{backgroundColor:t.background,border:t.border}}),children:[
16
- /* @__PURE__ */b(Ra,{src:ha,alt:"",size:28,rounded:"pill"}),
17
- /* @__PURE__ */v(Wa,{grow:!0,minWidth:"0",children:[/* @__PURE__ */b(rs,{render:/* @__PURE__ */b(qa,{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(ns,{render:/* @__PURE__ */b(qa,{as:"span",block:!0,inheritColor:!0,style:{fontSize:"12px",color:t.bodyColor,opacity:.8,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}})})]}),e.actionProps&&/* @__PURE__ */b(ds,{render:/* @__PURE__ */b(_a,{type:"button",variant:"ghost",shape:"pill",size:"sm",style:{color:t.titleColor,backgroundColor:t.actionBackground,border:t.border}})}),
18
- /* @__PURE__ */b(ls,{render:/* @__PURE__ */b(Ba,{label:"Dismiss",size:"xs",tone:"inherit",style:{color:t.closeColor,padding:"2px"}}),children:/* @__PURE__ */b($a,{name:"closeSmall",size:12})})]},e.id)})},Ya=({children:e,container:t,offsetBottom:n=20})=>/* @__PURE__ */v(pi,{children:[e,/* @__PURE__ */b(Ss,{container:t??void 0,children:/* @__PURE__ */b(Ni,{className:"mtx-toast-viewport",style:{zIndex:2147483004,bottom:`${n}px`},children:/* @__PURE__ */b(Va,{})})})]}),Ka=pa,Xa=({error:e,onClearError:t,onRetry:n,greeting:r,greetingBody:o,onGreetingDismiss:i})=>{const{add:s,close:c}=Ka();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};function Ga(e){const t=[...e.parts],n=e.content.trim();return 0===t.length&&n&&t.push({type:"text",content:n}),{...e,timestamp:new Date(e.timestamp),parts:t}}function Ja({videoStream:e,...t}){const n=t.timestamp.toISOString();if(!e)return{...t,timestamp:n};const r="Screenshare ended";return{...t,timestamp:n,content:r,isSystemMessage:!0,parts:[{type:"text",content:r}]}}var Za=new class{restore(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=Le.getContext();return{...o,messages:r.map(Ga)}}persist(e){Le.updateContext({...e,messages:e.messages.map(Ja)})}};function Qa(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 ec=(e,t,n="user-message")=>Qa(n,"user",e.trim(),{mode:t}),tc=e=>Qa("agent-message","agent",e.trim()),nc=(e,t,n,r)=>Qa(r,n,e,{mode:t,isSystemMessage:!0}),rc={show:"Show",tell:"Tell",do:"Do"},oc=e=>rc[e];function ic(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}function sc({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);for(const s of i){const t=ic(e,s);if(t>=0)return{index:t,message:e[t]}}return console.warn("[MessageFinder] No message found for progress update",{totalMessages:e.length,isTaskRunning:t,currentMode:n}),null}var ac=/* @__PURE__ */new Set(["click_element","type_text","select_dropdown_option","send_keys"]),cc=e=>e.replace(/\(?cancelled by cleanup\)?/gi,"").trim();function lc(e,t,n){if(t<0)return e;const r=[...e.parts];return r[t]={...r[t],...n},{...e,parts:r}}var dc=(e,t)=>e.parts.findIndex(e=>(e=>"progress"===e.type&&"in_progress"===e.status)(e)&&e.browserToolName===t),uc=/* @__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"]]),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=new class{async executeTool(e,t,n="do",r=""){const o=t;try{if("show"===n&&ac.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){if(!e.url)return xc("URL is required");if(e.new_tab)return window.open(e.url,"_blank")?vc(`Opened ${e.url} in new tab`):xc("The browser blocked opening a new tab");const t=e.url;return{...vc(`Navigating to ${t}`),afterResponseAttempt:()=>{window.location.href=t}}}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}`),{...vc(`Searching for "${e.query}" on ${t}`),afterResponseAttempt:()=>{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)),{...vc(`Clicked element ${e.index}`),afterResponseAttempt:()=>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"):{...vc("Navigated back"),afterResponseAttempt:()=>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=pr();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=sc({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;if("failed"===i?c=function(e,t,n){const r=dc(e,t);if(r<0)return e;const o=cc(e.parts[r].content),i=cc(n);return lc(e,r,{status:"failed",content:i?`${o} (${i})`:o})}(c,r,s||""):"done"!==r&&(c="in_progress"===i?function(e,t,n){const r=cc(n),o=dc(e,t);return o>=0?lc(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||(e=>uc.get(e)??e)(r)):((e,t)=>lc(e,dc(e,t),{status:"completed"}))(c,r)),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&ac.has(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const l=[...e];return l[a.index]=c,l}var Mc=e=>({...e,isPlaceholder:!1}),Tc=e=>"stopped"===e.phase?e:{phase:"idle"};function Rc(e,t,n){const r=sc({messages:e.messages,isTaskRunning:"running"===e.task.phase,currentMode:t}),o=[...e.messages];return r&&(o[r.index]=Mc(n(r.message))),{messages:o,task:Tc(e.task)}}var Oc={completed:"done",failed:"failed",stopped:"stopped"};function Ac(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 _c=(e,t)=>{const n=[...e.parts,{type:"text",content:t}];return{...e,content:Cc(n),parts:n}},Dc=(e,t)=>({...Mc(_c(e,t)),placeholderState:void 0,taskStatus:"failed"});function Pc(e,t,n){const r=e.messages.map(e=>e.id===t?Dc(e,n):e);return{...e,messages:r}}var Nc=n(void 0),Lc=({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(Nc.Provider,{value:{uiState:t,uiActions:r},children:e})},Fc=()=>{const e=s(Nc);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},zc=n(void 0),$c=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=Fc(),[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?Pc(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(ec(e,o)),void m(tc("This is a preview. In production, I'll respond to your messages here."));const i=Le.getCredentialedConfig();if(!i)return console.error("Config not loaded or incomplete"),void m(tc("Configuration error: Missing API credentials. Please check your widget settings."));r||m(ec(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 Fe.getOrCreateChatId();!function(e,t,n){const r={question:t,mode:n,chat_id:Le.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=lr.getInstance();await s.ready(o),await s.send(i)}(i,e,o,s)}catch(c){console.error("Failed to send message:",c),f(e=>Pc(e,s,"I'm sorry, I encountered an error processing your request. Please try again."))}},[t,m,f]);a(()=>{if(t)return;const e=lr.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??"Tool execution failed";f(e=>function(e,t,n,r,o,i){return{...e,messages:Ic(e.messages,"running"===e.task.phase,o,t,n,r,i)}}(e,r,s,c?"failed":"completed",l.current,c)),c||"done"!==r||f(e=>function(e,t){return Rc(e,t,e=>({...e,taskStatus:"done"}))}(e,l.current)),await e.send({type:"tool/response",tool_call_id:n,success:a.success,data:JSON.stringify(a.data),error:c}).catch(e=>console.error("Failed to send tool response:",e)),a.afterResponseAttempt?.()},o={onMessage:e=>{if("tool/call"===e.type){const t=e.tool_call_id;if(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 Oc&&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"},o=t.explanation||"";return{state:{messages:Ic(e.messages,!0,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?_c(e,t.message):e;return{state:Rc(e,n,"has_question"===r?e=>({...o(e),placeholderState:"waiting-for-user"}):e=>({...o(e),taskStatus:Oc[r]})),effects:[]}}case"chat/delta":return{state:Ac(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:Ac(e,t.request_id,t.text,!1),effects:[]};case"chat/error":return{state:Pc(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 cr&&f(t=>function(e,t){return{messages:e.messages.map(e=>e.isPlaceholder?Dc(e,t):e),task:Tc(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{...Rc(e,t,e=>({...e,taskStatus:"stopped"})),task:{phase:"stopped"}}}(e,l.current)),t||lr.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
- return b(zc.Provider,{value:{messages:o.messages,chatActions:E,taskState:o.task,taskActions:I},children:e})},Bc=()=>{const e=s(zc);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},Wc=n(null),Uc=()=>{const{uiState:e}=Fc(),{messages:t}=Bc();return a(()=>{const{currentMode:n,isOpen:r}=e;Za.persist({messages:t,currentMode:n,isOpen:r})},[t,e]),null},Hc=({children:e,previewMode:t})=>{const{uiActions:n}=Fc(),{chatActions:r}=Bc(),[o,i]=p(!1);return a(()=>{if(t)return;let e=!1;return(async()=>{const{messages:t,...o}=Za.restore();n.applyState(o),r.setMessages(t),i(!0);const s=await Fe.getOrCreateChatId();e||lr.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(Uc,{})]})},jc=({children:e,previewMode:t=!1})=>/* @__PURE__ */b(Lc,{children:/* @__PURE__ */b($c,{previewMode:t,children:/* @__PURE__ */b(Hc,{previewMode:t,children:e})})}),qc=/^#?([a-f\d]{3}|[a-f\d]{6})$/i,Vc=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i;function Yc(e){const t=qc.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=Vc.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 Kc(e){const t=function(e){const t=Yc(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 Xc(e,t){const n=Yc(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}var Gc={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"};function Jc(e={}){const t=Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e));return function(e){return{color:{background:e.widget_background_color,foreground:e.widget_text_color,foregroundMuted:Xc(e.widget_text_color,.6),foregroundFaint:Xc(e.widget_text_color,.4),border:e.widget_border_color,primary:e.widget_accent_color,primaryForeground:Kc(e.widget_accent_color),primaryHover:Xc(e.widget_accent_color,.85),secondary:e.widget_secondary_color,secondaryForeground:"#ffffff",secondaryBg:Xc(e.widget_secondary_color,.2),secondaryHover:Xc(e.widget_secondary_color,.3)},radius:"12px",motion:{durationAnimation:"300ms",durationFade:"200ms"}}}({...Gc,...t})}var Zc=n(null),Qc=()=>{const e=s(Zc);if(!e)throw new Error("useWidgetConfig must be used within WidgetRoot");return e},el=()=>{const{uiState:e,uiActions:t}=Fc(),{messages:n,chatActions:r,taskState:o,taskActions:s}=Bc(),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])}},tl={bottom_right:{vertical:"bottom",horizontal:"right"},bottom_left:{vertical:"bottom",horizontal:"left"},top_right:{vertical:"top",horizontal:"right"},top_left:{vertical:"top",horizontal:"left"}},nl=Object.keys(tl),rl=e=>tl[e],ol=e=>{const{vertical:t,horizontal:n}=rl(e);return{[t]:"20px",[n]:"20px"}},il={top:"bottom",bottom:"top",left:"right",right:"left"},sl=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=rl(e);return{x:"left"===s?20:t-20-r,y:"top"===i?20:n-20-o}},al=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}},cl="cubic-bezier(0.16, 1, 0.3, 1)",ll=({onPositionCommit:e})=>{const{isPreviewMode:n=!1,widget_accent_color:r,widget_background_color:o,widget_position:s,widget_position_z_index:a}=Qc(),{state:c,actions:d}=el(),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=sl(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=sl(e,S,k,c.w,c.h),d=sl(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 ${cl}, top 600ms ${cl}`,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=sl(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 nl){const e=sl(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
- return b(Na,{ref:S,className:"mtx-fab-anchor","data-animated":k?"false":"true","data-preview":n?"true":"false",style:{zIndex:a,pointerEvents:h?"none":"auto",...ol(s),...C},children:/* @__PURE__ */v(Na,{className:"mtx-fab","data-open":h?"true":"false",children:[g&&/* @__PURE__ */b(Na,{className:w,"aria-hidden":!0}),y&&!k&&/* @__PURE__ */b(_a,{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
- /* @__PURE__ */b(_a,{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(La,{className:"mtx-fab-center",children:/* @__PURE__ */v(Na,{className:"mtx-fab-badge",style:{borderRadius:"12px",backgroundColor:h?o:r,boxShadow:fa.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})}),
23
- /* @__PURE__ */b(La,{className:"mtx-fab-icon-layer",style:{transform:h?"rotate(30deg) scale(0)":"rotate(0deg) scale(1)",opacity:h?0:1,transitionProperty:"transform, opacity",transitionDuration:"0.16s, 0.08s",transitionTimingFunction:"linear"},"aria-hidden":h,children:/* @__PURE__ */b(Ra,{src:ha,alt:"",className:"mtx-fab-avatar",draggable:!1,onDragStart:e=>e.preventDefault(),style:{borderRadius:"12px",border:"none",outline:"none",backgroundColor:"transparent",pointerEvents:"none",userSelect:"none"}})}),
24
- /* @__PURE__ */b(La,{className:"mtx-fab-icon-layer",style:{transform:h?"rotate(0deg) scale(1)":"rotate(-30deg) scale(0)",opacity:h?1:0,transitionProperty:"transform, opacity",transitionDuration:"0.16s, 0.08s",transitionTimingFunction:"linear"},"aria-hidden":!h,children:/* @__PURE__ */b($a,{name:"chevronDown",size:24,className:"mtx-fab-chevron"})})]})})})]})})},dl=/*#__PURE__*/e.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function ul(t){const{children:n,elementsRef:r,labelsRef:o,onMapChange:i}=t,s=Hr(i),[,a]=e.useState(!1),c=Rr(hl).current,l=Rr(pl).current,d=e.useRef(0),u=e.useRef(!0),p=e.useRef([]),h=e.useRef(null),f=Hr(()=>{u.current||(u.current=!0,a(e=>!e))}),m=Hr((e,t)=>{l.set(e,t),f()}),g=Hr(e=>{l.delete(e),f()}),y=Hr(e=>{const t=/* @__PURE__ */new Map;return r.current.length=0,o&&(o.current.length=0),e.forEach(e=>{t.set(e.element,{...e.registration.metadata??{},index:e.index}),r.current[e.index]=e.element,o&&(o.current[e.index]=void 0!==e.registration.label?e.registration.label:e.registration.textRef?.current?.textContent??e.element.textContent)}),d.current=r.current.length,t}),v=Hr(()=>{const[e,t]=function(e){const t=/* @__PURE__ */new Set,n=[],r=[];e.forEach((e,o)=>{if(!o.isConnected)return;const i=e.index,s={index:i??-1,element:o,registration:e};null===i?r.push(s):i>=0&&(t.add(i),n.push(s))});let o=0;return r.sort((e,t)=>ml(e.element,t.element)),r.forEach(e=>{for(;t.has(o);)o+=1;e.index=o,n.push(e),o+=1}),t.size>0&&n.sort((e,t)=>e.index-t.index),[n,r.map(e=>e.element)]}(l),n=y(e);!function(e){if(h.current?.disconnect(),h.current=null,"function"!=typeof MutationObserver||e.length<2)return;const t=new MutationObserver(n=>{if(!function(e){for(const t of e)for(let e=0;e<t.removedNodes.length;e+=1)if(t.removedNodes[e].isConnected)return!0;return!1}(n))return;let r=null;for(const o of e)if(o.isConnected){if(r&&ml(r,o)>0)return t.disconnect(),void f();r=o}});h.current=t;const n=/* @__PURE__ */new Set;for(let r=1;r<e.length;r+=1){const t=fl(e[r-1],e[r]);t&&n.add(t)}n.forEach(e=>t.observe(e,{childList:!0}))}(t),p.current=e,u.current=!1,c.forEach(e=>e(n)),s(n)});Or(()=>(u.current||y(p.current),()=>{r.current=[],o&&(o.current=[])}),[r,o,y]),Or(()=>{u.current&&v()}),Or(()=>()=>{h.current?.disconnect(),u.current=!0},[]);const w=Hr(e=>(c.add(e),()=>{c.delete(e)})),x=e.useMemo(()=>({register:m,unregister:g,subscribeMapChange:w,nextIndexRef:d}),[m,g,w,d]);/*#__PURE__*/
25
- return b(dl.Provider,{value:x,children:n})}function pl(){/* @__PURE__ */
26
- return new Map}function hl(){/* @__PURE__ */
27
- return new Set}function fl(e,t){let n=e.parentElement;for(;n&&!n.contains(t);)n=n.parentElement;return n}function ml(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}var gl=/*#__PURE__*/e.createContext(void 0);function yl(){const t=e.useContext(gl);if(void 0===t)throw new Error(Ar(64));return t}var bl={tabActivationDirection:e=>({"data-activation-direction":e})},vl=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,defaultValue:o=0,onValueChange:i,orientation:s="horizontal",render:a,value:c,style:l,...d}=t,u=void 0!==t.defaultValue,p=e.useRef([]),[h,f]=e.useState(()=>/* @__PURE__ */new Map),[m,g]=function({controlled:t,default:n,name:r,state:o="value"}){const{current:i}=e.useRef(void 0!==t),[s,a]=e.useState(n);return[i?t:s,e.useCallback(e=>{i||a(e)},[])]}({controlled:c,default:o,name:"Tabs",state:"value"}),y=void 0!==c,[v,w]=e.useState(()=>/* @__PURE__ */new Map),x=e.useRef(void 0),S=e.useCallback(e=>wl(v,e),[v]),[k,C]=e.useState(()=>({previousValue:m,tabActivationDirection:"none"})),{previousValue:E,tabActivationDirection:I}=k;let M=I,T=!1;E!==m&&(M=xl(E,m,s,v),T=null!=E&&null!=m&&null==S(m));const R=T?E:m,O=E!==R||I!==M;Or(()=>{O&&C({previousValue:R,tabActivationDirection:M})},[R,O,M]);const A=Hr((e,t)=>{t.activationDirection=xl(m,e,s,v),i?.(e,t),t.isCanceled||g(e)}),_=Hr((e,t)=>{i?.(e,fs(t,void 0,void 0,{activationDirection:"none"}))}),D=Hr((e,t)=>(f(n=>{const r=new Map(n);return r.set(e,t),r}),()=>{f(n=>{if(n.get(e)!==t)return n;const r=new Map(n);return r.delete(e),r})})),P=e.useCallback(e=>h.get(e),[h]),N=e.useCallback(e=>{for(const t of v.values())if(e===t.value)return t.id},[v]),L=e.useMemo(()=>({getTabElementBySelectedValue:S,getTabIdByPanelValue:N,getTabPanelIdByValue:P,onValueChange:A,orientation:s,registerMountedTabPanel:D,setTabMap:w,tabActivationDirection:M,value:m}),[S,N,P,A,s,D,w,M,m]),F=e.useMemo(()=>{for(const e of v.values())if(e.value===m)return e},[v,m]),z=e.useMemo(()=>{for(const e of v.values())if(!e.disabled)return e.value},[v]),$=e.useRef(!u),B=e.useRef(o),W=e.useRef(u),U=e.useRef(!1);Or(()=>{if(y)return;function e(e,t){g(e),C({previousValue:e,tabActivationDirection:"none"}),_(e,t),$.current=!1}if(0===v.size)return void(U.current&&null!==m&&!x.current?.isConnected&&e(null,ps));U.current=!0,x.current=v.keys().next().value;const t=F?.disabled,n=null==F&&null!==m;if(t||m!==B.current||(W.current=!1),W.current&&t&&m===B.current)return;const r=$.current;if(t||n){const n=z??null;if(m===n)return void($.current=!1);let o=ps;return r?o=hs:t&&(o="disabled"),void e(n,o)}r&&null!=F&&(_(m,hs),$.current=!1)},[z,y,_,F,g,v,m]);const H=Di("div",t,{state:{orientation:s,tabActivationDirection:M},ref:n,props:d,stateAttributesMapping:bl});/*#__PURE__*/
28
- return b(gl.Provider,{value:L,children:/*#__PURE__*/b(ul,{elementsRef:p,children:H})})});function wl(e,t){for(const[n,r]of e.entries())if(t===r.value)return n;return null}function xl(e,t,n,r){if(null==e||null==t)return"none";const[o,i,s]="horizontal"===n?["left","left","right"]:["top","up","down"],a=wl(r,e),c=wl(r,t);if(null==a||null==c)return a===c||"number"!=typeof e&&"string"!=typeof e||typeof e!=typeof t?"none":t>e?s:i;const l=a.getBoundingClientRect()[o],d=c.getBoundingClientRect()[o];return d<l?i:d>l?s:"none"}function Sl(e){return Ji(e,"base-ui")}var kl="data-composite-item-active";function Cl(t={}){const{guess:n,label:r,metadata:o,textRef:i,index:s}=t,{register:a,unregister:c,subscribeMapChange:l,nextIndexRef:d}=e.useContext(dl),u=e.useRef(-1),[p,h]=e.useState(null==s&&n?()=>{if(-1===u.current){const e=d.current;d.current+=1,u.current=e}return u.current}:-1),f=s??p,m=e.useRef(null),g=e.useCallback(e=>{const t=m.current;t&&c(t),m.current=e,e&&a(e,{metadata:o??null,index:s??null,label:r,textRef:i})},[s,a,c,o,r,i]);return Or(()=>{if(null==s)return l(e=>{const t=m.current?e.get(m.current)?.index:null;null!=t&&h(t)})},[s,l]),{ref:g,index:f}}var El=/*#__PURE__*/e.createContext(void 0),Il=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,disabled:o=!1,render:i,value:s,id:a,nativeButton:c=!0,style:l,...d}=t,{value:u,getTabPanelIdByValue:p,onValueChange:h,orientation:f,tabActivationDirection:m}=yl(),{activateOnFocus:g,registerTabResizeObserverElement:y,tabsListElement:b}=function(){const t=e.useContext(El);if(void 0===t)throw new Error(Ar(65));return t}(),{highlightedIndex:v,onHighlightedIndexChange:w}=is(),x=Sl(a),S=e.useMemo(()=>({disabled:o,id:x,value:s}),[o,x,s]),{compositeProps:k,compositeRef:C,index:E}=function(t={}){const{highlightItemOnHover:n,highlightedIndex:r,onHighlightedIndexChange:o}=is(),{ref:i,index:s}=Cl(t),a=r===s,c=e.useRef(null),l=gi(i,c);return{compositeProps:{tabIndex:a?0:-1,onFocus(){o(s)},onMouseMove(){const e=c.current;if(!n||!e)return;const t=e.hasAttribute("disabled")||"true"===e.ariaDisabled;a||t||e.focus()}},compositeRef:l,index:s}}({metadata:S}),I=s===u,M=e.useRef(!1),T=e.useRef(null),R=Hr(e=>{T.current?.(),T.current=e?y(e):null});Or(()=>{if(M.current)return void(M.current=!1);if(!(I&&E>-1&&v!==E))return;const e=b;if(null!=e){const t=Ro(oo(e));if(t&&Oo(e,t))return}o||w(E)},[I,E,v,w,o,b]);const{getButtonProps:O,buttonRef:A}=as({disabled:o,native:c,focusableWhenDisabled:!0}),_=p(s),D=e.useRef(!1),P=e.useRef(!1);function N(e){h(s,fs(us,e.nativeEvent,void 0,{activationDirection:"none"}))}return Di("button",t,{state:{disabled:o,active:I,orientation:f,tabActivationDirection:m},ref:[n,A,C,R],props:[k,{role:"tab","aria-controls":_,"aria-selected":I,id:x,onClick:function(e){I||o||N(e)},onFocus:function(e){I||o||!g||D.current&&!P.current||N(e)},onPointerDown:function(e){if(I||o)return;D.current=!0,P.current=0===e.button;const t=oo(e.currentTarget);function n(){D.current=!1,P.current=!1,t.removeEventListener("pointerup",n),t.removeEventListener("pointercancel",n)}t.addEventListener("pointerup",n),t.addEventListener("pointercancel",n)},[kl]:I?"":void 0,onKeyDownCapture(){M.current=!0}},d,O],stateAttributesMapping:bl})}),Ml={...bl,...Ui},Tl=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,value:o,render:i,keepMounted:s=!1,style:a,...c}=t,{value:l,getTabIdByPanelValue:d,orientation:u,tabActivationDirection:p,registerMountedTabPanel:h}=yl(),f=Sl(),{ref:m,index:g}=Cl(),y=o===l,{mounted:b,transitionStatus:v,setMounted:w}=Gs(y),x=!b,S=d(o),k={hidden:x,orientation:u,tabActivationDirection:p,transitionStatus:v},C=e.useRef(null),E=Di("div",t,{state:k,ref:[n,m,C],props:[{"aria-labelledby":S,hidden:x,id:f,role:"tabpanel",tabIndex:y?0:-1,inert:Li(!y),"data-index":g},c],stateAttributesMapping:Ml});return ji({open:y,ref:C,onComplete(){y||w(!1)}}),Or(()=>{if(null!=f&&(!x||s))return h(o,f)},[x,s,o,f,h]),s||b?E:null}),Rl="ArrowUp",Ol="ArrowDown",Al="ArrowLeft",_l="ArrowRight",Dl=/* @__PURE__ */new Set([Rl,Ol,Al,_l,"Home","End"]),Pl=["Shift","Control","Alt","Meta"];function Nl(e){return!(!function(e){return Zr(e)&&"INPUT"===e.tagName}(e)||null==e.selectionStart)||!(!Zr(e)||"TEXTAREA"!==e.tagName)}function Ll(e,t,n,r){if(!e||!t||!t.scrollTo)return;let o=e.scrollLeft,i=e.scrollTop;const s=e.clientWidth<e.scrollWidth,a=e.clientHeight<e.scrollHeight;if(s&&"vertical"!==r){const r=Fl(e,t,"left"),i=zl(e),s=zl(t);"ltr"===n&&(r+t.offsetWidth+s.scrollMarginRight>e.scrollLeft+e.clientWidth-i.scrollPaddingRight?o=r+t.offsetWidth+s.scrollMarginRight-e.clientWidth+i.scrollPaddingRight:r-s.scrollMarginLeft<e.scrollLeft+i.scrollPaddingLeft&&(o=r-s.scrollMarginLeft-i.scrollPaddingLeft)),"rtl"===n&&(r-s.scrollMarginLeft<e.scrollLeft+i.scrollPaddingLeft?o=r-s.scrollMarginLeft-i.scrollPaddingLeft:r+t.offsetWidth+s.scrollMarginRight>e.scrollLeft+e.clientWidth-i.scrollPaddingRight&&(o=r+t.offsetWidth+s.scrollMarginRight-e.clientWidth+i.scrollPaddingRight))}if(a&&"horizontal"!==r){const n=Fl(e,t,"top"),r=zl(e),o=zl(t);n-o.scrollMarginTop<e.scrollTop+r.scrollPaddingTop?i=n-o.scrollMarginTop-r.scrollPaddingTop:n+t.offsetHeight+o.scrollMarginBottom>e.scrollTop+e.clientHeight-r.scrollPaddingBottom&&(i=n+t.offsetHeight+o.scrollMarginBottom-e.clientHeight+r.scrollPaddingBottom)}e.scrollTo({left:o,top:i,behavior:"auto"})}function Fl(e,t,n){const r="left"===n?"offsetLeft":"offsetTop";let o=0;for(;t.offsetParent&&(o+=t[r],t.offsetParent!==e);)t=t.offsetParent;return o}function zl(e){const t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}var $l=[];function Bl(t){const{render:n,className:r,style:o,refs:i=Er,props:s=Er,state:a=Ir,stateAttributesMapping:c,highlightedIndex:l,onHighlightedIndexChange:d,orientation:u,grid:p,loopFocus:h,onLoop:f,enableHomeAndEndKeys:m,onMapChange:g,stopEventPropagation:y=!0,rootRef:v,disabledIndices:w,modifierKeys:x,highlightItemOnHover:S=!1,tag:k="div",...C}=t,E=e.useContext(sa)?.direction??"ltr",{props:I,highlightedIndex:M,onHighlightedIndexChange:T,elementsRef:R,onMapChange:O,relayKeyboardEvent:A}=function(t){const{loopFocus:n=!0,orientation:r="both",grid:o,onLoop:i,direction:s,highlightedIndex:a,onHighlightedIndexChange:c,rootRef:l,enableHomeAndEndKeys:d=!1,stopEventPropagation:u,disabledIndices:p,modifierKeys:h=$l}=t,[f,m]=e.useState(0),g=null!=o,y=e.useRef(null),b=gi(y,l),v=e.useRef([]),w=e.useRef(!1),x=a??f,S=Hr((e,t=!1)=>{if((c??m)(e),t){const t=v.current[e];Ll(y.current,t,s,r)}}),k=Hr(e=>{if(0===e.size||w.current)return;w.current=!0;const t=Array.from(e.keys()),n=t.find(e=>e?.hasAttribute("data-composite-item-active"))??null,o=n?e.get(n)?.index??-1:-1;if(-1!==o)S(o);else if(Wo(t,x,p)){const e=Bo(t,{disabledIndices:p});$o(t,e)||S(e)}Ll(y.current,n,s,r)});Or(()=>{if(null==p||null!=a||!w.current)return;const e=v.current;if(Wo(e,x,p)){const t=Bo(e,{disabledIndices:p});$o(e,t)||S(t)}},[p,a,x,v,S]);const C=Hr((e,t,n)=>i?i(e,t,n,v):n),E=Hr(e=>{const t="Home"===e.key||"End"===e.key;if(!Dl.has(e.key)||!d&&t)return;if(function(e,t){for(const n of Pl)if(!t.includes(n)&&e.getModifierState(n))return!0;return!1}(e,h))return;if(!y.current)return;const a="rtl"===s,c=a?Al:_l,l=a?_l:Al,f="vertical"===r?Ol:c,m="vertical"===r?Rl:l,b=Ao(e.nativeEvent);if(null!=b&&Nl(b)&&null!=(w=b)&&!w.hasAttribute("disabled")&&"true"!==w.getAttribute("aria-disabled")){const t=b.selectionStart,n=b.selectionEnd,r=b.value;if(null==t||e.shiftKey||t!==n)return;if(e.key!==m&&t<r.length)return;if(e.key!==f&&t>0)return}var w;let k=x;const E=function(e,t){return Bo(e.current,{disabledIndices:t})}(v,p),I=function(e,t){return Bo(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}(v,p);null!=o&&(k=o({disabledIndices:p,elementsRef:v,event:e,highlightedIndex:x,loopFocus:n,maxIndex:I,minIndex:E,onLoop:C,orientation:r,rtl:a}));const M="vertical"!==r&&e.key===c||"horizontal"!==r&&"ArrowDown"===e.key,T="vertical"!==r&&e.key===l||"horizontal"!==r&&"ArrowUp"===e.key;d&&("Home"===e.key?k=E:"End"===e.key&&(k=I)),k===x&&(M||T)&&(n&&k===I&&M?(k=E,i&&(k=i(e,x,k,v))):n&&k===E&&T?(k=I,i&&(k=i(e,x,k,v))):k=Bo(v.current,{startingIndex:k,decrement:T,disabledIndices:p})),k===x||$o(v.current,k)||(u&&e.stopPropagation(),(g||t||M||T)&&e.preventDefault(),S(k,!0),queueMicrotask(()=>{v.current[k]?.focus()}))});return{props:{ref:b,onFocus(e){const t=y.current,n=Ao(e.nativeEvent);t&&null!=n&&Nl(n)&&n.setSelectionRange(0,n.value.length)},onKeyDown:E},highlightedIndex:x,onHighlightedIndexChange:S,elementsRef:v,onMapChange:k,relayKeyboardEvent:E}}({grid:p,loopFocus:h,onLoop:f,orientation:u,highlightedIndex:l,onHighlightedIndexChange:d,rootRef:v,stopEventPropagation:y,enableHomeAndEndKeys:m,direction:E,disabledIndices:w,modifierKeys:x}),_=Di(k,t,{state:a,ref:i,props:[I,...s,C],stateAttributesMapping:c}),D=e.useMemo(()=>({highlightedIndex:M,onHighlightedIndexChange:T,highlightItemOnHover:S,relayKeyboardEvent:A}),[M,T,S,A]);/*#__PURE__*/
29
- return b(os.Provider,{value:D,children:/*#__PURE__*/b(ul,{elementsRef:R,onMapChange:e=>{g?.(e),O(e)},children:_})})}var Wl=/*#__PURE__*/e.forwardRef(function(t,n){const{activateOnFocus:r=!1,className:o,loopFocus:i=!0,render:s,style:a,...c}=t,{orientation:l,setTabMap:d,tabActivationDirection:u}=yl(),[p,h]=e.useState(0),[f,m]=e.useState(null),g=e.useRef(/* @__PURE__ */new Set),y=e.useRef(/* @__PURE__ */new Set),v=e.useRef(null);Or(()=>{if("undefined"==typeof ResizeObserver)return;const e=new ResizeObserver(()=>{g.current.forEach(e=>{e()})});return v.current=e,f&&e.observe(f),y.current.forEach(t=>{e.observe(t)}),()=>{e.disconnect(),v.current=null}},[f]);const w=Hr(e=>(g.current.add(e),()=>{g.current.delete(e)})),x=Hr(e=>(y.current.add(e),v.current?.observe(e),()=>{y.current.delete(e),v.current?.unobserve(e)})),S={orientation:l,tabActivationDirection:u},k={"aria-orientation":"vertical"===l?"vertical":void 0,role:"tablist"},C=e.useMemo(()=>({activateOnFocus:r,registerIndicatorUpdateListener:w,registerTabResizeObserverElement:x,tabsListElement:f}),[r,w,x,f]);/*#__PURE__*/
30
- return b(El.Provider,{value:C,children:/*#__PURE__*/b(Bl,{render:s,className:o,style:a,state:S,refs:[n,m],props:[k,c],stateAttributesMapping:bl,highlightedIndex:p,enableHomeAndEndKeys:!0,loopFocus:i,orientation:l,onHighlightedIndexChange:h,onMapChange:d,disabledIndices:Er})})});function Ul(e){const t=e.getRootNode();return(t instanceof ShadowRoot?t.activeElement:document.activeElement)??null}function Hl(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent&&!e.hasAttribute("aria-hidden"))}function jl(e,t,n){return Math.min(Math.max(e,t),n)}function ql({width:e,height:t}){return{width:jl(e,280,600),height:jl(t,320,Math.floor(.85*window.innerHeight))}}function Vl(e,t){const n=/^\s*(\d+(?:\.\d+)?)px\s*$/.exec(e??"");return n?Number(n[1]):t}var Yl=({title:e,subtitle:t,onClose:n,controls:r})=>/* @__PURE__ */v(La,{align:"center",justify:"between",paddingX:"lg",paddingY:"md",border:"bottom",shrink:!1,elevation:"section",children:[/* @__PURE__ */v(La,{align:"center",gap:"md",minWidth:"0",grow:!0,children:[/* @__PURE__ */b(Ra,{src:ha,alt:"",size:"md",rounded:"lg",elevation:"card"}),/* @__PURE__ */v(Wa,{minWidth:"0",children:[/* @__PURE__ */b(qa,{size:"sm",weight:"semibold",truncate:!0,leading:"tight",children:e}),null!=t&&/* @__PURE__ */b(qa,{as:"p",size:"xs",variant:"muted",truncate:!0,children:t})]})]}),/* @__PURE__ */v(La,{align:"center",gap:"2xs",shrink:!1,children:[r,/* @__PURE__ */b(Ba,{size:"sm",label:"Close",onClick:n,children:/* @__PURE__ */b($a,{name:"close",size:16})})]})]});function Kl(e){const t=u(e);return t.current=e,t}function Xl(...e){return t=>{e.forEach(e=>{"function"==typeof e?e(t):e&&(e.current=t)})}}function Gl({value:e,onChange:t,onSubmit:n,modes:r=[],activeMode:o,onModeChange:s,disabled:c=!1,taskRunning:l=!1,onStop:d,ref:p}){const h=u(null);a(()=>{const e=h.current;if(!e)return;e.style.height="auto";const{scrollHeight:t}=e;e.style.height=`${Math.min(t,66)}px`,e.style.overflowY=t>66?"auto":"hidden"},[e]);const f=i(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),n())},[n]),m=Boolean(e.trim())&&!c;/* @__PURE__ */
31
- return v(Wa,{background:"card",rounded:"xl",border:!0,overflow:"hidden",className:"mtx-composer",children:[/* @__PURE__ */b("textarea",{ref:Xl(h,p),value:e,onChange:e=>t(e.target.value),onKeyDown:f,placeholder:"Ask anything",disabled:c,rows:1,className:"mtx-composer-input",style:{lineHeight:"20px",paddingTop:"4px",paddingBottom:"2px",minHeight:"unset"}}),/* @__PURE__ */v(La,{align:"center",justify:"between",paddingX:"sm",paddingTop:"xs",paddingBottom:"sm",children:[/* @__PURE__ */b(La,{align:"center",gap:"xs",children:r.map(e=>{const t=o===e.id;/* @__PURE__ */
32
- return v("button",{type:"button",className:"mtx-mode-chip","data-active":t?"true":"false",onClick:t=>{t.preventDefault(),t.stopPropagation(),s?.(e.id)},children:[/* @__PURE__ */b($a,{name:e.icon,size:12}),/* @__PURE__ */b(qa,{as:"span",inheritColor:!0,children:e.label})]},e.id)})}),/* @__PURE__ */b(Ba,{variant:l?"secondary":"primary",size:"sm",disabled:!l&&!m,label:l?"Stop the assistant":"Send message",onClick:e=>{e.preventDefault(),e.stopPropagation(),l&&d?d():n()},children:/* @__PURE__ */b($a,l?{name:"stop",size:14}:{name:"send",size:16})})]})]})}var Jl=/*#__PURE__*/e.createContext(void 0);function Zl(t){const n=e.useContext(Jl);if(!t&&void 0===n)throw new Error(Ar(27));return n}var Ql=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,forceRender:i=!1,...s}=e,a=Zl(),c=a.useState("open"),l=a.useState("nested"),d=a.useState("mounted");return Di("div",e,{state:{open:c,transitionStatus:a.useState("transitionStatus")},ref:[a.context.backdropRef,t],stateAttributesMapping:ua,props:[{role:"presentation",hidden:!d,style:{userSelect:"none",WebkitUserSelect:"none"}},s],enabled:i||!l})}),ed=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,...s}=e,a=Zl(),c=Sl(i);return a.useSyncedValueWithCleanup("descriptionElementId",c),Di("p",e,{ref:t,props:[{id:c},s]})}),td=/*#__PURE__*/e.createContext(void 0),nd={...da,...Ui,nestedDialogOpen:e=>e?{"data-nested-dialog-open":""}:null},rd=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,finalFocus:s,initialFocus:a,...c}=t,l=Zl(),d=l.useState("descriptionElementId"),u=l.useState("disablePointerDismissal"),p=l.useState("floatingRootContext"),h=l.useState("popupProps"),f=l.useState("modal"),m=l.useState("mounted"),g=l.useState("nested"),y=l.useState("nestedOpenDialogCount"),v=l.useState("open"),w=l.useState("openMethod"),x=l.useState("titleElementId"),S=l.useState("transitionStatus"),k=l.useState("role"),C=p.useState("floatingId");!function(){if(void 0===e.useContext(td))throw new Error(Ar(26))}(),ji({open:v,ref:l.context.popupRef,onComplete(){v&&l.context.onOpenChangeComplete?.(!0)}});const E=void 0===a?(I=l.context.popupRef,e=>"touch"!==e||I.current):a;var I;const M=y>0,T=l.useStateSetter("popupElement"),R=Di("div",t,{state:{open:v,nested:g,transitionStatus:S,nestedDialogOpen:M},props:[h,{id:C,"aria-labelledby":x,"aria-describedby":d,role:k,...Js,hidden:!m,onKeyDown(e){Dl.has(e.key)&&e.stopPropagation()},style:{"--nested-dialogs":y}},c],ref:[n,l.context.popupRef,T],stateAttributesMapping:nd});/*#__PURE__*/
33
- return b(Vs,{context:p,openInteractionType:w,disabled:!m,closeOnFocusOut:!u,initialFocus:E,returnFocus:s,modal:!1!==f,restoreFocus:"popup",children:R})}),od=/*#__PURE__*/e.forwardRef(function(e,t){const{cutout:n,...r}=e;let o;if(n){const e=n.getBoundingClientRect();o=`polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${e.left}px ${e.top}px,${e.left}px ${e.bottom}px,${e.right}px ${e.bottom}px,${e.right}px ${e.top}px,${e.left}px ${e.top}px)`}/*#__PURE__*/
34
- return b("div",{ref:t,role:"presentation","data-base-ui-inert":"",...r,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:o}})}),id=/*#__PURE__*/e.forwardRef(function(e,t){const{keepMounted:n=!1,...r}=e,o=Zl(),i=o.useState("mounted"),s=o.useState("modal"),a=o.useState("open");return i||n?/*#__PURE__*/b(td.Provider,{value:n,children:/*#__PURE__*/v(ws,{ref:t,...r,children:[i&&!0===s&&/*#__PURE__*/b(od,{ref:o.context.internalBackdropRef,inert:Li(!a)}),e.children]})}):null}),sd={},ad={},cd="";function ld(e,t){return function(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=to(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==o&&"contents"!==o}(e)?e:t}function dd(e,t,n){return/hidden|clip/.test(e.getComputedStyle(ld(t,n)).overflowY)}var ud=new class{lockCount=0;restore=null;timeoutLock=uo.create();timeoutUnlock=uo.create();acquire(e){return this.lockCount+=1,1===this.lockCount&&null===this.restore&&this.timeoutLock.start(0,()=>this.lock(e)),this.release}release=()=>{this.lockCount-=1,0===this.lockCount&&this.restore&&this.timeoutUnlock.start(0,this.unlock)};unlock=()=>{0===this.lockCount&&this.restore&&(this.restore?.(),this.restore=null)};lock(e){if(0===this.lockCount||null!==this.restore)return;const t=oo(e),n=t.documentElement,r=t.body,o=Xr(n);if(dd(o,n,r)){const t=new o.MutationObserver(()=>{dd(o,n,r)||(t.disconnect(),this.restore=null,this.lock(e))}),i={attributes:!0};return t.observe(n,i),t.observe(r,i),void(this.restore=()=>t.disconnect())}const i=wo||!function(e){if("undefined"==typeof document)return!1;const t=oo(e);return Xr(t).innerWidth-t.documentElement.clientWidth>0}(e);this.restore=i?function(e){const t=oo(e),n=ld(t.documentElement,t.body),r={overflowY:n.style.overflowY,overflowX:n.style.overflowX};return Object.assign(n.style,{overflowY:"hidden",overflowX:"hidden"}),()=>{Object.assign(n.style,r)}}(e):function(e){const t=oo(e),n=t.documentElement,r=t.body,o=Xr(n);let i=0,s=0,a=!1;const c=co.create();if(Eo&&1!==(o.visualViewport?.scale??1))return()=>{};function l(){const t=o.getComputedStyle(n),c=o.getComputedStyle(r),l=(t.scrollbarGutter||"").includes("both-edges")?"stable both-edges":"stable";i=n.scrollTop,s=n.scrollLeft,sd={scrollbarGutter:n.style.scrollbarGutter,overflowY:n.style.overflowY,overflowX:n.style.overflowX},cd=n.style.scrollBehavior,ad={position:r.style.position,height:r.style.height,width:r.style.width,boxSizing:r.style.boxSizing,overflowY:r.style.overflowY,overflowX:r.style.overflowX,scrollBehavior:r.style.scrollBehavior};const d=n.scrollHeight>n.clientHeight,u=n.scrollWidth>n.clientWidth,p="scroll"===t.overflowY||"scroll"===c.overflowY,h="scroll"===t.overflowX||"scroll"===c.overflowX,f=Math.max(0,o.innerWidth-r.clientWidth),m=Math.max(0,o.innerHeight-r.clientHeight),g=parseFloat(c.marginTop)+parseFloat(c.marginBottom),y=parseFloat(c.marginLeft)+parseFloat(c.marginRight),b=ld(n,r);if(a=function(e){if("undefined"==typeof CSS||!CSS.supports||!CSS.supports("scrollbar-gutter","stable")||"undefined"==typeof document)return!1;const t=oo(e),n=t.documentElement,r=ld(n,t.body),o=r.style.overflowY,i=n.style.scrollbarGutter;n.style.scrollbarGutter="stable",r.style.overflowY="scroll";const s=r.offsetWidth;r.style.overflowY="hidden";const a=r.offsetWidth;return r.style.overflowY=o,n.style.scrollbarGutter=i,s===a}(e),a)return n.style.scrollbarGutter=l,b.style.overflowY="hidden",void(b.style.overflowX="hidden");Object.assign(n.style,{scrollbarGutter:l,overflowY:"hidden",overflowX:"hidden"}),(d||p)&&(n.style.overflowY="scroll"),(u||h)&&(n.style.overflowX="scroll"),Object.assign(r.style,{position:"relative",height:g||m?`calc(100dvh - ${g+m}px)`:"100dvh",width:y||f?`calc(100vw - ${y+f}px)`:"100vw",boxSizing:"border-box",overflowY:"hidden",overflowX:"hidden",scrollBehavior:"unset"}),r.scrollTop=i,r.scrollLeft=s,n.setAttribute("data-base-ui-scroll-locked",""),n.style.scrollBehavior="unset"}function d(){Object.assign(n.style,sd),Object.assign(r.style,ad),a||(n.scrollTop=i,n.scrollLeft=s,n.removeAttribute("data-base-ui-scroll-locked"),n.style.scrollBehavior=cd)}l();const u=io(o,"resize",function(){d(),c.request(l)});return()=>{c.cancel(),d(),"function"==typeof o.removeEventListener&&u()}}(e)}};function pd({store:t,parentContext:n,isDrawer:r}){const o=t.useState("open"),i=t.useState("disablePointerDismissal"),s=t.useState("modal"),a=t.useState("popupElement"),c=t.useState("floatingRootContext"),[l,d]=e.useState(0),[u,p]=e.useState(0),h=0===l,f=function(t,n={}){const{enabled:r=!0,escapeKey:o=!0,outsidePress:i=!0,outsidePressEvent:s="sloppy",referencePress:a=Ys,bubbles:c,externalTree:l}=n,d="rootStore"in t?t.rootStore:t,u=d.useState("open"),p=d.useState("floatingElement"),{dataRef:h}=d.context,f=Bs(l),m=Hr("function"==typeof i?i:()=>!1),g="function"==typeof i?m:i,y=!1!==g,b=Hr(()=>s),{escapeKey:v,outsidePress:w}={escapeKey:"boolean"==typeof(x=c)?x:x?.escapeKey??!1,outsidePress:"boolean"==typeof x?x:x?.outsidePress??!0};var x;const S=e.useRef(!1),k=e.useRef(!1),C=e.useRef(!1),E=e.useRef(!1),I=e.useRef(""),M=e.useRef(null),T=po(),R=po(),O=Hr(()=>{R.clear(),h.current.insideReactTree=!1}),A=Hr(e=>{const t=h.current.floatingContext?.nodeId;return(f?Fo(f.nodesRef.current,t):[]).some(t=>t.context?.open&&!t.context.dataRef.current[e])}),_=Hr(e=>_o(e,d.select("floatingElement"))||_o(e,d.select("domReferenceElement"))),D=Hr(e=>{a()&&d.setOpen(!1,fs("trigger-press",e.nativeEvent))}),P=Hr(e=>{if(!u||!r||!o||"Escape"!==e.key)return;if(E.current)return;if(!v&&A("__escapeKeyBubbles"))return;const t=fs("escape-key",function(e){return"nativeEvent"in e}(e)?e.nativeEvent:e);d.setOpen(!1,t),t.isCanceled||e.preventDefault(),v||t.isPropagationAllowed||e.stopPropagation()}),N=Hr(()=>{h.current.insideReactTree=!0,R.start(0,O)}),L=Hr(e=>{if(!u||!r||0!==e.button)return;const t=Ao(e.nativeEvent);Oo(d.select("floatingElement"),t)&&(S.current||(S.current=!0,k.current=!1))}),F=Hr(e=>{u&&r&&(e.defaultPrevented||e.nativeEvent.defaultPrevented)&&S.current&&(k.current=!0)});e.useEffect(()=>{if(!u||!r)return O;h.current.__escapeKeyBubbles=v,h.current.__outsidePressBubbles=w;const e=new uo,t=new uo;function n(){C.current=!0,t.start(0,()=>{C.current=!1})}function i(){S.current=!1,k.current=!1}function s(){const e=I.current,t="pen"!==e&&e?e:"mouse",n=b(),r="function"==typeof n?n():n;return"string"==typeof r?r:r[t]}function a(e){const t=h.current.floatingContext?.nodeId,n=f&&Fo(f.nodesRef.current,t).some(t=>_o(e,t.context?.elements.floating));return _(e)||n}function c(e){if(function(e){const t=s();return"intentional"===t&&"click"!==e.type||"sloppy"===t&&"click"===e.type}(e))return"click"===e.type||_(e)||(t.clear(),C.current=!1),void O();if(h.current.insideReactTree)return void O();const n=Ao(e),r=`[${ms("inert")}]`,o=Jr(n)?n.getRootNode():null,i=Array.from((Qr(o)?o:oo(d.select("floatingElement"))).querySelectorAll(r)),c=d.context.triggerElements;if(n&&(c.hasElement(n)||c.hasMatchingElement(e=>Oo(e,n))))return;let l=Jr(n)?n:null;for(;l&&!eo(l);){const e=no(l);if(eo(e)||!Jr(e))break;l=e}if(!i.length||!Jr(n)||n.matches("html,body")||Oo(n,d.select("floatingElement"))||!i.every(e=>!Oo(l,e))){if(Zr(n)&&!("touches"in e)){const t=eo(n),r=to(n),o=/auto|scroll/,i=t||o.test(r.overflowX),s=t||o.test(r.overflowY),a=i&&n.clientWidth>0&&n.scrollWidth>n.clientWidth,c=s&&n.clientHeight>0&&n.scrollHeight>n.clientHeight,l="rtl"===r.direction,d=c&&(l?e.offsetX<=n.offsetWidth-n.clientWidth:e.offsetX>n.clientWidth),u=a&&e.offsetY>n.clientHeight;if(d||u)return}if(!a(e))return"intentional"===s()&&C.current?(t.clear(),void(C.current=!1)):void(("function"!=typeof g||g(e))&&(A("__outsidePressBubbles")||(d.setOpen(!1,fs("outside-press",e)),O())))}}function l(e){if("sloppy"!==s()||!d.select("open")||!r||_(e))return;const t=e.touches[0];t&&(M.current={startTime:Date.now(),startX:t.clientX,startY:t.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},T.start(1e3,()=>{M.current&&(M.current.dismissOnTouchEnd=!1,M.current.dismissOnMouseDown=!1)}))}function m(e,t){const n=Ao(e);if(!n)return;const r=io(n,e.type,()=>{t(e),r()})}function x(e){T.clear(),"pointerdown"===e.type&&(I.current=e.pointerType),"mousedown"===e.type&&M.current&&!M.current.dismissOnMouseDown||m(e,e=>{"pointerdown"===e.type?function(e){"sloppy"===s()&&"touch"!==e.pointerType&&d.select("open")&&r&&!_(e)&&c(e)}(e):c(e)})}function R(e){if(!S.current)return;const r=k.current;i(),"intentional"===s()&&("pointercancel"!==e.type?a(e)||(r?n():("function"!=typeof g||g(e))&&(t.clear(),C.current=!0,O())):r&&n())}function D(e){if("sloppy"!==s()||!M.current||_(e))return;const t=e.touches[0];if(!t)return;const n=Math.abs(t.clientX-M.current.startX),r=Math.abs(t.clientY-M.current.startY),o=Math.sqrt(n*n+r*r);o>5&&(M.current.dismissOnTouchEnd=!0),o>10&&(c(e),T.clear(),M.current=null)}function N(e){"sloppy"===s()&&M.current&&!_(e)&&(M.current.dismissOnTouchEnd&&c(e),T.clear(),M.current=null)}const L=oo(p),F=ro(o&&ro(io(L,"keydown",P),io(L,"compositionstart",function(){e.clear(),E.current=!0}),io(L,"compositionend",function(){e.start(Eo?5:0,()=>{E.current=!1})})),y&&ro(io(L,"click",x,!0),io(L,"pointerdown",x,!0),io(L,"pointerup",R,!0),io(L,"pointercancel",R,!0),io(L,"mousedown",x,!0),io(L,"mouseup",R,!0),io(L,"touchstart",function(e){I.current="touch",m(e,l)},!0),io(L,"touchmove",function(e){m(e,D)},!0),io(L,"touchend",function(e){m(e,N)},!0)));return()=>{F(),e.clear(),t.clear(),i(),C.current=!1,O()}},[h,p,o,y,g,u,r,v,w,P,O,b,A,_,f,d,T]);const z=e.useMemo(()=>({onKeyDown:P,onPointerDown:D,onClick:D}),[P,D]),$=e.useMemo(()=>({onKeyDown:P,onPointerDown:F,onMouseDown:F,onClickCapture:N,onMouseDownCapture(e){N(),L(e)},onPointerDownCapture(e){N(),L(e)},onMouseUpCapture:N,onTouchEndCapture:N,onTouchMoveCapture:N}),[P,N,L,F]);return e.useMemo(()=>r?{reference:z,floating:$,trigger:z}:{},[r,z,$])}(c,{outsidePressEvent:()=>t.context.internalBackdropRef.current||t.context.backdropRef.current?"intentional":{mouse:"trap-focus"===s?"sloppy":"intentional",touch:"sloppy"},outsidePress(e){if(!t.context.outsidePressEnabledRef.current)return!1;if("button"in e&&0!==e.button)return!1;if("touches"in e)if("touchend"===e.type){if(1!==e.changedTouches.length||0!==e.touches.length)return!1}else if(1!==e.touches.length)return!1;const n=Ao(e);if(h&&!i){if(s){const e=t.context.internalBackdropRef.current,r=t.context.backdropRef.current;return!e&&!r||e===n||r===n||Oo(n,a)&&!n?.hasAttribute("data-base-ui-portal")}return!0}return!1},escapeKey:h});return function(e=!0,t=null){Or(()=>{if(e)return ud.acquire(t)},[e,t])}(o&&!0===s,a),t.useContextCallback("onNestedDialogOpen",(e,t)=>{d(e),p(t)}),Or(()=>(n?.onNestedDialogOpen&&(o?n.onNestedDialogOpen(l+1,u+(r?1:0)):n.onNestedDialogOpen(0,0)),()=>{n?.onNestedDialogOpen&&o&&n.onNestedDialogOpen(0,0)}),[r,o,l,u,n]),function(e,t){e.useSyncedValues(t),Or(()=>()=>{e.update({activeTriggerProps:Ir,inactiveTriggerProps:Ir,popupProps:Ir})},[e])}(t,{activeTriggerProps:f.reference,inactiveTriggerProps:f.trigger,popupProps:f.floating,nestedOpenDialogCount:l,nestedOpenDrawerCount:u}),null}var hd={...ia,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role},fd=class extends Vr{constructor(t,n,r){const o=new Qs,i=function(e,t,n,r=!1){const o={open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:new Xs({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:new Qs,floatingId:void 0,syncOnly:!1,nested:!1,onOpenChange:void 0}),floatingId:void 0,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:Ir,inactiveTriggerProps:Ir,popupProps:Ir,modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e};return o.floatingRootContext=function(e,t,n=!1){return new Xs({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:e,floatingId:t,syncOnly:!0,nested:n,onOpenChange:void 0})}(t,n,r),o}(t,o,n,r);super(i,function(t){return{popupRef:/*#__PURE__*/e.createRef(),backdropRef:/*#__PURE__*/e.createRef(),internalBackdropRef:/*#__PURE__*/e.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:t,onOpenChange:void 0,onOpenChangeComplete:void 0}}(o),hd)}setOpen=(e,t)=>{if(t.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},e||null!=t.trigger||null==this.state.activeTriggerId||(t.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);const n={open:e};!function(e,t,n,r=!1){t?e.preventUnmountingOnClose=!1:r&&(e.preventUnmountingOnClose=!0);const o=n?.id??null;(o||t)&&(e.activeTriggerId=o,e.activeTriggerElement=n??null)}(n,e,t.trigger),this.update(n)}};function md(t){return function(t,n){const{children:r,open:o,defaultOpen:i=!1,onOpenChange:s,onOpenChangeComplete:a,disablePointerDismissal:c=!1,modal:l=!0,actionsRef:d,handle:u,triggerId:p,defaultTriggerId:h=null}=n,f="drawer"===t,m="alert-dialog"===t,g=!!m||l,y=m||c,w=m?"alertdialog":"dialog",x=Zl(!0),S={modal:g,disablePointerDismissal:y,nested:null!=x,role:w},k=function(t,n=!1){const r=Ji(),o=null!=(e.useContext(zs)?.id||null),i=Rr(()=>t(r,o)).current;return function(t){const{popupStore:n,treatPopupAsFloatingElement:r=!1,floatingRootContext:o,floatingId:i,nested:s,onOpenChange:a}=t,c=n.useState("open"),l=n.useState("activeTriggerElement"),d=n.useState(r?"popupElement":"positionerElement"),u=n.context.triggerElements,p=a,h=e.useRef(null);void 0===o&&null===h.current&&(h.current=new Xs({open:c,transitionStatus:void 0,referenceElement:l,floatingElement:d,triggerElements:u,onOpenChange:p,floatingId:i,syncOnly:!0,nested:s}));const f=o??h.current;n.useSyncedValue("floatingId",i),Or(()=>{const e={open:c,floatingId:i,referenceElement:l,floatingElement:d};Jr(l)&&(e.domReferenceElement=l),f.state.positionReference===f.state.referenceElement&&(e.positionReference=l),f.update(e)},[c,i,l,d,f]),f.context.onOpenChange=p,f.context.nested=s}({popupStore:i,treatPopupAsFloatingElement:n,floatingRootContext:i.state.floatingRootContext,floatingId:r,nested:o,onOpenChange:i.setOpen}),i}((e,t)=>new fd({open:i,openProp:o,activeTriggerId:h,triggerIdProp:p,...S},e,t),!0);k.useControlledProp("openProp",o),k.useControlledProp("triggerIdProp",p),k.useSyncedValues(S),k.useContextCallback("onOpenChange",s),k.useContextCallback("onOpenChangeComplete",a);const C=k.useState("open"),E=k.useState("mounted"),I=k.useState("payload");!function(e,t){Or(()=>{t||null===e.state.openMethod||e.set("openMethod",null)},[t,e]),Or(()=>()=>{null!==e.state.openMethod&&e.set("openMethod",null)},[e])}(k,C),function(t,n={}){const{closeOnActiveTriggerUnmount:r=!1}=n,o=e.useRef(null),i=t.useState("open"),s=t.useState("triggerCount"),a=t.useState("activeTriggerId"),c=t.useState("activeTriggerElement");Or(()=>{if(!i)return o.current=null,void(0!==t.state.triggerCount&&t.set("triggerCount",0));const e=t.context.triggerElements.size,n={};t.state.triggerCount!==e&&(n.triggerCount=e);const s=t.select("activeTriggerId");let a=null;if(s){const e=t.context.triggerElements.getById(s);if(e)o.current=s,e!==t.state.activeTriggerElement&&(n.activeTriggerElement=e);else{for(const[e,r]of t.context.triggerElements.entries())if(r===t.state.activeTriggerElement){n.activeTriggerId=e,n.activeTriggerElement=r,o.current=e;break}void 0===n.activeTriggerId&&(o.current===s?a=s:o.current=null)}}else o.current=null;if(!a&&!s&&1===e){const e=t.context.triggerElements.entries().next();if(!e.done){const[t,r]=e.value;n.activeTriggerId=t,n.activeTriggerElement=r,o.current=t}}void 0===n.triggerCount&&void 0===n.activeTriggerId&&void 0===n.activeTriggerElement||t.update(n),a&&r&&queueMicrotask(()=>{if(t.select("open")&&t.select("activeTriggerId")===a&&!t.context.triggerElements.getById(a)){const e=fs(us);t.setOpen(!1,e),e.isCanceled||t.update({activeTriggerId:null,activeTriggerElement:null})}})},[i,t,s,a,c,r])}(k);const{forceUnmount:M}=function(e,t){const{mounted:n,setMounted:r,transitionStatus:o}=Gs(e),i=t.useState("preventUnmountingOnClose"),s=!e&&i;t.useSyncedValues({mounted:n,transitionStatus:o,preventUnmountingOnClose:s});const a=Hr(()=>{r(!1),t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),t.context.onOpenChangeComplete?.(!1)});return ji({enabled:n&&!e&&!s,open:e,ref:t.context.popupRef,onComplete(){e||a()}}),{forceUnmount:a,transitionStatus:o}}(C,k);e.useImperativeHandle(d,()=>({unmount:M,close:()=>k.setOpen(!1,fs("imperative-action"))}),[M,k]);const T=C||E;/*#__PURE__*/
35
- return v(Jl.Provider,{value:k,children:[u&&/*#__PURE__*/b(Zs,{handle:u,store:k}),T&&/*#__PURE__*/b(pd,{store:k,parentContext:x?.context,isDrawer:f}),"function"==typeof r?r({payload:I}):r]})}("dialog",t)}var gd=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,...s}=e,a=Zl(),c=Sl(i);return a.useSyncedValueWithCleanup("titleElementId",c),Di("h2",e,{ref:t,props:[{id:c},s]})}),yd=({open:e,onClose:t,title:n,description:r,onConfirm:o,confirmLabel:i="Confirm",cancelLabel:a="Cancel",finalFocusRef:c})=>{const l=s(Wc)??document.body;/* @__PURE__ */
36
- return b(md,{open:e,onOpenChange:(e,n)=>{e||"none"===n.reason||t()},children:/* @__PURE__ */v(id,{container:l,children:[/* @__PURE__ */b(Ql,{className:"mtx-dialog-backdrop",style:{zIndex:wa}}),/* @__PURE__ */v(rd,{className:"mtx-dialog-popup",finalFocus:c,style:{...va("panel"),zIndex:wa},children:[
37
- /* @__PURE__ */b(gd,{className:"mtx-dialog-title",children:n}),null!=r&&/* @__PURE__ */b(ed,{className:"mtx-dialog-description",children:r}),
38
- /* @__PURE__ */v(La,{gap:"md",justify:"end",children:[/* @__PURE__ */b(_a,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),t()},children:a}),/* @__PURE__ */b(_a,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),o?.()},children:i})]})]})]})})},bd={sm:{width:"14px",height:"14px",borderWidth:"1.5px"},md:{width:"20px",height:"20px",borderWidth:"2px"},lg:{width:"24px",height:"24px",borderWidth:"2px"}};function vd({size:e="md",style:t,ref:n}){/* @__PURE__ */
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:bd[e]}),/* @__PURE__ */b("span",{className:"mtx-visually-hidden",children:"Loading"})]})}var wd=({isWaitingForUser:e})=>/* @__PURE__ */v(La,{align:"center",gap:"sm",paddingY:"2xs",children:[/* @__PURE__ */b(vd,{size:"sm"}),/* @__PURE__ */b(qa,{as:"span",size:"xs",weight:"normal",variant:"faint",children:e?"Waiting for you to complete the action":"Thinking"})]}),xd=({message:e,isLastMessage:t})=>{const{isTaskRunning:n}=el().state,r="waiting-for-user"===e.placeholderState,o=n&&t&&("show"===e.mode||"do"===e.mode);return e.parts.length>0?/* @__PURE__ */v(Wa,{gap:"sm",children:[e.parts.map((e,t)=>"text"===e.type?e.content?/* @__PURE__ */b(qa,{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(La,{align:"start",gap:"md",children:/* @__PURE__ */b(qa,{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(wd,{isWaitingForUser:r})]}):e.isPlaceholder||n&&t&&("show"===e.mode||"do"===e.mode)?/* @__PURE__ */b(wd,{isWaitingForUser:r}):/* @__PURE__ */b(Na,{})},Sd={done:{name:"checkCircle",opacity:1},failed:{name:"exclamationCircle",opacity:.75},stopped:{name:"circle",opacity:.5}},kd=({status:e})=>{const{name:t,opacity:n}=Sd[e];/* @__PURE__ */
40
- return b($a,{name:t,size:14,style:{color:Xc(Qc().widget_accent_color,n),flexShrink:0}})},Cd="8px 8px 0 0",Ed=({label:e,children:t})=>/* @__PURE__ */b(La,{position:"absolute",inset:"0",align:"center",justify:"center",style:{backgroundColor:"#111827",borderRadius:Cd,zIndex:10},children:/* @__PURE__ */v(La,{direction:"column",align:"center",gap:"md",style:{textAlign:"center",padding:"0 16px"},children:[t,/* @__PURE__ */b(qa,{as:"span",size:"xs",weight:"medium",style:{color:"rgba(255,255,255,0.7)"},children:e})]})}),Id=({stream:e})=>{const t=u(null),n=u(null),[r,o]=p(!1),[i,s]=p(!1),c=()=>{n.current?.catch(()=>{}),n.current=null};return a(()=>{if(t.current&&e){const r=t.current;o(!1),s(!1),c(),r.srcObject=e;const i=()=>{o(!0)},a=()=>{s(!0),o(!1)};r.addEventListener("loadedmetadata",i),r.addEventListener("error",a);const l=r.play();return n.current=l,l.then(()=>{o(!0)}).catch(e=>{e instanceof Error&&"AbortError"!==e.name&&(console.error("Error playing video stream:",e),s(!0)),n.current=null}),()=>{r.removeEventListener("loadedmetadata",i),r.removeEventListener("error",a)}}return()=>{c(),t.current&&(t.current.srcObject=null),o(!1),s(!1)}},[e]),e?/* @__PURE__ */v(Na,{width:"full",overflow:"hidden",position:"relative",style:{marginBottom:"4px",borderRadius:Cd,backgroundColor:"#000000",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06)"},children:[!r&&!i&&/* @__PURE__ */b(Ed,{label:"Loading stream...",children:/* @__PURE__ */b(vd,{size:"lg",style:{color:"white"}})}),i&&/* @__PURE__ */b(Ed,{label:"Failed to load stream",children:/* @__PURE__ */b($a,{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:Cd,transition:"opacity 500ms",opacity:r?1:0,minHeight:"120px",background:"linear-gradient(135deg, #111827 0%, #374151 100%)"}}),r&&!i&&/* @__PURE__ */v(La,{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(La,{position:"relative",align:"center",justify:"center",children:[/* @__PURE__ */b(Na,{position:"absolute",rounded:"pill",animate:"ping",style:{width:"8px",height:"8px",backgroundColor:"white",opacity:.75}}),/* @__PURE__ */b(Na,{position:"relative",rounded:"pill",style:{width:"6px",height:"6px",backgroundColor:"white"}})]}),/* @__PURE__ */b(qa,{as:"span",size:"xs",weight:"semibold",style:{color:"white",textTransform:"uppercase",letterSpacing:"0.05em",fontSize:"10px"},children:"Live"})]}),
42
- /* @__PURE__ */b(La,{position:"absolute",inset:"0",align:"center",justify:"center",style:{borderRadius:Cd,backgroundColor:"rgba(0,0,0,0)",zIndex:30,pointerEvents:"none"},children:/* @__PURE__ */b(Na,{rounded:"lg",style:{padding:"4px 12px",backgroundColor:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:/* @__PURE__ */b(qa,{as:"div",size:"xs",weight:"medium",style:{color:"white"},children:"Screen Sharing Active"})})})]}):null},Md=({message:e,index:t,isLastMessage:n,onScreenAccessAllow:r,onScreenAccessDeny:o})=>{if(e.isSystemMessage)/* @__PURE__ */return b(La,{justify:"center",align:"center",children:/* @__PURE__ */b(qa,{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
- return v(Wa,{style:{marginTop:"10px"},role:"article","aria-roledescription":"message","aria-label":i?"You said…":"Agent says…",animate:n?"fadeIn":void 0,children:[/* @__PURE__ */v(La,{align:"start",gap:"sm",width:"full",children:[
44
- /* @__PURE__ */b(La,{shrink:!1,style:{width:"20px",height:"20px",marginTop:"6px"},children:!i&&/* @__PURE__ */b(Ra,{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
- /* @__PURE__ */v(Wa,{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(Id,{stream:e.videoStream}),!e.videoStream&&(s?/* @__PURE__ */v(La,{align:"start",gap:"sm",children:[/* @__PURE__ */b(La,{shrink:!1,style:{marginTop:"3px"},children:/* @__PURE__ */b($a,{name:s,size:13})}),/* @__PURE__ */b(Wa,{grow:!0,children:/* @__PURE__ */b(xd,{message:e,isLastMessage:n})})]}):/* @__PURE__ */b(xd,{message:e,isLastMessage:n})),e.isScreenAccessRequest&&!e.screenShareStatus&&/* @__PURE__ */v(La,{align:"center",gap:"sm",style:{marginTop:"6px"},children:[/* @__PURE__ */b(_a,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:()=>r?.(),children:"Yes"}),/* @__PURE__ */b(_a,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:()=>o?.(),children:"No"})]}),e.isScreenAccessRequest&&e.screenShareStatus&&/* @__PURE__ */b(qa,{as:"div",variant:"faint",size:"xs",italic:!0,style:{marginTop:"2px"},children:"allowed"===e.screenShareStatus?"Sure":"No"}),!i&&e.taskStatus&&/* @__PURE__ */b(La,{position:"absolute",align:"center",justify:"center",style:{bottom:"4px",right:"4px"},children:/* @__PURE__ */b(kd,{status:e.taskStatus})})]}),
46
- /* @__PURE__ */b(La,{shrink:!1,style:{width:"20px"}})]}),!e.isPlaceholder&&/* @__PURE__ */b(qa,{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},Td={boxShadow:fa.button,backgroundColor:"var(--card)",border:"1px solid var(--border)",pointerEvents:"auto"},Rd=({messagesEndRef:e,onScreenAccessAllow:t,onScreenAccessDeny:n})=>{const r=Qc(),{state:o,actions:i}=el(),{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(Na,{position:"relative",height:"full",children:[
47
- /* @__PURE__ */v(Na,{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:`${Xc(r.widget_border_color,.3)} ${Xc(r.widget_border_color,.1)}`,scrollbarWidth:"thin"},children:[w.map((e,r)=>/* @__PURE__ */b(Md,{message:e,index:r,isLastMessage:r===w.length-1,onScreenAccessAllow:t,onScreenAccessDeny:n},`message-${e.id}-${r}`)),s.length>0&&/* @__PURE__ */b(La,{justify:"center",style:{marginTop:"12px",marginBottom:"4px"},children:/* @__PURE__ */b(_a,{type:"button",variant:"bare",onClick:i.clearChatHistory,children:/* @__PURE__ */b(qa,{size:"xs",variant:"muted",style:{cursor:"pointer"},children:"Clear conversation"})})}),
48
- /* @__PURE__ */b(Na,{ref:e},"scroll-anchor")]},"message-list-container"),l&&/* @__PURE__ */b(La,{position:"absolute",justify:"center",style:{top:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */b(Ba,{variant:"secondary",size:"sm",label:"Scroll to top",onClick:()=>{g.current?.scrollTo({top:0,behavior:"smooth"})},style:Td,children:/* @__PURE__ */b($a,{name:"arrowUp",size:10,style:{color:r.widget_accent_color}})})}),f&&/* @__PURE__ */b(La,{position:"absolute",justify:"center",style:{bottom:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */b(Ba,{variant:"secondary",size:"sm",label:"Scroll to bottom",onClick:()=>{e.current&&!c&&e.current.scrollIntoView({behavior:"smooth"})},style:Td,children:/* @__PURE__ */b($a,{name:"arrowDown",size:10,style:{color:r.widget_accent_color}})})})]})},Od=[{id:"tell",icon:"chatBubble",flag:"widget_feature_tell"},{id:"show",icon:"mousePointerClick",flag:"widget_feature_show"},{id:"do",icon:"ticktick",flag:"widget_feature_do"}],Ad=({onScreenSharingChange:e,toggleScreenShareRef:t,messageInputRef:n})=>{const r=Qc(),{state:o,actions:i}=el(),{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=Kl(l),y=Kl(u),b=Kl(e),v=e=>{e&&o?.(e),n(nc("Stopped screenshare","show","user","stopped-sharing")),h(null)},w=Kl(v);a(()=>{const e=()=>{const e=null!==pr(),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[ic(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===Le.getContext().config?.use_screenshare)throw new Error("Screen sharing is disabled for this widget");const e=pr();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 ur=t,t.getVideoTracks()[0].addEventListener("ended",()=>{ur=null}),t}();d(!0),e?.(!0),k("allowed"),n(nc("Started screenshare","show","user","started-screenshare"));const r=((e,t="show")=>Qa("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?(hr(),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)=>Qa("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
- return v(Wa,{height:"full",children:[w&&/* @__PURE__ */b(yd,{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
- /* @__PURE__ */b(Na,{grow:!0,overflow:"hidden",paddingY:"2xs",style:{display:"flex",flexDirection:"column",minHeight:0},children:/* @__PURE__ */b(al,{label:"Chat",fallback:/* @__PURE__ */b(qa,{as:"div",size:"xs",align:"center",variant:"muted",style:{padding:"16px"},children:"Something went wrong displaying messages. Please refresh."}),children:/* @__PURE__ */b(Rd,{messagesEndRef:m,onScreenAccessAllow:k,onScreenAccessDeny:C})})}),
51
- /* @__PURE__ */b(Na,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px",marginTop:"auto"},children:/* @__PURE__ */b(Gl,{ref:n,value:h,onChange:f,onSubmit:()=>{if(!h.trim()||I)return;const e=h.trim();f(""),i.addMessage(ec(e,s)),!1===r.use_screenshare||"show"!==s&&"do"!==s||g?i.messageDispatch(e,s,!0):E(s,e)},modes:Od.filter(({flag:e})=>r[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:oc(e)})),activeMode:s,onModeChange:e=>{e!==s&&(i.addMessage(nc(`Switched to ${oc(e)} mode`,e,"agent","mode-change")),i.setMode(e))},disabled:I,taskRunning:l,onStop:()=>{bc.cleanup(),i.stopTask()}})})]})},_d=[{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"}],Dd=({actions:e,onActionClick:t})=>{const n=Qc();return 0===e.length?null:/* @__PURE__ */b(Wa,{gap:"sm",children:e.map((e,r)=>/* @__PURE__ */b(_a,{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(qa,{as:"span",weight:"normal",leading:"tight",children:e.text})},`welcome-chip-${e.id}-${r}`))})},Pd=({onNavigateToChat:e,onChipClick:t})=>{const n=Qc(),{messages:r}=el().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}):_d}(n);/* @__PURE__ */
52
- return v(Wa,{height:"full",overflow:"hidden",children:[/* @__PURE__ */v(Wa,{grow:!0,overflowY:"auto",padding:"lg",children:[/* @__PURE__ */v(Na,{style:{textAlign:"center",paddingTop:"8px",paddingBottom:"16px"},children:[/* @__PURE__ */b(qa,{as:"h2",size:"lg",weight:"semibold",children:n.widget_greeting}),/* @__PURE__ */b(qa,{as:"p",variant:"muted",size:"sm",style:{marginTop:"2px"},children:n.widget_body})]}),/* @__PURE__ */v(Wa,{gap:"sm",children:[/* @__PURE__ */v(_a,{type:"button",variant:"primary",full:!0,onClick:e,"aria-label":"Ask a question",style:{paddingTop:"10px",paddingBottom:"10px"},children:[/* @__PURE__ */b($a,{name:"chat",size:16}),"Ask a question"]}),/* @__PURE__ */b(Dd,{actions:o,onActionClick:async(n,r)=>{r.preventDefault(),r.stopPropagation(),e(),t(n)}})]})]}),r.length>0&&/* @__PURE__ */v(Na,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px"},children:[
53
- /* @__PURE__ */b(qa,{as:"p",size:"xs",weight:"semibold",style:{marginBottom:"2px"},children:"Recent conversation"}),
54
- /* @__PURE__ */b(qa,{as:"p",size:"xs",variant:"muted",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:r[r.length-1].content||"Message"}),
55
- /* @__PURE__ */b(qa,{as:"p",size:"xs",variant:"muted",onClick:e,style:{marginTop:"4px",cursor:"pointer"},children:"Continue conversation →"})]})]})},Nd=({grip:e,onMouseDown:t})=>/* @__PURE__ */b("div",{role:"separator","aria-label":`Resize widget from ${e.vertical} ${e.horizontal}`,title:"Drag to resize",style:{position:"absolute",[e.vertical]:0,[e.horizontal]:0,width:"20px",height:"20px",padding:"4px",touchAction:"none",zIndex:10,display:"flex",alignItems:"top"===e.vertical?"flex-start":"flex-end",justifyContent:"left"===e.horizontal?"flex-start":"flex-end",cursor:e.cursor},onMouseDown:t}),Ld=[{id:"home",icon:"home",label:"Home"},{id:"chat",icon:"chat",label:"Chat"}],Fd=()=>/* @__PURE__ */b(Wl,{render:/* @__PURE__ */b(La,{align:"center",justify:"around",shrink:!1,border:"top"}),style:{height:48},children:Ld.map(e=>/* @__PURE__ */v(Il,{value:e.id,render:/* @__PURE__ */b(_a,{stacked:!0,variant:"tab"}),children:[
1
+ import*as e from"react";import t,{createContext as n,createElement as r,forwardRef as o,useCallback as i,useContext as s,useEffect as a,useImperativeHandle as c,useLayoutEffect as l,useMemo as d,useRef as u,useState as p,useSyncExternalStore as h,useSyncExternalStore as f}from"react";import{createRoot as m}from"react-dom/client";import*as g from"react-dom";import{Fragment as y,jsx as b,jsxs as v}from"react/jsx-runtime";function w(e){return Array.isArray(e)?e:null==e?[]:[e]}var x="orpc",S=class extends Error{constructor(...e){super(...e),this.name="AbortError"}};function k(e){let t;return()=>{if(t)return t.result;const n=e();return t={result:n},n}}function C(){return globalThis["__@orpc/shared@1.15.0/otel/config__"]}function E(e,t={},n){return(C()?.tracer)?.startSpan(e,t,n)}function I(e,t,n={}){if(!e)return;const r=function(e){if(e instanceof Error){const t={message:e.message,name:e.name,stack:e.stack};return!("code"in e)||"string"!=typeof e.code&&"number"!=typeof e.code||(t.code=e.code),t}return{message:String(e)}}(t);e.recordException(r),n.signal?.aborted&&n.signal.reason===t||e.setStatus({code:2,message:r.message})}async function M({name:e,context:t,...n},r){const o=C()?.tracer;if(!o)return r();const i=async e=>{try{return await r(e)}catch(t){throw I(e,t,n),t}finally{e.end()}};return t?o.startActiveSpan(e,n,t,i):o.startActiveSpan(e,n,i)}async function T(e,t){const n=C();if(!e||!n)return t();const r=n.trace.setSpan(n.context.active(),e);return n.context.with(r,t)}function R(e){return!(!e||"object"!=typeof e)&&"next"in e&&"function"==typeof e.next&&Symbol.asyncIterator in e&&"function"==typeof e[Symbol.asyncIterator]}var O=Symbol.asyncDispose??Symbol.for("asyncDispose"),A=class{#e=!1;#t=!1;#n;#r;constructor(e,t){this.#n=t,this.#r=function(e){let t=Promise.resolve();return(...n)=>t=t.catch(()=>{}).then(()=>e(...n))}(async()=>{if(this.#e)return{done:!0,value:void 0};try{const t=await e();return t.done&&(this.#e=!0),t}catch(t){throw this.#e=!0,t}finally{this.#e&&!this.#t&&(this.#t=!0,await this.#n("next"))}})}next(){return this.#r()}async return(e){return this.#e=!0,this.#t||(this.#t=!0,await this.#n("return")),{done:!0,value:e}}async throw(e){throw this.#e=!0,this.#t||(this.#t=!0,await this.#n("throw")),e}async[O](){this.#e=!0,this.#t||(this.#t=!0,await this.#n("dispose"))}[Symbol.asyncIterator](){return this}};function _({name:e,...t},n){let r;return new A(async()=>{r??=E(e);try{const e=await T(r,()=>n.next());return r?.addEvent(e.done?"completed":"yielded"),e}catch(o){throw I(r,o,t),o}},async e=>{try{"next"!==e&&await T(r,()=>n.return?.())}catch(o){throw I(r,o,t),o}finally{r?.end()}})}function D(e,t,n){const r=(t,o)=>{const i=e[o];return i?i({...t,next:(e=t)=>r(e,o+1)}):n(t)};return r(t,0)}function P(e){if(e)return JSON.parse(e)}function N(e){return JSON.stringify(e)}function L(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||!t||!t.constructor}function F(e){return!!e&&("object"==typeof e||"function"==typeof e)}function z(e,...t){return"function"==typeof e?e(...t):e}function $(e){return new Proxy(e,{get(e,t,n){const r=Reflect.get(e,t,n);return"then"!==t||"function"!=typeof r?r:new Proxy(r,{apply(t,n,r){if(2!==r.length||r.some(e=>{return!("function"==typeof(t=e)&&W.test(t.toString()));var t}))return Reflect.apply(t,n,r);let o=!0;r[0].call(n,$(new Proxy(e,{get:(e,t,n)=>{if(!o||"then"!==t)return Reflect.get(e,t,n);o=!1}})))}})}})}var B,W=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/,U=/* @__PURE__ */new Set(["bind","valueOf","toString","toJSON"]),H={BAD_REQUEST:{status:400,message:"Bad Request"},UNAUTHORIZED:{status:401,message:"Unauthorized"},FORBIDDEN:{status:403,message:"Forbidden"},NOT_FOUND:{status:404,message:"Not Found"},METHOD_NOT_SUPPORTED:{status:405,message:"Method Not Supported"},NOT_ACCEPTABLE:{status:406,message:"Not Acceptable"},TIMEOUT:{status:408,message:"Request Timeout"},CONFLICT:{status:409,message:"Conflict"},PRECONDITION_FAILED:{status:412,message:"Precondition Failed"},PAYLOAD_TOO_LARGE:{status:413,message:"Payload Too Large"},UNSUPPORTED_MEDIA_TYPE:{status:415,message:"Unsupported Media Type"},UNPROCESSABLE_CONTENT:{status:422,message:"Unprocessable Content"},TOO_MANY_REQUESTS:{status:429,message:"Too Many Requests"},CLIENT_CLOSED_REQUEST:{status:499,message:"Client Closed Request"},INTERNAL_SERVER_ERROR:{status:500,message:"Internal Server Error"},NOT_IMPLEMENTED:{status:501,message:"Not Implemented"},BAD_GATEWAY:{status:502,message:"Bad Gateway"},SERVICE_UNAVAILABLE:{status:503,message:"Service Unavailable"},GATEWAY_TIMEOUT:{status:504,message:"Gateway Timeout"}},j=class e extends Error{defined;code;status;data;static{const t=Symbol.for("__@orpc/client@1.15.0/error/ORPC_ERROR_CONSTRUCTORS__");globalThis[t]??=/* @__PURE__ */new WeakSet,(B=globalThis[t]).add(e)}constructor(e,...t){const n=function(e){return e[0]??{}}(t);if(void 0!==n.status&&!q(n.status))throw new Error("[ORPCError] Invalid error status code.");const r=function(e,t){return t||H[e]?.message||e}(e,n.message);super(r,n),this.code=e,this.status=function(e,t){return t??H[e]?.status??500}(e,n.status),this.defined=n.defined??!1,this.data=n.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance](e){if(B.has(this)){const t=function(e){return F(e)?Object.getPrototypeOf(e)?.constructor:null}(e);if(t&&B.has(t))return!0}return super[Symbol.hasInstance](e)}};function q(e){return e<200||e>=400}function V(e){if(!L(e))return!1;const t=["defined","code","status","message","data"];return!Object.keys(e).some(e=>!t.includes(e))&&"defined"in e&&"boolean"==typeof e.defined&&"code"in e&&"string"==typeof e.code&&"status"in e&&"number"==typeof e.status&&q(e.status)&&"message"in e&&"string"==typeof e.message}function Y(e,t={}){return new j(e.code,{...t,...e})}var K=class extends TypeError{},X=class extends TypeError{},G=class extends Error{data;constructor(e){super(e?.message??"An error event was received",e),this.data=e?.data}},J=/\r\n|\r(?!\n)|\n/,Z=/(?:\r\n|\r(?!\n)|\n){2}/,Q=/(?:\r\n|\r(?!\n)|\n){2}/g;function ee(e){const t={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(const n of e.split(J)){if(""===n)continue;const e=n.indexOf(":"),r=-1===e?"":n.slice(32===n.charCodeAt(e+1)?e+2:e+1);if(0!==e)switch(-1===e?n:n.slice(0,e)){case"data":t.data=void 0===t.data?r:`${t.data}\n${r}`;break;case"event":t.event=r;break;case"id":t.id=r;break;case"retry":{const e=Number.parseInt(r,10);e>=0&&e.toString()===r&&(t.retry=e);break}}else t.comments.push(r)}return t}var te=class{constructor(e={}){this.options=e}pending=[];tail="";discardLeadingLF=!1;feed(e){if(""===e)return;if(this.discardLeadingLF&&(this.discardLeadingLF=!1,10===e.charCodeAt(0)&&""===(e=e.slice(1))))return;const t=this.tail+e;if(!Z.test(t))return this.pending.push(e),void(this.tail=t.slice(-3));this.pending.push(e);const n=1===this.pending.length?e:this.pending.join(""),r=n.length-t.length,o=[];let i=0;for(const a of t.matchAll(Q))o.push(n.slice(i,r+a.index)),i=r+a.index+a[0].length;const s=n.slice(i);this.pending.length=0,this.tail=s.slice(-3),""===s?this.discardLeadingLF=13===e.charCodeAt(e.length-1):this.pending.push(s);for(const a of o){const e=ee(a);this.options.onEvent&&this.options.onEvent(e)}}end(){if(0!==this.pending.length)throw new X("Event Iterator ended before complete")}},ne=class extends TransformStream{constructor(){let e;super({start(t){e=new te({onEvent:e=>{t.enqueue(e)}})},transform(t){e.feed(t)},flush(){e.end()}})}},re=/\r\n|[\n\r]/,oe=/\r\n|[\n\r]/g;function ie(e){return re.test(e)}function se(e){if(ie(e))throw new K("Event's id must not contain a carriage return or newline character")}function ae(e){if(!Number.isInteger(e)||e<0)throw new K("Event's retry must be a integer and >= 0")}function ce(e){if(ie(e))throw new K("Event's comment must not contain a carriage return or newline character")}function le(e){let t="";var n;return t+=function(e){let t="";for(const n of e??[])ce(n),t+=`: ${n}\n`;return t}(e.comments),void 0!==e.event&&(function(e){if(ie(e))throw new K("Event's event must not contain a carriage return or newline character")}(e.event),t+=`event: ${e.event}\n`),void 0!==e.retry&&(ae(e.retry),t+=`retry: ${e.retry}\n`),void 0!==e.id&&(se(e.id),t+=`id: ${e.id}\n`),t+=void 0===(n=e.data)?"":`data: ${n.replace(oe,"\ndata: ")}\n`,t+="\n",t}var de=Symbol("ORPC_EVENT_SOURCE_META");function ue(e,t){if(void 0===t.id&&void 0===t.retry&&!t.comments?.length)return e;if(void 0!==t.id&&se(t.id),void 0!==t.retry&&ae(t.retry),void 0!==t.comments)for(const n of t.comments)ce(n);return new Proxy(e,{get:(e,n,r)=>n===de?t:Reflect.get(e,n,r)})}function pe(e){return F(e)?Reflect.get(e,de):void 0}function he(e,t){const n=async e=>{let n=await t.error(e);if(n!==e){const t=pe(e);t&&F(n)&&(n=ue(n,t))}return n};return new A(async()=>{const{done:r,value:o}=await(async()=>{try{return await e.next()}catch(t){throw await n(t)}})();let i=await t.value(o,r);if(i!==o){const e=pe(o);e&&F(i)&&(i=ue(i,e))}return{done:r,value:i}},async()=>{try{await(e.return?.())}catch(t){throw await n(t)}})}function fe(e,t={}){const n=t.path??[];return $(new Proxy(async(...[t,r={}])=>await e.call(n,t,function(e){return{...e,context:e.context??{}}}(r)),{get:(r,o)=>"string"!=typeof o||U.has(o)?Reflect.get(r,o):fe(e,{...t,path:[...n,o]})}))}function me(e,t={}){return e.forEach((e,n)=>{Array.isArray(t[n])?t[n].push(e):void 0!==t[n]?t[n]=[t[n],e]:t[n]=e}),t}var ge=class{plugins;constructor(e=[]){this.plugins=[...e].sort((e,t)=>(e.order??0)-(t.order??0))}init(e){for(const t of this.plugins)t.init?.(e)}},ye=class{constructor(e,t,n={}){this.codec=e,this.sender=t,new ge(n.plugins).init(n),this.interceptors=w(n.interceptors),this.clientInterceptors=w(n.clientInterceptors)}interceptors;clientInterceptors;call(e,t,n){return M({name:`${x}.${e.join("/")}`,signal:n.signal},r=>(r?.setAttribute("rpc.system",x),r?.setAttribute("rpc.method",e.join(".")),R(t)&&(t=_({name:"consume_event_iterator_input",signal:n.signal},t)),D(this.interceptors,{...n,path:e,input:t},async({path:e,input:t,...n})=>{const o=C();let i;const s=o?.trace.getActiveSpan()??r;s&&o&&(i=o?.trace.setSpan(o.context.active(),s));const a=await M({name:"encode_request",context:i},()=>this.codec.encode(e,t,n)),c=await D(this.clientInterceptors,{...n,input:t,path:e,request:a},({input:e,path:t,request:n,...r})=>M({name:"send_request",signal:r.signal,context:i},()=>this.sender.call(n,r,t,e))),l=await M({name:"decode_response",context:i},()=>this.codec.decode(c,n,e,t));return R(l)?_({name:"consume_event_iterator_output",signal:n.signal},l):l})))}},be=class{customSerializers;constructor(e={}){if(this.customSerializers=e.customJsonSerializers??[],this.customSerializers.length!==new Set(this.customSerializers.map(e=>e.type)).size)throw new Error("Custom serializer type must be unique.")}serialize(e,t=[],n=[],r=[],o=[]){for(const i of this.customSerializers)if(i.condition(e)){const s=this.serialize(i.serialize(e),t,n,r,o);return n.push([i.type,...t]),s}if(e instanceof Blob)return r.push(t),o.push(e),[e,n,r,o];if("bigint"==typeof e)return n.push([0,...t]),[e.toString(),n,r,o];if(e instanceof Date)return n.push([1,...t]),Number.isNaN(e.getTime())?[null,n,r,o]:[e.toISOString(),n,r,o];if(Number.isNaN(e))return n.push([2,...t]),[null,n,r,o];if(e instanceof URL)return n.push([4,...t]),[e.toString(),n,r,o];if(e instanceof RegExp)return n.push([5,...t]),[e.toString(),n,r,o];if(e instanceof Set){const i=this.serialize(Array.from(e),t,n,r,o);return n.push([6,...t]),i}if(e instanceof Map){const i=this.serialize(Array.from(e.entries()),t,n,r,o);return n.push([7,...t]),i}if(Array.isArray(e))return[e.map((e,i)=>void 0===e?(n.push([3,...t,i]),null):this.serialize(e,[...t,i],n,r,o)[0]),n,r,o];if(L(e)){const i={};for(const s in e)"toJSON"===s&&"function"==typeof e[s]||(i[s]=this.serialize(e[s],[...t,s],n,r,o)[0]);return[i,n,r,o]}return[e,n,r,o]}deserialize(e,t,n,r){const o={data:e};n&&r&&n.forEach((e,t)=>{let n=o,i="data";e.forEach(e=>{if(n=n[i],i=e,!Object.hasOwn(n,i))throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${i}`)}),n[i]=r(t)});for(const i of t){const e=i[0];let t=o,n="data";for(let r=1;r<i.length;r++)if(t=t[n],n=i[r],!Object.hasOwn(t,n))throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${n}`);for(const r of this.customSerializers)if(r.type===e){t[n]=r.deserialize(t[n]);break}switch(e){case 0:t[n]=BigInt(t[n]);break;case 1:t[n]=new Date(t[n]??"Invalid Date");break;case 2:t[n]=NaN;break;case 3:t[n]=void 0;break;case 4:t[n]=new URL(t[n]);break;case 5:{const[,e,r]=t[n].match(/^\/(.*)\/([a-z]*)$/);t[n]=new RegExp(e,r);break}case 6:t[n]=new Set(t[n]);break;case 7:t[n]=new Map(t[n])}}return o.data}},ve=class{constructor(e,t){this.serializer=e,this.baseUrl=t.url,this.maxUrlLength=t.maxUrlLength??2083,this.fallbackMethod=t.fallbackMethod??"POST",this.expectedMethod=t.method??this.fallbackMethod,this.headers=t.headers??{}}baseUrl;maxUrlLength;fallbackMethod;expectedMethod;headers;async encode(e,t,n){let r=function(e){return"function"==typeof e.forEach?me(e):e}(await z(this.headers,n,e,t));void 0!==n.lastEventId&&(r=function(e,t){const n={...e};for(const r in t)Array.isArray(t[r])?n[r]=[...w(n[r]),...t[r]]:void 0!==t[r]&&(Array.isArray(n[r])?n[r]=[...n[r],t[r]]:void 0!==n[r]?n[r]=[n[r],t[r]]:n[r]=t[r]);return n}(r,{"last-event-id":n.lastEventId}));const o=await z(this.expectedMethod,n,e,t),i=await z(this.baseUrl,n,e,t),s=new URL(i);s.pathname=`${s.pathname.replace(/\/$/,"")}${function(e){return`/${e.map(encodeURIComponent).join("/")}`}(e)}`;const a=this.serializer.serialize(t);if(!("GET"!==o||a instanceof FormData||R(a))){const i=await z(this.maxUrlLength,n,e,t),c=new URL(s);if(c.searchParams.append("data",N(a)),c.toString().length<=i)return{body:void 0,method:o,headers:r,url:c,signal:n.signal}}return{url:s,method:"GET"===o?this.fallbackMethod:o,headers:r,body:a,signal:n.signal}}async decode(e){const t=!q(e.status),n=await(async()=>{let t=!1;try{const n=await e.body();return t=!0,this.serializer.deserialize(n)}catch(n){if(!t)throw new Error("Cannot parse response body, please check the response body and content-type.",{cause:n});throw new Error("Invalid RPC response format.",{cause:n})}})();if(!t){if(V(n))throw Y(n);throw new j((r=e.status,Object.entries(H).find(([,e])=>e.status===r)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"),{status:e.status,data:{...e,body:n}})}var r;return n}},we=class{constructor(e){this.jsonSerializer=e}serialize(e){return R(e)?he(e,{value:async e=>this.#o(e,!1),error:async e=>{return new G({data:this.#o((t=e,t instanceof j?t:new j("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:t})).toJSON(),!1),cause:e});var t}}):this.#o(e,!0)}#o(e,t){const[n,r,o,i]=this.jsonSerializer.serialize(e),s=0===r.length?void 0:r;if(!t||0===i.length)return{json:n,meta:s};const a=new FormData;return a.set("data",N({json:n,meta:s,maps:o})),i.forEach((e,t)=>{a.set(t.toString(),e)}),a}deserialize(e){return R(e)?he(e,{value:async e=>this.#i(e),error:async e=>{if(!(e instanceof G))return e;const t=this.#i(e.data);return V(t)?Y(t,{cause:e}):new G({data:t,cause:e})}}):this.#i(e)}#i(e){if(void 0===e)return;if(!(e instanceof FormData))return this.jsonSerializer.deserialize(e.json,e.meta??[]);const t=JSON.parse(e.get("data"));return this.jsonSerializer.deserialize(t.json,t.meta??[],t.maps,t=>e.get(t.toString()))}},xe=class extends ye{constructor(e,t){const n=new be(t),r=new we(n);super(new ve(r,t),e,t)}},Se=class extends ge{initRuntimeAdapter(e){for(const t of this.plugins)t.initRuntimeAdapter?.(e)}},ke=class{fetch;toFetchRequestOptions;adapterInterceptors;constructor(e){new Se(e.plugins).initRuntimeAdapter(e),this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=e,this.adapterInterceptors=w(e.adapterInterceptors)}async call(e,t,n,r){const o=function(e,t={}){const n=function(e,t=new Headers){for(const[n,r]of Object.entries(e))if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.append(n,r);return t}(e.headers),r=function(e,t,n={}){if(e instanceof ReadableStream)return e;const r=t.get("content-disposition");return t.delete("content-type"),t.delete("content-disposition"),void 0!==e?e instanceof Blob?(t.set("content-type",e.type),t.set("content-length",e.size.toString()),t.set("content-disposition",r??function(e,t="inline"){return`${t}; filename="${e.replace(/[^\x20-\x7E]/g,"_").replace(/"/g,'\\"')}"; filename*=utf-8''${encodeURIComponent(e).replace(/['()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)))}`}(e instanceof File?e.name:"blob")),e):e instanceof FormData||e instanceof URLSearchParams?e:R(e)?(t.set("content-type","text/event-stream"),function(e,t={}){const n=t.eventIteratorKeepAliveEnabled??!0,r=t.eventIteratorKeepAliveInterval??5e3,o=t.eventIteratorKeepAliveComment??"",i=t.eventIteratorInitialCommentEnabled??!0,s=t.eventIteratorInitialComment??"";let a,c,l=!1;return new ReadableStream({start(e){c=E("stream_event_iterator"),i&&e.enqueue(le({comments:[s]}))},async pull(t){try{n&&(a=setInterval(()=>{t.enqueue(le({comments:[o]})),c?.addEvent("keepalive")},r));const i=await T(c,()=>e.next());if(clearInterval(a),l)return;const s=pe(i.value);if(!i.done||void 0!==i.value||void 0!==s){const e=i.done?"done":"message";t.enqueue(le({...s,event:e,data:N(i.value)})),c?.addEvent(e)}i.done&&(t.close(),c?.end())}catch(i){if(clearInterval(a),l)return;i instanceof G?(t.enqueue(le({...pe(i),event:"error",data:N(i.data)})),c?.addEvent("error"),t.close()):(I(c,i),t.error(i)),c?.end()}},async cancel(){try{l=!0,clearInterval(a),c?.addEvent("cancelled"),await T(c,()=>e.return?.())}catch(t){throw I(c,t),t}finally{c?.end()}}}).pipeThrough(new TextEncoderStream)}(e,n)):(t.set("content-type","application/json"),N(e)):void 0}(e.body,n,t);return new Request(e.url,{signal:e.signal,method:e.method,headers:n,body:r})}(e,this.toFetchRequestOptions);return function(e,t={}){return{body:k(()=>function(e,t={}){return M({name:"parse_standard_body",signal:t.signal},async()=>{const n=e.headers.get("content-disposition");if("string"==typeof n){const t=function(e){const t=e.match(/filename\*=(UTF-8'')?([^;]*)/i);if(t&&"string"==typeof t[2])return function(e){try{return decodeURIComponent(e)}catch{return e}}(t[2]);const n=e.match(/filename="((?:\\"|[^"])*)"/i);return n&&"string"==typeof n[1]?n[1].replace(/\\"/g,'"'):void 0}(n)??"blob",r=await e.blob();return new File([r],t,{type:r.type})}const r=e.headers.get("content-type");if(!r||r.startsWith("application/json"))return P(await e.text());if(r.startsWith("multipart/form-data"))return await e.formData();if(r.startsWith("application/x-www-form-urlencoded")){const t=await e.text();return new URLSearchParams(t)}if(r.startsWith("text/event-stream"))return function(e,t={}){const n=(e?.pipeThrough(new TextDecoderStream).pipeThrough(new ne))?.getReader();let r,o=!1;return new A(async()=>{r??=E("consume_event_iterator_stream");try{for(;;){if(void 0===n)return{done:!0,value:void 0};const{done:e,value:t}=await T(r,()=>n.read());if(e){if(o)throw new S("Stream was cancelled");return{done:!0,value:void 0}}switch(t.event){case"message":{let e=P(t.data);return F(e)&&(e=ue(e,t)),r?.addEvent("message"),{done:!1,value:e}}case"error":{let e=new G({data:P(t.data)});throw e=ue(e,t),r?.addEvent("error"),e}case"done":{let e=P(t.data);return F(e)&&(e=ue(e,t)),r?.addEvent("done"),{done:!0,value:e}}default:r?.addEvent("maybe_keepalive")}}}catch(e){throw e instanceof G||I(r,e,t),e}},async e=>{try{"next"!==e&&(o=!0,r?.addEvent("cancelled")),await T(r,()=>n?.cancel())}catch(i){throw I(r,i,t),i}finally{r?.end()}})}(e.body,t);if(r.startsWith("text/plain"))return await e.text();const o=await e.blob();return new File([o],"blob",{type:o.type})})}(e,t)),status:e.status,get headers(){const t=me(e.headers);return Object.defineProperty(this,"headers",{value:t,writable:!0}),t},set headers(e){Object.defineProperty(this,"headers",{value:e,writable:!0})}}}(await D(this.adapterInterceptors,{...t,request:o,path:n,input:r,init:{redirect:"manual"}},({request:e,path:t,input:n,init:r,...o})=>this.fetch(e,r,o,t,n)),{signal:o.signal})}},Ce=class extends xe{constructor(e){super(new ke(e),e)}};function Ee(e){return fe(new Ce({url:e}))}var Ie="",Me=Ee(""),Te=new Proxy({},{get:(e,t)=>Me[t]}),Re="marketrix_chat_context";function Oe(e){return e.mtxId??(null!=e.mtxApp?String(e.mtxApp):"default")}var Ae={chat_id:null,messages:[],currentMode:"tell",isOpen:!1,config:null,timestamp:0};function _e(e){try{return"undefined"==typeof localStorage?null:localStorage.getItem(e)}catch(t){return console.warn("[StorageService] localStorage is unreadable:",t),null}}function De(e,t){try{"undefined"!=typeof localStorage&&localStorage.setItem(e,t)}catch(n){console.warn("[StorageService] localStorage is unwritable:",n)}}function Pe(e){const t=_e(e);if(!t)return{...Ae};try{const e={...Ae,...JSON.parse(t)};if(Date.now()-e.timestamp<=6048e5)return e}catch(n){console.warn("[StorageService] Failed to parse the stored context:",n)}return{...Ae}}var Ne,Le=new class{key=Re;context=Pe(this.key);getContext(){return this.context}updateContext(e){this.context={...this.context,...e,timestamp:Date.now()},De(this.key,JSON.stringify(this.context))}getChatId(){return this.context.chat_id}setChatId(e){this.updateContext({chat_id:e})}getCredentialedConfig(){const{config:e}=this.context;return e?.mtxId&&e.mtxKey?e:null}setConfig(e){this.key=`${Re}_${Oe(e)}`,this.context=Pe(this.key),this.updateContext({config:e})}},Fe=new class{creation=null;async getOrCreateChatId(){return Le.getChatId()||(this.creation??=this.createChatId().finally(()=>{this.creation=null}),this.creation)}async createChatId(){const e=await Te.chatCreate(void 0);if(!e)throw new Error("API returned empty chat ID");return Le.setChatId(e),e}},ze=Object.defineProperty,$e=(e,t,n)=>((e,t,n)=>t in e?ze(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n),Be=/* @__PURE__ */(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e[e.Asset=7]="Asset",e))(Be||{}),We=/* @__PURE__ */(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(We||{}),Ue=/* @__PURE__ */(e=>(e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e))(Ue||{}),He=/* @__PURE__ */(e=>(e[e.Mouse=0]="Mouse",e[e.Pen=1]="Pen",e[e.Touch=2]="Touch",e))(He||{}),je=/* @__PURE__ */(e=>(e[e["2D"]=0]="2D",e[e.WebGL=1]="WebGL",e[e.WebGL2=2]="WebGL2",e))(je||{}),qe=/* @__PURE__ */(e=>(e[e.Play=0]="Play",e[e.Pause=1]="Pause",e[e.Seeked=2]="Seeked",e[e.VolumeChange=3]="VolumeChange",e[e.RateChange=4]="RateChange",e))(qe||{}),Ve=/* @__PURE__ */(e=>(e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e))(Ve||{}),Ye={Node:["childNodes","parentNode","parentElement","textContent","ownerDocument"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Ke={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Xe={},Ge={};function Je(e){if(Xe[e])return Xe[e];const t=globalThis[e],n=t.prototype,r=e in Ye?Ye[e]:void 0,o=Boolean(r&&r.every(e=>{var t,r;return Boolean(null==(r=null==(t=Object.getOwnPropertyDescriptor(n,e))?void 0:t.get)?void 0:r.toString().includes("[native code]"))})),i=e in Ke?Ke[e]:void 0,s=Boolean(i&&i.every(e=>{var t;return"function"==typeof n[e]&&(null==(t=n[e])?void 0:t.toString().includes("[native code]"))}));if(o&&s&&!globalThis.Zone)return Xe[e]=t.prototype,t.prototype;try{const r=document.createElement("iframe");r.style.display="none",document.body.appendChild(r);const o=r.contentWindow;if(!o)return t.prototype;const i=o[e].prototype;if(!i)return r.remove(),n;const s=navigator.userAgent;return s.includes("Safari")&&!s.includes("Chrome")?(r.classList.add("rr-block"),r.setAttribute("__rrwebUntaintedMutationObserver",""),Ge[e]=()=>r.remove()):r.remove(),Xe[e]=i}catch{return n}}var Ze={};function Qe(e,t,n){var r;const o=`${e}.${String(n)}`;if(Ze[o])return Ze[o].call(t);const i=Je(e),s=null==(r=Object.getOwnPropertyDescriptor(i,n))?void 0:r.get;return s?(Ze[o]=s,s.call(t)):t[n]}var et={};function tt(e,t,n){const r=`${e}.${String(n)}`;if(et[r])return et[r].bind(t);const o=Je(e)[n];return"function"!=typeof o?t[n]:(et[r]=o,o.bind(t))}var nt=Date.now;function rt(e,t,n){try{if(!(t in e))return()=>{};const r=e[t],o=n(r);return"function"==typeof o&&(o.prototype=o.prototype||{},Object.defineProperties(o,{__rrweb_original__:{enumerable:!1,value:r}})),e[t]=o,()=>{e[t]=r}}catch{return()=>{}}}/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())||(nt=()=>/* @__PURE__ */(new Date).getTime());var ot=function(e){return Qe("Node",e,"ownerDocument")},it=function(e){return Qe("Node",e,"childNodes")},st=function(e){return Qe("Node",e,"parentNode")},at=function(e){return Qe("Node",e,"parentElement")},ct=function(e){return Qe("Node",e,"textContent")},lt=function(e,t){return tt("Node",e,"contains")(t)},dt=function(e){return tt("Node",e,"getRootNode")()},ut=function(e){return e&&"host"in e?Qe("ShadowRoot",e,"host"):null},pt=function(e){return e&&"shadowRoot"in e?Qe("Element",e,"shadowRoot"):null};function ht(e){return e.nodeType===e.ELEMENT_NODE}function ft(e){const t=e&&"host"in e&&"mode"in e&&ut(e)||null;return Boolean(t&&"shadowRoot"in t&&pt(t)===e)}function mt(e){return"[object ShadowRoot]"===Object.prototype.toString.call(e)}function gt(e){try{const n=e.rules||e.cssRules;if(!n)return null;let r=e.href;return!r&&e.ownerNode&&(r=e.ownerNode.baseURI),(t=Array.from(n,e=>yt(e,r)).join("")).includes(" background-clip: text;")&&!t.includes(" -webkit-background-clip: text;")&&(t=t.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),t}catch(n){return null}var t}function yt(e,t){if(function(e){return"styleSheet"in e}(e)){let t;try{t=gt(e.styleSheet)||function(e){const{cssText:t}=e;if(t.split('"').length<3)return t;const n=["@import",`url(${JSON.stringify(e.href)})`];return""===e.layerName?n.push("layer"):e.layerName&&n.push(`layer(${e.layerName})`),e.supportsText&&n.push(`supports(${e.supportsText})`),e.media.length&&n.push(e.media.mediaText),n.join(" ")+";"}(e)}catch(n){t=e.cssText}return e.styleSheet.href?Tt(t,e.styleSheet.href):t}{let n=e.cssText;return function(e){return"selectorText"in e}(e)&&e.selectorText.includes(":")&&(n=n.replace(/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm,"$1\\$2")),t?Tt(n,t):n}}var bt=class{constructor(){$e(this,"idNodeMap",/* @__PURE__ */new Map),$e(this,"nodeMetaMap",/* @__PURE__ */new WeakMap)}getId(e){var t;return e?(null==(t=this.getMeta(e))?void 0:t.id)??-1:-1}getNode(e){return this.idNodeMap.get(e)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(e){return this.nodeMetaMap.get(e)||null}removeNodeFromMap(e){const t=this.getId(e);this.idNodeMap.delete(t),e.childNodes&&e.childNodes.forEach(e=>this.removeNodeFromMap(e))}has(e){return this.idNodeMap.has(e)}hasNode(e){return this.nodeMetaMap.has(e)}add(e,t){const n=t.id;this.idNodeMap.set(n,e),this.nodeMetaMap.set(e,t)}replace(e,t){const n=this.getNode(e);if(n){const e=this.nodeMetaMap.get(n);e&&this.nodeMetaMap.set(t,e)}this.idNodeMap.set(e,t)}reset(){this.idNodeMap=/* @__PURE__ */new Map,this.nodeMetaMap=/* @__PURE__ */new WeakMap}};function vt({element:e,maskInputOptions:t,tagName:n,type:r,value:o,maskInputFn:i}){let s=o||"";const a=r&&wt(r);return(t[n.toLowerCase()]||a&&t[a])&&(s=i?i(s,e):"*".repeat(s.length)),s}function wt(e){return e.toLowerCase()}var xt="__rrweb_original__";function St(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?wt(t):null}function kt(e,t){let n;try{n=new URL(e,t??window.location.href)}catch(o){return null}const r=n.pathname.match(/\.([0-9a-z]+)(?:$)/i);return(null==r?void 0:r[1])??null}var Ct=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,Et=/^(?:[a-z+]+:)?\/\//i,It=/^www\..*/i,Mt=/^(data:)([^,]*),(.*)/i;function Tt(e,t){return(e||"").replace(Ct,(e,n,r,o,i,s)=>{const a=r||i||s,c=n||o||"";if(!a)return e;if(Et.test(a)||It.test(a))return`url(${c}${a}${c})`;if(Mt.test(a))return`url(${c}${a}${c})`;if("/"===a[0])return`url(${c}${function(e){let t="";return t=e.indexOf("//")>-1?e.split("/").slice(0,3).join("/"):e.split("/")[0],t=t.split("?")[0],t}(t)+a}${c})`;const l=a.split("#")[0],d=a.substring(l.length),u=t.split("#")[0].split("/"),p=l.split("/");u.pop();for(const t of p)"."!==t&&(".."===t?u.pop():u.push(t));return`url(${c}${u.join("/")}${d}${c})`})}function Rt(e,t=!1){return t?e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,""):e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"").replace(/0px/g,"0")}var Ot,At,_t=1,Dt=/* @__PURE__ */new RegExp("[^a-z0-9-_:]");function Pt(){return _t++}var Nt=/^[^ \t\n\r\u000c]+/,Lt=/^[, \t\n\r\u000c]+/,Ft=/* @__PURE__ */new WeakMap;function zt(e,t){return t&&""!==t.trim()?$t(e,t):t}function $t(e,t){let n=Ft.get(e);if(n||(n=e.createElement("a"),Ft.set(e,n)),t){if(t.startsWith("blob:")||t.startsWith("data:"))return t}else t="";return n.setAttribute("href",t),n.href}function Bt(e,t,n,r){return r?"src"===n||"href"===n&&("use"!==t||"#"!==r[0])||"xlink:href"===n&&"#"!==r[0]||"background"===n&&["table","td","th"].includes(t)?zt(e,r):"srcset"===n?function(e,t){if(""===t.trim())return t;let n=0;function r(e){let r;const o=e.exec(t.substring(n));return o?(r=o[0],n+=r.length,r):""}const o=[];for(;r(Lt),!(n>=t.length);){let i=r(Nt);if(","===i.slice(-1))i=zt(e,i.substring(0,i.length-1)),o.push(i);else{let r="";i=zt(e,i);let s=!1;for(;;){const e=t.charAt(n);if(""===e){o.push((i+r).trim());break}if(s)")"===e&&(s=!1);else{if(","===e){n+=1,o.push((i+r).trim());break}"("===e&&(s=!0)}r+=e,n+=1}}}return o.join(", ")}(e,r):"style"===n?Tt(r,$t(e)):"object"===t&&"data"===n?zt(e,r):r:r}function Wt(e,t,n){return["video","audio"].includes(e)&&"autoplay"===t}function Ut(e,t,n){if(!e)return!1;if(e.nodeType!==e.ELEMENT_NODE)return!!n&&Ut(st(e),t,n);for(let r=e.classList.length;r--;){const n=e.classList[r];if(t.test(n))return!0}return!!n&&Ut(st(e),t,n)}function Ht(e,t,n,r){let o;if(ht(e)){if(o=e,!it(o).length)return!1}else{if(null===at(e))return!1;o=at(e)}try{if("string"==typeof t){if(r){if(o.closest(`.${t}`))return!0}else if(o.classList.contains(t))return!0}else if(Ut(o,t,r))return!0;if(n)if(r){if(o.closest(n))return!0}else if(o.matches(n))return!0}catch(i){}return!1}function jt(e){return null==e?"":e.toLowerCase()}function qt(e){return!0===e||"all"===e?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===e,headMetaDescKeywords:"all"===e,headTitleMutations:"all"===e}:e||{}}function Vt(e,t){const{doc:n,mirror:r,blockClass:o,blockSelector:i,maskTextClass:s,maskTextSelector:a,skipChild:c=!1,inlineStylesheet:l=!0,maskInputOptions:d={},maskTextFn:u,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f={},inlineImages:m=!1,recordCanvas:g=!1,onSerialize:y,onIframeLoad:b,iframeLoadTimeout:v=5e3,onStylesheetLoad:w,stylesheetLoadTimeout:x=5e3,keepIframeSrcFn:S=()=>!1,newlyAddedElement:k=!1,cssCaptured:C=!1}=t;let{needsMask:E}=t,{preserveWhiteSpace:I=!0}=t;E||(E=Ht(e,s,a,void 0===E));const M=function(e,t){const{doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:s,inlineStylesheet:a,maskInputOptions:c={},maskTextFn:l,maskInputFn:d,dataURLOptions:u={},inlineImages:p,recordCanvas:h,keepIframeSrcFn:f,newlyAddedElement:m=!1,cssCaptured:g=!1}=t,y=function(e,t){if(!t.hasNode(e))return;const n=t.getId(e);return 1===n?void 0:n}(n,r);switch(e.nodeType){case e.DOCUMENT_NODE:return"CSS1Compat"!==e.compatMode?{type:Ve.Document,childNodes:[],compatMode:e.compatMode}:{type:Ve.Document,childNodes:[]};case e.DOCUMENT_TYPE_NODE:return{type:Ve.DocumentType,name:e.name,publicId:e.publicId,systemId:e.systemId,rootId:y};case e.ELEMENT_NODE:return function(e,t){const{doc:n,blockClass:r,blockSelector:o,inlineStylesheet:i,maskInputOptions:s={},maskInputFn:a,dataURLOptions:c={},inlineImages:l,recordCanvas:d,keepIframeSrcFn:u,newlyAddedElement:p=!1,rootId:h}=t,f=function(e,t,n){try{if("string"==typeof t){if(e.classList.contains(t))return!0}else for(let n=e.classList.length;n--;){const r=e.classList[n];if(t.test(r))return!0}if(n)return e.matches(n)}catch(r){}return!1}(e,r,o),m=function(e){if(e instanceof HTMLFormElement)return"form";const t=wt(e.tagName);return Dt.test(t)?"div":t}(e);let g={};const y=e.attributes.length;for(let x=0;x<y;x++){const t=e.attributes[x];Wt(m,t.name,t.value)||(g[t.name]=Bt(n,m,wt(t.name),t.value))}if("link"===m&&i){const t=Array.from(n.styleSheets).find(t=>t.href===e.href);let r=null;t&&(r=gt(t)),r&&(delete g.rel,delete g.href,g._cssText=r)}if("style"===m&&e.sheet){let t=gt(e.sheet);t&&(e.childNodes.length>1&&(t=function(e,t){return function(e,t,n=!1){const r=Array.from(t.childNodes),o=[];let i=0;if(r.length>1&&e&&"string"==typeof e){let t=Rt(e,n);const s=t.length/e.length;for(let a=1;a<r.length;a++)if(r[a].textContent&&"string"==typeof r[a].textContent){const c=Rt(r[a].textContent,n),l=100;let d=3;for(;d<c.length&&(c[d].match(/[a-zA-Z0-9]/)||-1!==c.indexOf(c.substring(0,d),1));d++);for(;d<c.length;d++){let u=c.substring(0,d),p=t.split(u),h=-1;if(2===p.length)h=p[0].length;else if(p.length>2&&""===p[0]&&""!==r[a-1].textContent)h=t.indexOf(u,1);else if(1===p.length){if(u=u.substring(0,u.length-1),p=t.split(u),p.length<=1)return o.push(e),o;d=101}else d===c.length-1&&(h=t.indexOf(u));if(p.length>=2&&d>l){const e=r[a-1].textContent;if(e&&"string"==typeof e){const n=Rt(e).length;h=t.indexOf(u,n)}-1===h&&(h=p[0].length)}if(-1!==h){let a=Math.floor(h/s);for(;a>0&&a<e.length;){if(i+=1,i>50*r.length)return o.push(e),o;const c=Rt(e.substring(0,a),n);if(c.length===h){o.push(e.substring(0,a)),e=e.substring(a),t=t.substring(h);break}c.length<h?a+=Math.max(1,Math.floor((h-c.length)/s)):a-=Math.max(1,Math.floor((c.length-h)*s))}break}}}}return o.push(e),o}(e,t).join("/* rr_split */")}(t,e)),g._cssText=t)}if(["input","textarea","select"].includes(m)){const t=e.value,n=e.checked;"radio"!==g.type&&"checkbox"!==g.type&&"submit"!==g.type&&"button"!==g.type&&t?g.value=vt({element:e,type:St(e),tagName:m,value:t,maskInputOptions:s,maskInputFn:a}):n&&(g.checked=n)}if("option"===m&&(e.selected&&!s.select?g.selected=!0:delete g.selected),"dialog"===m&&e.open&&(g.rr_open_mode=e.matches("dialog:modal")?"modal":"non-modal"),"canvas"===m&&d)if("2d"===e.__context)(function(e){const t=e.getContext("2d");if(!t)return!0;for(let n=0;n<e.width;n+=50)for(let r=0;r<e.height;r+=50){const o=t.getImageData,i=xt in o?o[xt]:o;if(new Uint32Array(i.call(t,n,r,Math.min(50,e.width-n),Math.min(50,e.height-r)).data.buffer).some(e=>0!==e))return!1}return!0})(e)||(g.rr_dataURL=e.toDataURL(c.type,c.quality));else if(!("__context"in e)){const t=e.toDataURL(c.type,c.quality),r=n.createElement("canvas");r.width=e.width,r.height=e.height,t!==r.toDataURL(c.type,c.quality)&&(g.rr_dataURL=t)}if("img"===m&&l){Ot||(Ot=n.createElement("canvas"),At=Ot.getContext("2d"));const t=e,r=t.currentSrc||t.getAttribute("src")||"<unknown-src>",o=t.crossOrigin,i=()=>{t.removeEventListener("load",i);try{Ot.width=t.naturalWidth,Ot.height=t.naturalHeight,At.drawImage(t,0,0),g.rr_dataURL=Ot.toDataURL(c.type,c.quality)}catch(e){if("anonymous"!==t.crossOrigin)return t.crossOrigin="anonymous",void(t.complete&&0!==t.naturalWidth?i():t.addEventListener("load",i));console.warn(`Cannot inline img src=${r}! Error: ${e}`)}"anonymous"===t.crossOrigin&&(o?g.crossOrigin=o:t.removeAttribute("crossorigin"))};t.complete&&0!==t.naturalWidth?i():t.addEventListener("load",i)}if(["audio","video"].includes(m)){const t=g;t.rr_mediaState=e.paused?"paused":"played",t.rr_mediaCurrentTime=e.currentTime,t.rr_mediaPlaybackRate=e.playbackRate,t.rr_mediaMuted=e.muted,t.rr_mediaLoop=e.loop,t.rr_mediaVolume=e.volume}if(p||(e.scrollLeft&&(g.rr_scrollLeft=e.scrollLeft),e.scrollTop&&(g.rr_scrollTop=e.scrollTop)),f){const{width:t,height:n}=e.getBoundingClientRect();g={class:g.class,rr_width:`${t}px`,rr_height:`${n}px`}}let b;"iframe"!==m||u(g.src)||(e.contentDocument||(g.rr_src=g.src),delete g.src);try{customElements.get(m)&&(b=!0)}catch(w){}return{type:Ve.Element,tagName:m,attributes:g,childNodes:[],isSVG:(v=e,Boolean("svg"===v.tagName||v.ownerSVGElement)||void 0),needBlock:f,rootId:h,isCustom:b};var v}(e,{doc:n,blockClass:o,blockSelector:i,inlineStylesheet:a,maskInputOptions:c,maskInputFn:d,dataURLOptions:u,inlineImages:p,recordCanvas:h,keepIframeSrcFn:f,newlyAddedElement:m,rootId:y});case e.TEXT_NODE:return function(e,t){const{needsMask:n,maskTextFn:r,rootId:o,cssCaptured:i}=t,s=st(e),a=s&&s.tagName;let c="";const l="STYLE"===a||void 0,d="SCRIPT"===a||void 0;return d?c="SCRIPT_PLACEHOLDER":i||(c=ct(e),l&&c&&(c=Tt(c,$t(t.doc)))),!l&&!d&&c&&n&&(c=r?r(c,at(e)):c.replace(/[\S]/g,"*")),{type:Ve.Text,textContent:c||"",rootId:o}}(e,{doc:n,needsMask:s,maskTextFn:l,rootId:y,cssCaptured:g});case e.CDATA_SECTION_NODE:return{type:Ve.CDATA,textContent:"",rootId:y};case e.COMMENT_NODE:return{type:Ve.Comment,textContent:ct(e)||"",rootId:y};default:return!1}}(e,{doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:E,inlineStylesheet:l,maskInputOptions:d,maskTextFn:u,maskInputFn:p,dataURLOptions:f,inlineImages:m,recordCanvas:g,keepIframeSrcFn:S,newlyAddedElement:k,cssCaptured:C});if(!M)return console.warn(e,"not serialized"),null;let T;T=r.hasNode(e)?r.getId(e):function(e,t){if(t.comment&&e.type===Ve.Comment)return!0;if(e.type===Ve.Element){if(t.script&&("script"===e.tagName||"link"===e.tagName&&("preload"===e.attributes.rel&&"script"===e.attributes.as||"modulepreload"===e.attributes.rel)||"link"===e.tagName&&"prefetch"===e.attributes.rel&&"string"==typeof e.attributes.href&&"js"===kt(e.attributes.href)))return!0;if(t.headFavicon&&("link"===e.tagName&&"shortcut icon"===e.attributes.rel||"meta"===e.tagName&&(jt(e.attributes.name).match(/^msapplication-tile(image|color)$/)||"application-name"===jt(e.attributes.name)||"icon"===jt(e.attributes.rel)||"apple-touch-icon"===jt(e.attributes.rel)||"shortcut icon"===jt(e.attributes.rel))))return!0;if("meta"===e.tagName){if(t.headMetaDescKeywords&&jt(e.attributes.name).match(/^description|keywords$/))return!0;if(t.headMetaSocial&&(jt(e.attributes.property).match(/^(og|twitter|fb):/)||jt(e.attributes.name).match(/^(og|twitter):/)||"pinterest"===jt(e.attributes.name)))return!0;if(t.headMetaRobots&&("robots"===jt(e.attributes.name)||"googlebot"===jt(e.attributes.name)||"bingbot"===jt(e.attributes.name)))return!0;if(t.headMetaHttpEquiv&&void 0!==e.attributes["http-equiv"])return!0;if(t.headMetaAuthorship&&("author"===jt(e.attributes.name)||"generator"===jt(e.attributes.name)||"framework"===jt(e.attributes.name)||"publisher"===jt(e.attributes.name)||"progid"===jt(e.attributes.name)||jt(e.attributes.property).match(/^article:/)||jt(e.attributes.property).match(/^product:/)))return!0;if(t.headMetaVerification&&("google-site-verification"===jt(e.attributes.name)||"yandex-verification"===jt(e.attributes.name)||"csrf-token"===jt(e.attributes.name)||"p:domain_verify"===jt(e.attributes.name)||"verify-v1"===jt(e.attributes.name)||"verification"===jt(e.attributes.name)||"shopify-checkout-api-token"===jt(e.attributes.name)))return!0}}return!1}(M,h)||!I&&M.type===Ve.Text&&!M.textContent.replace(/^\s+|\s+$/gm,"").length?-2:Pt();const R=Object.assign(M,{id:T});if(r.add(e,R),-2===T)return null;y&&y(e);let O=!c;if(R.type===Ve.Element){O=O&&!R.needBlock,delete R.needBlock;const t=pt(e);t&&mt(t)&&(R.isShadowHost=!0)}if((R.type===Ve.Document||R.type===Ve.Element)&&O){h.headWhitespace&&R.type===Ve.Element&&"head"===R.tagName&&(I=!1);const t={doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:E,maskTextClass:s,maskTextSelector:a,skipChild:c,inlineStylesheet:l,maskInputOptions:d,maskTextFn:u,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:I,onSerialize:y,onIframeLoad:b,iframeLoadTimeout:v,onStylesheetLoad:w,stylesheetLoadTimeout:x,keepIframeSrcFn:S,cssCaptured:!1};if(R.type===Ve.Element&&"textarea"===R.tagName&&void 0!==R.attributes.value);else{R.type===Ve.Element&&void 0!==R.attributes._cssText&&"string"==typeof R.attributes._cssText&&(t.cssCaptured=!0);for(const n of Array.from(it(e))){const e=Vt(n,t);e&&R.childNodes.push(e)}}let k=null;if(ht(e)&&(k=pt(e)))for(const e of Array.from(it(k))){const n=Vt(e,t);n&&(mt(k)&&(n.isShadow=!0),R.childNodes.push(n))}}const A=st(e);return A&&ft(A)&&mt(A)&&(R.isShadow=!0),R.type===Ve.Element&&"iframe"===R.tagName&&function(e,t,n){const r=e.contentWindow;if(!r)return;let o,i=!1;try{o=r.document.readyState}catch(a){return}if("complete"!==o){const r=setTimeout(()=>{i||(t(),i=!0)},n);return void e.addEventListener("load",()=>{clearTimeout(r),i=!0,t()})}const s="about:blank";if(r.location.href!==s||e.src===s||""===e.src)return setTimeout(t,0),e.addEventListener("load",t);e.addEventListener("load",t)}(e,()=>{const t=e.contentDocument;if(t&&b){const n=Vt(t,{doc:t,mirror:r,blockClass:o,blockSelector:i,needsMask:E,maskTextClass:s,maskTextSelector:a,skipChild:!1,inlineStylesheet:l,maskInputOptions:d,maskTextFn:u,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:I,onSerialize:y,onIframeLoad:b,iframeLoadTimeout:v,onStylesheetLoad:w,stylesheetLoadTimeout:x,keepIframeSrcFn:S});n&&b(e,n)}},v),R.type===Ve.Element&&"link"===R.tagName&&"string"==typeof R.attributes.rel&&("stylesheet"===R.attributes.rel||"preload"===R.attributes.rel&&"string"==typeof R.attributes.href&&"css"===kt(R.attributes.href))&&function(e,t,n){let r,o=!1;try{r=e.sheet}catch(s){return}if(r)return;const i=setTimeout(()=>{o||(t(),o=!0)},n);e.addEventListener("load",()=>{clearTimeout(i),o=!0,t()})}(e,()=>{if(w){const t=Vt(e,{doc:n,mirror:r,blockClass:o,blockSelector:i,needsMask:E,maskTextClass:s,maskTextSelector:a,skipChild:!1,inlineStylesheet:l,maskInputOptions:d,maskTextFn:u,maskInputFn:p,slimDOMOptions:h,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:I,onSerialize:y,onIframeLoad:b,iframeLoadTimeout:v,onStylesheetLoad:w,stylesheetLoadTimeout:x,keepIframeSrcFn:S});t&&w(e,t)}},x),R}var Yt=class e{constructor(...e){$e(this,"parentElement",null),$e(this,"parentNode",null),$e(this,"ownerDocument"),$e(this,"firstChild",null),$e(this,"lastChild",null),$e(this,"previousSibling",null),$e(this,"nextSibling",null),$e(this,"ELEMENT_NODE",1),$e(this,"TEXT_NODE",3),$e(this,"nodeType"),$e(this,"nodeName"),$e(this,"RRNodeType")}get childNodes(){const e=[];let t=this.firstChild;for(;t;)e.push(t),t=t.nextSibling;return e}contains(t){if(!(t instanceof e))return!1;if(t.ownerDocument!==this.ownerDocument)return!1;if(t===this)return!0;for(;t.parentNode;){if(t.parentNode===this)return!0;t=t.parentNode}return!1}appendChild(e){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(e,t){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(e){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}};function Kt(e,t,n=document){const r={capture:!0,passive:!0};return n.addEventListener(e,t,r),()=>n.removeEventListener(e,t,r)}var Xt="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.",Gt={map:{},getId:()=>(console.error(Xt),-1),getNode:()=>(console.error(Xt),null),removeNodeFromMap(){console.error(Xt)},has:()=>(console.error(Xt),!1),reset(){console.error(Xt)}};function Jt(e,t,n={}){let r=null,o=0;return function(...i){const s=Date.now();o||!1!==n.leading||(o=s);const a=t-(s-o),c=this;a<=0||a>t?(r&&(clearTimeout(r),r=null),o=s,e.apply(c,i)):r||!1===n.trailing||(r=setTimeout(()=>{o=!1===n.leading?0:Date.now(),r=null,e.apply(c,i)},a))}}function Zt(e,t,n,r,o=window){const i=o.Object.getOwnPropertyDescriptor(e,t);return o.Object.defineProperty(e,t,r?n:{set(e){setTimeout(()=>{n.set.call(this,e)},0),i&&i.set&&i.set.call(this,e)}}),()=>Zt(e,t,i||{},!0)}function Qt(e){var t,n,r,o;const i=e.document;return{left:i.scrollingElement?i.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:i.documentElement.scrollLeft||(null==i?void 0:i.body)&&(null==(t=at(i.body))?void 0:t.scrollLeft)||(null==(n=null==i?void 0:i.body)?void 0:n.scrollLeft)||0,top:i.scrollingElement?i.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==i?void 0:i.documentElement.scrollTop)||(null==i?void 0:i.body)&&(null==(r=at(i.body))?void 0:r.scrollTop)||(null==(o=null==i?void 0:i.body)?void 0:o.scrollTop)||0}}function en(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function tn(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function nn(e){return e?e.nodeType===e.ELEMENT_NODE?e:at(e):null}function rn(e,t,n,r){if(!e)return!1;const o=nn(e);if(!o)return!1;try{if("string"==typeof t){if(o.classList.contains(t))return!0;if(r&&null!==o.closest("."+t))return!0}else if(Ut(o,t,r))return!0}catch(i){}if(n){if(o.matches(n))return!0;if(r&&null!==o.closest(n))return!0}return!1}function on(e,t,n){return!("TITLE"!==e.tagName||!n.headTitleMutations)||-2===t.getId(e)}function sn(e,t){if(ft(e))return!1;const n=t.getId(e);if(!t.has(n))return!0;const r=st(e);return(!r||r.nodeType!==e.DOCUMENT_NODE)&&(!r||sn(r,t))}function an(e){return Boolean(e.changedTouches)}function cn(e,t){return Boolean("IFRAME"===e.nodeName&&t.getMeta(e))}function ln(e,t){return Boolean("LINK"===e.nodeName&&e.nodeType===e.ELEMENT_NODE&&e.getAttribute&&"stylesheet"===e.getAttribute("rel")&&t.getMeta(e))}function dn(e){return!!e&&(e instanceof Yt&&"shadowRoot"in e?Boolean(e.shadowRoot):Boolean(pt(e)))}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(Gt=new Proxy(Gt,{get:(e,t,n)=>("map"===t&&console.error(Xt),Reflect.get(e,t,n))}));var un=class{constructor(){$e(this,"id",1),$e(this,"styleIDMap",/* @__PURE__ */new WeakMap),$e(this,"idStyleMap",/* @__PURE__ */new Map)}getId(e){return this.styleIDMap.get(e)??-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let n;return n=void 0===t?this.id++:t,this.styleIDMap.set(e,n),this.idStyleMap.set(n,e),n}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=/* @__PURE__ */new WeakMap,this.idStyleMap=/* @__PURE__ */new Map,this.id=1}generateId(){return this.id++}};function pn(e){var t;let n=null;return"getRootNode"in e&&(null==(t=dt(e))?void 0:t.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&ut(dt(e))&&(n=ut(dt(e))),n}function hn(e){const t=ot(e);return!!t&&(lt(t,e)||function(e){const t=ot(e);if(!t)return!1;const n=function(e){let t,n=e;for(;t=pn(n);)n=t;return n}(e);return lt(t,n)}(e))}function fn(e){return"__ln"in e}var mn,gn=class{constructor(){$e(this,"length",0),$e(this,"head",null),$e(this,"tail",null)}get(e){if(e>=this.length)throw new Error("Position outside of list range");let t=this.head;for(let n=0;n<e;n++)t=(null==t?void 0:t.next)||null;return t}addNode(e){const t={value:e,previous:null,next:null};if(e.__ln=t,e.previousSibling&&fn(e.previousSibling)){const n=e.previousSibling.__ln.next;t.next=n,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,n&&(n.previous=t)}else if(e.nextSibling&&fn(e.nextSibling)&&e.nextSibling.__ln.previous){const n=e.nextSibling.__ln.previous;t.previous=n,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,n&&(n.next=t)}else this.head&&(this.head.previous=t),t.next=this.head,this.head=t;null===t.next&&(this.tail=t),this.length++}removeNode(e){const t=e.__ln;this.head&&(t.previous?(t.previous.next=t.next,t.next?t.next.previous=t.previous:this.tail=t.previous):(this.head=t.next,this.head?this.head.previous=null:this.tail=null),e.__ln&&delete e.__ln,this.length--)}},yn=(e,t)=>`${e}@${t}`,bn=class{constructor(){$e(this,"frozen",!1),$e(this,"locked",!1),$e(this,"texts",[]),$e(this,"attributes",[]),$e(this,"attributeMap",/* @__PURE__ */new WeakMap),$e(this,"removes",[]),$e(this,"mapRemoves",[]),$e(this,"movedMap",{}),$e(this,"addedSet",/* @__PURE__ */new Set),$e(this,"movedSet",/* @__PURE__ */new Set),$e(this,"droppedSet",/* @__PURE__ */new Set),$e(this,"removesSubTreeCache",/* @__PURE__ */new Set),$e(this,"mutationCb"),$e(this,"blockClass"),$e(this,"blockSelector"),$e(this,"maskTextClass"),$e(this,"maskTextSelector"),$e(this,"inlineStylesheet"),$e(this,"maskInputOptions"),$e(this,"maskTextFn"),$e(this,"maskInputFn"),$e(this,"keepIframeSrcFn"),$e(this,"recordCanvas"),$e(this,"inlineImages"),$e(this,"slimDOMOptions"),$e(this,"dataURLOptions"),$e(this,"doc"),$e(this,"mirror"),$e(this,"iframeManager"),$e(this,"stylesheetManager"),$e(this,"shadowDomManager"),$e(this,"canvasManager"),$e(this,"processedNodeManager"),$e(this,"unattachedDoc"),$e(this,"processMutations",e=>{e.forEach(this.processMutation),this.emit()}),$e(this,"emit",()=>{if(this.frozen||this.locked)return;const e=[],t=/* @__PURE__ */new Set,n=new gn,r=e=>{let t=e,n=-2;for(;-2===n;)t=t&&t.nextSibling,n=t&&this.mirror.getId(t);return n},o=o=>{const i=st(o);if(!i||!hn(o))return;let s=!1;if(o.nodeType===Node.TEXT_NODE){const e=i.tagName;if("TEXTAREA"===e)return;"STYLE"===e&&this.addedSet.has(i)&&(s=!0)}const a=ft(i)?this.mirror.getId(pn(o)):this.mirror.getId(i),c=r(o);if(-1===a||-1===c)return n.addNode(o);const l=Vt(o,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:e=>{cn(e,this.mirror)&&this.iframeManager.addIframe(e),ln(e,this.mirror)&&this.stylesheetManager.trackLinkElement(e),dn(o)&&this.shadowDomManager.addShadowRoot(pt(o),this.doc)},onIframeLoad:(e,t)=>{this.iframeManager.attachIframe(e,t),this.shadowDomManager.observeAttachShadow(e)},onStylesheetLoad:(e,t)=>{this.stylesheetManager.attachLinkElement(e,t)},cssCaptured:s});l&&(e.push({parentId:a,nextId:c,node:l}),t.add(l.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const a of this.movedSet)wn(this.removesSubTreeCache,a,this.mirror)&&!this.movedSet.has(st(a))||o(a);for(const a of this.addedSet)xn(this.droppedSet,a)||wn(this.removesSubTreeCache,a,this.mirror)?xn(this.movedSet,a)?o(a):this.droppedSet.add(a):o(a);let i=null;for(;n.length;){let e=null;if(i){const t=this.mirror.getId(st(i.value)),n=r(i.value);-1!==t&&-1!==n&&(e=i)}if(!e){let t=n.tail;for(;t;){const n=t;if(t=t.previous,n){const t=this.mirror.getId(st(n.value));if(-1===r(n.value))continue;if(-1!==t){e=n;break}{const t=n.value,r=st(t);if(r&&r.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const t=ut(r);if(-1!==this.mirror.getId(t)){e=n;break}}}}}}if(!e){for(;n.head;)n.removeNode(n.head.value);break}i=e.previous,n.removeNode(e.value),o(e.value)}const s={texts:this.texts.map(e=>{const t=e.node,n=st(t);return n&&"TEXTAREA"===n.tagName&&this.genTextAreaValueMutation(n),{id:this.mirror.getId(t),value:e.value}}).filter(e=>!t.has(e.id)).filter(e=>this.mirror.has(e.id)),attributes:this.attributes.map(e=>{const{attributes:t}=e;if("string"==typeof t.style){const n=JSON.stringify(e.styleDiff),r=JSON.stringify(e._unchangedStyles);n.length<t.style.length&&(n+r).split("var(").length===t.style.split("var(").length&&(t.style=e.styleDiff)}return{id:this.mirror.getId(e.node),attributes:t}}).filter(e=>!t.has(e.id)).filter(e=>this.mirror.has(e.id)),removes:this.removes,adds:e};(s.texts.length||s.attributes.length||s.removes.length||s.adds.length)&&(this.texts=[],this.attributes=[],this.attributeMap=/* @__PURE__ */new WeakMap,this.removes=[],this.addedSet=/* @__PURE__ */new Set,this.movedSet=/* @__PURE__ */new Set,this.droppedSet=/* @__PURE__ */new Set,this.removesSubTreeCache=/* @__PURE__ */new Set,this.movedMap={},this.mutationCb(s))}),$e(this,"genTextAreaValueMutation",e=>{let t=this.attributeMap.get(e);t||(t={node:e,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(t),this.attributeMap.set(e,t));const n=Array.from(it(e),e=>ct(e)||"").join("");t.attributes.value=vt({element:e,maskInputOptions:this.maskInputOptions,tagName:e.tagName,type:St(e),value:n,maskInputFn:this.maskInputFn})}),$e(this,"processMutation",e=>{if(!on(e.target,this.mirror,this.slimDOMOptions))switch(e.type){case"characterData":{const t=ct(e.target);rn(e.target,this.blockClass,this.blockSelector,!1)||t===e.oldValue||this.texts.push({value:Ht(e.target,this.maskTextClass,this.maskTextSelector,!0)&&t?this.maskTextFn?this.maskTextFn(t,nn(e.target)):t.replace(/[\S]/g,"*"):t,node:e.target});break}case"attributes":{const n=e.target;let r=e.attributeName,o=e.target.getAttribute(r);if("value"===r){const e=St(n);o=vt({element:n,maskInputOptions:this.maskInputOptions,tagName:n.tagName,type:e,value:o,maskInputFn:this.maskInputFn})}if(rn(e.target,this.blockClass,this.blockSelector,!1)||o===e.oldValue)return;let i=this.attributeMap.get(e.target);if("IFRAME"===n.tagName&&"src"===r&&!this.keepIframeSrcFn(o)){if(n.contentDocument)return;r="rr_src"}if(i||(i={node:e.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(i),this.attributeMap.set(e.target,i)),"type"===r&&"INPUT"===n.tagName&&"password"===(e.oldValue||"").toLowerCase()&&n.setAttribute("data-rr-is-password","true"),!Wt(n.tagName,r))if(i.attributes[r]=Bt(this.doc,wt(n.tagName),wt(r),o),"style"===r){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(t){this.unattachedDoc=this.doc}const r=this.unattachedDoc.createElement("span");e.oldValue&&r.setAttribute("style",e.oldValue);for(const e of Array.from(n.style)){const t=n.style.getPropertyValue(e),o=n.style.getPropertyPriority(e);t!==r.style.getPropertyValue(e)||o!==r.style.getPropertyPriority(e)?i.styleDiff[e]=""===o?t:[t,o]:i._unchangedStyles[e]=[t,o]}for(const e of Array.from(r.style))""===n.style.getPropertyValue(e)&&(i.styleDiff[e]=!1)}else"open"===r&&"DIALOG"===n.tagName&&(n.matches("dialog:modal")?i.attributes.rr_open_mode="modal":i.attributes.rr_open_mode="non-modal");break}case"childList":if(rn(e.target,this.blockClass,this.blockSelector,!0))return;if("TEXTAREA"===e.target.tagName)return void this.genTextAreaValueMutation(e.target);e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{const n=this.mirror.getId(t),r=ft(e.target)?this.mirror.getId(ut(e.target)):this.mirror.getId(e.target);rn(e.target,this.blockClass,this.blockSelector,!1)||on(t,this.mirror,this.slimDOMOptions)||!function(e,t){return-1!==t.getId(e)}(t,this.mirror)||(this.addedSet.has(t)?(vn(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&-1===n||sn(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[yn(n,r)]?vn(this.movedSet,t):(this.removes.push({parentId:r,id:n,isShadow:!(!ft(e.target)||!mt(e.target))||void 0}),function(e,t){const n=[e];for(;n.length;){const e=n.pop();t.has(e)||(t.add(e),it(e).forEach(e=>n.push(e)))}}(t,this.removesSubTreeCache))),this.mapRemoves.push(t))})}}),$e(this,"genAdds",(e,t)=>{if(!this.processedNodeManager.inOtherBuffer(e,this)&&!this.addedSet.has(e)&&!this.movedSet.has(e)){if(this.mirror.hasNode(e)){if(on(e,this.mirror,this.slimDOMOptions))return;this.movedSet.add(e);let n=null;t&&this.mirror.hasNode(t)&&(n=this.mirror.getId(t)),n&&-1!==n&&(this.movedMap[yn(this.mirror.getId(e),n)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);rn(e,this.blockClass,this.blockSelector,!1)||(it(e).forEach(e=>this.genAdds(e)),dn(e)&&it(pt(e)).forEach(t=>{this.processedNodeManager.add(t,this),this.genAdds(t,e)}))}})}init(e){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}};function vn(e,t){e.delete(t),it(t).forEach(t=>vn(e,t))}function wn(e,t,n){return 0!==e.size&&function(e,t){const n=st(t);return!!n&&e.has(n)}(e,t)}function xn(e,t){return 0!==e.size&&Sn(e,t)}function Sn(e,t){const n=st(t);return!!n&&(!!e.has(n)||Sn(e,n))}var kn=e=>mn?(...t)=>{try{return e(...t)}catch(n){if(mn&&!0===mn(n))return;throw n}}:e,Cn=[];function En(e){try{if("composedPath"in e){const t=e.composedPath();if(t.length)return t[0]}else if("path"in e&&e.path.length)return e.path[0]}catch{}return e&&e.target}function In(e,t){const n=new bn;Cn.push(n),n.init(e);const[r,o]=[Je("MutationObserver").constructor,Ge.MutationObserver??(()=>{})],i=new r(kn(n.processMutations.bind(n)));return i.observe(t,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),[i,o]}function Mn({scrollCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,sampling:i}){return Kt("scroll",kn(Jt(kn(i=>{const s=En(i);if(!s||rn(s,r,o,!0))return;const a=n.getId(s);if(s===t&&t.defaultView){const n=Qt(t.defaultView);e({id:a,x:n.left,y:n.top})}else e({id:a,x:s.scrollLeft,y:s.scrollTop})}),i.scroll||100)),t)}var Tn=["INPUT","TEXTAREA","SELECT"],Rn=/* @__PURE__ */new WeakMap;function On(e){return function e(t,n){if(Pn("CSSGroupingRule")&&t.parentRule instanceof CSSGroupingRule||Pn("CSSMediaRule")&&t.parentRule instanceof CSSMediaRule||Pn("CSSSupportsRule")&&t.parentRule instanceof CSSSupportsRule||Pn("CSSConditionRule")&&t.parentRule instanceof CSSConditionRule){const r=Array.from(t.parentRule.cssRules).indexOf(t);return n.unshift(r),e(t.parentRule,n)}if(t.parentStyleSheet){const e=Array.from(t.parentStyleSheet.cssRules).indexOf(t);n.unshift(e)}return n}(e,[])}function An(e,t,n){let r,o;return e?(e.ownerNode?r=t.getId(e.ownerNode):o=n.getId(e),{styleId:o,id:r}):{}}function _n({mirror:e,stylesheetManager:t},n){var r,o,i;let s=null;s="#document"===n.nodeName?e.getId(n):e.getId(ut(n));const a="#document"===n.nodeName?null==(r=n.defaultView)?void 0:r.Document:null==(i=null==(o=n.ownerDocument)?void 0:o.defaultView)?void 0:i.ShadowRoot,c=(null==a?void 0:a.prototype)?Object.getOwnPropertyDescriptor(null==a?void 0:a.prototype,"adoptedStyleSheets"):void 0;return null!==s&&-1!==s&&a&&c?(Object.defineProperty(n,"adoptedStyleSheets",{configurable:c.configurable,enumerable:c.enumerable,get(){var e;return null==(e=c.get)?void 0:e.call(this)},set(e){var n;const r=null==(n=c.set)?void 0:n.call(this,e);if(null!==s&&-1!==s)try{t.adoptStyleSheets(e,s)}catch(o){}return r}}),kn(()=>{Object.defineProperty(n,"adoptedStyleSheets",{configurable:c.configurable,enumerable:c.enumerable,get:c.get,set:c.set})})):()=>{}}function Dn(e,t={}){const n=e.doc.defaultView;if(!n)return()=>{};let r;!function(e,t){const{mutationCb:n,mousemoveCb:r,mouseInteractionCb:o,scrollCb:i,viewportResizeCb:s,inputCb:a,mediaInteractionCb:c,styleSheetRuleCb:l,styleDeclarationCb:d,canvasMutationCb:u,fontCb:p,selectionCb:h,customElementCb:f}=e;e.mutationCb=(...e)=>{t.mutation&&t.mutation(...e),n(...e)},e.mousemoveCb=(...e)=>{t.mousemove&&t.mousemove(...e),r(...e)},e.mouseInteractionCb=(...e)=>{t.mouseInteraction&&t.mouseInteraction(...e),o(...e)},e.scrollCb=(...e)=>{t.scroll&&t.scroll(...e),i(...e)},e.viewportResizeCb=(...e)=>{t.viewportResize&&t.viewportResize(...e),s(...e)},e.inputCb=(...e)=>{t.input&&t.input(...e),a(...e)},e.mediaInteractionCb=(...e)=>{t.mediaInteaction&&t.mediaInteaction(...e),c(...e)},e.styleSheetRuleCb=(...e)=>{t.styleSheetRule&&t.styleSheetRule(...e),l(...e)},e.styleDeclarationCb=(...e)=>{t.styleDeclaration&&t.styleDeclaration(...e),d(...e)},e.canvasMutationCb=(...e)=>{t.canvasMutation&&t.canvasMutation(...e),u(...e)},e.fontCb=(...e)=>{t.font&&t.font(...e),p(...e)},e.selectionCb=(...e)=>{t.selection&&t.selection(...e),h(...e)},e.customElementCb=(...e)=>{t.customElement&&t.customElement(...e),f(...e)}}(e,t);let o=()=>{};e.recordDOM&&([r,o]=In(e,e.doc));const i=function({mousemoveCb:e,sampling:t,doc:n,mirror:r}){if(!1===t.mousemove)return()=>{};const o="number"==typeof t.mousemove?t.mousemove:50,i="number"==typeof t.mousemoveCallback?t.mousemoveCallback:500;let s,a=[];const c=Jt(kn(t=>{const n=Date.now()-s;e(a.map(e=>(e.timeOffset-=n,e)),t),a=[],s=null}),i),l=kn(Jt(kn(e=>{const t=En(e),{clientX:n,clientY:o}=an(e)?e.changedTouches[0]:e;s||(s=nt()),a.push({x:n,y:o,id:r.getId(t),timeOffset:nt()-s}),c("undefined"!=typeof DragEvent&&e instanceof DragEvent?We.Drag:e instanceof MouseEvent?We.MouseMove:We.TouchMove)}),o,{trailing:!1})),d=[Kt("mousemove",l,n),Kt("touchmove",l,n),Kt("drag",l,n)];return kn(()=>{d.forEach(e=>e())})}(e),s=function({mouseInteractionCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,sampling:i}){if(!1===i.mouseInteraction)return()=>{};const s=!0===i.mouseInteraction||void 0===i.mouseInteraction?{}:i.mouseInteraction,a=[];let c=null;return Object.keys(Ue).filter(e=>Number.isNaN(Number(e))&&!e.endsWith("_Departed")&&!1!==s[e]).forEach(i=>{let s=wt(i);const l=(t=>i=>{const s=En(i);if(rn(s,r,o,!0))return;let a=null,l=t;if("pointerType"in i){switch(i.pointerType){case"mouse":a=He.Mouse;break;case"touch":a=He.Touch;break;case"pen":a=He.Pen}a===He.Touch?Ue[t]===Ue.MouseDown?l="TouchStart":Ue[t]===Ue.MouseUp&&(l="TouchEnd"):He.Pen}else an(i)&&(a=He.Touch);null!==a?(c=a,(l.startsWith("Touch")&&a===He.Touch||l.startsWith("Mouse")&&a===He.Mouse)&&(a=null)):Ue[t]===Ue.Click&&(a=c,c=null);const d=an(i)?i.changedTouches[0]:i;if(!d)return;const u=n.getId(s),{clientX:p,clientY:h}=d;kn(e)({type:Ue[l],id:u,x:p,y:h,...null!==a&&{pointerType:a}})})(i);if(window.PointerEvent)switch(Ue[i]){case Ue.MouseDown:case Ue.MouseUp:s=s.replace("mouse","pointer");break;case Ue.TouchStart:case Ue.TouchEnd:return}a.push(Kt(s,l,t))}),kn(()=>{a.forEach(e=>e())})}(e),a=Mn(e),c=function({viewportResizeCb:e},{win:t}){let n=-1,r=-1;return Kt("resize",kn(Jt(kn(()=>{const t=en(),o=tn();n===t&&r===o||(e({width:Number(o),height:Number(t)}),n=t,r=o)}),200)),t)}(e,{win:n}),l=function({inputCb:e,doc:t,mirror:n,blockClass:r,blockSelector:o,ignoreClass:i,ignoreSelector:s,maskInputOptions:a,maskInputFn:c,sampling:l,userTriggeredOnInput:d}){function u(e){let n=En(e);const l=e.isTrusted,u=n&&n.tagName;if(n&&"OPTION"===u&&(n=at(n)),!n||!u||Tn.indexOf(u)<0||rn(n,r,o,!0))return;if(n.classList.contains(i)||s&&n.matches(s))return;let h=n.value,f=!1;const m=St(n)||"";"radio"===m||"checkbox"===m?f=n.checked:(a[u.toLowerCase()]||a[m])&&(h=vt({element:n,maskInputOptions:a,tagName:u,type:m,value:h,maskInputFn:c})),p(n,d?{text:h,isChecked:f,userTriggered:l}:{text:h,isChecked:f});const g=n.name;"radio"===m&&g&&f&&t.querySelectorAll(`input[type="radio"][name="${g}"]`).forEach(e=>{if(e!==n){const t=e.value;p(e,d?{text:t,isChecked:!f,userTriggered:!1}:{text:t,isChecked:!f})}})}function p(t,r){const o=Rn.get(t);if(!o||o.text!==r.text||o.isChecked!==r.isChecked){Rn.set(t,r);const o=n.getId(t);kn(e)({...r,id:o})}}const h=("last"===l.input?["change"]:["input","change"]).map(e=>Kt(e,kn(u),t)),f=t.defaultView;if(!f)return()=>{h.forEach(e=>e())};const m=f.Object.getOwnPropertyDescriptor(f.HTMLInputElement.prototype,"value"),g=[[f.HTMLInputElement.prototype,"value"],[f.HTMLInputElement.prototype,"checked"],[f.HTMLSelectElement.prototype,"value"],[f.HTMLTextAreaElement.prototype,"value"],[f.HTMLSelectElement.prototype,"selectedIndex"],[f.HTMLOptionElement.prototype,"selected"]];return m&&m.set&&h.push(...g.map(e=>Zt(e[0],e[1],{set(){kn(u)({target:this,isTrusted:!1})}},!1,f))),kn(()=>{h.forEach(e=>e())})}(e),d=function({mediaInteractionCb:e,blockClass:t,blockSelector:n,mirror:r,sampling:o,doc:i}){const s=kn(i=>Jt(kn(o=>{const s=En(o);if(!s||rn(s,t,n,!0))return;const{currentTime:a,volume:c,muted:l,playbackRate:d,loop:u}=s;e({type:i,id:r.getId(s),currentTime:a,volume:c,muted:l,playbackRate:d,loop:u})}),o.media||500)),a=[Kt("play",s(qe.Play),i),Kt("pause",s(qe.Pause),i),Kt("seeked",s(qe.Seeked),i),Kt("volumechange",s(qe.VolumeChange),i),Kt("ratechange",s(qe.RateChange),i)];return kn(()=>{a.forEach(e=>e())})}(e);let u=()=>{},p=()=>{},h=()=>{},f=()=>{};e.recordDOM&&(u=function({styleSheetRuleCb:e,mirror:t,stylesheetManager:n},{win:r}){if(!r.CSSStyleSheet||!r.CSSStyleSheet.prototype)return()=>{};const o=r.CSSStyleSheet.prototype.insertRule;r.CSSStyleSheet.prototype.insertRule=new Proxy(o,{apply:kn((r,o,i)=>{const[s,a]=i,{id:c,styleId:l}=An(o,t,n.styleMirror);return(c&&-1!==c||l&&-1!==l)&&e({id:c,styleId:l,adds:[{rule:s,index:a}]}),r.apply(o,i)})}),r.CSSStyleSheet.prototype.addRule=function(e,t,n=this.cssRules.length){const o=`${e} { ${t} }`;return r.CSSStyleSheet.prototype.insertRule.apply(this,[o,n])};const i=r.CSSStyleSheet.prototype.deleteRule;let s,a;r.CSSStyleSheet.prototype.deleteRule=new Proxy(i,{apply:kn((r,o,i)=>{const[s]=i,{id:a,styleId:c}=An(o,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,removes:[{index:s}]}),r.apply(o,i)})}),r.CSSStyleSheet.prototype.removeRule=function(e){return r.CSSStyleSheet.prototype.deleteRule.apply(this,[e])},r.CSSStyleSheet.prototype.replace&&(s=r.CSSStyleSheet.prototype.replace,r.CSSStyleSheet.prototype.replace=new Proxy(s,{apply:kn((r,o,i)=>{const[s]=i,{id:a,styleId:c}=An(o,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,replace:s}),r.apply(o,i)})})),r.CSSStyleSheet.prototype.replaceSync&&(a=r.CSSStyleSheet.prototype.replaceSync,r.CSSStyleSheet.prototype.replaceSync=new Proxy(a,{apply:kn((r,o,i)=>{const[s]=i,{id:a,styleId:c}=An(o,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,replaceSync:s}),r.apply(o,i)})}));const c={};Nn("CSSGroupingRule")?c.CSSGroupingRule=r.CSSGroupingRule:(Nn("CSSMediaRule")&&(c.CSSMediaRule=r.CSSMediaRule),Nn("CSSConditionRule")&&(c.CSSConditionRule=r.CSSConditionRule),Nn("CSSSupportsRule")&&(c.CSSSupportsRule=r.CSSSupportsRule));const l={};return Object.entries(c).forEach(([r,o])=>{l[r]={insertRule:o.prototype.insertRule,deleteRule:o.prototype.deleteRule},o.prototype.insertRule=new Proxy(l[r].insertRule,{apply:kn((r,o,i)=>{const[s,a]=i,{id:c,styleId:l}=An(o.parentStyleSheet,t,n.styleMirror);return(c&&-1!==c||l&&-1!==l)&&e({id:c,styleId:l,adds:[{rule:s,index:[...On(o),a||0]}]}),r.apply(o,i)})}),o.prototype.deleteRule=new Proxy(l[r].deleteRule,{apply:kn((r,o,i)=>{const[s]=i,{id:a,styleId:c}=An(o.parentStyleSheet,t,n.styleMirror);return(a&&-1!==a||c&&-1!==c)&&e({id:a,styleId:c,removes:[{index:[...On(o),s]}]}),r.apply(o,i)})})}),kn(()=>{r.CSSStyleSheet.prototype.insertRule=o,r.CSSStyleSheet.prototype.deleteRule=i,s&&(r.CSSStyleSheet.prototype.replace=s),a&&(r.CSSStyleSheet.prototype.replaceSync=a),Object.entries(c).forEach(([e,t])=>{t.prototype.insertRule=l[e].insertRule,t.prototype.deleteRule=l[e].deleteRule})})}(e,{win:n}),p=_n(e,e.doc),h=function({styleDeclarationCb:e,mirror:t,ignoreCSSAttributes:n,stylesheetManager:r},{win:o}){const i=o.CSSStyleDeclaration.prototype.setProperty;o.CSSStyleDeclaration.prototype.setProperty=new Proxy(i,{apply:kn((o,s,a)=>{var c;const[l,d,u]=a;if(n.has(l))return i.apply(s,[l,d,u]);const{id:p,styleId:h}=An(null==(c=s.parentRule)?void 0:c.parentStyleSheet,t,r.styleMirror);return(p&&-1!==p||h&&-1!==h)&&e({id:p,styleId:h,set:{property:l,value:d,priority:u},index:On(s.parentRule)}),o.apply(s,a)})});const s=o.CSSStyleDeclaration.prototype.removeProperty;return o.CSSStyleDeclaration.prototype.removeProperty=new Proxy(s,{apply:kn((o,i,a)=>{var c;const[l]=a;if(n.has(l))return s.apply(i,[l]);const{id:d,styleId:u}=An(null==(c=i.parentRule)?void 0:c.parentStyleSheet,t,r.styleMirror);return(d&&-1!==d||u&&-1!==u)&&e({id:d,styleId:u,remove:{property:l},index:On(i.parentRule)}),o.apply(i,a)})}),kn(()=>{o.CSSStyleDeclaration.prototype.setProperty=i,o.CSSStyleDeclaration.prototype.removeProperty=s})}(e,{win:n}),e.collectFonts&&(f=function({fontCb:e,doc:t}){const n=t.defaultView;if(!n)return()=>{};const r=[],o=/* @__PURE__ */new WeakMap,i=n.FontFace;n.FontFace=function(e,t,n){const r=new i(e,t,n);return o.set(r,{family:e,buffer:"string"!=typeof t,descriptors:n,fontSource:"string"==typeof t?t:JSON.stringify(Array.from(new Uint8Array(t)))}),r};const s=rt(t.fonts,"add",function(t){return function(n){return setTimeout(kn(()=>{const t=o.get(n);t&&(e(t),o.delete(n))}),0),t.apply(this,[n])}});return r.push(()=>{n.FontFace=i}),r.push(s),kn(()=>{r.forEach(e=>e())})}(e)));const m=function(e){const{doc:t,mirror:n,blockClass:r,blockSelector:o,selectionCb:i}=e;let s=!0;const a=kn(()=>{const e=t.getSelection();if(!e||s&&(null==e?void 0:e.isCollapsed))return;s=e.isCollapsed||!1;const a=[],c=e.rangeCount||0;for(let t=0;t<c;t++){const{startContainer:i,startOffset:s,endContainer:c,endOffset:l}=e.getRangeAt(t);rn(i,r,o,!0)||rn(c,r,o,!0)||a.push({start:n.getId(i),startOffset:s,end:n.getId(c),endOffset:l})}i({ranges:a})});return a(),Kt("selectionchange",a)}(e),g=function({doc:e,customElementCb:t}){const n=e.defaultView;return n&&n.customElements?rt(n.customElements,"define",function(e){return function(n,r,o){try{t({define:{name:n}})}catch(i){console.warn(`Custom element callback failed for ${n}`)}return e.apply(this,[n,r,o])}}):()=>{}}(e),y=[];for(const b of e.plugins)y.push(b.observer(b.callback,n,b.options));return kn(()=>{Cn.forEach(e=>e.reset()),r?.disconnect(),o(),i(),s(),a(),c(),l(),d(),u(),p(),h(),f(),m(),g(),y.forEach(e=>e())})}function Pn(e){return void 0!==window[e]}function Nn(e){return Boolean(void 0!==window[e]&&window[e].prototype&&"insertRule"in window[e].prototype&&"deleteRule"in window[e].prototype)}for(var Ln=class{constructor(e){$e(this,"iframeIdToRemoteIdMap",/* @__PURE__ */new WeakMap),$e(this,"iframeRemoteIdToIdMap",/* @__PURE__ */new WeakMap),this.generateIdFn=e}getId(e,t,n,r){const o=n||this.getIdToRemoteIdMap(e),i=r||this.getRemoteIdToIdMap(e);let s=o.get(t);return s||(s=this.generateIdFn(),o.set(t,s),i.set(s,t)),s}getIds(e,t){const n=this.getIdToRemoteIdMap(e),r=this.getRemoteIdToIdMap(e);return t.map(t=>this.getId(e,t,n,r))}getRemoteId(e,t,n){const r=n||this.getRemoteIdToIdMap(e);return"number"!=typeof t?t:r.get(t)||-1}getRemoteIds(e,t){const n=this.getRemoteIdToIdMap(e);return t.map(t=>this.getRemoteId(e,t,n))}reset(e){if(!e)return this.iframeIdToRemoteIdMap=/* @__PURE__ */new WeakMap,void(this.iframeRemoteIdToIdMap=/* @__PURE__ */new WeakMap);this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=/* @__PURE__ */new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=/* @__PURE__ */new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}},Fn=class{constructor(e){$e(this,"iframes",/* @__PURE__ */new WeakMap),$e(this,"crossOriginIframeMap",/* @__PURE__ */new WeakMap),$e(this,"crossOriginIframeMirror",new Ln(Pt)),$e(this,"crossOriginIframeStyleMirror"),$e(this,"crossOriginIframeRootIdMap",/* @__PURE__ */new WeakMap),$e(this,"mirror"),$e(this,"mutationCb"),$e(this,"wrappedEmit"),$e(this,"loadListener"),$e(this,"stylesheetManager"),$e(this,"recordCrossOriginIframes"),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new Ln(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var n,r;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&(null==(n=e.contentWindow)||n.addEventListener("message",this.handleMessage.bind(this))),null==(r=this.loadListener)||r.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){const t=e;if("rrweb"!==t.data.type||t.origin!==t.data.origin)return;if(!e.source)return;const n=this.crossOriginIframeMap.get(e.source);if(!n)return;const r=this.transformCrossOriginEvent(n,t.data.event);r&&this.wrappedEmit(r,t.data.isCheckout)}transformCrossOriginEvent(e,t){var n;switch(t.type){case Be.FullSnapshot:{this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e);const n=t.data.node.id;return this.crossOriginIframeRootIdMap.set(e,n),this.patchRootIdOnNode(t.data.node,n),{timestamp:t.timestamp,type:Be.IncrementalSnapshot,data:{source:We.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case Be.Meta:case Be.Load:case Be.DomContentLoaded:return!1;case Be.Plugin:return t;case Be.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case Be.IncrementalSnapshot:switch(t.data.source){case We.Mutation:return t.data.adds.forEach(t=>{this.replaceIds(t,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(t.node,e);const n=this.crossOriginIframeRootIdMap.get(e);n&&this.patchRootIdOnNode(t.node,n)}),t.data.removes.forEach(t=>{this.replaceIds(t,e,["parentId","id"])}),t.data.attributes.forEach(t=>{this.replaceIds(t,e,["id"])}),t.data.texts.forEach(t=>{this.replaceIds(t,e,["id"])}),t;case We.Drag:case We.TouchMove:case We.MouseMove:return t.data.positions.forEach(t=>{this.replaceIds(t,e,["id"])}),t;case We.ViewportResize:return!1;case We.MediaInteraction:case We.MouseInteraction:case We.Scroll:case We.CanvasMutation:case We.Input:return this.replaceIds(t.data,e,["id"]),t;case We.StyleSheetRule:case We.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case We.Font:return t;case We.Selection:return t.data.ranges.forEach(t=>{this.replaceIds(t,e,["start","end"])}),t;case We.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),null==(n=t.data.styles)||n.forEach(t=>{this.replaceStyleIds(t,e,["styleId"])}),t}}return!1}replace(e,t,n,r){for(const o of r)(Array.isArray(t[o])||"number"==typeof t[o])&&(Array.isArray(t[o])?t[o]=e.getIds(n,t[o]):t[o]=e.getId(n,t[o]));return t}replaceIds(e,t,n){return this.replace(this.crossOriginIframeMirror,e,t,n)}replaceStyleIds(e,t,n){return this.replace(this.crossOriginIframeStyleMirror,e,t,n)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id","rootId"]),"childNodes"in e&&e.childNodes.forEach(e=>{this.replaceIdOnNode(e,t)})}patchRootIdOnNode(e,t){e.type===Ve.Document||e.rootId||(e.rootId=t),"childNodes"in e&&e.childNodes.forEach(e=>{this.patchRootIdOnNode(e,t)})}},zn=class{constructor(e){$e(this,"shadowDoms",/* @__PURE__ */new WeakSet),$e(this,"mutationCb"),$e(this,"scrollCb"),$e(this,"bypassOptions"),$e(this,"mirror"),$e(this,"restoreHandlers",[]),this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(e,t){if(!mt(e))return;if(this.shadowDoms.has(e))return;this.shadowDoms.add(e);const[n]=In({...this.bypassOptions,doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},e);this.restoreHandlers.push(()=>n.disconnect()),this.restoreHandlers.push(Mn({...this.bypassOptions,scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(ut(e))),this.restoreHandlers.push(_n({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e))},0)}observeAttachShadow(e){e.contentWindow&&e.contentDocument&&this.patchAttachShadow(e.contentWindow.Element,e.contentDocument)}patchAttachShadow(e,t){const n=this;this.restoreHandlers.push(rt(e.prototype,"attachShadow",function(e){return function(r){const o=e.call(this,r),i=pt(this);return i&&hn(this)&&n.addShadowRoot(i,t),o}}))}reset(){this.restoreHandlers.forEach(e=>{try{e()}catch(t){}}),this.restoreHandlers=[],this.shadowDoms=/* @__PURE__ */new WeakSet}},$n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Bn="undefined"==typeof Uint8Array?[]:/* @__PURE__ */new Uint8Array(256),Wn=0;Wn<64;Wn++)Bn[$n.charCodeAt(Wn)]=Wn;var Un=function(e){var t,n=new Uint8Array(e),r=n.length,o="";for(t=0;t<r;t+=3)o+=$n[n[t]>>2],o+=$n[(3&n[t])<<4|n[t+1]>>4],o+=$n[(15&n[t+1])<<2|n[t+2]>>6],o+=$n[63&n[t+2]];return r%3==2?o=o.substring(0,o.length-1)+"=":r%3==1&&(o=o.substring(0,o.length-2)+"=="),o},Hn=/* @__PURE__ */new Map,jn=(e,t,n)=>{if(!e||!Yn(e,t)&&"object"!=typeof e)return;const r=function(e,t){let n=Hn.get(e);return n||(n=/* @__PURE__ */new Map,Hn.set(e,n)),n.has(t)||n.set(t,[]),n.get(t)}(n,e.constructor.name);let o=r.indexOf(e);return-1===o&&(o=r.length,r.push(e)),o};function qn(e,t,n){if(e instanceof Array)return e.map(e=>qn(e,t,n));if(null===e)return e;if(e instanceof Float32Array||e instanceof Float64Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Uint8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Int8Array||e instanceof Uint8ClampedArray)return{rr_type:e.constructor.name,args:[Object.values(e)]};if(e instanceof ArrayBuffer)return{rr_type:e.constructor.name,base64:Un(e)};if(e instanceof DataView)return{rr_type:e.constructor.name,args:[qn(e.buffer,t,n),e.byteOffset,e.byteLength]};if(e instanceof HTMLImageElement){const t=e.constructor.name,{src:n}=e;return{rr_type:t,src:n}}return e instanceof HTMLCanvasElement?{rr_type:"HTMLImageElement",src:e.toDataURL()}:e instanceof ImageData?{rr_type:e.constructor.name,args:[qn(e.data,t,n),e.width,e.height]}:Yn(e,t)||"object"==typeof e?{rr_type:e.constructor.name,index:jn(e,t,n)}:e}var Vn=(e,t,n)=>e.map(e=>qn(e,t,n)),Yn=(e,t)=>{const n=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(e=>"function"==typeof t[e]);return Boolean(n.find(n=>e instanceof t[n]))};function Kn(e,t,n,r){const o=[];try{const i=rt(e.HTMLCanvasElement.prototype,"getContext",function(e){return function(o,...i){if(!rn(this,t,n,!0)){const e=function(e){return"experimental-webgl"===e?"webgl":e}(o);if("__context"in this||(this.__context=e),r&&["webgl","webgl2"].includes(e))if(i[0]&&"object"==typeof i[0]){const e=i[0];e.preserveDrawingBuffer||(e.preserveDrawingBuffer=!0)}else i.splice(0,1,{preserveDrawingBuffer:!0})}return e.apply(this,[o,...i])}});o.push(i)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{o.forEach(e=>e())}}function Xn(e,t,n,r,o,i){const s=[],a=Object.getOwnPropertyNames(e);for(const c of a)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(c))try{if("function"!=typeof e[c])continue;const a=rt(e,c,function(e){return function(...s){const a=e.apply(this,s);if(jn(a,i,this),"tagName"in this.canvas&&!rn(this.canvas,r,o,!0)){const e=Vn(s,i,this),r={type:t,property:c,args:e};n(this.canvas,r)}return a}});s.push(a)}catch{const r=Zt(e,c,{set(e){n(this.canvas,{type:t,property:c,args:[e],setter:!0})}});s.push(r)}return s}var Gn='(function() {\n "use strict";\n var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\n var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);\n for (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n }\n var encode = function(arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = "";\n for (i2 = 0; i2 < len; i2 += 3) {\n base64 += chars[bytes[i2] >> 2];\n base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];\n base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];\n base64 += chars[bytes[i2 + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + "=";\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + "==";\n }\n return base64;\n };\n const lastBlobMap = /* @__PURE__ */ new Map();\n const transparentBlobMap = /* @__PURE__ */ new Map();\n async function getTransparentBlobFor(width, height, dataURLOptions) {\n const id = `${width}-${height}`;\n if ("OffscreenCanvas" in globalThis) {\n if (transparentBlobMap.has(id)) return transparentBlobMap.get(id);\n const offscreen = new OffscreenCanvas(width, height);\n offscreen.getContext("2d");\n const blob = await offscreen.convertToBlob(dataURLOptions);\n const arrayBuffer = await blob.arrayBuffer();\n const base64 = encode(arrayBuffer);\n transparentBlobMap.set(id, base64);\n return base64;\n } else {\n return "";\n }\n }\n const worker = self;\n worker.onmessage = async function(e) {\n if ("OffscreenCanvas" in globalThis) {\n const { id, bitmap, width, height, dataURLOptions } = e.data;\n const transparentBase64 = getTransparentBlobFor(\n width,\n height,\n dataURLOptions\n );\n const offscreen = new OffscreenCanvas(width, height);\n const ctx = offscreen.getContext("2d");\n ctx.drawImage(bitmap, 0, 0);\n bitmap.close();\n const blob = await offscreen.convertToBlob(dataURLOptions);\n const type = blob.type;\n const arrayBuffer = await blob.arrayBuffer();\n const base64 = encode(arrayBuffer);\n if (!lastBlobMap.has(id) && await transparentBase64 === base64) {\n lastBlobMap.set(id, base64);\n return worker.postMessage({ id });\n }\n if (lastBlobMap.get(id) === base64) return worker.postMessage({ id });\n worker.postMessage({\n id,\n type,\n base64,\n width,\n height\n });\n lastBlobMap.set(id, base64);\n } else {\n return worker.postMessage({ id: e.data.id });\n }\n };\n})();\n//# sourceMappingURL=image-bitmap-data-url-worker-IJpC7g_b.js.map\n',Jn="undefined"!=typeof self&&self.Blob&&new Blob([Gn],{type:"text/javascript;charset=utf-8"});function Zn(e){let t;try{if(t=Jn&&(self.URL||self.webkitURL).createObjectURL(Jn),!t)throw"";const n=new Worker(t,{name:null==e?void 0:e.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch(n){return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Gn),{name:null==e?void 0:e.name})}finally{t&&(self.URL||self.webkitURL).revokeObjectURL(t)}}var Qn,er,tr,nr=class{constructor(e){$e(this,"pendingCanvasMutations",/* @__PURE__ */new Map),$e(this,"rafStamps",{latestId:0,invokeId:null}),$e(this,"mirror"),$e(this,"mutationCb"),$e(this,"resetObservers"),$e(this,"frozen",!1),$e(this,"locked",!1),$e(this,"processMutation",(e,t)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(e)||this.pendingCanvasMutations.set(e,[]),this.pendingCanvasMutations.get(e).push(t)});const{sampling:t="all",win:n,blockClass:r,blockSelector:o,recordCanvas:i,dataURLOptions:s}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,i&&"all"===t&&this.initCanvasMutationObserver(n,r,o),i&&"number"==typeof t&&this.initCanvasFPSObserver(t,n,r,o,{dataURLOptions:s})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,n,r,o){const i=Kn(t,n,r,!0),s=/* @__PURE__ */new Map,a=new Zn;a.onmessage=e=>{const{id:t}=e.data;if(s.set(t,!1),!("base64"in e.data))return;const{base64:n,type:r,width:o,height:i}=e.data;this.mutationCb({id:t,type:je["2D"],commands:[{property:"clearRect",args:[0,0,o,i]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:n}],type:r}]},0,0]}]})};const c=1e3/e;let l,d=0;const u=e=>{d&&e-d<c||(d=e,(()=>{const e=[];return t.document.querySelectorAll("canvas").forEach(t=>{rn(t,n,r,!0)||e.push(t)}),e})().forEach(async e=>{var t;const n=this.mirror.getId(e);if(s.get(n))return;if(0===e.width||0===e.height)return;if(s.set(n,!0),["webgl","webgl2"].includes(e.__context)){const n=e.getContext(e.__context);!1===(null==(t=null==n?void 0:n.getContextAttributes())?void 0:t.preserveDrawingBuffer)&&n.clear(n.COLOR_BUFFER_BIT)}const r=await createImageBitmap(e);a.postMessage({id:n,bitmap:r,width:e.width,height:e.height,dataURLOptions:o.dataURLOptions},[r])})),l=requestAnimationFrame(u)};l=requestAnimationFrame(u),this.resetObservers=()=>{i(),cancelAnimationFrame(l)}}initCanvasMutationObserver(e,t,n){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const r=Kn(e,t,n,!1),o=function(e,t,n,r){const o=[],i=Object.getOwnPropertyNames(t.CanvasRenderingContext2D.prototype);for(const s of i)try{if("function"!=typeof t.CanvasRenderingContext2D.prototype[s])continue;const i=rt(t.CanvasRenderingContext2D.prototype,s,function(o){return function(...i){return rn(this.canvas,n,r,!0)||setTimeout(()=>{const n=Vn(i,t,this);e(this.canvas,{type:je["2D"],property:s,args:n})},0),o.apply(this,i)}});o.push(i)}catch{const n=Zt(t.CanvasRenderingContext2D.prototype,s,{set(t){e(this.canvas,{type:je["2D"],property:s,args:[t],setter:!0})}});o.push(n)}return()=>{o.forEach(e=>e())}}(this.processMutation.bind(this),e,t,n),i=function(e,t,n,r){const o=[];return void 0!==t.WebGLRenderingContext&&o.push(...Xn(t.WebGLRenderingContext.prototype,je.WebGL,e,n,r,t)),void 0!==t.WebGL2RenderingContext&&o.push(...Xn(t.WebGL2RenderingContext.prototype,je.WebGL2,e,n,r,t)),()=>{o.forEach(e=>e())}}(this.processMutation.bind(this),e,t,n);this.resetObservers=()=>{r(),o(),i()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{const n=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,n)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;const n=this.pendingCanvasMutations.get(e);if(!n||-1===t)return;const r=n.map(e=>{const{type:t,...n}=e;return n}),{type:o}=n[0];this.mutationCb({id:t,type:o,commands:r}),this.pendingCanvasMutations.delete(e)}},rr=class{constructor(e){$e(this,"trackedLinkElements",/* @__PURE__ */new WeakSet),$e(this,"mutationCb"),$e(this,"adoptedStyleSheetCb"),$e(this,"styleMirror",new un),this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(0===e.length)return;const n={id:t,styleIds:[]},r=[];for(const o of e){let e;this.styleMirror.has(o)?e=this.styleMirror.getId(o):(e=this.styleMirror.add(o),r.push({styleId:e,rules:Array.from(o.rules||CSSRule,(e,t)=>({rule:yt(e,o.href),index:t}))})),n.styleIds.push(e)}r.length>0&&(n.styles=r),this.adoptedStyleSheetCb(n)}reset(){this.styleMirror.reset(),this.trackedLinkElements=/* @__PURE__ */new WeakSet}trackStylesheetInLinkElement(e){}},or=class{constructor(){$e(this,"nodeMap",/* @__PURE__ */new WeakMap),$e(this,"active",!1)}inOtherBuffer(e,t){const n=this.nodeMap.get(e);return n&&Array.from(n).some(e=>e!==t)}add(e,t){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=/* @__PURE__ */new WeakMap,this.active=!1})),this.nodeMap.set(e,(this.nodeMap.get(e)||/* @__PURE__ */new Set).add(t))}destroy(){}},ir=!1;try{if(2!==Array.from([1],e=>2*e)[0]){const e=document.createElement("iframe");document.body.appendChild(e),Array.from=(null==(Ne=e.contentWindow)?void 0:Ne.Array.from)||Array.from,document.body.removeChild(e)}}catch(au){}var sr=new bt;function ar(e={}){const{emit:t,checkoutEveryNms:n,checkoutEveryNth:r,blockClass:o="rr-block",blockSelector:i=null,ignoreClass:s="rr-ignore",ignoreSelector:a=null,maskTextClass:c="rr-mask",maskTextSelector:l=null,inlineStylesheet:d=!0,maskAllInputs:u,maskInputOptions:p,slimDOMOptions:h,maskInputFn:f,maskTextFn:m,hooks:g,packFn:y,sampling:b={},dataURLOptions:v={},mousemoveWait:w,recordDOM:x=!0,recordCanvas:S=!1,recordCrossOriginIframes:k=!1,recordAfter:C=("DOMContentLoaded"===e.recordAfter?e.recordAfter:"load"),userTriggeredOnInput:E=!1,collectFonts:I=!1,inlineImages:M=!1,plugins:T,keepIframeSrcFn:R=()=>!1,ignoreCSSAttributes:O=/* @__PURE__ */new Set([]),errorHandler:A}=e;mn=A;const _=!k||window.parent===window;let D=!1;if(!_)try{window.parent.document&&(D=!1)}catch(V){D=!0}if(_&&!t)throw new Error("emit function is required");if(!_&&!D)return()=>{};void 0!==w&&void 0===b.mousemove&&(b.mousemove=w),sr.reset();const P=!0===u?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:void 0!==p?p:{password:!0},N=qt(h);let L;!function(e=window){"NodeList"in e&&!e.NodeList.prototype.forEach&&(e.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in e&&!e.DOMTokenList.prototype.forEach&&(e.DOMTokenList.prototype.forEach=Array.prototype.forEach)}();let F=0;const z=e=>{for(const t of T||[])t.eventProcessor&&(e=t.eventProcessor(e));return y&&!D&&(e=y(e)),e};Qn=(e,o)=>{var i;const s=e;if(s.timestamp=nt(),!(null==(i=Cn[0])?void 0:i.isFrozen())||s.type===Be.FullSnapshot||s.type===Be.IncrementalSnapshot&&s.data.source===We.Mutation||Cn.forEach(e=>e.unfreeze()),_)t?.(z(s),o);else if(D){const e={type:"rrweb",event:z(s),origin:window.location.origin,isCheckout:o};window.parent.postMessage(e,"*")}if(s.type===Be.FullSnapshot)L=s,F=0;else if(s.type===Be.IncrementalSnapshot){if(s.data.source===We.Mutation&&s.data.isAttachIframe)return;F++;const e=r&&F>=r,t=n&&s.timestamp-L.timestamp>n;(e||t)&&er(!0)}};const $=e=>{Qn({type:Be.IncrementalSnapshot,data:{source:We.Mutation,...e}})},B=e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.Scroll,...e}}),W=e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.CanvasMutation,...e}}),U=new rr({mutationCb:$,adoptedStyleSheetCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.AdoptedStyleSheet,...e}})}),H=new Fn({mirror:sr,mutationCb:$,stylesheetManager:U,recordCrossOriginIframes:k,wrappedEmit:Qn});for(const K of T||[])K.getMirror&&K.getMirror({nodeMirror:sr,crossOriginIframeMirror:H.crossOriginIframeMirror,crossOriginIframeStyleMirror:H.crossOriginIframeStyleMirror});const j=new or;tr=new nr({recordCanvas:S,mutationCb:W,win:window,blockClass:o,blockSelector:i,mirror:sr,sampling:b.canvas,dataURLOptions:v});const q=new zn({mutationCb:$,scrollCb:B,bypassOptions:{blockClass:o,blockSelector:i,maskTextClass:c,maskTextSelector:l,inlineStylesheet:d,maskInputOptions:P,dataURLOptions:v,maskTextFn:m,maskInputFn:f,recordCanvas:S,inlineImages:M,sampling:b,slimDOMOptions:N,iframeManager:H,stylesheetManager:U,canvasManager:tr,keepIframeSrcFn:R,processedNodeManager:j},mirror:sr});er=(e=!1)=>{if(!x)return;Qn({type:Be.Meta,data:{href:window.location.href,width:tn(),height:en()}},e),U.reset(),q.init(),Cn.forEach(e=>e.lock());const t=function(e,t){const{mirror:n=new bt,blockClass:r="rr-block",blockSelector:o=null,maskTextClass:i="rr-mask",maskTextSelector:s=null,inlineStylesheet:a=!0,inlineImages:c=!1,recordCanvas:l=!1,maskAllInputs:d=!1,maskTextFn:u,maskInputFn:p,slimDOM:h=!1,dataURLOptions:f,preserveWhiteSpace:m,onSerialize:g,onIframeLoad:y,iframeLoadTimeout:b,onStylesheetLoad:v,stylesheetLoadTimeout:w,keepIframeSrcFn:x=()=>!1}=t;return Vt(e,{doc:e,mirror:n,blockClass:r,blockSelector:o,maskTextClass:i,maskTextSelector:s,skipChild:!1,inlineStylesheet:a,maskInputOptions:!0===d?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:!1===d?{password:!0}:d,maskTextFn:u,maskInputFn:p,slimDOMOptions:qt(h),dataURLOptions:f,inlineImages:c,recordCanvas:l,preserveWhiteSpace:m,onSerialize:g,onIframeLoad:y,iframeLoadTimeout:b,onStylesheetLoad:v,stylesheetLoadTimeout:w,keepIframeSrcFn:x,newlyAddedElement:!1})}(document,{mirror:sr,blockClass:o,blockSelector:i,maskTextClass:c,maskTextSelector:l,inlineStylesheet:d,maskAllInputs:P,maskTextFn:m,maskInputFn:f,slimDOM:N,dataURLOptions:v,recordCanvas:S,inlineImages:M,onSerialize:e=>{cn(e,sr)&&H.addIframe(e),ln(e,sr)&&U.trackLinkElement(e),dn(e)&&q.addShadowRoot(pt(e),document)},onIframeLoad:(e,t)=>{H.attachIframe(e,t),q.observeAttachShadow(e)},onStylesheetLoad:(e,t)=>{U.attachLinkElement(e,t)},keepIframeSrcFn:R});if(!t)return console.warn("Failed to snapshot the document");Qn({type:Be.FullSnapshot,data:{node:t,initialOffset:Qt(window)}},e),Cn.forEach(e=>e.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&U.adoptStyleSheets(document.adoptedStyleSheets,sr.getId(document))};try{const e=[],t=e=>{var t;return kn(Dn)({mutationCb:$,mousemoveCb:(e,t)=>Qn({type:Be.IncrementalSnapshot,data:{source:t,positions:e}}),mouseInteractionCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.MouseInteraction,...e}}),scrollCb:B,viewportResizeCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.ViewportResize,...e}}),inputCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.Input,...e}}),mediaInteractionCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.MediaInteraction,...e}}),styleSheetRuleCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.StyleSheetRule,...e}}),styleDeclarationCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.StyleDeclaration,...e}}),canvasMutationCb:W,fontCb:e=>Qn({type:Be.IncrementalSnapshot,data:{source:We.Font,...e}}),selectionCb:e=>{Qn({type:Be.IncrementalSnapshot,data:{source:We.Selection,...e}})},customElementCb:e=>{Qn({type:Be.IncrementalSnapshot,data:{source:We.CustomElement,...e}})},blockClass:o,ignoreClass:s,ignoreSelector:a,maskTextClass:c,maskTextSelector:l,maskInputOptions:P,inlineStylesheet:d,sampling:b,recordDOM:x,recordCanvas:S,inlineImages:M,userTriggeredOnInput:E,collectFonts:I,doc:e,maskInputFn:f,maskTextFn:m,keepIframeSrcFn:R,blockSelector:i,slimDOMOptions:N,dataURLOptions:v,mirror:sr,iframeManager:H,stylesheetManager:U,shadowDomManager:q,processedNodeManager:j,canvasManager:tr,ignoreCSSAttributes:O,plugins:(null==(t=null==T?void 0:T.filter(e=>e.observer))?void 0:t.map(e=>({observer:e.observer,options:e.options,callback:t=>Qn({type:Be.Plugin,data:{plugin:e.name,payload:t}})})))||[]},g)};H.addLoadListener(n=>{try{e.push(t(n.contentDocument))}catch(r){console.warn(r)}});const n=()=>{er(),e.push(t(document)),ir=!0};return["interactive","complete"].includes(document.readyState)?n():(e.push(Kt("DOMContentLoaded",()=>{Qn({type:Be.DomContentLoaded,data:{}}),"DOMContentLoaded"===C&&n()})),e.push(Kt("load",()=>{Qn({type:Be.Load,data:{}}),"load"===C&&n()},window))),()=>{e.forEach(e=>{try{e()}catch(t){String(t).toLowerCase().includes("cross-origin")||console.warn(t)}}),j.destroy(),ir=!1,mn=void 0}}catch(Y){console.warn(Y)}}ar.addCustomEvent=(e,t)=>{if(!ir)throw new Error("please add custom event after start recording");Qn({type:Be.Custom,data:{tag:e,payload:t}})},ar.freezePage=()=>{Cn.forEach(e=>e.freeze())},ar.takeFullSnapshot=e=>{if(!ir)throw new Error("please take full snapshot after start recording");er(e)},ar.mirror=sr;var cr=class extends Error{},lr=class e{static instance=null;abortController=null;chatId=null;status="disconnected";callbacks=/* @__PURE__ */new Set;tornDown=!1;credentialRejected=!1;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;maxReconnectDelay=3e4;reconnectTimer=null;connectionId=0;tabId=globalThis.crypto.randomUUID();registrationWaiters=/* @__PURE__ */new Set;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}addCallbacks(e){this.callbacks.add(e)}removeCallbacks(e){this.callbacks.delete(e)}isConnected(){return"registered"===this.status}reconnectSuppressed(){return this.tornDown||this.credentialRejected}canReconnect(){return null!==this.chatId&&!this.reconnectSuppressed()&&!this.isConnected()}reconnectNow(){this.canReconnect()&&null!==this.chatId&&(this.clearReconnectTimer(),this.reconnectAttempts=0,this.reconnectDelay=1e3,this.abortConnection(),this.connect(this.chatId).catch(console.error))}async ready(e){await this.connect(e),await this.waitUntilRegistered()}async waitUntilRegistered(){if(!this.isConnected()){if(this.credentialRejected)throw new cr("Chat is unavailable — the widget credentials were rejected.");await new Promise((e,t)=>this.registrationWaiters.add({resolve:e,reject:t}))}}async connect(e){if(this.credentialRejected)return;if(this.tornDown=!1,this.chatId===e&&("connecting"===this.status||"open"===this.status||"registered"===this.status))return;this.abortConnection(),this.chatId=e,this.status="connecting";const t=++this.connectionId;this.abortController=new AbortController;const n=this.abortController.signal;try{const r=Le.getCredentialedConfig(),o=await Te.widgetStream({chat_id:e,tab_id:this.tabId,...r&&{marketrix_id:r.mtxId,marketrix_key:r.mtxKey}},{signal:n});this.status="open",this.consumeEvents(o,t)}catch(r){n.aborted||(console.error("[StreamClient] Connection failed:",r),this.status="error",this.notifyError(/* @__PURE__ */new Error("Stream connection failed")),this.scheduleReconnect())}}async consumeEvents(e,t){let n=!1;try{for await(const r of e){if(this.connectionId!==t){n=!0;break}this.handleMessage(r)}}catch(r){this.connectionId!==t?n=!0:this.reconnectSuppressed()||(console.warn("[StreamClient] Stream error:",r),this.status="error")}finally{n||this.connectionId!==t||this.reconnectSuppressed()||(this.status="disconnected",this.scheduleReconnect())}}disconnect(){this.tornDown=!0,this.credentialRejected=!1,this.clearReconnectTimer(),this.abortConnection(),this.chatId=null,this.settleWaiters(/* @__PURE__ */new Error("Stream disconnected before registration"))}send(e){return this.chatId?Te.widgetMessagePost({chat_id:this.chatId,tab_id:this.tabId,command:e}).then(()=>{}).catch(e=>{throw this.notifyError(/* @__PURE__ */new Error(`Failed to send message: ${String(e)}`)),e}):Promise.reject(/* @__PURE__ */new Error("No active chat"))}notifyError(e){this.callbacks.forEach(t=>t.onError?.(e))}settleWaiters(e){for(const t of this.registrationWaiters)t.reject(e);this.registrationWaiters.clear()}giveUp(e){const t=new cr(e);this.notifyError(t),this.settleWaiters(t)}handleMessage(e){if(!this.reconnectSuppressed()&&"heartbeat"!==e.type){if("registered"===e.type&&e.chat_id===this.chatId){this.status="registered",this.reconnectAttempts=0,this.reconnectDelay=1e3;for(const e of this.registrationWaiters)e.resolve();this.registrationWaiters.clear()}"chat/error"===e.type&&"auth"===e.request_id&&(console.error("[StreamClient] Authentication failed — will not reconnect"),this.credentialRejected=!0,this.giveUp("Chat is unavailable — the widget credentials were rejected.")),this.callbacks.forEach(t=>t.onMessage?.(e))}}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.giveUp("Could not reconnect to the assistant. Try again.");this.clearReconnectTimer(),this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);this.reconnectTimer=setTimeout(()=>{!this.reconnectSuppressed()&&this.chatId&&this.connect(this.chatId).catch(console.error)},e)}abortConnection(){this.abortController?.abort(),this.abortController=null,this.status="disconnected"}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},dr=class{chatId;applicationId;events=[];sessionId=globalThis.crypto.randomUUID();stopRecording=null;flushTimer=null;flushPromise=Promise.resolve();stopped=!1;constructor(e,t){this.chatId=e,this.applicationId=t}async start(){this.stopRecording||this.stopped||(await lr.getInstance().ready(this.chatId),this.stopped||(await Te.widgetMessagePost({chat_id:this.chatId,command:{type:"rrweb/metadata",rrweb_session_id:this.sessionId,chat_id:this.chatId,application_id:this.applicationId,url:window.location.href,user_agent:navigator.userAgent,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}}}),this.stopped||(this.stopRecording=ar({emit:e=>this.buffer(e),maskAllInputs:!0,maskTextClass:/^(rr-mask|mtx-mask)$/,blockClass:/^(rr-block|mtx-block)$/}))))}stop(){this.stopped=!0,this.stopRecording?.(),this.stopRecording=null,this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null,this.flush()}buffer(e){this.events.push(e),this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flush()},500))}flush(){return this.flushPromise=this.flushPromise.then(async()=>{this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null;const e=this.events.splice(0);if(e.length)try{await Te.widgetMessagePost({chat_id:this.chatId,command:{type:"rrweb/events",rrweb_session_id:this.sessionId,events:e}})}catch(t){this.events=e.concat(this.events).slice(0,2e4),console.error("Failed to record session events:",t)}}),this.flushPromise}},ur=null;function pr(){return ur?.active&&"live"===ur.getVideoTracks()[0]?.readyState?ur:(ur=null,null)}function hr(){ur&&(ur.getTracks().forEach(e=>e.stop()),ur=null)}var fr=e=>"string"==typeof e,mr=e=>"boolean"==typeof e,gr=(...e)=>t=>"string"==typeof t&&e.includes(t),yr={widget_enabled:mr,widget_appearance:gr("default","hidden"),widget_position:gr("bottom_left","bottom_right","top_left","top_right"),widget_header:fr,widget_body:fr,widget_greeting:fr,widget_greeting_toast:mr,widget_recording:mr,widget_feature_tell:mr,widget_feature_show:mr,widget_feature_do:mr,widget_background_color:fr,widget_text_color:fr,widget_border_color:fr,widget_accent_color:fr,widget_secondary_color:fr,widget_border_radius:fr,widget_font_size:fr,widget_width:fr,widget_height:fr,widget_animation_duration:fr,widget_fade_duration:fr,widget_chips:e=>Array.isArray(e)&&e.every(e=>"object"==typeof e&&null!==e&&gr("tell","show","do")(e.chip_mode)&&fr(e.chip_text))},br=Object.keys(yr),vr=/* @__PURE__ */new Set(["widget_border_radius","widget_font_size","widget_animation_duration","widget_fade_duration"]);function wr(e){if("object"!=typeof e||null===e)return{invalidFields:["settings"]};const t=e,n=br.filter(e=>!yr[e](t[e]));if(n.length>0)return{invalidFields:n};const r={};for(const o of br)vr.has(o)||(r[o]=t[o]);return{settings:r}}var xr=e=>`Widget settings are invalid: ${e.join(", ")}`;function Sr(e,t={}){return{...t,...e}}function kr(e){return e instanceof Error?e.message:"string"==typeof e?e:"Unknown error"}function Cr(e,t){const n=new Error(e);return n.cause=t,n}function Er(){}var Ir=Object.freeze([]),Mr=Object.freeze({});function Tr(t){e.useEffect(t,Ir)}var Rr={};function Or(t,n){const r=e.useRef(Rr);return r.current===Rr&&(r.current=t(n)),r}var Ar="undefined"!=typeof document?e.useLayoutEffect:()=>{},_r=function(e,...t){const n=new URL("https://base-ui.com/production-error");return n.searchParams.set("code",e.toString()),t.forEach(e=>n.searchParams.append("args[]",e)),`Base UI error #${e}; visit ${n} for the full message.`},Dr=/*#__PURE__*/e.createContext(void 0);function Pr(){const t=e.useContext(Dr);if(!t)throw new Error(_r(73));return t}var Nr=parseInt(e.version,10);function Lr(e){return Nr>=e}var Fr,zr=Lr(19)?function(t,n,r,o,i){return function(t,n,r,o,i){const s=e.useCallback(()=>n(t.getSnapshot(),r,o,i),[t,n,r,o,i]);return f(t.subscribe,s,s)}(t,n,r,o,i)}:function(e,t,n,r,o){return function(e,t,n,r){const o=u(null),i=e=>{const t=o.current;if(t&&Object.is(t.snapshot,e))return t.selection;const n=r(e);return o.current={snapshot:e,selection:n},n};return h(e,()=>i(t()),n&&(()=>i(n())))}(e.subscribe,e.getSnapshot,e.getSnapshot,e=>t(e,n,r,o))};function $r(e,t,n,r,o){return zr(e,t,n,r,o)}Fr={before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let n=0;n<e.syncHooks.length;n+=1){const r=e.syncHooks[n],o=r.selector(r.store.state,r.a1,r.a2,r.a3);Object.is(r.value,o)||(t=!0,r.value=o)}return t&&(e.syncTick+=1),e.syncTick})},after(e){e.syncHooks.length>0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{const n=/* @__PURE__ */new Set;for(const o of e.syncHooks)n.add(o.store);const r=[];for(const e of n)r.push(e.subscribe(t));return()=>{for(const e of r)e()}}),f(e.subscribe,e.getSnapshot,e.getSnapshot))}},[].push(Fr);var Br=class{constructor(e){this.state=e,this.listeners=/* @__PURE__ */new Set,this.updateTick=0}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.state;setState(e){if(this.state===e)return;this.state=e,this.updateTick+=1;const t=this.updateTick;for(const n of this.listeners){if(t!==this.updateTick)return;n(e)}}update(e){for(const t in e)if(!Object.is(this.state[t],e[t]))return void this.setState({...this.state,...e})}set(e,t){Object.is(this.state[e],t)||this.setState({...this.state,[e]:t})}notifyAll(){const e={...this.state};this.setState(e)}use(e,t,n,r){return $r(this,e,t,n,r)}},Wr={...e},Ur=Wr.useInsertionEffect,Hr=Ur&&Ur!==Wr.useLayoutEffect?Ur:e=>e();function jr(e){const t=Or(qr).current;return t.next=e,Hr(t.effect),t.trampoline}function qr(){const e={next:void 0,callback:Vr,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function Vr(){}var Yr=class extends Br{constructor(e,t={},n){super(e),this.context=t,this.selectors=n}useSyncedValue(t,n){e.useDebugValue(t);const r=this;Ar(()=>{r.state[t]!==n&&r.set(t,n)},[r,t,n])}useSyncedValueWithCleanup(e,t){const n=this;Ar(()=>(n.state[e]!==t&&n.set(e,t),()=>{n.set(e,void 0)}),[n,e,t])}useSyncedValues(e){const t=this,n=Object.values(e);Ar(()=>{t.update(e)},[t,...n])}useControlledProp(t,n){e.useDebugValue(t);const r=this,o=void 0!==n;Ar(()=>{o&&!Object.is(r.state[t],n)&&r.setState({...r.state,[t]:n})},[r,t,n,o])}select(e,t,n,r){return(0,this.selectors[e])(this.state,t,n,r)}useState(t,n,r,o){return e.useDebugValue(t),$r(this,this.selectors[t],n,r,o)}useContextCallback(t,n){e.useDebugValue(t);const r=jr(n??Er);this.context[t]=r}useStateSetter(t){const n=e.useRef(void 0);return void 0===n.current&&(n.current=e=>{this.set(t,e)}),n.current}observe(e,t){let n;n="function"==typeof e?e:this.selectors[e];let r=n(this.state);return t(r,r,this),this.subscribe(e=>{const o=n(e);if(!Object.is(r,o)){const e=r;r=o,t(o,e,this)}})}};function Kr(){return"undefined"!=typeof window}function Xr(e){return Jr(e)?(e.nodeName||"").toLowerCase():"#document"}function Gr(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Jr(e){return!!Kr()&&(e instanceof Node||e instanceof Gr(e).Node)}function Zr(e){return!!Kr()&&(e instanceof Element||e instanceof Gr(e).Element)}function Qr(e){return!!Kr()&&(e instanceof HTMLElement||e instanceof Gr(e).HTMLElement)}function eo(e){return!(!Kr()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Gr(e).ShadowRoot)}function to(e){return/^(html|body|#document)$/.test(Xr(e))}function no(e){return Gr(e).getComputedStyle(e)}function ro(e){if("html"===Xr(e))return e;const t=e.assignedSlot||e.parentNode||eo(e)&&e.host||function(e){var t;return null==(t=(Jr(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}(e);return eo(t)?t.host:t}function oo(...e){return()=>{for(let t=0;t<e.length;t+=1){const n=e[t];n&&n()}}}function io(e){return e?.ownerDocument||document}function so(e,t,n,r){return e.addEventListener(t,n,r),()=>{e.removeEventListener(t,n,r)}}var ao=null;globalThis.requestAnimationFrame;var co=new class{callbacks=[];callbacksCount=0;nextId=1;startId=1;isScheduled=!1;tick=e=>{this.isScheduled=!1;const t=this.callbacks,n=this.callbacksCount;if(this.callbacks=[],this.callbacksCount=0,this.startId=this.nextId,n>0)for(let r=0;r<t.length;r+=1)t[r]?.(e)};request(e){const t=this.nextId;return this.nextId+=1,this.callbacks.push(e),this.callbacksCount+=1,this.isScheduled||(requestAnimationFrame(this.tick),this.isScheduled=!0),t}cancel(e){const t=e-this.startId;t<0||t>=this.callbacks.length||(this.callbacks[t]=null,this.callbacksCount-=1)}},lo=class e{static create(){return new e}static request(e){return co.request(e)}static cancel(e){return co.cancel(e)}currentId=ao;request(e){this.cancel(),this.currentId=co.request(()=>{this.currentId=ao,e()})}cancel=()=>{this.currentId!==ao&&(co.cancel(this.currentId),this.currentId=ao)};disposeEffect=()=>this.cancel};function uo(){const e=Or(lo.create).current;return Tr(e.disposeEffect),e}var po=class e{static create(){return new e}currentId=0;start(e,t){this.clear(),this.currentId=setTimeout(()=>{this.currentId=0,t()},e)}isStarted(){return 0!==this.currentId}clear=()=>{0!==this.currentId&&(clearTimeout(this.currentId),this.currentId=0)};disposeEffect=()=>this.clear};function ho(){const e=Or(po.create).current;return Tr(e.disposeEffect),e}var fo=0;function mo(e,t){if("string"==typeof e)return{description:e};if("function"==typeof e){const n=e(t);return"string"==typeof n?{description:n}:n}return e}var{userAgent:go,platform:yo,maxTouchPoints:bo}="undefined"==typeof navigator?{userAgent:"",platform:"",maxTouchPoints:0}:{userAgent:navigator.userAgent,platform:navigator.platform??"",maxTouchPoints:navigator.maxTouchPoints??0},vo=go.toLowerCase(),wo=yo.toLowerCase(),xo=/^i(os$|p)/.test(wo)||"macintel"===wo&&bo>1,So="android",ko=wo===So||vo.includes(So),Co=!xo&&wo.startsWith("mac"),Eo=(wo.startsWith("win"),!ko&&/^(linux|chrome os)/.test(wo),Co||xo),Io="undefined"!=typeof CSS&&!!CSS.supports?.("-webkit-backdrop-filter:none"),Mo=(!Io&&vo.includes("firefox"),!Io&&vo.includes("chrom"),Eo),To=/jsdom|happydom/.test(vo),Ro="data-base-ui-focusable";function Oo(e){let t=e.activeElement;for(;null!=t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t}function Ao(e,t){if(!e||!t)return!1;const n=t.getRootNode?.();if(e.contains(t))return!0;if(n&&eo(n)){let n=t;for(;n;){if(e===n)return!0;n=n.parentNode||n.host}}return!1}function _o(e){return"composedPath"in e?e.composedPath()[0]:e.target}function Do(e,t){if(null==t)return!1;if("composedPath"in e)return e.composedPath().includes(t);const n=e;return null!=n.target&&t.contains(n.target)}function Po(e){return Qr(e)&&e.matches("input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])")}function No(e){return!!e&&"combobox"===e.getAttribute("role")&&Po(e)}function Lo(e){if(!e||To)return!0;try{return e.matches(":focus-visible")}catch(t){return!0}}function Fo(e){return e?e.hasAttribute("data-base-ui-focusable")?e:e.querySelector("[data-base-ui-focusable]")||e:null}function zo(e,t,n=!0){return e.filter(e=>e.parentId===t).flatMap(t=>[...!n||t.context?.open?[t]:[],...zo(e,t.id,n)])}function $o(e,t){let n=[],r=e.find(e=>e.id===t)?.parentId;for(;r;){const t=e.find(e=>e.id===r);r=t?.parentId,t&&(n=n.concat(t))}return n}function Bo(e,t){return t<0||t>=e.length}function Wo(e,{startingIndex:t=-1,decrement:n=!1,disabledIndices:r,amount:o=1}={}){let i=t;do{i+=n?-o:o}while(i>=0&&i<=e.length-1&&Uo(e,i,r));return i}function Uo(e,t,n){if("function"==typeof n?n(t):n?.includes(t))return!0;const r=e[t];return!!r&&(!Ho(r)||!!r.matches(":disabled")||!n&&(r.hasAttribute("disabled")||"true"===r.getAttribute("aria-disabled")))}function Ho(e,t=(e?no(e):null)){return!(!(e&&e.isConnected&&t)||function(e){return"hidden"===e.visibility||"collapse"===e.visibility}(t))&&("function"==typeof e.checkVisibility?e.checkVisibility():"none"!==t.display&&"contents"!==t.display)}function jo(e){const t=e.assignedSlot;if(t)return t;if(e.parentElement)return e.parentElement;const n=e.getRootNode();return eo(n)?n.host:null}function qo(e){for(const t of Array.from(e.children))if("summary"===Xr(t))return t;return null}function Vo(e,t){const n=qo(t);return!!n&&(e===n||Ao(n,e))}function Yo(e){const t=e?Xr(e):"";return null!=e&&e.matches('a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]')&&("summary"!==t||null!=e.parentElement&&"details"===Xr(e.parentElement)&&qo(e.parentElement)===e)&&("details"!==t||null==qo(e))&&("input"!==t||"hidden"!==e.type)}function Ko(e){if(!Yo(e)||!e.isConnected||e.matches(":disabled"))return!1;for(let t=e;t;t=jo(t)){const n=t!==e,r="slot"===Xr(t);if(t.hasAttribute("inert"))return!1;if(n&&"details"===Xr(t)&&!t.open&&!Vo(e,t)||t.hasAttribute("hidden")||!r&&!Xo(t,n))return!1}return!0}function Xo(e,t){const n=no(e);return t?"none"!==n.display:Ho(e,n)}function Go(e){const t=e.tabIndex;if(t<0){const t=Xr(e);if("details"===t||"audio"===t||"video"===t||Qr(e)&&e.isContentEditable)return 0}return t}function Jo(e){if("input"!==Xr(e))return null;const t=e;return"radio"===t.type&&""!==t.name?t:null}function Zo(e){if(Qr(e)&&"slot"===Xr(e)){const t=e.assignedElements({flatten:!0});if(t.length>0)return t}return Qr(e)&&e.shadowRoot?Array.from(e.shadowRoot.children):Array.from(e.children)}function Qo(e,t){Zo(e).forEach(e=>{Yo(e)&&t.push(e),Qo(e,t)})}function ei(e,t,n){Zo(e).forEach(e=>{Qr(e)&&e.matches(t)&&n.push(e),ei(e,t,n)})}function ti(e){return Ko(e)&&Go(e)>=0}function ni(e){const t=[];return Qo(e,t),t.filter(Ko)}function ri(e){const t=ni(e);return t.filter(e=>Go(e)>=0&&function(e,t){const n=Jo(e);if(!n)return!0;const r=t.find(e=>{const t=Jo(e);return t?.name===n.name&&t.form===n.form&&t.checked});return r?r===n:t.find(e=>{const t=Jo(e);return t?.name===n.name&&t.form===n.form})===n}(e,t))}function oi(e,t){const n=ri(e),r=n.length;if(0===r)return;const o=Oo(io(e)),i=n.indexOf(o);return n[-1===i?1===t?0:r-1:i+t]}function ii(e){return oi(io(e).body,1)||e}function si(e){return oi(io(e).body,-1)||e}function ai(e,t){const n=t||e.currentTarget,r=e.relatedTarget;return!r||!Ao(n,r)}function ci(e){const t=[];ei(e,"[data-tabindex]",t),t.forEach(e=>{const t=e.dataset.tabindex;delete e.dataset.tabindex,t?e.setAttribute("tabindex",t):e.removeAttribute("tabindex")})}function li(e){const t=/* @__PURE__ */new Map;let n=0,r=0;return e.forEach((e,o)=>{const i="ending"===e.transitionStatus;t.set(e.id,{value:e,domIndex:o,visibleIndex:i?-1:n,offsetY:r}),r+=e.height||0,i||(n+=1)}),t}function di(e,t){let n=0;return e.map(e=>{if("ending"===e.transitionStatus)return e;const r=n>=t;return n+=1,e.limited===r?e:{...e,limited:r}})}var ui={toasts:e=>e.toasts,isEmpty:e=>0===e.toasts.length,toast:(e,t)=>e.toastMetadata.get(t)?.value,toastIndex:(e,t)=>e.toastMetadata.get(t)?.domIndex??-1,toastOffsetY:(e,t)=>e.toastMetadata.get(t)?.offsetY??0,toastVisibleIndex:(e,t)=>e.toastMetadata.get(t)?.visibleIndex??-1,focused:e=>e.focused,expanded:e=>e.hovering||e.focused,expandedOrOutOfFocus:e=>e.hovering||e.focused||!e.isWindowFocused,prevFocusElement:e=>e.prevFocusElement},pi=class extends Yr{timers=/* @__PURE__ */new Map;areTimersPaused=!1;constructor(e){super({...e,toastMetadata:li(e.toasts)},{},ui)}setViewport=e=>{this.set("viewport",e)};syncProviderProps(e,t){const n=this.state.limit!==t;if(this.state.timeout===e&&!n)return;const r={timeout:e,limit:t};if(n){const e=di(this.state.toasts,t);r.toasts=e,r.toastMetadata=li(e)}this.update(r)}disposeEffect=()=>()=>{this.timers.forEach(e=>{e.timeout?.clear()}),this.timers.clear()};removeToast(e,t=!1){const n=ui.toastIndex(this.state,e);if(-1===n)return;const r=this.state.toasts[n];t||r?.onRemove?.();const o=[...this.state.toasts];o.splice(n,1),this.setToasts(o)}addToast=e=>{const{timeout:t,limit:n}=this.state,r=e.id||(fo+=1,`toast-${Math.random().toString(36).slice(2,6)}-${fo}`);if(e.id){const t=ui.toast(this.state,e.id);if(t){if("ending"!==t.transitionStatus){const{id:t,transitionStatus:n,...r}=e;return this.updateToastInternal(e.id,r,!0,!0),e.id}this.removeToast(e.id,!0)}}const o={...e,id:r,updateKey:0,transitionStatus:"starting"},i=[o,...this.state.toasts];this.setToasts(di(i,n));const s=o.timeout??t;return"loading"!==o.type&&s>0&&this.scheduleTimer(r,s,()=>this.closeToast(r)),ui.expandedOrOutOfFocus(this.state)&&this.pauseTimers(),r};updateToast=(e,t)=>{this.updateToastInternal(e,t,!1,!0)};updateToastInternal=(e,t,n=!1,r=!1)=>{const{timeout:o,toasts:i}=this.state,s=ui.toast(this.state,e);if(!s)return;if("ending"===s.transitionStatus)return;const a={...s,...t,...r&&{updateKey:s.updateKey+1}};this.setToasts(i.map(t=>t.id===e?a:t));const c=a.timeout??o,l=s.timeout??o,d=Object.hasOwn(t,"timeout"),u="ending"!==a.transitionStatus&&"loading"!==a.type&&c>0,p=this.timers.has(e),h=l!==c,f="loading"===s.type;u||!p?u&&(!p||h||d||f||n)&&(this.clearTimer(e),this.scheduleTimer(e,c,()=>this.closeToast(e)),ui.expandedOrOutOfFocus(this.state)&&this.pauseTimers()):this.clearTimer(e)};closeToast=e=>{const t=void 0===e,{limit:n,toasts:r}=this.state;let o;if(t)o=r,this.clearTimers();else{const t=ui.toast(this.state,e);if(!t)return;o=[t],this.clearTimer(e)}const i=di(r.map(n=>t||n.id===e?{...n,transitionStatus:"ending",height:0}:n),n);this.setToasts(i,!i.some(e=>"ending"!==e.transitionStatus)),o.forEach(e=>{"ending"!==e.transitionStatus&&e.onClose?.()}),this.handleFocusManagement(e)};promiseToast=(e,t)=>{const n=mo(t.loading),r=this.addToast({...n,type:"loading"}),o=e.then(e=>{const n=mo(t.success,e);return this.updateToast(r,{...n,type:"success",timeout:n.timeout}),e}).catch(e=>{const n=mo(t.error,e);return this.updateToast(r,{...n,type:"error",timeout:n.timeout}),Promise.reject(e)});return{}.hasOwnProperty.call(t,"setPromise")&&t.setPromise(o),o};pauseTimers(){this.areTimersPaused||(this.areTimersPaused=!0,this.timers.forEach(e=>{e.timeout&&(e.timeout.clear(),e.remaining=Math.max(e.remaining-(Date.now()-e.start),0))}))}resumeTimers(){this.areTimersPaused&&(this.areTimersPaused=!1,this.timers.forEach((e,t)=>{e.remaining=e.remaining>0?e.remaining:e.delay,e.timeout??=po.create(),e.timeout.start(e.remaining,()=>{this.handleTimerFired(t),e.callback()}),e.start=Date.now()}))}restoreFocusToPrevElement(){this.state.prevFocusElement?.focus({preventScroll:!0})}handleDocumentPointerDown=e=>{if("touch"!==e.pointerType)return;const t=_o(e);Ao(this.state.viewport,t)||(this.resumeTimers(),this.update({hovering:!1,focused:!1}))};scheduleTimer(e,t,n){const r=Date.now(),o=ui.expandedOrOutOfFocus(this.state)?void 0:po.create();o?.start(t,()=>{this.handleTimerFired(e),n()}),this.timers.set(e,{timeout:o,start:r,delay:t,remaining:t,callback:n})}clearTimers(){this.timers.forEach(e=>{e.timeout?.clear()}),this.timers.clear(),this.areTimersPaused=!1}clearTimer(e){this.timers.get(e)?.timeout?.clear(),this.timers.delete(e),this.resetPausedStateIfNoTimersRemain()}handleTimerFired(e){this.timers.delete(e),this.resetPausedStateIfNoTimersRemain()}resetPausedStateIfNoTimersRemain(){0===this.timers.size&&(this.areTimersPaused=!1)}setToasts(e,t=0===e.length){const n={toasts:e,toastMetadata:li(e)};t&&(n.hovering=!1,n.focused=!1),this.update(n)}handleFocusManagement(e){const t=Oo(io(this.state.viewport));if(!this.state.viewport||!Ao(this.state.viewport,t)||!Lo(t))return;if(void 0===e)return void this.restoreFocusToPrevElement();const n=ui.toasts(this.state),r=ui.toastIndex(this.state,e),o=(e,t)=>{for(let r=e;r>=0&&r<n.length;r+=t)if("ending"!==n[r].transitionStatus)return n[r];return null},i=o(r+1,1)??o(r-1,-1);i?i.ref?.current?.focus():this.restoreFocusToPrevElement()}},hi=function(t){const{children:n,timeout:r=5e3,limit:o=3,toastManager:i}=t,s=Or(()=>new pi({timeout:r,limit:o,viewport:null,toasts:[],hovering:!1,focused:!1,isWindowFocused:!0,prevFocusElement:null})).current;return Tr(s.disposeEffect),e.useEffect(function(){if(i)return i[" subscribe"](({action:e,options:t})=>{const n=t.id;"promise"===e&&t.promise?s.promiseToast(t.promise,t):"update"===e&&n?s.updateToast(n,t):"close"===e?s.closeToast(n):s.addToast(t)})},[s,i]),/*#__PURE__*/v(Dr.Provider,{value:s,children:[/*#__PURE__*/b(fi,{store:s,timeout:r,limit:o}),n]})};function fi(e){const{store:t,timeout:n,limit:r}=e;return Ar(()=>{t.syncProviderProps(n,r)},[t,n,r]),null}var mi={clipPath:"inset(50%)",overflow:"hidden",whiteSpace:"nowrap",border:0,padding:0,width:1,height:1,margin:-1,position:"fixed",top:0,left:0},gi=/*#__PURE__*/e.forwardRef(function(t,n){const[r,o]=e.useState();return Ar(()=>{Mo&&Io&&o("button")},[]),/*#__PURE__*/b("span",{...t,ref:n,style:mi,"aria-hidden":!r||void 0,tabIndex:0,role:r,"data-base-ui-focus-guard":""})});function yi(e,t,n,r){const o=Or(bi).current;return function(e,t,n,r,o){return e.refs[0]!==t||e.refs[1]!==n||e.refs[2]!==r||e.refs[3]!==o}(o,e,t,n,r)&&vi(o,[e,t,n,r]),o.callback}function bi(){return{callback:null,cleanup:null,refs:[]}}function vi(e,t){e.refs=t,t.every(e=>null==e)?e.callback=null:e.callback=n=>{if(e.cleanup&&(e.cleanup(),e.cleanup=null),null!=n){const r=Array(t.length).fill(null);for(let e=0;e<t.length;e+=1){const o=t[e];if(null!=o)switch(typeof o){case"function":{const t=o(n);"function"==typeof t&&(r[e]=t);break}case"object":o.current=n}}e.cleanup=()=>{for(let e=0;e<t.length;e+=1){const n=t[e];if(null!=n)switch(typeof n){case"function":{const t=r[e];"function"==typeof t?t():n(null);break}case"object":n.current=null}}}}}}function wi(t){if(!/*#__PURE__*/e.isValidElement(t))return null;const n=t,r=n.props;return(Lr(19)?r?.ref:n.ref)??null}function xi(e,t){return e&&!t?e:!e&&t?t:e||t?{...e,...t}:void 0}var Si={};function ki(e,t,n,r,o){if(!(n||r||o||e))return Ci(t);let i=Ci(e);return t&&(i=Ei(i,t)),n&&(i=Ei(i,n)),r&&(i=Ei(i,r)),o&&(i=Ei(i,o)),i}function Ci(e){return Mi(e)?{...Ti(e,Si)}:function(e){const t={...e};for(const n in t){const e=t[n];Ii(n,e)&&(t[n]=Oi(e))}return t}(e)}function Ei(e,t){return Mi(t)?Ti(t,e):function(e,t){if(!t)return e;for(const n in t){const r=t[n];switch(n){case"style":e[n]=xi(e.style,r);break;case"className":e[n]=_i(e.className,r);break;default:Ii(n,r)?e[n]=Ri(e[n],r):e[n]=r}}return e}(e,t)}function Ii(e,t){const n=e.charCodeAt(0),r=e.charCodeAt(1),o=e.charCodeAt(2);return 111===n&&110===r&&o>=65&&o<=90&&("function"==typeof t||void 0===t)}function Mi(e){return"function"==typeof e}function Ti(e,t){return Mi(e)?e(t):e??Si}function Ri(e,t){return t?e?(...n)=>{const r=n[0];if(Di(r)){const o=r;Ai(o);const i=t(...n);return o.baseUIHandlerPrevented||e?.(...n),i}const o=t(...n);return e?.(...n),o}:Oi(t):e}function Oi(e){return e?(...t)=>{const n=t[0];return Di(n)&&Ai(n),e(...t)}:e}function Ai(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function _i(e,t){return t?e?t+" "+e:t:e}function Di(e){return null!=e&&"object"==typeof e&&"nativeEvent"in e}function Pi(t,n,o={}){const i=n.render,s=function(e,t={}){const{className:n,style:r,render:o}=e,{state:i=Mr,ref:s,props:a,stateAttributesMapping:c,enabled:l=!0}=t,d=l?function(e,t){return"function"==typeof e?e(t):e}(n,i):void 0,u=l?function(e,t){return"function"==typeof e?e(t):e}(r,i):void 0,p=l?function(e,t){const n={};for(const r in e){const o=e[r];if(t?.hasOwnProperty(r)){const e=t[r](o);null!=e&&Object.assign(n,e);continue}!0===o?n[`data-${r.toLowerCase()}`]="":o&&(n[`data-${r.toLowerCase()}`]=o.toString())}return n}(i,c):Mr,h=l&&a?function(e){return Array.isArray(e)?function(e){if(0===e.length)return Si;if(1===e.length)return Ci(e[0]);let t=Ci(e[0]);for(let n=1;n<e.length;n+=1)t=Ei(t,e[n]);return t}(e):ki(void 0,e)}(a):void 0,f=l?xi(p,h)??{}:Mr;return"undefined"!=typeof document&&(l?Array.isArray(s)?f.ref=function(e){const t=Or(bi).current;return function(e,t){return e.refs.length!==t.length||e.refs.some((e,n)=>e!==t[n])}(t,e)&&vi(t,e),t.callback}([f.ref,wi(o),...s]):f.ref=yi(f.ref,wi(o),s):yi(null,null)),l?(void 0!==d&&(f.className=_i(f.className,d)),void 0!==u&&(f.style=xi(f.style,u)),f):Mr}(n,o);return!1===o.enabled?null:function(t,n,o,i){if(n){if("function"==typeof n)return n(o,i);const t=ki(o,n.props);t.ref=o.ref;let r=n;return r?.$$typeof===Ni&&(r=e.Children.toArray(n)[0]),/*#__PURE__*/e.cloneElement(r,t)}if(t&&"string"==typeof t)return function(t,n){return"button"===t?/*#__PURE__*/r("button",{type:"button",...n,key:n.key}):"img"===t?/*#__PURE__*/r("img",{alt:"",...n,key:n.key}):/*#__PURE__*/e.createElement(t,n)}(t,o);throw new Error(_r(8))}(t,i,s,o.state??Mr)}var Ni=Symbol.for("react.lazy"),Li=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,children:s,...a}=t,c=Pr(),l=ho(),d=e.useRef(!1),u=e.useRef(!1),p=e.useRef(!1),h=c.useState("isEmpty"),f=c.useState("toasts"),m=c.useState("focused"),g=c.useState("expanded"),y=c.useState("prevFocusElement"),w=f[0]?.height,x=f.some(e=>"ending"===e.transitionStatus),S=f.filter(e=>"high"===e.priority);function k(){c.state.toasts.some(e=>"ending"===e.transitionStatus)||p.current||!u.current||(c.state.isWindowFocused&&c.resumeTimers(),c.set("hovering",!1),u.current=!1)}function C(){c.pauseTimers(),c.set("hovering",!0),u.current=!1}function E(e){"touch"===e.pointerType&&(p.current=!1,k())}function I(){d.current?d.current=!1:m||Lo(Oo(io(c.state.viewport)))&&(c.set("focused",!0),c.pauseTimers())}e.useEffect(()=>{const e=c.state.viewport;if(!e||h)return;const t=Gr(e),n=io(e);return oo(so(t,"keydown",function(t){"F6"===t.key&&_o(t)!==e&&(t.preventDefault(),c.set("prevFocusElement",Oo(n)),e?.focus({preventScroll:!0}),c.pauseTimers(),c.set("focused",!0))}),so(t,"blur",function(e){_o(e)===t&&(c.set("isWindowFocused",!1),c.pauseTimers())},!0),so(t,"focus",function(n){if(n.relatedTarget)return;const r=_o(n),o=Oo(io(e));r!==t&&Ao(e,r)&&Lo(o)||c.resumeTimers(),l.start(0,()=>c.set("isWindowFocused",!0))},!0),so(n,"pointerdown",c.handleDocumentPointerDown,!0))},[c,l,h]),e.useEffect(k,[x,c]);const M={tabIndex:-1,role:"region","aria-live":"polite","aria-atomic":!1,"aria-relevant":"additions text","aria-label":"Notifications",onMouseEnter:C,onMouseMove:C,onMouseLeave:function(){u.current=!0,k()},onFocus:I,onBlur:function(e){m&&!Ao(c.state.viewport,e.relatedTarget)&&(c.set("focused",!1),c.state.isWindowFocused&&c.resumeTimers())},onKeyDown:function(e){"Tab"===e.key&&e.shiftKey&&_o(e.nativeEvent)===c.state.viewport&&(e.preventDefault(),c.restoreFocusToPrevElement())},onClick:I,onPointerDown:function(e){"touch"===e.pointerType&&(p.current=!0)},onPointerUp:E,onPointerCancel:E,style:{"--toast-frontmost-height":w?`${w}px`:void 0}},T={expanded:g},R=!h&&y&&/*#__PURE__*/b(gi,{onFocus:function(e){d.current=!0;const t=e.relatedTarget===c.state.viewport?f.find(e=>"ending"!==e.transitionStatus&&!e.limited):void 0;t?t.ref?.current?.focus():c.restoreFocusToPrevElement()}}),O=Pi("div",t,{ref:[n,c.setViewport],state:T,props:[M,a,{children:/*#__PURE__*/v(e.Fragment,{children:[R,s,R]})}]});/*#__PURE__*/
2
+ return v(e.Fragment,{children:[R,O,!m&&S.length>0&&/*#__PURE__*/b("div",{style:mi,children:S.map(e=>/*#__PURE__*/v("div",{role:"alert","aria-atomic":!0,children:[/*#__PURE__*/b("div",{children:e.title}),/*#__PURE__*/b("div",{children:e.description})]},e.id))})]})});function Fi(e){return Lr(19)?e:e?"true":void 0}var zi=/*#__PURE__*/e.createContext(void 0);function $i(){const t=e.useContext(zi);if(!t)throw new Error(_r(66));return t}var Bi=/*#__PURE__*/function(e){return e.startingStyle="data-starting-style",e.endingStyle="data-ending-style",e}({}),Wi={"data-starting-style":""},Ui={"data-ending-style":""},Hi={transitionStatus:e=>"starting"===e?Wi:"ending"===e?Ui:null};function ji(e){return null==e?e:"current"in e?e.current:e}function qi(t){const{enabled:n=!0,open:r,ref:o,onComplete:i}=t,s=jr(i),a=function(e,t=!1){const n=uo();return jr((r,o=null)=>{n.cancel();const i=ji(e);if(null==i)return;const s=i,a=()=>{g.flushSync(r)};if("function"!=typeof s.getAnimations||globalThis.BASE_UI_ANIMATIONS_DISABLED)r();else{if(t){const e="data-starting-style";if(!s.hasAttribute(e))return void n.request(c);const t=new MutationObserver(()=>{s.hasAttribute(e)||(t.disconnect(),c())});return t.observe(s,{attributes:!0,attributeFilter:[e]}),void o?.addEventListener("abort",()=>t.disconnect(),{once:!0})}n.request(c)}function c(){Promise.all(s.getAnimations().map(e=>e.finished)).then(()=>{o?.aborted||a()},()=>{o?.aborted||(s.getAnimations().some(e=>e.pending||"finished"!==e.playState)?c():a())})}})}(o,r);e.useEffect(()=>{if(!n)return;const e=new AbortController;return a(s,e.signal),()=>{e.abort()}},[n,r,s,a])}var Vi={clipPath:"inset(50%)",position:"fixed",top:0,left:0};function Yi(e,t,n){switch(e){case"up":return-n;case"down":return n;case"left":return-t;case"right":return t;default:return 0}}var Ki={...Hi,swipeDirection:e=>e?{"data-swipe-direction":e}:null},Xi=/*#__PURE__*/e.forwardRef(function(t,n){const{toast:r,render:o,className:i,swipeDirection:s=["down","right"],style:a,...c}=t,l=void 0!==r.positionerProps?.anchor;let d=[];l||(d=Array.isArray(s)?s:[s]);const u=d.length>0,p=Pr(),[h,f]=e.useState(void 0),[m,y]=e.useState(!1),[v,w]=e.useState(!1),[x,S]=e.useState({x:0,y:0}),[k,C]=e.useState({x:0,y:0,scale:1}),[E,I]=e.useState(),[M,T]=e.useState(),[R,O]=e.useState(null),A=e.useRef(null),_=e.useRef(void 0),D=e.useRef({x:0,y:0}),P=e.useRef({x:0,y:0,scale:1}),N=e.useRef(void 0),L=e.useRef(0),F=e.useRef(!1),z=e.useRef({x:0,y:0}),$=e.useRef(!1),B=e.useRef({x:0,y:0}),W=e.useRef(null),U=e.useRef(null),H=p.useState("toastIndex",r.id),j=p.useState("toastVisibleIndex",r.id),q=p.useState("toastOffsetY",r.id),V=p.useState("focused"),Y=p.useState("expanded");qi({open:"ending"!==r.transitionStatus,ref:A,onComplete(){"ending"===r.transitionStatus&&p.removeToast(r.id)}});const K=jr((e=!1)=>{const t=A.current;if(!t)return;const n=t.style.height;t.style.height="auto";const o=t.offsetHeight;function i(){p.updateToastInternal(r.id,{ref:A,height:o,transitionStatus:void 0})}t.style.height=n,e?g.flushSync(i):i()});function X(e){B.current=e,S(e)}Ar(()=>{const e=_.current;"starting"!==r.transitionStatus&&e===r.id||(void 0!==e&&(f(void 0),C({x:0,y:0,scale:1}),X({x:0,y:0})),_.current=r.id,K())},[K,r.id,r.transitionStatus]),Ar(()=>()=>{U.current?.abort()},[]);const G=jr(e=>{if(e.pointerId!==W.current)return;W.current=null,U.current?.abort(),U.current=null,y(!1),w(!1),O(null);const t=P.current;if("pointercancel"===e.type||F.current)return X({x:t.x,y:t.y}),void f(void 0);const n=B.current,o=n.x-t.x,i=n.y-t.y;let s;for(const r of d)if(Yi(r,o,i)>40){s=r;break}s?(f(s),p.closeToast(r.id)):(X({x:t.x,y:t.y}),f(void 0))});e.useEffect(()=>{const e=A.current;if(u&&e)return so(e,"touchmove",function(t){null!==W.current&&Ao(e,_o(t))&&t.preventDefault()},{passive:!1})},[u]);const J="high"===r.priority,Z={role:J?"alertdialog":"dialog",tabIndex:0,"aria-modal":!1,"aria-labelledby":E,"aria-describedby":M,"aria-hidden":!(!J||V)||void 0,onPointerDown:u?function(e){if(0!==e.button)return;if("touch"===e.pointerType&&p.pauseTimers(),_o(e.nativeEvent)?.closest('button,a,input,textarea,[role="button"],[data-base-ui-swipe-ignore],[data-swipe-ignore]'))return;F.current=!1,N.current=void 0,L.current=0,W.current=e.pointerId,D.current={x:e.clientX,y:e.clientY},z.current=D.current;const t=e.currentTarget,n=function(e){const t=Gr(e).getComputedStyle(e).transform;let n=0,r=0,o=1;if(t&&"none"!==t){const e=t.match(/matrix(?:3d)?\(([^)]+)\)/);if(e){const t=e[1].split(", ").map(parseFloat);6===t.length?(n=t[4],r=t[5],o=Math.sqrt(t[0]*t[0]+t[1]*t[1])):16===t.length&&(n=t[12],r=t[13],o=t[0])}}return{x:n,y:r,scale:o}}(t);P.current=n,C(n),X({x:n.x,y:n.y}),p.set("hovering",!0),y(!0),w(!1),O(null),$.current=!0,U.current?.abort();const r=new AbortController;U.current=r;const o=io(t);o.addEventListener("pointerup",G,{signal:r.signal}),o.addEventListener("pointercancel",G,{signal:r.signal}),t.setPointerCapture?.(e.pointerId)}:void 0,onPointerMove:u?function(e){if(e.pointerId!==W.current)return;e.preventDefault(),$.current&&(D.current={x:e.clientX,y:e.clientY},$.current=!1);const{clientY:t,clientX:n,movementX:r,movementY:o}=e;(o<0&&t>z.current.y||o>0&&t<z.current.y)&&(z.current={x:z.current.x,y:t}),(r<0&&n>z.current.x||r>0&&n<z.current.x)&&(z.current={x:n,y:z.current.y});const i=n-D.current.x,s=t-D.current.y,a=t-z.current.y,c=n-z.current.x;let l,u=R;if(!v&&Math.sqrt(i*i+s*s)>=1){w(!0);const e=d.includes("left")||d.includes("right"),t=d.includes("up")||d.includes("down");e&&t&&(u=Math.abs(i)>Math.abs(s)?"horizontal":"vertical",O(u))}if(N.current){const e=N.current,t=Yi(e,c,a);t>40?(F.current=!1,f(e)):d.includes("left")&&d.includes("right")||d.includes("up")&&d.includes("down")||!(L.current-t>=10)||(F.current=!0)}else"vertical"===u?s>0?l="down":s<0&&(l="up"):"horizontal"===u?i>0?l="right":i<0&&(l="left"):l=Math.abs(i)>=Math.abs(s)?i>0?"right":"left":s>0?"down":"up",l&&d.includes(l)&&(N.current=l,L.current=Yi(l,i,s),f(l));const p=function(e,t){const n=e=>e>0?e**.5:-(Math.abs(e)**.5),r=e>0&&!d.includes("right")||e<0&&!d.includes("left"),o=t>0&&!d.includes("down")||t<0&&!d.includes("up");return{x:r?n(e):e,y:o?n(t):t}}(i,s);let h=P.current.x,m=P.current.y;const g=d.includes("left")||d.includes("right"),y=d.includes("up")||d.includes("down");"vertical"!==u&&g&&(h+=p.x),"horizontal"!==u&&y&&(m+=p.y),X({x:h,y:m})}:void 0,onPointerUp:u?G:void 0,onPointerCancel:u?G:void 0,onKeyDown:function(e){if("Escape"===e.key){if(!A.current||!Ao(A.current,Oo(io(A.current))))return;p.closeToast(r.id)}},inert:Fi(r.limited),style:{...function(){const e=x.x-k.x,t=x.y-k.y;return{transition:m?"none":void 0,transform:m?`translateX(${x.x}px) translateY(${x.y}px) scale(${k.scale})`:void 0,"--toast-swipe-movement-x":`${e}px`,"--toast-swipe-movement-y":`${t}px`}}(),"--toast-index":"ending"===r.transitionStatus?H:j,"--toast-offset-y":`${q}px`,"--toast-height":r.height?`${r.height}px`:void 0}},Q=e.useMemo(()=>({toast:r,setTitleId:I,setDescriptionId:T,recalculateHeight:K,visibleIndex:j,expanded:Y}),[r,I,T,K,j,Y]),ee={transitionStatus:r.transitionStatus,expanded:Y,limited:r.limited||!1,type:r.type,swiping:m,swipeDirection:h},te=Pi("div",t,{ref:[n,A],state:ee,stateAttributesMapping:Ki,props:[Z,c]});/*#__PURE__*/
3
+ return b(zi.Provider,{value:Q,children:te})}),Gi=0,Ji=Wr.useId;function Zi(t,n){if(void 0!==Ji){const e=Ji();return t??(n?`${n}-${e}`:e)}return function(t,n="mui"){const[r,o]=e.useState(t),i=t||r;return e.useEffect(()=>{null==r&&o(`${n}-${Gi+=1}`)},[r,n]),i}(t,n)}function Qi(e){return null!=e&&"boolean"!=typeof e&&""!==e&&(!Array.isArray(e)||e.some(Qi))}function es(t){/*#__PURE__*/
4
+ return e.isValidElement(t)&&Qi(t.props.children)}function ts(e,t,n){const{toast:r,setTitleId:o,setDescriptionId:i}=$i(),s="title"===n?o:i,a=t??("title"===n?r.title:r.description);return{id:Zi(e),children:a,type:r.type,setId:s}}function ns(e,t,n){const r=es(e);return Ar(()=>{if(r)return n(t),()=>{n(e=>e===t?void 0:e)}},[r,t,n]),r?e:null}var rs=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,children:s,...a}=e,{id:c,children:l,type:d,setId:u}=ts(i,s,"description");return ns(Pi("p",e,{ref:t,state:{type:d},props:{...a,id:c,children:l}}),c,u)}),os=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,children:s,...a}=e,{id:c,children:l,type:d,setId:u}=ts(i,s,"title");return ns(Pi("h2",e,{ref:t,state:{type:d},props:{...a,id:c,children:l}}),c,u)}),is=/*#__PURE__*/e.createContext(void 0);function ss(t=!1){const n=e.useContext(is);if(void 0===n&&!t)throw new Error(_r(16));return n}function as(e,t,{detail:n=0}={}){e.dispatchEvent(new(Gr(e).PointerEvent)("click",{bubbles:!0,cancelable:!0,composed:!0,detail:n,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,metaKey:t.metaKey}))}function cs(t={}){const{disabled:n=!1,focusableWhenDisabled:r,tabIndex:o=0,native:i=!0,composite:s}=t,a=e.useRef(null),c=ss(!0),l=s??void 0!==c,{props:d}=function(t){const{focusableWhenDisabled:n,disabled:r,composite:o=!1,tabIndex:i=0,isNativeButton:s}=t,a=o&&!1!==n,c=o&&!1===n;return{props:e.useMemo(()=>{const e={onKeyDown(e){r&&n&&"Tab"!==e.key&&e.preventDefault()}};return o||(e.tabIndex=i,!s&&r&&(e.tabIndex=n?i:-1)),(s&&(n||a)||!s&&r)&&(e["aria-disabled"]=r),!s||n&&!c||(e.disabled=r),e},[o,r,n,a,c,s,i])}}({focusableWhenDisabled:r,disabled:n,composite:l,tabIndex:o,isNativeButton:i}),u=e.useCallback(()=>{const e=a.current;ls(e)&&l&&n&&void 0===d.disabled&&e.disabled&&(e.disabled=!1)},[n,d.disabled,l]);return Ar(u,[u]),{getButtonProps:e.useCallback((e={})=>{const{onClick:t,onMouseDown:r,onKeyUp:o,onKeyDown:s,onPointerDown:a,...c}=e;return ki({onClick(e){n?e.preventDefault():t?.(e)},onMouseDown(e){n||r?.(e)},onKeyDown(e){if(n)return;if(Ai(e),s?.(e),e.baseUIHandlerPrevented)return;const t=e.target===e.currentTarget,r=e.currentTarget,o=ls(r),a=!i&&Qr(c=r)&&"A"===c.tagName&&Boolean(c.href);var c;const d=t&&(i?o:!a),u="Enter"===e.key,p=" "===e.key,h=r.getAttribute("role"),f=h?.startsWith("menuitem")||"option"===h||"gridcell"===h;if(t&&l&&p){if(e.defaultPrevented&&f)return;return e.preventDefault(),void(i&&!o||(e.preventBaseUIHandler(),as(r,e)))}d&&!i&&(p||u)?e.defaultPrevented||(e.preventDefault(),u&&(e.preventBaseUIHandler(),as(r,e))):t&&a&&p&&e.preventDefault()},onKeyUp(e){n||(Ai(e),o?.(e),e.target===e.currentTarget&&i&&l&&ls(e.currentTarget)&&" "===e.key?e.preventDefault():e.baseUIHandlerPrevented||e.target!==e.currentTarget||i||l||e.defaultPrevented||" "!==e.key||(e.preventBaseUIHandler(),as(e.currentTarget,e)))},onPointerDown(e){n?e.preventDefault():a?.(e)}},i?{type:"button"}:{role:"button"},d,c)},[n,d,l,i]),buttonRef:jr(e=>{a.current=e,u()})}}function ls(e){return Qr(e)&&"BUTTON"===e.tagName}var ds=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,disabled:s,nativeButton:a=!0,...c}=t,l=Pr(),{toast:d,expanded:u}=$i(),[p,h]=e.useState(!1),{getButtonProps:f,buttonRef:m}=cs({disabled:s,native:a});return Pi("button",t,{ref:[n,m],state:{type:d.type},props:[{"aria-hidden":!u&&!p,onClick(){l.closeToast(d.id)},onFocus(){h(!0)},onBlur(){h(!1)}},c,f]})}),us=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,disabled:i,nativeButton:s=!0,...a}=e,{toast:c}=$i(),l=c.actionProps?.children??a.children,{getButtonProps:d,buttonRef:u}=cs({disabled:i,native:s}),p=Pi("button",e,{ref:[t,u],state:{type:c.type},props:[a,c.actionProps,d,{children:l}]});return es(p)?p:null}),ps="none",hs="missing",fs="initial";function ms(e,t,n,r){let o=!1,i=!1;const s=r??Mr;return{reason:e,event:t??new Event("base-ui"),cancel(){o=!0},allowPropagation(){i=!0},get isCanceled(){return o},get isPropagationAllowed(){return i},trigger:n,...s}}function gs(e){return`data-base-ui-${e}`}var ys=/*#__PURE__*/e.createContext(null),bs=()=>e.useContext(ys),vs=gs("portal");function ws(t={}){const{ref:n,container:r,componentProps:o=Mr,elementProps:i}=t,s=Zi(),a=bs()?.portalNode,[c,l]=e.useState(null),[d,u]=e.useState(null),p=jr(e=>{null!==e&&u(e)}),h=e.useRef(null);Ar(()=>{if(null===r)return void(h.current&&(h.current=null,u(null),l(null)));const e=(r&&(Jr(r)?r:r.current))??a??document.body;null!=e?h.current!==e&&(h.current=e,u(null),l(e)):h.current&&(h.current=null,u(null),l(null))},[r,a]);const f=Pi("div",o,{ref:[n,p],props:[{id:s,[vs]:""},i]}),m=c&&f?/*#__PURE__*/g.createPortal(f,c):null;return{node:d,nodeId:/*#__PURE__*/e.isValidElement(f)?f.props.id:void 0,subtree:m}}var xs=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,children:s,container:a,...c}=t,{node:l,nodeId:d,subtree:u}=ws({container:a,ref:n,componentProps:t,elementProps:c}),p=e.useRef(null),h=e.useRef(null),f=e.useRef(null),m=e.useRef(null),[y,w]=e.useState(null),x=e.useRef(!1),S=y?.modal,k=y?.open,C=!!y&&!y.modal&&y.open&&!!l;e.useEffect(()=>{if(l&&!S)return oo(so(l,"focusin",e,!0),so(l,"focusout",e,!0));function e(e){l&&e.relatedTarget&&ai(e)&&("focusin"===e.type?x.current&&(ci(l),x.current=!1):(function(e){ri(e).forEach(e=>{e.dataset.tabindex=e.getAttribute("tabindex")||"",e.setAttribute("tabindex","-1")})}(l),x.current=!0))}},[l,S]),Ar(()=>{l&&!0===k&&x.current&&(ci(l),x.current=!1)},[k,l]);const E=e.useMemo(()=>({beforeOutsideRef:p,afterOutsideRef:h,beforeInsideRef:f,afterInsideRef:m,portalNode:l,setFocusManagerState:w}),[l]);/*#__PURE__*/
5
+ return v(e.Fragment,{children:[u,/*#__PURE__*/v(ys.Provider,{value:E,children:[C&&l&&/*#__PURE__*/b(gi,{"data-type":"outside",ref:p,onFocus:e=>{if(ai(e,l))f.current?.focus();else{const e=y?y.domReference:null;si(e)?.focus()}}}),C&&l&&/*#__PURE__*/b("span",{"aria-owns":d,style:Vi}),l&&/*#__PURE__*/g.createPortal(s,l),C&&l&&/*#__PURE__*/b(gi,{"data-type":"outside",ref:h,onFocus:e=>{if(ai(e,l))m.current?.focus();else{const t=y?y.domReference:null;ii(t)?.focus(),y?.closeOnFocusOut&&y?.onOpenChange(!1,ms("focus-out",e.nativeEvent))}}})]})]})}),Ss=/*#__PURE__*/e.forwardRef(function(t,n){const{children:r,container:o,className:i,render:s,style:a,...c}=t,{node:l,subtree:d}=ws({container:o,ref:n,componentProps:t,elementProps:c});return d||l?/*#__PURE__*/v(e.Fragment,{children:[d,l&&/*#__PURE__*/g.createPortal(r,l)]}):null}),ks=/*#__PURE__*/e.forwardRef(function(e,t){/*#__PURE__*/
6
+ return b(Ss,{ref:t,...e})});function Cs(e){const t=Or(Es,e).current;return t.next=e,Ar(t.effect),t}function Es(e){const t={current:e,next:e,effect:()=>{t.current=t.next}};return t}var Is=0;function Ms(e,t={}){const{preventScroll:n=!1,sync:r=!1,shouldFocus:o}=t;function i(){o&&!o()||e?.focus({preventScroll:n})}if(cancelAnimationFrame(Is),r)return i(),Er;const s=requestAnimationFrame(i);return Is=s,()=>{Is===s&&(cancelAnimationFrame(s),Is=0)}}var Ts={inert:/* @__PURE__ */new WeakMap,"aria-hidden":/* @__PURE__ */new WeakMap},Rs="data-base-ui-inert",Os={inert:/* @__PURE__ */new WeakSet,"aria-hidden":/* @__PURE__ */new WeakSet},As=/* @__PURE__ */new WeakMap,_s=0;function Ds(e){return e?eo(e)?e.host:Ds(e.parentNode):null}var Ps=(e,t)=>t.map(t=>{if(e.contains(t))return t;const n=Ds(t);return e.contains(n)?n:null}).filter(e=>null!=e),Ns=e=>{const t=/* @__PURE__ */new Set;return e.forEach(e=>{let n=e;for(;n&&!t.has(n);)t.add(n),n=n.parentNode}),t},Ls=(e,t,n)=>{const r=[],o=e=>{e&&!n.has(e)&&Array.from(e.children).forEach(e=>{"script"!==Xr(e)&&(t.has(e)?o(e):r.push(e))})};return o(e),r};function Fs(e,t={}){const{ariaHidden:n=!1,inert:r=!1,mark:o=!0}=t;return function(e,t,n,r,{mark:o=!0}){let i=null;r?i="inert":n&&(i="aria-hidden");let s=null,a=null;const c=Ps(t,e),l=o?Ls(t,Ns(c),new Set(c)):[],d=[],u=[];if(i){const e=Ts[i],n=function(e){return Os[e]}(i);a=n,s=e;const r=Ps(t,Array.from(t.querySelectorAll("[aria-live]"))),o=c.concat(r);Ls(t,Ns(o),new Set(o)).forEach(t=>{const r=t.getAttribute(i),o=null!==r&&"false"!==r,s=(e.get(t)||0)+1;e.set(t,s),d.push(t),1===s&&o&&n.add(t),o||t.setAttribute(i,"inert"===i?"":"true")})}return o&&l.forEach(e=>{const t=(As.get(e)||0)+1;As.set(e,t),u.push(e),1===t&&e.setAttribute(Rs,"")}),_s+=1,()=>{s&&d.forEach(e=>{const t=(s.get(e)||0)-1;s.set(e,t),t||(!a?.has(e)&&i&&e.removeAttribute(i),a?.delete(e))}),o&&u.forEach(e=>{const t=(As.get(e)||0)-1;As.set(e,t),t||e.removeAttribute(Rs)}),(_s-=1)||(Ts.inert=/* @__PURE__ */new WeakMap,Ts["aria-hidden"]=/* @__PURE__ */new WeakMap,Os.inert=/* @__PURE__ */new WeakSet,Os["aria-hidden"]=/* @__PURE__ */new WeakSet,As=/* @__PURE__ */new WeakMap)}}(e,io(e[0]).body,n,r,{mark:o})}function zs(){const e=/* @__PURE__ */new Map;return{emit(t,n){e.get(t)?.forEach(e=>e(n))},on(t,n){e.has(t)||e.set(t,/* @__PURE__ */new Set),e.get(t).add(n)},off(t,n){e.get(t)?.delete(n)}}}var $s=/*#__PURE__*/e.createContext(null),Bs=/*#__PURE__*/e.createContext(null),Ws=t=>{const n=e.useContext(Bs);return t??n},Us=[];function Hs(){Us=Us.filter(e=>e.deref()?.isConnected)}function js(e){Hs(),e&&"body"!==Xr(e)&&(Us.push(new WeakRef(e)),Us.length>20&&(Us=Us.slice(-20)))}function qs(){return Hs(),Us[Us.length-1]?.deref()}function Vs(e){if(e.hasAttribute("tabindex")&&!e.hasAttribute("data-tabindex"))return;if(!e.getAttribute("role")?.includes("dialog"))return;const t=ni(e).filter(e=>{const t=e.getAttribute("data-tabindex")||"";return ti(e)||e.hasAttribute("data-tabindex")&&!t.startsWith("-")}),n=e.getAttribute("tabindex");0===t.length?"0"!==n&&(e.setAttribute("tabindex","0"),e.setAttribute("data-tabindex","0")):("-1"!==n||e.hasAttribute("data-tabindex")&&"-1"!==e.getAttribute("data-tabindex"))&&(e.setAttribute("tabindex","-1"),e.setAttribute("data-tabindex","-1"))}function Ys(t){const{context:n,children:r,disabled:o=!1,initialFocus:i=!0,returnFocus:s=!0,restoreFocus:a=!1,modal:c=!0,closeOnFocusOut:l=!0,openInteractionType:d="",nextFocusableElement:u,previousFocusableElement:p,beforeContentFocusGuardRef:h,externalTree:f,getInsideElements:m}=t,g="rootStore"in n?n.rootStore:n,y=g.useState("open"),w=g.useState("domReferenceElement"),x=g.useState("floatingElement"),{events:S,dataRef:k}=g.context,C=jr(()=>k.current.floatingContext?.nodeId),E=!1===i,I=No(w)&&E,M=Cs(i),T=Cs(s),R=Cs(d),O=Cs(y),A=Ws(f),_=bs(),D=e.useRef(!1),P=e.useRef(!1),N=e.useRef(!1),L=e.useRef(null),F=e.useRef(""),z=e.useRef(""),$=e.useRef(null),B=e.useRef(null),W=yi($,h,_?.beforeInsideRef),U=yi(B,_?.afterInsideRef),H=ho(),j=ho(),q=uo(),V=null!=_,Y=Fo(x),K=jr((e=Y)=>e?ri(e):[]),X=jr(()=>m?.().filter(e=>null!=e)??[]);e.useEffect(()=>{if(!o&&c)return so(io(Y),"keydown",function(e){"Tab"===e.key&&Ao(Y,Oo(io(Y)))&&0===K().length&&!I&&function(e){e.preventDefault(),e.stopPropagation()}(e)})},[o,Y,c,I,K]),e.useEffect(()=>{if(o||!y)return;const e=io(Y);function t(){N.current=!1}return oo(so(e,"pointerdown",function(e){const t=_o(e),n=X(),r=Ao(x,t)||Ao(w,t)||Ao(_?.portalNode,t)||n.some(e=>e===t||Ao(e,t));N.current=!r,z.current=e.pointerType||"keyboard",t?.closest("[data-base-ui-click-trigger]")&&(P.current=!0,j.start(0,()=>{P.current=!1}))},!0),so(e,"pointerup",t,!0),so(e,"pointercancel",t,!0),so(e,"keydown",function(){z.current="keyboard"},!0),t)},[o,x,w,Y,y,_,j,X]),e.useEffect(()=>{if(o||!l)return;const e=io(Y);function t(t){const n=t.relatedTarget,r=t.currentTarget,o=_o(t);c&&null==n&&null!=o&&Ao(x,o)&&js(o),queueMicrotask(()=>{const i=C(),s=g.context.triggerElements,l=X(),d=n?.hasAttribute(gs("focus-guard"))&&[$.current,B.current,_?.beforeInsideRef.current,_?.afterInsideRef.current,_?.beforeOutsideRef.current,_?.afterOutsideRef.current,ji(p),ji(u)].includes(n),h=!(Ao(w,n)||Ao(x,n)||Ao(n,x)||Ao(_?.portalNode,n)||l.some(e=>e===n||Ao(e,n))||s.hasMatchingElement(e=>Ao(e,n))||d||A&&(zo(A.nodesRef.current,i).find(e=>Ao(e.context?.elements.floating,n)||Ao(e.context?.elements.domReference,n))||$o(A.nodesRef.current,i).find(e=>[e.context?.elements.floating,Fo(e.context?.elements.floating)].includes(n)||e.context?.elements.domReference===n)));if(r===w&&Y&&Vs(Y),a&&r!==w&&!Ho(o)&&Oo(e)===e.body){if(Qr(Y)&&(Y.focus(),"popup"===a))return void q.request(()=>{Y.focus()});const e=K(),t=L.current,n=(t&&e.includes(t)?t:null)||e[e.length-1]||Y;Qr(n)&&n.focus()}k.current.insideReactTree?k.current.insideReactTree=!1:!I&&c||!n||!h||P.current||!I&&n===qs()||(D.current=!0,g.setOpen(!1,ms("focus-out",t)))})}const n=Qr(w)?w:null;return x||n?oo(n&&so(n,"focusout",t),n&&so(n,"pointerdown",function(){P.current=!0,j.start(0,()=>{P.current=!1})}),x&&so(x,"focusin",function(e){const t=_o(e);ti(t)&&(L.current=t)}),x&&so(x,"focusout",t),x&&_&&so(x,"focusout",function(){N.current||(k.current.insideReactTree=!0,H.start(0,()=>{k.current.insideReactTree=!1}))},!0)):void 0},[o,w,x,Y,c,A,_,g,l,a,K,I,C,k,H,j,q,u,p,X]),e.useEffect(()=>{if(o||!x||!y)return;const e=Array.from(_?.portalNode?.querySelectorAll(`[${gs("portal")}]`)||[]),t=(A?$o(A.nodesRef.current,C()):[]).find(e=>No(e.context?.elements.domReference||null))?.context?.elements.domReference,n=Fs([x,...e,$.current,B.current,_?.beforeOutsideRef.current,_?.afterOutsideRef.current,...X(),t,ji(p),ji(u),I?w:null].filter(e=>null!=e),{ariaHidden:c||I,mark:!1}),r=Fs([x,...e].filter(e=>null!=e));return()=>{r(),n()}},[y,o,w,x,c,_,I,A,C,u,p,X]),Ar(()=>{if(!y||o||!Qr(Y))return;F.current="",z.current="";const e=io(Y),t=Oo(e);queueMicrotask(()=>{const n=M.current,r="function"==typeof n?n(R.current||""):n;if(void 0===r||!1===r)return;if(Ao(Y,t))return;let o=null;const i=()=>(null==o&&(o=K(Y)),o[0]||Y);let s;s=!0===r||null===r?i():ji(r),s=s||i();const a=Ao(Y,Oo(e));Ms(s,{preventScroll:s===Y,shouldFocus(){if(!O.current)return!1;if(a)return!0;const t=Oo(e);return!(t!==s&&Ao(Y,t))}})})},[o,y,Y,K,M,R,O]),Ar(()=>{if(o||!Y)return;const e=io(Y),t=Oo(e),n=null==R.current;function r(e){var t;if(e.open||(F.current=function(e,t){const n=Gr(_o(e));return e instanceof n.KeyboardEvent?"keyboard":e instanceof n.FocusEvent?t||"keyboard":"pointerType"in e?e.pointerType||"keyboard":"touches"in e?"touch":e instanceof n.MouseEvent?t||(0===e.detail?"keyboard":"mouse"):""}(e.nativeEvent,z.current)),"trigger-hover"===e.reason&&"mouseleave"===e.nativeEvent.type&&(D.current=!0),"outside-press"===e.reason)if(e.nested)D.current=!1;else if(""===(t=e.nativeEvent).pointerType&&t.isTrusted||(ko&&t.pointerType?"click"===t.type&&1===t.buttons:0===t.detail&&!t.pointerType)||function(e){return!To&&(!ko&&0===e.width&&0===e.height||ko&&1===e.width&&1===e.height&&0===e.pressure&&0===e.detail&&"mouse"===e.pointerType||e.width<1&&e.height<1&&0===e.pressure&&0===e.detail&&"touch"===e.pointerType)}(e.nativeEvent))D.current=!1;else{let e=!1;io(Y).createElement("div").focus({get preventScroll(){return e=!0,!1}}),D.current=!e}}return js(t),S.on("openchange",r),()=>{S.off("openchange",r);const o=Oo(e),i=X(),s=Ao(x,o)||i.some(e=>e===o||Ao(e,o))||A&&zo(A.nodesRef.current,C(),!1).some(e=>Ao(e.context?.elements.floating,o)),a=T.current,c=F.current,l=function(e){const r=T.current;let o="function"==typeof r?r(e):r;if(void 0===o||!1===o)return null;null===o&&(o=!0);const i=w?.isConnected?w:null,s=t?.isConnected&&"body"!==Xr(t)?t:null;let a=n?s||i:i||s;return a||(a=qs()||null),"boolean"==typeof o?a:ji(o)||a||null}(c);queueMicrotask(()=>{const t=(n=l)?ti(n)?n:ri(n)[0]||n:null;var n;const r="boolean"!=typeof a;if(a&&!D.current&&Qr(t)&&(r||t===o||o===e.body||s)){const e={preventScroll:!0};"keyboard"===c&&(e.focusVisible=!0),t.focus(e)}D.current=!1})}},[o,x,Y,T,R,S,A,w,C,X]),Ar(()=>{if(!Io||y||!x)return;const e=Oo(io(x));Qr(e)&&Po(e)&&Ao(x,e)&&e.blur()},[y,x]),Ar(()=>{if(!o&&_)return _.setFocusManagerState({modal:c,closeOnFocusOut:l,open:y,onOpenChange:g.setOpen,domReference:w}),()=>{_.setFocusManagerState(null)}},[o,_,c,y,g,l,w]),Ar(()=>{if(!o&&Y)return Vs(Y),()=>{queueMicrotask(Hs)}},[o,Y]);const G=!o&&(!c||!I)&&(V||c);/*#__PURE__*/
7
+ return v(e.Fragment,{children:[G&&/*#__PURE__*/b(gi,{"data-type":"inside",ref:W,onFocus:e=>{if(c){const e=K();Ms(e[e.length-1])}else _?.portalNode&&(D.current=!1,ai(e,_.portalNode)?ii(w)?.focus():ji(p??_.beforeOutsideRef)?.focus())}}),r,G&&/*#__PURE__*/b(gi,{"data-type":"inside",ref:U,onFocus:e=>{c?Ms(K()[0]):_?.portalNode&&(l&&(D.current=!0),ai(e,_.portalNode)?si(w)?.focus():ji(u??_.afterOutsideRef)?.focus())}})]})}function Ks(){return!1}var Xs={open:e=>e.open,transitionStatus:e=>e.transitionStatus,domReferenceElement:e=>e.domReferenceElement,referenceElement:e=>e.positionReference??e.referenceElement,floatingElement:e=>e.floatingElement,floatingId:e=>e.floatingId},Gs=class extends Yr{constructor(e){const{syncOnly:t,nested:n,onOpenChange:r,triggerElements:o,...i}=e;super({...i,positionReference:i.referenceElement,domReferenceElement:i.referenceElement},{onOpenChange:r,dataRef:{current:{}},events:zs(),nested:n,triggerElements:o},Xs),this.syncOnly=t}syncOpenEvent=(e,t)=>{(!e||!this.state.open||null!=t&&function(e){const t=e.type;return"click"===t||"mousedown"===t||"keydown"===t||"keyup"===t}(t))&&(this.context.dataRef.current.openEvent=e?t:void 0)};dispatchOpenChange=(e,t)=>{this.syncOpenEvent(e,t.event);const n={open:e,reason:t.reason,nativeEvent:t.event,nested:this.context.nested,triggerElement:t.trigger};this.context.events.emit("openchange",n)};setOpen=(e,t)=>{this.syncOnly||this.dispatchOpenChange(e,t),this.context.onOpenChange?.(e,t)}};function Js(t,n=!1,r=!1){const[o,i]=e.useState(t&&n?"idle":void 0),[s,a]=e.useState(t);return t&&!s&&(a(!0),i("starting")),t||!s||"ending"===o||r||i("ending"),t||s||"ending"!==o||i(void 0),Ar(()=>{if(!t&&s&&"ending"!==o&&r){const e=lo.request(()=>{i("ending")});return()=>{lo.cancel(e)}}},[t,s,o,r]),Ar(()=>{if(!t||n)return;const e=lo.request(()=>{i(void 0)});return()=>{lo.cancel(e)}},[n,t]),Ar(()=>{if(!t||!n)return;t&&s&&"idle"!==o&&i("starting");const e=lo.request(()=>{i("idle")});return()=>{lo.cancel(e)}},[n,t,s,o]),{mounted:s,setMounted:a,transitionStatus:o}}var Zs={tabIndex:-1,[Ro]:""};function Qs({handle:e,store:t}){return Ar(()=>e.attachStore(t),[e,t]),null}var ea=class{constructor(){this.idMap=/* @__PURE__ */new Map}add(e,t){this.idMap.set(e,t)}delete(e){this.idMap.delete(e)}hasElement(e){for(const t of this.idMap.values())if(t===e)return!0;return!1}hasMatchingElement(e){for(const t of this.idMap.values())if(e(t))return!0;return!1}getById(e){return this.idMap.get(e)}entries(){return this.idMap.entries()}elements(){return this.idMap.values()}get size(){return this.idMap.size}},ta=e=>e.triggerIdProp??e.activeTriggerId,na=e=>e.openProp??e.open,ra=e=>(e.popupElement?.id??e.floatingId)||void 0;function oa(e,t){return void 0!==t&&na(e)&&ta(e)===t}var ia,sa={open:na,mounted:e=>e.mounted,transitionStatus:e=>e.transitionStatus,floatingRootContext:e=>e.floatingRootContext,triggerCount:e=>e.triggerCount,preventUnmountingOnClose:e=>e.preventUnmountingOnClose,payload:e=>e.payload,activeTriggerId:ta,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:ra,isTriggerActive:(e,t)=>void 0!==t&&ta(e)===t,isOpenedByTrigger:(e,t)=>oa(e,t),isMountedByTrigger:(e,t)=>void 0!==t&&ta(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>function(e,t){return!!oa(e,t)||void 0!==t&&na(e)&&null==ta(e)&&1===e.triggerCount}(e,t)?ra(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement},aa=/*#__PURE__*/e.createContext(void 0);(ia={}).open="data-open",ia.closed="data-closed",ia[ia.startingStyle=Bi.startingStyle]="startingStyle",ia[ia.endingStyle=Bi.endingStyle]="endingStyle",ia.anchorHidden="data-anchor-hidden",ia.side="data-side",ia.align="data-align";var ca={"data-open":""},la={"data-closed":""},da={"data-anchor-hidden":""},ua={open:e=>e?ca:la,anchorHidden:e=>e?da:null},pa={...ua,...Hi};function ha(){const t=Pr(),n=t.useState("toasts");return e.useMemo(()=>({toasts:n,add:t.addToast,close:t.closeToast,update:t.updateToast,promise:t.promiseToast}),[n,t])}var fa="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",ma={none:"none",card:"0 1px 4px rgba(0,0,0,0.1)",section:"0 2px 8px rgba(0,0,0,0.06)",panel:"0 12px 40px rgba(0,0,0,0.16), 0 4px 12px rgba(0,0,0,0.08)",fab:"0 2px 8px rgba(0,0,0,0.18), 0 0 0 1px rgba(0,0,0,0.04)",button:"0 4px 6px -1px rgba(0,0,0,0.1)"},ga={none:"0",sm:"calc(var(--radius) - 4px)",md:"calc(var(--radius) - 2px)",lg:"var(--radius)",xl:"calc(var(--radius) + 4px)",pill:"9999px"},ya={default:"var(--foreground)",muted:"var(--foreground-muted)",faint:"var(--foreground-faint)",primary:"var(--primary)",inherit:"inherit"},ba={tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625"},va={info:{background:"#f0f9ff",border:"1px solid #bae6fd",titleColor:"#0c4a6e",bodyColor:"#0369a1",closeColor:"#7dd3fc",actionBackground:"#e0f2fe"},error:{background:"#fef2f2",border:"1px solid #fecaca",titleColor:"#b91c1c",bodyColor:"#b91c1c",closeColor:"#f87171",actionBackground:"#fee2e2"},neutral:{background:"rgba(255, 255, 255, 0.95)",border:"1px solid rgba(255, 255, 255, 0.2)",titleColor:"#1f2937",bodyColor:"#1f2937",closeColor:"#6b7280",actionBackground:"transparent"}};function wa(e){if(e&&"none"!==e)return{boxShadow:ma[e]}}var xa=2147483003,Sa={none:"0","2xs":"2px",xs:"4px",sm:"6px",md:"8px",lg:"12px",xl:"16px","2xl":"24px"},ka={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch",baseline:"baseline"},Ca={start:"flex-start",center:"center",end:"flex-end",between:"space-between",around:"space-around"},Ea={spin:"mtx-spin 1s linear infinite",ping:"mtx-ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"mtx-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",fadeIn:"mtx-fade-in 0.5s ease-out"},Ia={top:"borderTopWidth",bottom:"borderBottomWidth",left:"borderLeftWidth",right:"borderRightWidth"},Ma=/* @__PURE__ */new Set(["padding","paddingX","paddingY","paddingTop","paddingBottom","gap","align","justify","grow","shrink","position","inset","overflow","overflowY","width","height","minWidth","border","rounded","animate","hidden","as","style"]);function Ta(e){const t={};return void 0!==e.padding&&(t.padding=Sa[e.padding]),void 0!==e.paddingX&&(t.paddingLeft=Sa[e.paddingX],t.paddingRight=Sa[e.paddingX]),void 0!==e.paddingY&&(t.paddingTop=Sa[e.paddingY],t.paddingBottom=Sa[e.paddingY]),void 0!==e.paddingTop&&(t.paddingTop=Sa[e.paddingTop]),void 0!==e.paddingBottom&&(t.paddingBottom=Sa[e.paddingBottom]),void 0!==e.gap&&(t.gap=Sa[e.gap]),void 0!==e.align&&(t.alignItems=ka[e.align]),void 0!==e.justify&&(t.justifyContent=Ca[e.justify]),!0===e.grow&&(t.flex="1 1 0%"),!1===e.shrink&&(t.flexShrink=0),void 0!==e.position&&(t.position=e.position),void 0!==e.inset&&(t.inset="0"===e.inset?"0":Sa[e.inset]),void 0!==e.overflow&&(t.overflow=e.overflow),void 0!==e.overflowY&&(t.overflowY=e.overflowY),void 0!==e.width&&(t.width="full"===e.width?"100%":"auto"),void 0!==e.height&&(t.height="full"===e.height?"100%":"auto"),"0"===e.minWidth&&(t.minWidth=0),void 0!==e.border&&!1!==e.border&&(t.borderColor="var(--border)",t.borderStyle="solid",!0===e.border?t.borderWidth="1px":t[Ia[e.border]]="1px"),void 0!==e.rounded&&!1!==e.rounded&&(!0===e.rounded?t.borderRadius=ga.lg:t.borderRadius=ga[e.rounded]),void 0!==e.animate&&"none"!==e.animate&&(t.animation=Ea[e.animate]),!0===e.hidden&&(t.display="none"),t}var Ra={sm:20,md:32,lg:48};function Oa(e){const{src:t,alt:n,elevation:r,fit:o="contain",size:i="md",rounded:s,className:a,style:c,ref:l,...d}=e,u="string"==typeof i?Ra[i]:i;/* @__PURE__ */
8
+ return b("img",{...d,ref:l,alt:n,className:a?`mtx-avatar ${a}`:"mtx-avatar",src:t,style:{objectFit:o,width:u,height:u,...Ta({rounded:s}),...wa(r),...c}})}var Aa=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,disabled:o=!1,focusableWhenDisabled:i=!1,nativeButton:s=!0,style:a,...c}=e,{getButtonProps:l,buttonRef:d}=cs({disabled:o,focusableWhenDisabled:i,native:s});return Pi("button",e,{state:{disabled:o},ref:[t,d],props:[c,l]})}),_a={default:ga.lg,pill:ga.pill};function Da({className:e,disabled:t,elevation:n,full:r,shape:o="default",size:i="md",stacked:s=!1,type:a="button",variant:c="primary",style:l,ref:d,...u}){/* @__PURE__ */
9
+ return b(Aa,{...u,ref:d,className:e?`mtx-button ${e}`:"mtx-button","data-disabled":t?"true":"false","data-full":r?"true":"false","data-size":i,"data-stacked":s?"true":"false","data-variant":c,disabled:t,style:{borderRadius:_a[o],...wa(n),...l},type:a})}var Pa={default:{},card:{backgroundColor:"var(--card)",color:"var(--card-foreground)"}},Na={none:{},card:{padding:"8px 12px"},toast:{padding:"8px 12px 8px 8px"}},La=o(function(e,t){const{as:n="div",background:r="default",className:o,elevation:i,paddingPreset:s="none",style:a,...c}=e,l=function(e){const t={};for(const n in e)Ma.has(n)||(t[n]=e[n]);return t}(c);/* @__PURE__ */
10
+ return b(n,{...l,ref:t,className:o,style:{...Pa[r],...Na[s],...wa(i),...Ta(e),...a}})}),Fa=o(function(e,t){const{direction:n,hidden:r,style:o,...i}=e;/* @__PURE__ */
11
+ return b(La,{...i,ref:t,hidden:r,style:{display:!0===r?"none":"flex",..."column"===n&&{flexDirection:"column"},...o}})}),za=(e,t=2)=>({d:e,stroke:"currentColor",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round"}),$a={checkCircle:{viewBox:"0 0 512 512",paths:[{d:"M504 256c0 136.967-111.033 248-248 248S8 392.967 8 256 119.033 8 256 8s248 111.033 248 248zM227.314 387.314l184-184c6.248-6.248 6.248-16.379 0-22.627l-22.627-22.627c-6.248-6.249-16.379-6.249-22.628 0L216 308.118l-70.059-70.059c-6.248-6.248-16.379-6.248-22.628 0l-22.627 22.627c-6.248 6.248-6.248 16.379 0 22.627l104 104c6.249 6.249 16.379 6.249 22.628.001z"}]},circle:{viewBox:"0 0 512 512",paths:[{d:"M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"}]},exclamationCircle:{viewBox:"0 0 512 512",paths:[{d:"M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"}]},arrowUp:{viewBox:"0 0 448 512",paths:[{d:"M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z"}]},arrowDown:{viewBox:"0 0 448 512",paths:[{d:"M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z"}]},chatBubble:{viewBox:"0 0 512 512",paths:[{d:"M87.48 380c1.2-4.38-1.43-10.47-3.94-14.86a42.63 42.63 0 0 0-2.54-3.8 199.81 199.81 0 0 1-33-110C47.64 139.09 140.72 48 255.82 48 356.2 48 440 117.54 459.57 209.85a199 199 0 0 1 4.43 41.64c0 112.41-89.49 204.93-204.59 204.93-18.31 0-43-4.6-56.47-8.37s-26.92-8.77-30.39-10.11a31.14 31.14 0 0 0-11.13-2.07 30.7 30.7 0 0 0-12.08 2.43L81.5 462.78a15.92 15.92 0 0 1-4.66 1.22 9.61 9.61 0 0 1-9.58-9.74 15.85 15.85 0 0 1 .6-3.29z",fill:"none",stroke:"currentColor",strokeWidth:32,strokeLinecap:"round"},{d:"M160 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0"},{d:"M256 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0"},{d:"M352 256 m-32 0 a32 32 0 1 1 64 0 a32 32 0 1 1 -64 0"}]},stop:{viewBox:"0 0 512 512",paths:[{d:"M392 432H120a40 40 0 0 1-40-40V120a40 40 0 0 1 40-40h272a40 40 0 0 1 40 40v272a40 40 0 0 1-40 40z"}]},mousePointerClick:{viewBox:"0 0 24 24",paths:[za("M14 4.1 12 6"),za("m5.1 8-2.9-.8"),za("m6 12-1.9 2"),za("M7.2 2.2 8 5.1"),za("M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z")]},ticktick:{viewBox:"0 0 24 24",paths:[{d:"M12 0C5.383 0 0 5.383 0 12s5.383 12 12 12 12-5.383 12-12h-2.7c0 5.128-4.172 9.3-9.3 9.3-5.128 0-9.3-4.172-9.3-9.3 0-5.128 4.172-9.3 9.3-9.3V0Zm7.4 2.583-7.505 9.371L8.388 9.08l-2.002 2.436 4.741 3.888a1.573 1.573 0 0 0 2.231-.233l8.504-10.617L19.4 2.583Z"}]},home:{viewBox:"0 0 24 24",paths:[za("M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6")]},chat:{viewBox:"0 0 24 24",paths:[za("M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z")]},send:{viewBox:"0 0 24 24",paths:[za("M5 12h14m-7-7l7 7-7 7")]},closeSmall:{viewBox:"0 0 12 12",paths:[za("M9 3L3 9M3 3l6 6",1.5)]},close:{viewBox:"0 0 20 20",paths:[{d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",fillRule:"evenodd",clipRule:"evenodd"}]},chevronDown:{viewBox:"0 0 24 24",paths:[za("M19 9l-7 7-7-7",2.5)]},screenShare:{viewBox:"0 0 24 24",paths:[za("M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z")]},alertCircle:{viewBox:"0 0 24 24",paths:[za("M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z")]}};function Ba({name:e,size:t=16,className:n,ref:r,...o}){const i=$a[e];return i?/* @__PURE__ */b("svg",{...o,ref:r,"aria-hidden":"true",className:n?`mtx-icon ${n}`:"mtx-icon",fill:"none",height:t,viewBox:i.viewBox,width:t,xmlns:"http://www.w3.org/2000/svg",children:i.paths.map((e,t)=>/* @__PURE__ */b("path",{clipRule:e.clipRule,d:e.d,fill:e.fill??(e.stroke?"none":"currentColor"),fillRule:e.fillRule,stroke:e.stroke,strokeLinecap:e.strokeLinecap,strokeLinejoin:e.strokeLinejoin,strokeMiterlimit:e.strokeMiterlimit,strokeWidth:e.strokeWidth},t))}):null}function Wa({variant:e="ghost",size:t="sm",tone:n,label:r,disabled:o,children:i,style:s,ref:a,...c}){/* @__PURE__ */
12
+ return b("button",{...c,ref:a,type:"button",disabled:o,"aria-label":r,className:"mtx-icon-button","data-disabled":o?"true":"false","data-size":t,"data-variant":e,style:n?{color:ya[n],...s}:s,children:i})}var Ua=o(function(e,t){/* @__PURE__ */
13
+ return b(Fa,{...e,ref:t,direction:"column"})}),Ha={xxs:"10px",xs:"0.75rem",sm:"0.875rem",lg:"1.125rem"},ja={normal:400,medium:500,semibold:600},qa={overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function Va({as:e="span",block:t=!1,inheritColor:n=!1,italic:r=!1,leading:o,variant:i="default",size:s,weight:a,truncate:c,align:l,className:d,ref:u,style:p,...h}){/* @__PURE__ */
14
+ return b(e,{...h,ref:u,className:d,style:{color:ya[n?"inherit":i],...s&&{fontSize:Ha[s]},...a&&{fontWeight:ja[a]},...l&&{textAlign:l},...o&&{lineHeight:ba[o]},...t&&{display:"block"},...r&&{fontStyle:"italic"},...c&&qa,...p}})}var Ya=()=>{const{toasts:e}=ha();return e.map(e=>{const t=va[n=e.type,"error"===n||"info"===n?n:"neutral"];var n;/* @__PURE__ */
15
+ return v(Xi,{toast:e,className:"mtx-toast",render:/* @__PURE__ */b(Fa,{align:"center",gap:"md",rounded:"pill",paddingPreset:"toast",elevation:"panel",style:{backgroundColor:t.background,border:t.border}}),children:[
16
+ /* @__PURE__ */b(Oa,{src:fa,alt:"",size:28,rounded:"pill"}),
17
+ /* @__PURE__ */v(Ua,{grow:!0,minWidth:"0",children:[/* @__PURE__ */b(os,{render:/* @__PURE__ */b(Va,{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(rs,{render:/* @__PURE__ */b(Va,{as:"span",block:!0,inheritColor:!0,style:{fontSize:"12px",color:t.bodyColor,opacity:.8,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}})})]}),e.actionProps&&/* @__PURE__ */b(us,{render:/* @__PURE__ */b(Da,{type:"button",variant:"ghost",shape:"pill",size:"sm",style:{color:t.titleColor,backgroundColor:t.actionBackground,border:t.border}})}),
18
+ /* @__PURE__ */b(ds,{render:/* @__PURE__ */b(Wa,{label:"Dismiss",size:"xs",tone:"inherit",style:{color:t.closeColor,padding:"2px"}}),children:/* @__PURE__ */b(Ba,{name:"closeSmall",size:12})})]},e.id)})},Ka=({children:e,container:t,offsetBottom:n=20})=>/* @__PURE__ */v(hi,{children:[e,/* @__PURE__ */b(ks,{container:t??void 0,children:/* @__PURE__ */b(Li,{className:"mtx-toast-viewport",style:{zIndex:2147483004,bottom:`${n}px`},children:/* @__PURE__ */b(Ya,{})})})]}),Xa=ha,Ga=({error:e,onClearError:t,onRetry:n,greeting:r,greetingBody:o,onGreetingDismiss:i})=>{const{add:s,close:c}=Xa();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};function Ja(e){const t=[...e.parts],n=e.content.trim();return 0===t.length&&n&&t.push({type:"text",content:n}),{...e,timestamp:new Date(e.timestamp),parts:t}}function Za({videoStream:e,...t}){const n=t.timestamp.toISOString();if(!e)return{...t,timestamp:n};const r="Screenshare ended";return{...t,timestamp:n,content:r,isSystemMessage:!0,parts:[{type:"text",content:r}]}}var Qa=new class{restore(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=Le.getContext();return{...o,messages:r.map(Ja)}}persist(e){Le.updateContext({...e,messages:e.messages.map(Za)})}};function ec(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 tc=(e,t,n="user-message")=>ec(n,"user",e.trim(),{mode:t}),nc=e=>ec("agent-message","agent",e.trim()),rc=(e,t,n,r)=>ec(r,n,e,{mode:t,isSystemMessage:!0}),oc={show:"Show",tell:"Tell",do:"Do"},ic=e=>oc[e];function sc(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}function ac({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=sc(e,e=>"agent"===e.sender&&!!e.taskStatus)+1,a=e.slice(s);for(const c of i){const e=sc(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 cc=/* @__PURE__ */new Set(["click_element","type_text","select_dropdown_option","send_keys"]),lc=e=>e.replace(/\(?cancelled by cleanup\)?/gi,"").trim();function dc(e,t,n){if(t<0)return e;const r=[...e.parts];return r[t]={...r[t],...n},{...e,parts:r}}var uc=(e,t)=>e.parts.findIndex(e=>(e=>"progress"===e.type&&"in_progress"===e.status)(e)&&e.browserToolName===t),pc=/* @__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"]]),hc=/* @__PURE__ */new Set(["button","link","textbox","checkbox","radio","switch","tab","menuitem"]);function*fc(e){let t=e;for(;t;){yield t;const e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}}function mc(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")||hc.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 fc(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 gc=["id","type","role","aria-label","name","href"],yc=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)?gc.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||mc(r))&&(this.index.set(n,{element:r,selector:this.generateAnchoredSelector(r),identity:gc.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 fc(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}}},bc=["scroll","resize","touchmove","wheel"],vc=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 bc)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 bc)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=yc.getSequenceForElement(e)??-1,r=yc.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}},wc=e=>({success:!0,data:{text:e}}),xc=e=>({success:!0,data:e}),Sc=e=>({success:!1,data:{text:""},error:e}),kc=e=>({success:!1,data:{options:[]},error:e}),Cc=(e,t)=>({success:!0,data:{text:e},afterResponseAttempt:t}),Ec=new class{async executeTool(e,t,n="do",r=""){const o=t;try{if("show"===n&&cc.has(e)){const t=o.index;if(void 0!==t){const{element:n,error:o}=yc.getValidatedElement(t);if(!n)return Sc(o||`Element ${t} not found`);await vc.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 Sc(`Unknown tool: ${e}`)}}catch(i){return Sc(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")?wc(`Opened ${t} in new tab`):Sc("The browser blocked opening a new tab"):Cc(`Navigating to ${t}`,()=>{window.location.href=t}):Sc("An http(s) URL is required")}search(e){if(!e.query)return Sc("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}`),Cc(`Searching for "${e.query}" on ${t}`,()=>{window.location.href=r})}async clickElement(e){if(void 0===e.index)return Sc("Index required");const{element:t,error:n}=yc.getValidatedElement(e.index);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),Cc(`Clicking element ${e.index}`,()=>t.click())):Sc(n||`Element ${e.index} not found`)}typeText(e){if(void 0===e.index||void 0===e.text)return Sc("Index and text required");const t=!1!==e.clear,{element:n,error:r}=yc.getValidatedElement(e.index);if(!n)return Sc(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 Sc(`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 Sc(`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 Sc(`Failed to set textContent: ${o instanceof Error?o.message:String(o)}`)}return wc(`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 Sc("Invalid direction")}return wc(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return Sc("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"}),wc(`Scrolled to "${e.text}"`);return Sc(`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 xc(n)}goBack(){return window.history.length<=1?Sc("No history"):Cc("Going back",()=>window.history.back())}async wait({seconds:e}){return void 0===e?Sc("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),wc(`Waited ${e}s`))}selectDropdownOption(e){if(void 0===e.index||!e.option)return Sc("Index/Option required");const{element:t,error:n}=yc.getValidatedElement(e.index);if(!t)return Sc(n||`Select ${e.index} not found`);if(!(t instanceof HTMLSelectElement))return Sc(`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})),wc(`Selected ${e.option}`)):Sc(`Option ${e.option} not found`)}getDropdownOptions(e){const t=e.index;if(void 0===t)return kc("Index required");const{element:n,error:r}=yc.getValidatedElement(t);if(!n)return kc(r||`Select ${t} not found`);if(!(n instanceof HTMLSelectElement))return kc(`Element ${t} is not a select element`);const o=Array.from(n.options).map(e=>({value:e.value,text:e.text}));return xc({options:o})}sendKeys(e){if(void 0===e.index||!e.keys)return Sc("Index/Keys required");const{element:t,error:n}=yc.getValidatedElement(e.index);if(!t)return Sc(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 wc(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?wc("Tab closed"):Sc("The browser refused to close a tab this script did not open")}done(e){return wc(e.message||"Task ended")}getHtml(){try{const e=yc.reindexAndSnapshot();return wc(e)}catch(e){return Sc(String(e))}}async getScreenshot(){const e=pr();if(!e)return Sc("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),wc(n.toDataURL("image/jpeg",.75))):Sc("Could not read the shared screen: the browser refused a 2d canvas context.")}catch(n){return Sc(String(n))}finally{t.remove()}}},Ic=e=>e.filter(e=>"text"===e.type).map(e=>e.content).join("\n"),Mc=e=>({state:e,effects:[]});function Tc(e,t,n,r,o,i,s){const a=ac({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;if("failed"===i?c=function(e,t,n){const r=uc(e,t);if(r<0)return e;const o=lc(e.parts[r].content),i=lc(n);return dc(e,r,{status:"failed",content:i?`${o} (${i})`:o})}(c,r,s||""):"done"!==r&&(c="in_progress"===i?function(e,t,n){const r=lc(n),o=uc(e,t);return o>=0?dc(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||(e=>pc.get(e)??e)(r)):((e,t)=>dc(e,uc(e,t),{status:"completed"}))(c,r)),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&cc.has(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const l=[...e];return l[a.index]=c,l}var Rc=e=>({...e,isPlaceholder:!1}),Oc=e=>"stopped"===e.phase?e:{phase:"idle"};function Ac(e,t,n){const r=ac({messages:e.messages,isTaskRunning:"running"===e.task.phase,currentMode:t}),o=[...e.messages];return r&&(o[r.index]=Rc(n(r.message))),{messages:o,task:Oc(e.task)}}var _c={completed:"done",failed:"failed",stopped:"stopped"};function Dc(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:Ic(o),isPlaceholder:!1,placeholderState:void 0,parts:o}});return{...e,messages:o}}var Pc=(e,t)=>{const n=[...e.parts,{type:"text",content:t}];return{...e,content:Ic(n),parts:n}},Nc=(e,t)=>({...Rc(Pc(e,t)),placeholderState:void 0,taskStatus:"failed"});function Lc(e,t,n){const r=e.messages.map(e=>e.id===t?Nc(e,n):e);return{...e,messages:r}}var Fc=n(void 0),zc=({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(Fc.Provider,{value:{uiState:t,uiActions:r},children:e})},$c=()=>{const e=s(Fc);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},Bc=n(void 0),Wc=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=$c(),[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?Lc(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(tc(e,o)),void m(nc("This is a preview. In production, I'll respond to your messages here."));const i=Le.getCredentialedConfig();if(!i)return console.error("Config not loaded or incomplete"),void m(nc("Configuration error: Missing API credentials. Please check your widget settings."));r||m(tc(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 Fe.getOrCreateChatId();!function(e,t,n){const r={question:t,mode:n,chat_id:Le.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=lr.getInstance();await s.ready(o),await s.send(i)}(i,e,o,s)}catch(c){console.error("Failed to send message:",c),f(e=>Lc(e,s,"I'm sorry, I encountered an error processing your request. Please try again."))}},[t,m,f]);a(()=>{if(t)return;const e=lr.getInstance(),n=async t=>{const{toolCallId:n,tool:r,args:o,mode:i,explanation:s}=t,a=await Ec.executeTool(r,o,i,s),c=a.success?void 0:a.error??"Tool execution failed";f(e=>function(e,t,n,r,o,i){return{...e,messages:Tc(e.messages,"running"===e.task.phase,o,t,n,r,i)}}(e,r,s,c?"failed":"completed",l.current,c)),c||"done"!==r||f(e=>function(e,t){return Ac(e,t,e=>({...e,taskStatus:"done"}))}(e,l.current)),await e.send({type:"tool/response",tool_call_id:n,success:a.success,data:JSON.stringify(a.data),error:c}).catch(e=>console.error("Failed to send tool response:",e)),a.afterResponseAttempt?.()},o={onMessage:e=>{if("tool/call"===e.type){const t=e.tool_call_id;if(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 _c&&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 Mc(e);const r="running"===e.task.phase?e.task:{phase:"running"},o=t.explanation||"";return{state:{messages:Tc(e.messages,!0,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 Mc(e);const r=t.status,o=e=>t.message?Pc(e,t.message):e;return{state:Ac(e,n,"has_question"===r?e=>({...o(e),placeholderState:"waiting-for-user"}):e=>({...o(e),taskStatus:_c[r]})),effects:[]}}case"chat/delta":return{state:Dc(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:Dc(e,t.request_id,t.text,!1),effects:[]};case"chat/error":return{state:Lc(e,t.request_id,`Error: ${t.error}`),effects:[]};default:return Mc(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 cr&&f(t=>function(e,t){return{messages:e.messages.map(e=>e.isPlaceholder?Nc(e,t):e),task:Oc(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{...Ac(e,t,e=>({...e,taskStatus:"stopped"})),task:{phase:"stopped"}}}(e,l.current)),t||lr.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
+ return b(Bc.Provider,{value:{messages:o.messages,chatActions:E,taskState:o.task,taskActions:I},children:e})},Uc=()=>{const e=s(Bc);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},Hc=n(null),jc=()=>{const{uiState:e}=$c(),{messages:t}=Uc();return a(()=>{const{currentMode:n,isOpen:r}=e;Qa.persist({messages:t,currentMode:n,isOpen:r})},[t,e]),null},qc=({children:e,previewMode:t})=>{const{uiActions:n}=$c(),{chatActions:r}=Uc(),[o,i]=p(!1);return a(()=>{if(t)return;let e=!1;return(async()=>{const{messages:t,...o}=Qa.restore();n.applyState(o),r.setMessages(t),i(!0);const s=await Fe.getOrCreateChatId();e||lr.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(jc,{})]})},Vc=({children:e,previewMode:t=!1})=>/* @__PURE__ */b(zc,{children:/* @__PURE__ */b(Wc,{previewMode:t,children:/* @__PURE__ */b(qc,{previewMode:t,children:e})})}),Yc=/^#?([a-f\d]{3}|[a-f\d]{6})$/i,Kc=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i;function Xc(e){const t=Yc.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=Kc.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 Gc(e){const t=function(e){const t=Xc(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 Jc(e,t){const n=Xc(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}var Zc={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"};function Qc(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:Jc(e.widget_text_color,.6),foregroundFaint:Jc(e.widget_text_color,.4),border:e.widget_border_color,primary:e.widget_accent_color,primaryForeground:Gc(e.widget_accent_color),primaryHover:Jc(e.widget_accent_color,.85),secondary:e.widget_secondary_color,secondaryForeground:"#ffffff",secondaryBg:Jc(e.widget_secondary_color,.2),secondaryHover:Jc(e.widget_secondary_color,.3)},radius:"12px",motion:{durationAnimation:"300ms",durationFade:"200ms"}}}({...Zc,...t})}var el=n(null),tl=()=>{const e=s(el);if(!e)throw new Error("useWidgetConfig must be used within WidgetRoot");return e},nl=()=>{const{uiState:e,uiActions:t}=$c(),{messages:n,chatActions:r,taskState:o,taskActions:s}=Uc(),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])}},rl={bottom_right:{vertical:"bottom",horizontal:"right"},bottom_left:{vertical:"bottom",horizontal:"left"},top_right:{vertical:"top",horizontal:"right"},top_left:{vertical:"top",horizontal:"left"}},ol=Object.keys(rl),il=e=>rl[e],sl=e=>{const{vertical:t,horizontal:n}=il(e);return{[t]:"20px",[n]:"20px"}},al={top:"bottom",bottom:"top",left:"right",right:"left"},cl=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=il(e);return{x:"left"===s?20:t-20-r,y:"top"===i?20:n-20-o}},ll=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}},dl="cubic-bezier(0.16, 1, 0.3, 1)",ul=({onPositionCommit:e})=>{const{isPreviewMode:n=!1,widget_accent_color:r,widget_background_color:o,widget_position:s,widget_position_z_index:a}=tl(),{state:c,actions:d}=nl(),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=cl(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=cl(e,S,k,c.w,c.h),d=cl(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 ${dl}, top 600ms ${dl}`,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=cl(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 ol){const e=cl(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
+ return b(La,{ref:S,className:"mtx-fab-anchor","data-animated":k?"false":"true","data-preview":n?"true":"false",style:{zIndex:a,pointerEvents:h?"none":"auto",...sl(s),...C},children:/* @__PURE__ */v(La,{className:"mtx-fab","data-open":h?"true":"false",children:[g&&/* @__PURE__ */b(La,{className:w,"aria-hidden":!0}),y&&!k&&/* @__PURE__ */b(Da,{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
+ /* @__PURE__ */b(Da,{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(Fa,{className:"mtx-fab-center",children:/* @__PURE__ */v(La,{className:"mtx-fab-badge",style:{borderRadius:"12px",backgroundColor:h?o:r,boxShadow:ma.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})}),
23
+ /* @__PURE__ */b(Fa,{className:"mtx-fab-icon-layer",style:{transform:h?"rotate(30deg) scale(0)":"rotate(0deg) scale(1)",opacity:h?0:1,transitionProperty:"transform, opacity",transitionDuration:"0.16s, 0.08s",transitionTimingFunction:"linear"},"aria-hidden":h,children:/* @__PURE__ */b(Oa,{src:fa,alt:"",className:"mtx-fab-avatar",draggable:!1,onDragStart:e=>e.preventDefault(),style:{borderRadius:"12px",border:"none",outline:"none",backgroundColor:"transparent",pointerEvents:"none",userSelect:"none"}})}),
24
+ /* @__PURE__ */b(Fa,{className:"mtx-fab-icon-layer",style:{transform:h?"rotate(0deg) scale(1)":"rotate(-30deg) scale(0)",opacity:h?1:0,transitionProperty:"transform, opacity",transitionDuration:"0.16s, 0.08s",transitionTimingFunction:"linear"},"aria-hidden":!h,children:/* @__PURE__ */b(Ba,{name:"chevronDown",size:24,className:"mtx-fab-chevron"})})]})})})]})})},pl=/*#__PURE__*/e.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function hl(t){const{children:n,elementsRef:r,labelsRef:o,onMapChange:i}=t,s=jr(i),[,a]=e.useState(!1),c=Or(ml).current,l=Or(fl).current,d=e.useRef(0),u=e.useRef(!0),p=e.useRef([]),h=e.useRef(null),f=jr(()=>{u.current||(u.current=!0,a(e=>!e))}),m=jr((e,t)=>{l.set(e,t),f()}),g=jr(e=>{l.delete(e),f()}),y=jr(e=>{const t=/* @__PURE__ */new Map;return r.current.length=0,o&&(o.current.length=0),e.forEach(e=>{t.set(e.element,{...e.registration.metadata??{},index:e.index}),r.current[e.index]=e.element,o&&(o.current[e.index]=void 0!==e.registration.label?e.registration.label:e.registration.textRef?.current?.textContent??e.element.textContent)}),d.current=r.current.length,t}),v=jr(()=>{const[e,t]=function(e){const t=/* @__PURE__ */new Set,n=[],r=[];e.forEach((e,o)=>{if(!o.isConnected)return;const i=e.index,s={index:i??-1,element:o,registration:e};null===i?r.push(s):i>=0&&(t.add(i),n.push(s))});let o=0;return r.sort((e,t)=>yl(e.element,t.element)),r.forEach(e=>{for(;t.has(o);)o+=1;e.index=o,n.push(e),o+=1}),t.size>0&&n.sort((e,t)=>e.index-t.index),[n,r.map(e=>e.element)]}(l),n=y(e);!function(e){if(h.current?.disconnect(),h.current=null,"function"!=typeof MutationObserver||e.length<2)return;const t=new MutationObserver(n=>{if(!function(e){for(const t of e)for(let e=0;e<t.removedNodes.length;e+=1)if(t.removedNodes[e].isConnected)return!0;return!1}(n))return;let r=null;for(const o of e)if(o.isConnected){if(r&&yl(r,o)>0)return t.disconnect(),void f();r=o}});h.current=t;const n=/* @__PURE__ */new Set;for(let r=1;r<e.length;r+=1){const t=gl(e[r-1],e[r]);t&&n.add(t)}n.forEach(e=>t.observe(e,{childList:!0}))}(t),p.current=e,u.current=!1,c.forEach(e=>e(n)),s(n)});Ar(()=>(u.current||y(p.current),()=>{r.current=[],o&&(o.current=[])}),[r,o,y]),Ar(()=>{u.current&&v()}),Ar(()=>()=>{h.current?.disconnect(),u.current=!0},[]);const w=jr(e=>(c.add(e),()=>{c.delete(e)})),x=e.useMemo(()=>({register:m,unregister:g,subscribeMapChange:w,nextIndexRef:d}),[m,g,w,d]);/*#__PURE__*/
25
+ return b(pl.Provider,{value:x,children:n})}function fl(){/* @__PURE__ */
26
+ return new Map}function ml(){/* @__PURE__ */
27
+ return new Set}function gl(e,t){let n=e.parentElement;for(;n&&!n.contains(t);)n=n.parentElement;return n}function yl(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}var bl=/*#__PURE__*/e.createContext(void 0);function vl(){const t=e.useContext(bl);if(void 0===t)throw new Error(_r(64));return t}var wl={tabActivationDirection:e=>({"data-activation-direction":e})},xl=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,defaultValue:o=0,onValueChange:i,orientation:s="horizontal",render:a,value:c,style:l,...d}=t,u=void 0!==t.defaultValue,p=e.useRef([]),[h,f]=e.useState(()=>/* @__PURE__ */new Map),[m,g]=function({controlled:t,default:n,name:r,state:o="value"}){const{current:i}=e.useRef(void 0!==t),[s,a]=e.useState(n);return[i?t:s,e.useCallback(e=>{i||a(e)},[])]}({controlled:c,default:o,name:"Tabs",state:"value"}),y=void 0!==c,[v,w]=e.useState(()=>/* @__PURE__ */new Map),x=e.useRef(void 0),S=e.useCallback(e=>Sl(v,e),[v]),[k,C]=e.useState(()=>({previousValue:m,tabActivationDirection:"none"})),{previousValue:E,tabActivationDirection:I}=k;let M=I,T=!1;E!==m&&(M=kl(E,m,s,v),T=null!=E&&null!=m&&null==S(m));const R=T?E:m,O=E!==R||I!==M;Ar(()=>{O&&C({previousValue:R,tabActivationDirection:M})},[R,O,M]);const A=jr((e,t)=>{t.activationDirection=kl(m,e,s,v),i?.(e,t),t.isCanceled||g(e)}),_=jr((e,t)=>{i?.(e,ms(t,void 0,void 0,{activationDirection:"none"}))}),D=jr((e,t)=>(f(n=>{const r=new Map(n);return r.set(e,t),r}),()=>{f(n=>{if(n.get(e)!==t)return n;const r=new Map(n);return r.delete(e),r})})),P=e.useCallback(e=>h.get(e),[h]),N=e.useCallback(e=>{for(const t of v.values())if(e===t.value)return t.id},[v]),L=e.useMemo(()=>({getTabElementBySelectedValue:S,getTabIdByPanelValue:N,getTabPanelIdByValue:P,onValueChange:A,orientation:s,registerMountedTabPanel:D,setTabMap:w,tabActivationDirection:M,value:m}),[S,N,P,A,s,D,w,M,m]),F=e.useMemo(()=>{for(const e of v.values())if(e.value===m)return e},[v,m]),z=e.useMemo(()=>{for(const e of v.values())if(!e.disabled)return e.value},[v]),$=e.useRef(!u),B=e.useRef(o),W=e.useRef(u),U=e.useRef(!1);Ar(()=>{if(y)return;function e(e,t){g(e),C({previousValue:e,tabActivationDirection:"none"}),_(e,t),$.current=!1}if(0===v.size)return void(U.current&&null!==m&&!x.current?.isConnected&&e(null,hs));U.current=!0,x.current=v.keys().next().value;const t=F?.disabled,n=null==F&&null!==m;if(t||m!==B.current||(W.current=!1),W.current&&t&&m===B.current)return;const r=$.current;if(t||n){const n=z??null;if(m===n)return void($.current=!1);let o=hs;return r?o=fs:t&&(o="disabled"),void e(n,o)}r&&null!=F&&(_(m,fs),$.current=!1)},[z,y,_,F,g,v,m]);const H=Pi("div",t,{state:{orientation:s,tabActivationDirection:M},ref:n,props:d,stateAttributesMapping:wl});/*#__PURE__*/
28
+ return b(bl.Provider,{value:L,children:/*#__PURE__*/b(hl,{elementsRef:p,children:H})})});function Sl(e,t){for(const[n,r]of e.entries())if(t===r.value)return n;return null}function kl(e,t,n,r){if(null==e||null==t)return"none";const[o,i,s]="horizontal"===n?["left","left","right"]:["top","up","down"],a=Sl(r,e),c=Sl(r,t);if(null==a||null==c)return a===c||"number"!=typeof e&&"string"!=typeof e||typeof e!=typeof t?"none":t>e?s:i;const l=a.getBoundingClientRect()[o],d=c.getBoundingClientRect()[o];return d<l?i:d>l?s:"none"}function Cl(e){return Zi(e,"base-ui")}var El="data-composite-item-active";function Il(t={}){const{guess:n,label:r,metadata:o,textRef:i,index:s}=t,{register:a,unregister:c,subscribeMapChange:l,nextIndexRef:d}=e.useContext(pl),u=e.useRef(-1),[p,h]=e.useState(null==s&&n?()=>{if(-1===u.current){const e=d.current;d.current+=1,u.current=e}return u.current}:-1),f=s??p,m=e.useRef(null),g=e.useCallback(e=>{const t=m.current;t&&c(t),m.current=e,e&&a(e,{metadata:o??null,index:s??null,label:r,textRef:i})},[s,a,c,o,r,i]);return Ar(()=>{if(null==s)return l(e=>{const t=m.current?e.get(m.current)?.index:null;null!=t&&h(t)})},[s,l]),{ref:g,index:f}}var Ml=/*#__PURE__*/e.createContext(void 0),Tl=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,disabled:o=!1,render:i,value:s,id:a,nativeButton:c=!0,style:l,...d}=t,{value:u,getTabPanelIdByValue:p,onValueChange:h,orientation:f,tabActivationDirection:m}=vl(),{activateOnFocus:g,registerTabResizeObserverElement:y,tabsListElement:b}=function(){const t=e.useContext(Ml);if(void 0===t)throw new Error(_r(65));return t}(),{highlightedIndex:v,onHighlightedIndexChange:w}=ss(),x=Cl(a),S=e.useMemo(()=>({disabled:o,id:x,value:s}),[o,x,s]),{compositeProps:k,compositeRef:C,index:E}=function(t={}){const{highlightItemOnHover:n,highlightedIndex:r,onHighlightedIndexChange:o}=ss(),{ref:i,index:s}=Il(t),a=r===s,c=e.useRef(null),l=yi(i,c);return{compositeProps:{tabIndex:a?0:-1,onFocus(){o(s)},onMouseMove(){const e=c.current;if(!n||!e)return;const t=e.hasAttribute("disabled")||"true"===e.ariaDisabled;a||t||e.focus()}},compositeRef:l,index:s}}({metadata:S}),I=s===u,M=e.useRef(!1),T=e.useRef(null),R=jr(e=>{T.current?.(),T.current=e?y(e):null});Ar(()=>{if(M.current)return void(M.current=!1);if(!(I&&E>-1&&v!==E))return;const e=b;if(null!=e){const t=Oo(io(e));if(t&&Ao(e,t))return}o||w(E)},[I,E,v,w,o,b]);const{getButtonProps:O,buttonRef:A}=cs({disabled:o,native:c,focusableWhenDisabled:!0}),_=p(s),D=e.useRef(!1),P=e.useRef(!1);function N(e){h(s,ms(ps,e.nativeEvent,void 0,{activationDirection:"none"}))}return Pi("button",t,{state:{disabled:o,active:I,orientation:f,tabActivationDirection:m},ref:[n,A,C,R],props:[k,{role:"tab","aria-controls":_,"aria-selected":I,id:x,onClick:function(e){I||o||N(e)},onFocus:function(e){I||o||!g||D.current&&!P.current||N(e)},onPointerDown:function(e){if(I||o)return;D.current=!0,P.current=0===e.button;const t=io(e.currentTarget);function n(){D.current=!1,P.current=!1,t.removeEventListener("pointerup",n),t.removeEventListener("pointercancel",n)}t.addEventListener("pointerup",n),t.addEventListener("pointercancel",n)},[El]:I?"":void 0,onKeyDownCapture(){M.current=!0}},d,O],stateAttributesMapping:wl})}),Rl={...wl,...Hi},Ol=/*#__PURE__*/e.forwardRef(function(t,n){const{className:r,value:o,render:i,keepMounted:s=!1,style:a,...c}=t,{value:l,getTabIdByPanelValue:d,orientation:u,tabActivationDirection:p,registerMountedTabPanel:h}=vl(),f=Cl(),{ref:m,index:g}=Il(),y=o===l,{mounted:b,transitionStatus:v,setMounted:w}=Js(y),x=!b,S=d(o),k={hidden:x,orientation:u,tabActivationDirection:p,transitionStatus:v},C=e.useRef(null),E=Pi("div",t,{state:k,ref:[n,m,C],props:[{"aria-labelledby":S,hidden:x,id:f,role:"tabpanel",tabIndex:y?0:-1,inert:Fi(!y),"data-index":g},c],stateAttributesMapping:Rl});return qi({open:y,ref:C,onComplete(){y||w(!1)}}),Ar(()=>{if(null!=f&&(!x||s))return h(o,f)},[x,s,o,f,h]),s||b?E:null}),Al="ArrowUp",_l="ArrowDown",Dl="ArrowLeft",Pl="ArrowRight",Nl=/* @__PURE__ */new Set([Al,_l,Dl,Pl,"Home","End"]),Ll=["Shift","Control","Alt","Meta"];function Fl(e){return!(!function(e){return Qr(e)&&"INPUT"===e.tagName}(e)||null==e.selectionStart)||!(!Qr(e)||"TEXTAREA"!==e.tagName)}function zl(e,t,n,r){if(!e||!t||!t.scrollTo)return;let o=e.scrollLeft,i=e.scrollTop;const s=e.clientWidth<e.scrollWidth,a=e.clientHeight<e.scrollHeight;if(s&&"vertical"!==r){const r=$l(e,t,"left"),i=Bl(e),s=Bl(t);"ltr"===n&&(r+t.offsetWidth+s.scrollMarginRight>e.scrollLeft+e.clientWidth-i.scrollPaddingRight?o=r+t.offsetWidth+s.scrollMarginRight-e.clientWidth+i.scrollPaddingRight:r-s.scrollMarginLeft<e.scrollLeft+i.scrollPaddingLeft&&(o=r-s.scrollMarginLeft-i.scrollPaddingLeft)),"rtl"===n&&(r-s.scrollMarginLeft<e.scrollLeft+i.scrollPaddingLeft?o=r-s.scrollMarginLeft-i.scrollPaddingLeft:r+t.offsetWidth+s.scrollMarginRight>e.scrollLeft+e.clientWidth-i.scrollPaddingRight&&(o=r+t.offsetWidth+s.scrollMarginRight-e.clientWidth+i.scrollPaddingRight))}if(a&&"horizontal"!==r){const n=$l(e,t,"top"),r=Bl(e),o=Bl(t);n-o.scrollMarginTop<e.scrollTop+r.scrollPaddingTop?i=n-o.scrollMarginTop-r.scrollPaddingTop:n+t.offsetHeight+o.scrollMarginBottom>e.scrollTop+e.clientHeight-r.scrollPaddingBottom&&(i=n+t.offsetHeight+o.scrollMarginBottom-e.clientHeight+r.scrollPaddingBottom)}e.scrollTo({left:o,top:i,behavior:"auto"})}function $l(e,t,n){const r="left"===n?"offsetLeft":"offsetTop";let o=0;for(;t.offsetParent&&(o+=t[r],t.offsetParent!==e);)t=t.offsetParent;return o}function Bl(e){const t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}var Wl=[];function Ul(t){const{render:n,className:r,style:o,refs:i=Ir,props:s=Ir,state:a=Mr,stateAttributesMapping:c,highlightedIndex:l,onHighlightedIndexChange:d,orientation:u,grid:p,loopFocus:h,onLoop:f,enableHomeAndEndKeys:m,onMapChange:g,stopEventPropagation:y=!0,rootRef:v,disabledIndices:w,modifierKeys:x,highlightItemOnHover:S=!1,tag:k="div",...C}=t,E=e.useContext(aa)?.direction??"ltr",{props:I,highlightedIndex:M,onHighlightedIndexChange:T,elementsRef:R,onMapChange:O,relayKeyboardEvent:A}=function(t){const{loopFocus:n=!0,orientation:r="both",grid:o,onLoop:i,direction:s,highlightedIndex:a,onHighlightedIndexChange:c,rootRef:l,enableHomeAndEndKeys:d=!1,stopEventPropagation:u,disabledIndices:p,modifierKeys:h=Wl}=t,[f,m]=e.useState(0),g=null!=o,y=e.useRef(null),b=yi(y,l),v=e.useRef([]),w=e.useRef(!1),x=a??f,S=jr((e,t=!1)=>{if((c??m)(e),t){const t=v.current[e];zl(y.current,t,s,r)}}),k=jr(e=>{if(0===e.size||w.current)return;w.current=!0;const t=Array.from(e.keys()),n=t.find(e=>e?.hasAttribute("data-composite-item-active"))??null,o=n?e.get(n)?.index??-1:-1;if(-1!==o)S(o);else if(Uo(t,x,p)){const e=Wo(t,{disabledIndices:p});Bo(t,e)||S(e)}zl(y.current,n,s,r)});Ar(()=>{if(null==p||null!=a||!w.current)return;const e=v.current;if(Uo(e,x,p)){const t=Wo(e,{disabledIndices:p});Bo(e,t)||S(t)}},[p,a,x,v,S]);const C=jr((e,t,n)=>i?i(e,t,n,v):n),E=jr(e=>{const t="Home"===e.key||"End"===e.key;if(!Nl.has(e.key)||!d&&t)return;if(function(e,t){for(const n of Ll)if(!t.includes(n)&&e.getModifierState(n))return!0;return!1}(e,h))return;if(!y.current)return;const a="rtl"===s,c=a?Dl:Pl,l=a?Pl:Dl,f="vertical"===r?_l:c,m="vertical"===r?Al:l,b=_o(e.nativeEvent);if(null!=b&&Fl(b)&&null!=(w=b)&&!w.hasAttribute("disabled")&&"true"!==w.getAttribute("aria-disabled")){const t=b.selectionStart,n=b.selectionEnd,r=b.value;if(null==t||e.shiftKey||t!==n)return;if(e.key!==m&&t<r.length)return;if(e.key!==f&&t>0)return}var w;let k=x;const E=function(e,t){return Wo(e.current,{disabledIndices:t})}(v,p),I=function(e,t){return Wo(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}(v,p);null!=o&&(k=o({disabledIndices:p,elementsRef:v,event:e,highlightedIndex:x,loopFocus:n,maxIndex:I,minIndex:E,onLoop:C,orientation:r,rtl:a}));const M="vertical"!==r&&e.key===c||"horizontal"!==r&&"ArrowDown"===e.key,T="vertical"!==r&&e.key===l||"horizontal"!==r&&"ArrowUp"===e.key;d&&("Home"===e.key?k=E:"End"===e.key&&(k=I)),k===x&&(M||T)&&(n&&k===I&&M?(k=E,i&&(k=i(e,x,k,v))):n&&k===E&&T?(k=I,i&&(k=i(e,x,k,v))):k=Wo(v.current,{startingIndex:k,decrement:T,disabledIndices:p})),k===x||Bo(v.current,k)||(u&&e.stopPropagation(),(g||t||M||T)&&e.preventDefault(),S(k,!0),queueMicrotask(()=>{v.current[k]?.focus()}))});return{props:{ref:b,onFocus(e){const t=y.current,n=_o(e.nativeEvent);t&&null!=n&&Fl(n)&&n.setSelectionRange(0,n.value.length)},onKeyDown:E},highlightedIndex:x,onHighlightedIndexChange:S,elementsRef:v,onMapChange:k,relayKeyboardEvent:E}}({grid:p,loopFocus:h,onLoop:f,orientation:u,highlightedIndex:l,onHighlightedIndexChange:d,rootRef:v,stopEventPropagation:y,enableHomeAndEndKeys:m,direction:E,disabledIndices:w,modifierKeys:x}),_=Pi(k,t,{state:a,ref:i,props:[I,...s,C],stateAttributesMapping:c}),D=e.useMemo(()=>({highlightedIndex:M,onHighlightedIndexChange:T,highlightItemOnHover:S,relayKeyboardEvent:A}),[M,T,S,A]);/*#__PURE__*/
29
+ return b(is.Provider,{value:D,children:/*#__PURE__*/b(hl,{elementsRef:R,onMapChange:e=>{g?.(e),O(e)},children:_})})}var Hl=/*#__PURE__*/e.forwardRef(function(t,n){const{activateOnFocus:r=!1,className:o,loopFocus:i=!0,render:s,style:a,...c}=t,{orientation:l,setTabMap:d,tabActivationDirection:u}=vl(),[p,h]=e.useState(0),[f,m]=e.useState(null),g=e.useRef(/* @__PURE__ */new Set),y=e.useRef(/* @__PURE__ */new Set),v=e.useRef(null);Ar(()=>{if("undefined"==typeof ResizeObserver)return;const e=new ResizeObserver(()=>{g.current.forEach(e=>{e()})});return v.current=e,f&&e.observe(f),y.current.forEach(t=>{e.observe(t)}),()=>{e.disconnect(),v.current=null}},[f]);const w=jr(e=>(g.current.add(e),()=>{g.current.delete(e)})),x=jr(e=>(y.current.add(e),v.current?.observe(e),()=>{y.current.delete(e),v.current?.unobserve(e)})),S={orientation:l,tabActivationDirection:u},k={"aria-orientation":"vertical"===l?"vertical":void 0,role:"tablist"},C=e.useMemo(()=>({activateOnFocus:r,registerIndicatorUpdateListener:w,registerTabResizeObserverElement:x,tabsListElement:f}),[r,w,x,f]);/*#__PURE__*/
30
+ return b(Ml.Provider,{value:C,children:/*#__PURE__*/b(Ul,{render:s,className:o,style:a,state:S,refs:[n,m],props:[k,c],stateAttributesMapping:wl,highlightedIndex:p,enableHomeAndEndKeys:!0,loopFocus:i,orientation:l,onHighlightedIndexChange:h,onMapChange:d,disabledIndices:Ir})})});function jl(e){const t=e.getRootNode();return(t instanceof ShadowRoot?t.activeElement:document.activeElement)??null}function ql(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent&&!e.hasAttribute("aria-hidden"))}function Vl(e,t,n){return Math.min(Math.max(e,t),n)}function Yl({width:e,height:t}){return{width:Vl(e,280,600),height:Vl(t,320,Math.floor(.85*window.innerHeight))}}function Kl(e,t){const n=/^\s*(\d+(?:\.\d+)?)px\s*$/.exec(e??"");return n?Number(n[1]):t}var Xl=({title:e,subtitle:t,onClose:n,controls:r})=>/* @__PURE__ */v(Fa,{align:"center",justify:"between",paddingX:"lg",paddingY:"md",border:"bottom",shrink:!1,elevation:"section",children:[/* @__PURE__ */v(Fa,{align:"center",gap:"md",minWidth:"0",grow:!0,children:[/* @__PURE__ */b(Oa,{src:fa,alt:"",size:"md",rounded:"lg",elevation:"card"}),/* @__PURE__ */v(Ua,{minWidth:"0",children:[/* @__PURE__ */b(Va,{size:"sm",weight:"semibold",truncate:!0,leading:"tight",children:e}),null!=t&&/* @__PURE__ */b(Va,{as:"p",size:"xs",variant:"muted",truncate:!0,children:t})]})]}),/* @__PURE__ */v(Fa,{align:"center",gap:"2xs",shrink:!1,children:[r,/* @__PURE__ */b(Wa,{size:"sm",label:"Close",onClick:n,children:/* @__PURE__ */b(Ba,{name:"close",size:16})})]})]});function Gl(e){const t=u(e);return t.current=e,t}function Jl(...e){return t=>{e.forEach(e=>{"function"==typeof e?e(t):e&&(e.current=t)})}}function Zl({value:e,onChange:t,onSubmit:n,modes:r=[],activeMode:o,onModeChange:s,disabled:c=!1,taskRunning:l=!1,onStop:d,ref:p}){const h=u(null);a(()=>{const e=h.current;if(!e)return;e.style.height="auto";const{scrollHeight:t}=e;e.style.height=`${Math.min(t,66)}px`,e.style.overflowY=t>66?"auto":"hidden"},[e]);const f=i(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),n())},[n]),m=Boolean(e.trim())&&!c;/* @__PURE__ */
31
+ return v(Ua,{background:"card",rounded:"xl",border:!0,overflow:"hidden",className:"mtx-composer",children:[/* @__PURE__ */b("textarea",{ref:Jl(h,p),value:e,onChange:e=>t(e.target.value),onKeyDown:f,placeholder:"Ask anything",disabled:c,rows:1,className:"mtx-composer-input",style:{lineHeight:"20px",paddingTop:"4px",paddingBottom:"2px",minHeight:"unset"}}),/* @__PURE__ */v(Fa,{align:"center",justify:"between",paddingX:"sm",paddingTop:"xs",paddingBottom:"sm",children:[/* @__PURE__ */b(Fa,{align:"center",gap:"xs",children:r.map(e=>{const t=o===e.id;/* @__PURE__ */
32
+ return v("button",{type:"button",className:"mtx-mode-chip","data-active":t?"true":"false",onClick:t=>{t.preventDefault(),t.stopPropagation(),s?.(e.id)},children:[/* @__PURE__ */b(Ba,{name:e.icon,size:12}),/* @__PURE__ */b(Va,{as:"span",inheritColor:!0,children:e.label})]},e.id)})}),/* @__PURE__ */b(Wa,{variant:l?"secondary":"primary",size:"sm",disabled:!l&&!m,label:l?"Stop the assistant":"Send message",onClick:e=>{e.preventDefault(),e.stopPropagation(),l&&d?d():n()},children:/* @__PURE__ */b(Ba,l?{name:"stop",size:14}:{name:"send",size:16})})]})]})}var Ql=/*#__PURE__*/e.createContext(void 0);function ed(t){const n=e.useContext(Ql);if(!t&&void 0===n)throw new Error(_r(27));return n}var td=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,forceRender:i=!1,...s}=e,a=ed(),c=a.useState("open"),l=a.useState("nested"),d=a.useState("mounted");return Pi("div",e,{state:{open:c,transitionStatus:a.useState("transitionStatus")},ref:[a.context.backdropRef,t],stateAttributesMapping:pa,props:[{role:"presentation",hidden:!d,style:{userSelect:"none",WebkitUserSelect:"none"}},s],enabled:i||!l})}),nd=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,...s}=e,a=ed(),c=Cl(i);return a.useSyncedValueWithCleanup("descriptionElementId",c),Pi("p",e,{ref:t,props:[{id:c},s]})}),rd=/*#__PURE__*/e.createContext(void 0),od={...ua,...Hi,nestedDialogOpen:e=>e?{"data-nested-dialog-open":""}:null},id=/*#__PURE__*/e.forwardRef(function(t,n){const{render:r,className:o,style:i,finalFocus:s,initialFocus:a,...c}=t,l=ed(),d=l.useState("descriptionElementId"),u=l.useState("disablePointerDismissal"),p=l.useState("floatingRootContext"),h=l.useState("popupProps"),f=l.useState("modal"),m=l.useState("mounted"),g=l.useState("nested"),y=l.useState("nestedOpenDialogCount"),v=l.useState("open"),w=l.useState("openMethod"),x=l.useState("titleElementId"),S=l.useState("transitionStatus"),k=l.useState("role"),C=p.useState("floatingId");!function(){if(void 0===e.useContext(rd))throw new Error(_r(26))}(),qi({open:v,ref:l.context.popupRef,onComplete(){v&&l.context.onOpenChangeComplete?.(!0)}});const E=void 0===a?(I=l.context.popupRef,e=>"touch"!==e||I.current):a;var I;const M=y>0,T=l.useStateSetter("popupElement"),R=Pi("div",t,{state:{open:v,nested:g,transitionStatus:S,nestedDialogOpen:M},props:[h,{id:C,"aria-labelledby":x,"aria-describedby":d,role:k,...Zs,hidden:!m,onKeyDown(e){Nl.has(e.key)&&e.stopPropagation()},style:{"--nested-dialogs":y}},c],ref:[n,l.context.popupRef,T],stateAttributesMapping:od});/*#__PURE__*/
33
+ return b(Ys,{context:p,openInteractionType:w,disabled:!m,closeOnFocusOut:!u,initialFocus:E,returnFocus:s,modal:!1!==f,restoreFocus:"popup",children:R})}),sd=/*#__PURE__*/e.forwardRef(function(e,t){const{cutout:n,...r}=e;let o;if(n){const e=n.getBoundingClientRect();o=`polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${e.left}px ${e.top}px,${e.left}px ${e.bottom}px,${e.right}px ${e.bottom}px,${e.right}px ${e.top}px,${e.left}px ${e.top}px)`}/*#__PURE__*/
34
+ return b("div",{ref:t,role:"presentation","data-base-ui-inert":"",...r,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:o}})}),ad=/*#__PURE__*/e.forwardRef(function(e,t){const{keepMounted:n=!1,...r}=e,o=ed(),i=o.useState("mounted"),s=o.useState("modal"),a=o.useState("open");return i||n?/*#__PURE__*/b(rd.Provider,{value:n,children:/*#__PURE__*/v(xs,{ref:t,...r,children:[i&&!0===s&&/*#__PURE__*/b(sd,{ref:o.context.internalBackdropRef,inert:Fi(!a)}),e.children]})}):null}),cd={},ld={},dd="";function ud(e,t){return function(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=no(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&"inline"!==o&&"contents"!==o}(e)?e:t}function pd(e,t,n){return/hidden|clip/.test(e.getComputedStyle(ud(t,n)).overflowY)}var hd=new class{lockCount=0;restore=null;timeoutLock=po.create();timeoutUnlock=po.create();acquire(e){return this.lockCount+=1,1===this.lockCount&&null===this.restore&&this.timeoutLock.start(0,()=>this.lock(e)),this.release}release=()=>{this.lockCount-=1,0===this.lockCount&&this.restore&&this.timeoutUnlock.start(0,this.unlock)};unlock=()=>{0===this.lockCount&&this.restore&&(this.restore?.(),this.restore=null)};lock(e){if(0===this.lockCount||null!==this.restore)return;const t=io(e),n=t.documentElement,r=t.body,o=Gr(n);if(pd(o,n,r)){const t=new o.MutationObserver(()=>{pd(o,n,r)||(t.disconnect(),this.restore=null,this.lock(e))}),i={attributes:!0};return t.observe(n,i),t.observe(r,i),void(this.restore=()=>t.disconnect())}const i=xo||!function(e){if("undefined"==typeof document)return!1;const t=io(e);return Gr(t).innerWidth-t.documentElement.clientWidth>0}(e);this.restore=i?function(e){const t=io(e),n=ud(t.documentElement,t.body),r={overflowY:n.style.overflowY,overflowX:n.style.overflowX};return Object.assign(n.style,{overflowY:"hidden",overflowX:"hidden"}),()=>{Object.assign(n.style,r)}}(e):function(e){const t=io(e),n=t.documentElement,r=t.body,o=Gr(n);let i=0,s=0,a=!1;const c=lo.create();if(Io&&1!==(o.visualViewport?.scale??1))return()=>{};function l(){const t=o.getComputedStyle(n),c=o.getComputedStyle(r),l=(t.scrollbarGutter||"").includes("both-edges")?"stable both-edges":"stable";i=n.scrollTop,s=n.scrollLeft,cd={scrollbarGutter:n.style.scrollbarGutter,overflowY:n.style.overflowY,overflowX:n.style.overflowX},dd=n.style.scrollBehavior,ld={position:r.style.position,height:r.style.height,width:r.style.width,boxSizing:r.style.boxSizing,overflowY:r.style.overflowY,overflowX:r.style.overflowX,scrollBehavior:r.style.scrollBehavior};const d=n.scrollHeight>n.clientHeight,u=n.scrollWidth>n.clientWidth,p="scroll"===t.overflowY||"scroll"===c.overflowY,h="scroll"===t.overflowX||"scroll"===c.overflowX,f=Math.max(0,o.innerWidth-r.clientWidth),m=Math.max(0,o.innerHeight-r.clientHeight),g=parseFloat(c.marginTop)+parseFloat(c.marginBottom),y=parseFloat(c.marginLeft)+parseFloat(c.marginRight),b=ud(n,r);if(a=function(e){if("undefined"==typeof CSS||!CSS.supports||!CSS.supports("scrollbar-gutter","stable")||"undefined"==typeof document)return!1;const t=io(e),n=t.documentElement,r=ud(n,t.body),o=r.style.overflowY,i=n.style.scrollbarGutter;n.style.scrollbarGutter="stable",r.style.overflowY="scroll";const s=r.offsetWidth;r.style.overflowY="hidden";const a=r.offsetWidth;return r.style.overflowY=o,n.style.scrollbarGutter=i,s===a}(e),a)return n.style.scrollbarGutter=l,b.style.overflowY="hidden",void(b.style.overflowX="hidden");Object.assign(n.style,{scrollbarGutter:l,overflowY:"hidden",overflowX:"hidden"}),(d||p)&&(n.style.overflowY="scroll"),(u||h)&&(n.style.overflowX="scroll"),Object.assign(r.style,{position:"relative",height:g||m?`calc(100dvh - ${g+m}px)`:"100dvh",width:y||f?`calc(100vw - ${y+f}px)`:"100vw",boxSizing:"border-box",overflowY:"hidden",overflowX:"hidden",scrollBehavior:"unset"}),r.scrollTop=i,r.scrollLeft=s,n.setAttribute("data-base-ui-scroll-locked",""),n.style.scrollBehavior="unset"}function d(){Object.assign(n.style,cd),Object.assign(r.style,ld),a||(n.scrollTop=i,n.scrollLeft=s,n.removeAttribute("data-base-ui-scroll-locked"),n.style.scrollBehavior=dd)}l();const u=so(o,"resize",function(){d(),c.request(l)});return()=>{c.cancel(),d(),"function"==typeof o.removeEventListener&&u()}}(e)}};function fd({store:t,parentContext:n,isDrawer:r}){const o=t.useState("open"),i=t.useState("disablePointerDismissal"),s=t.useState("modal"),a=t.useState("popupElement"),c=t.useState("floatingRootContext"),[l,d]=e.useState(0),[u,p]=e.useState(0),h=0===l,f=function(t,n={}){const{enabled:r=!0,escapeKey:o=!0,outsidePress:i=!0,outsidePressEvent:s="sloppy",referencePress:a=Ks,bubbles:c,externalTree:l}=n,d="rootStore"in t?t.rootStore:t,u=d.useState("open"),p=d.useState("floatingElement"),{dataRef:h}=d.context,f=Ws(l),m=jr("function"==typeof i?i:()=>!1),g="function"==typeof i?m:i,y=!1!==g,b=jr(()=>s),{escapeKey:v,outsidePress:w}={escapeKey:"boolean"==typeof(x=c)?x:x?.escapeKey??!1,outsidePress:"boolean"==typeof x?x:x?.outsidePress??!0};var x;const S=e.useRef(!1),k=e.useRef(!1),C=e.useRef(!1),E=e.useRef(!1),I=e.useRef(""),M=e.useRef(null),T=ho(),R=ho(),O=jr(()=>{R.clear(),h.current.insideReactTree=!1}),A=jr(e=>{const t=h.current.floatingContext?.nodeId;return(f?zo(f.nodesRef.current,t):[]).some(t=>t.context?.open&&!t.context.dataRef.current[e])}),_=jr(e=>Do(e,d.select("floatingElement"))||Do(e,d.select("domReferenceElement"))),D=jr(e=>{a()&&d.setOpen(!1,ms("trigger-press",e.nativeEvent))}),P=jr(e=>{if(!u||!r||!o||"Escape"!==e.key)return;if(E.current)return;if(!v&&A("__escapeKeyBubbles"))return;const t=ms("escape-key",function(e){return"nativeEvent"in e}(e)?e.nativeEvent:e);d.setOpen(!1,t),t.isCanceled||e.preventDefault(),v||t.isPropagationAllowed||e.stopPropagation()}),N=jr(()=>{h.current.insideReactTree=!0,R.start(0,O)}),L=jr(e=>{if(!u||!r||0!==e.button)return;const t=_o(e.nativeEvent);Ao(d.select("floatingElement"),t)&&(S.current||(S.current=!0,k.current=!1))}),F=jr(e=>{u&&r&&(e.defaultPrevented||e.nativeEvent.defaultPrevented)&&S.current&&(k.current=!0)});e.useEffect(()=>{if(!u||!r)return O;h.current.__escapeKeyBubbles=v,h.current.__outsidePressBubbles=w;const e=new po,t=new po;function n(){C.current=!0,t.start(0,()=>{C.current=!1})}function i(){S.current=!1,k.current=!1}function s(){const e=I.current,t="pen"!==e&&e?e:"mouse",n=b(),r="function"==typeof n?n():n;return"string"==typeof r?r:r[t]}function a(e){const t=h.current.floatingContext?.nodeId,n=f&&zo(f.nodesRef.current,t).some(t=>Do(e,t.context?.elements.floating));return _(e)||n}function c(e){if(function(e){const t=s();return"intentional"===t&&"click"!==e.type||"sloppy"===t&&"click"===e.type}(e))return"click"===e.type||_(e)||(t.clear(),C.current=!1),void O();if(h.current.insideReactTree)return void O();const n=_o(e),r=`[${gs("inert")}]`,o=Zr(n)?n.getRootNode():null,i=Array.from((eo(o)?o:io(d.select("floatingElement"))).querySelectorAll(r)),c=d.context.triggerElements;if(n&&(c.hasElement(n)||c.hasMatchingElement(e=>Ao(e,n))))return;let l=Zr(n)?n:null;for(;l&&!to(l);){const e=ro(l);if(to(e)||!Zr(e))break;l=e}if(!i.length||!Zr(n)||n.matches("html,body")||Ao(n,d.select("floatingElement"))||!i.every(e=>!Ao(l,e))){if(Qr(n)&&!("touches"in e)){const t=to(n),r=no(n),o=/auto|scroll/,i=t||o.test(r.overflowX),s=t||o.test(r.overflowY),a=i&&n.clientWidth>0&&n.scrollWidth>n.clientWidth,c=s&&n.clientHeight>0&&n.scrollHeight>n.clientHeight,l="rtl"===r.direction,d=c&&(l?e.offsetX<=n.offsetWidth-n.clientWidth:e.offsetX>n.clientWidth),u=a&&e.offsetY>n.clientHeight;if(d||u)return}if(!a(e))return"intentional"===s()&&C.current?(t.clear(),void(C.current=!1)):void(("function"!=typeof g||g(e))&&(A("__outsidePressBubbles")||(d.setOpen(!1,ms("outside-press",e)),O())))}}function l(e){if("sloppy"!==s()||!d.select("open")||!r||_(e))return;const t=e.touches[0];t&&(M.current={startTime:Date.now(),startX:t.clientX,startY:t.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},T.start(1e3,()=>{M.current&&(M.current.dismissOnTouchEnd=!1,M.current.dismissOnMouseDown=!1)}))}function m(e,t){const n=_o(e);if(!n)return;const r=so(n,e.type,()=>{t(e),r()})}function x(e){T.clear(),"pointerdown"===e.type&&(I.current=e.pointerType),"mousedown"===e.type&&M.current&&!M.current.dismissOnMouseDown||m(e,e=>{"pointerdown"===e.type?function(e){"sloppy"===s()&&"touch"!==e.pointerType&&d.select("open")&&r&&!_(e)&&c(e)}(e):c(e)})}function R(e){if(!S.current)return;const r=k.current;i(),"intentional"===s()&&("pointercancel"!==e.type?a(e)||(r?n():("function"!=typeof g||g(e))&&(t.clear(),C.current=!0,O())):r&&n())}function D(e){if("sloppy"!==s()||!M.current||_(e))return;const t=e.touches[0];if(!t)return;const n=Math.abs(t.clientX-M.current.startX),r=Math.abs(t.clientY-M.current.startY),o=Math.sqrt(n*n+r*r);o>5&&(M.current.dismissOnTouchEnd=!0),o>10&&(c(e),T.clear(),M.current=null)}function N(e){"sloppy"===s()&&M.current&&!_(e)&&(M.current.dismissOnTouchEnd&&c(e),T.clear(),M.current=null)}const L=io(p),F=oo(o&&oo(so(L,"keydown",P),so(L,"compositionstart",function(){e.clear(),E.current=!0}),so(L,"compositionend",function(){e.start(Io?5:0,()=>{E.current=!1})})),y&&oo(so(L,"click",x,!0),so(L,"pointerdown",x,!0),so(L,"pointerup",R,!0),so(L,"pointercancel",R,!0),so(L,"mousedown",x,!0),so(L,"mouseup",R,!0),so(L,"touchstart",function(e){I.current="touch",m(e,l)},!0),so(L,"touchmove",function(e){m(e,D)},!0),so(L,"touchend",function(e){m(e,N)},!0)));return()=>{F(),e.clear(),t.clear(),i(),C.current=!1,O()}},[h,p,o,y,g,u,r,v,w,P,O,b,A,_,f,d,T]);const z=e.useMemo(()=>({onKeyDown:P,onPointerDown:D,onClick:D}),[P,D]),$=e.useMemo(()=>({onKeyDown:P,onPointerDown:F,onMouseDown:F,onClickCapture:N,onMouseDownCapture(e){N(),L(e)},onPointerDownCapture(e){N(),L(e)},onMouseUpCapture:N,onTouchEndCapture:N,onTouchMoveCapture:N}),[P,N,L,F]);return e.useMemo(()=>r?{reference:z,floating:$,trigger:z}:{},[r,z,$])}(c,{outsidePressEvent:()=>t.context.internalBackdropRef.current||t.context.backdropRef.current?"intentional":{mouse:"trap-focus"===s?"sloppy":"intentional",touch:"sloppy"},outsidePress(e){if(!t.context.outsidePressEnabledRef.current)return!1;if("button"in e&&0!==e.button)return!1;if("touches"in e)if("touchend"===e.type){if(1!==e.changedTouches.length||0!==e.touches.length)return!1}else if(1!==e.touches.length)return!1;const n=_o(e);if(h&&!i){if(s){const e=t.context.internalBackdropRef.current,r=t.context.backdropRef.current;return!e&&!r||e===n||r===n||Ao(n,a)&&!n?.hasAttribute("data-base-ui-portal")}return!0}return!1},escapeKey:h});return function(e=!0,t=null){Ar(()=>{if(e)return hd.acquire(t)},[e,t])}(o&&!0===s,a),t.useContextCallback("onNestedDialogOpen",(e,t)=>{d(e),p(t)}),Ar(()=>(n?.onNestedDialogOpen&&(o?n.onNestedDialogOpen(l+1,u+(r?1:0)):n.onNestedDialogOpen(0,0)),()=>{n?.onNestedDialogOpen&&o&&n.onNestedDialogOpen(0,0)}),[r,o,l,u,n]),function(e,t){e.useSyncedValues(t),Ar(()=>()=>{e.update({activeTriggerProps:Mr,inactiveTriggerProps:Mr,popupProps:Mr})},[e])}(t,{activeTriggerProps:f.reference,inactiveTriggerProps:f.trigger,popupProps:f.floating,nestedOpenDialogCount:l,nestedOpenDrawerCount:u}),null}var md={...sa,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role},gd=class extends Yr{constructor(t,n,r){const o=new ea,i=function(e,t,n,r=!1){const o={open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:new Gs({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:new ea,floatingId:void 0,syncOnly:!1,nested:!1,onOpenChange:void 0}),floatingId:void 0,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:Mr,inactiveTriggerProps:Mr,popupProps:Mr,modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e};return o.floatingRootContext=function(e,t,n=!1){return new Gs({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:e,floatingId:t,syncOnly:!0,nested:n,onOpenChange:void 0})}(t,n,r),o}(t,o,n,r);super(i,function(t){return{popupRef:/*#__PURE__*/e.createRef(),backdropRef:/*#__PURE__*/e.createRef(),internalBackdropRef:/*#__PURE__*/e.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:t,onOpenChange:void 0,onOpenChangeComplete:void 0}}(o),md)}setOpen=(e,t)=>{if(t.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},e||null!=t.trigger||null==this.state.activeTriggerId||(t.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);const n={open:e};!function(e,t,n,r=!1){t?e.preventUnmountingOnClose=!1:r&&(e.preventUnmountingOnClose=!0);const o=n?.id??null;(o||t)&&(e.activeTriggerId=o,e.activeTriggerElement=n??null)}(n,e,t.trigger),this.update(n)}};function yd(t){return function(t,n){const{children:r,open:o,defaultOpen:i=!1,onOpenChange:s,onOpenChangeComplete:a,disablePointerDismissal:c=!1,modal:l=!0,actionsRef:d,handle:u,triggerId:p,defaultTriggerId:h=null}=n,f="drawer"===t,m="alert-dialog"===t,g=!!m||l,y=m||c,w=m?"alertdialog":"dialog",x=ed(!0),S={modal:g,disablePointerDismissal:y,nested:null!=x,role:w},k=function(t,n=!1){const r=Zi(),o=null!=(e.useContext($s)?.id||null),i=Or(()=>t(r,o)).current;return function(t){const{popupStore:n,treatPopupAsFloatingElement:r=!1,floatingRootContext:o,floatingId:i,nested:s,onOpenChange:a}=t,c=n.useState("open"),l=n.useState("activeTriggerElement"),d=n.useState(r?"popupElement":"positionerElement"),u=n.context.triggerElements,p=a,h=e.useRef(null);void 0===o&&null===h.current&&(h.current=new Gs({open:c,transitionStatus:void 0,referenceElement:l,floatingElement:d,triggerElements:u,onOpenChange:p,floatingId:i,syncOnly:!0,nested:s}));const f=o??h.current;n.useSyncedValue("floatingId",i),Ar(()=>{const e={open:c,floatingId:i,referenceElement:l,floatingElement:d};Zr(l)&&(e.domReferenceElement=l),f.state.positionReference===f.state.referenceElement&&(e.positionReference=l),f.update(e)},[c,i,l,d,f]),f.context.onOpenChange=p,f.context.nested=s}({popupStore:i,treatPopupAsFloatingElement:n,floatingRootContext:i.state.floatingRootContext,floatingId:r,nested:o,onOpenChange:i.setOpen}),i}((e,t)=>new gd({open:i,openProp:o,activeTriggerId:h,triggerIdProp:p,...S},e,t),!0);k.useControlledProp("openProp",o),k.useControlledProp("triggerIdProp",p),k.useSyncedValues(S),k.useContextCallback("onOpenChange",s),k.useContextCallback("onOpenChangeComplete",a);const C=k.useState("open"),E=k.useState("mounted"),I=k.useState("payload");!function(e,t){Ar(()=>{t||null===e.state.openMethod||e.set("openMethod",null)},[t,e]),Ar(()=>()=>{null!==e.state.openMethod&&e.set("openMethod",null)},[e])}(k,C),function(t,n={}){const{closeOnActiveTriggerUnmount:r=!1}=n,o=e.useRef(null),i=t.useState("open"),s=t.useState("triggerCount"),a=t.useState("activeTriggerId"),c=t.useState("activeTriggerElement");Ar(()=>{if(!i)return o.current=null,void(0!==t.state.triggerCount&&t.set("triggerCount",0));const e=t.context.triggerElements.size,n={};t.state.triggerCount!==e&&(n.triggerCount=e);const s=t.select("activeTriggerId");let a=null;if(s){const e=t.context.triggerElements.getById(s);if(e)o.current=s,e!==t.state.activeTriggerElement&&(n.activeTriggerElement=e);else{for(const[e,r]of t.context.triggerElements.entries())if(r===t.state.activeTriggerElement){n.activeTriggerId=e,n.activeTriggerElement=r,o.current=e;break}void 0===n.activeTriggerId&&(o.current===s?a=s:o.current=null)}}else o.current=null;if(!a&&!s&&1===e){const e=t.context.triggerElements.entries().next();if(!e.done){const[t,r]=e.value;n.activeTriggerId=t,n.activeTriggerElement=r,o.current=t}}void 0===n.triggerCount&&void 0===n.activeTriggerId&&void 0===n.activeTriggerElement||t.update(n),a&&r&&queueMicrotask(()=>{if(t.select("open")&&t.select("activeTriggerId")===a&&!t.context.triggerElements.getById(a)){const e=ms(ps);t.setOpen(!1,e),e.isCanceled||t.update({activeTriggerId:null,activeTriggerElement:null})}})},[i,t,s,a,c,r])}(k);const{forceUnmount:M}=function(e,t){const{mounted:n,setMounted:r,transitionStatus:o}=Js(e),i=t.useState("preventUnmountingOnClose"),s=!e&&i;t.useSyncedValues({mounted:n,transitionStatus:o,preventUnmountingOnClose:s});const a=jr(()=>{r(!1),t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),t.context.onOpenChangeComplete?.(!1)});return qi({enabled:n&&!e&&!s,open:e,ref:t.context.popupRef,onComplete(){e||a()}}),{forceUnmount:a,transitionStatus:o}}(C,k);e.useImperativeHandle(d,()=>({unmount:M,close:()=>k.setOpen(!1,ms("imperative-action"))}),[M,k]);const T=C||E;/*#__PURE__*/
35
+ return v(Ql.Provider,{value:k,children:[u&&/*#__PURE__*/b(Qs,{handle:u,store:k}),T&&/*#__PURE__*/b(fd,{store:k,parentContext:x?.context,isDrawer:f}),"function"==typeof r?r({payload:I}):r]})}("dialog",t)}var bd=/*#__PURE__*/e.forwardRef(function(e,t){const{render:n,className:r,style:o,id:i,...s}=e,a=ed(),c=Cl(i);return a.useSyncedValueWithCleanup("titleElementId",c),Pi("h2",e,{ref:t,props:[{id:c},s]})}),vd=({open:e,onClose:t,title:n,description:r,onConfirm:o,confirmLabel:i="Confirm",cancelLabel:a="Cancel",finalFocusRef:c})=>{const l=s(Hc)??document.body;/* @__PURE__ */
36
+ return b(yd,{open:e,onOpenChange:(e,n)=>{e||"none"===n.reason||t()},children:/* @__PURE__ */v(ad,{container:l,children:[/* @__PURE__ */b(td,{className:"mtx-dialog-backdrop",style:{zIndex:xa}}),/* @__PURE__ */v(id,{className:"mtx-dialog-popup",finalFocus:c,style:{...wa("panel"),zIndex:xa},children:[
37
+ /* @__PURE__ */b(bd,{className:"mtx-dialog-title",children:n}),null!=r&&/* @__PURE__ */b(nd,{className:"mtx-dialog-description",children:r}),
38
+ /* @__PURE__ */v(Fa,{gap:"md",justify:"end",children:[/* @__PURE__ */b(Da,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),t()},children:a}),/* @__PURE__ */b(Da,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),o?.()},children:i})]})]})]})})},wd={sm:{width:"14px",height:"14px",borderWidth:"1.5px"},md:{width:"20px",height:"20px",borderWidth:"2px"},lg:{width:"24px",height:"24px",borderWidth:"2px"}};function xd({size:e="md",style:t,ref:n}){/* @__PURE__ */
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:wd[e]}),/* @__PURE__ */b("span",{className:"mtx-visually-hidden",children:"Loading"})]})}var Sd=({isWaitingForUser:e})=>/* @__PURE__ */v(Fa,{align:"center",gap:"sm",paddingY:"2xs",children:[/* @__PURE__ */b(xd,{size:"sm"}),/* @__PURE__ */b(Va,{as:"span",size:"xs",weight:"normal",variant:"faint",children:e?"Waiting for you to complete the action":"Thinking"})]}),kd=({message:e,isLastMessage:t})=>{const{isTaskRunning:n}=nl().state,r="waiting-for-user"===e.placeholderState,o=n&&t&&("show"===e.mode||"do"===e.mode);return e.parts.length>0?/* @__PURE__ */v(Ua,{gap:"sm",children:[e.parts.map((e,t)=>"text"===e.type?e.content?/* @__PURE__ */b(Va,{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(Fa,{align:"start",gap:"md",children:/* @__PURE__ */b(Va,{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(Sd,{isWaitingForUser:r})]}):e.isPlaceholder||n&&t&&("show"===e.mode||"do"===e.mode)?/* @__PURE__ */b(Sd,{isWaitingForUser:r}):/* @__PURE__ */b(La,{})},Cd={done:{name:"checkCircle",opacity:1},failed:{name:"exclamationCircle",opacity:.75},stopped:{name:"circle",opacity:.5}},Ed=({status:e})=>{const{name:t,opacity:n}=Cd[e];/* @__PURE__ */
40
+ return b(Ba,{name:t,size:14,style:{color:Jc(tl().widget_accent_color,n),flexShrink:0}})},Id="8px 8px 0 0",Md=({label:e,children:t})=>/* @__PURE__ */b(Fa,{position:"absolute",inset:"0",align:"center",justify:"center",style:{backgroundColor:"#111827",borderRadius:Id,zIndex:10},children:/* @__PURE__ */v(Fa,{direction:"column",align:"center",gap:"md",style:{textAlign:"center",padding:"0 16px"},children:[t,/* @__PURE__ */b(Va,{as:"span",size:"xs",weight:"medium",style:{color:"rgba(255,255,255,0.7)"},children:e})]})}),Td=({stream:e})=>{const t=u(null),n=u(null),[r,o]=p(!1),[i,s]=p(!1),c=()=>{n.current?.catch(()=>{}),n.current=null};return a(()=>{if(t.current&&e){const r=t.current;o(!1),s(!1),c(),r.srcObject=e;const i=()=>{o(!0)},a=()=>{s(!0),o(!1)};r.addEventListener("loadedmetadata",i),r.addEventListener("error",a);const l=r.play();return n.current=l,l.then(()=>{o(!0)}).catch(e=>{e instanceof Error&&"AbortError"!==e.name&&(console.error("Error playing video stream:",e),s(!0)),n.current=null}),()=>{r.removeEventListener("loadedmetadata",i),r.removeEventListener("error",a)}}return()=>{c(),t.current&&(t.current.srcObject=null),o(!1),s(!1)}},[e]),e?/* @__PURE__ */v(La,{width:"full",overflow:"hidden",position:"relative",style:{marginBottom:"4px",borderRadius:Id,backgroundColor:"#000000",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06)"},children:[!r&&!i&&/* @__PURE__ */b(Md,{label:"Loading stream...",children:/* @__PURE__ */b(xd,{size:"lg",style:{color:"white"}})}),i&&/* @__PURE__ */b(Md,{label:"Failed to load stream",children:/* @__PURE__ */b(Ba,{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:Id,transition:"opacity 500ms",opacity:r?1:0,minHeight:"120px",background:"linear-gradient(135deg, #111827 0%, #374151 100%)"}}),r&&!i&&/* @__PURE__ */v(Fa,{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(Fa,{position:"relative",align:"center",justify:"center",children:[/* @__PURE__ */b(La,{position:"absolute",rounded:"pill",animate:"ping",style:{width:"8px",height:"8px",backgroundColor:"white",opacity:.75}}),/* @__PURE__ */b(La,{position:"relative",rounded:"pill",style:{width:"6px",height:"6px",backgroundColor:"white"}})]}),/* @__PURE__ */b(Va,{as:"span",size:"xs",weight:"semibold",style:{color:"white",textTransform:"uppercase",letterSpacing:"0.05em",fontSize:"10px"},children:"Live"})]}),
42
+ /* @__PURE__ */b(Fa,{position:"absolute",inset:"0",align:"center",justify:"center",style:{borderRadius:Id,backgroundColor:"rgba(0,0,0,0)",zIndex:30,pointerEvents:"none"},children:/* @__PURE__ */b(La,{rounded:"lg",style:{padding:"4px 12px",backgroundColor:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:/* @__PURE__ */b(Va,{as:"div",size:"xs",weight:"medium",style:{color:"white"},children:"Screen Sharing Active"})})})]}):null},Rd=({message:e,index:t,isLastMessage:n,onScreenAccessAllow:r,onScreenAccessDeny:o})=>{if(e.isSystemMessage)/* @__PURE__ */return b(Fa,{justify:"center",align:"center",children:/* @__PURE__ */b(Va,{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
+ return v(Ua,{style:{marginTop:"10px"},role:"article","aria-roledescription":"message","aria-label":i?"You said…":"Agent says…",animate:n?"fadeIn":void 0,children:[/* @__PURE__ */v(Fa,{align:"start",gap:"sm",width:"full",children:[
44
+ /* @__PURE__ */b(Fa,{shrink:!1,style:{width:"20px",height:"20px",marginTop:"6px"},children:!i&&/* @__PURE__ */b(Oa,{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
+ /* @__PURE__ */v(Ua,{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(Td,{stream:e.videoStream}),!e.videoStream&&(s?/* @__PURE__ */v(Fa,{align:"start",gap:"sm",children:[/* @__PURE__ */b(Fa,{shrink:!1,style:{marginTop:"3px"},children:/* @__PURE__ */b(Ba,{name:s,size:13})}),/* @__PURE__ */b(Ua,{grow:!0,children:/* @__PURE__ */b(kd,{message:e,isLastMessage:n})})]}):/* @__PURE__ */b(kd,{message:e,isLastMessage:n})),e.isScreenAccessRequest&&!e.screenShareStatus&&/* @__PURE__ */v(Fa,{align:"center",gap:"sm",style:{marginTop:"6px"},children:[/* @__PURE__ */b(Da,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:()=>r?.(),children:"Yes"}),/* @__PURE__ */b(Da,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:()=>o?.(),children:"No"})]}),e.isScreenAccessRequest&&e.screenShareStatus&&/* @__PURE__ */b(Va,{as:"div",variant:"faint",size:"xs",italic:!0,style:{marginTop:"2px"},children:"allowed"===e.screenShareStatus?"Sure":"No"}),!i&&e.taskStatus&&/* @__PURE__ */b(Fa,{position:"absolute",align:"center",justify:"center",style:{bottom:"4px",right:"4px"},children:/* @__PURE__ */b(Ed,{status:e.taskStatus})})]}),
46
+ /* @__PURE__ */b(Fa,{shrink:!1,style:{width:"20px"}})]}),!e.isPlaceholder&&/* @__PURE__ */b(Va,{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},Od={boxShadow:ma.button,backgroundColor:"var(--card)",border:"1px solid var(--border)",pointerEvents:"auto"},Ad=({messagesEndRef:e,onScreenAccessAllow:t,onScreenAccessDeny:n})=>{const r=tl(),{state:o,actions:i}=nl(),{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(La,{position:"relative",height:"full",children:[
47
+ /* @__PURE__ */v(La,{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:`${Jc(r.widget_border_color,.3)} ${Jc(r.widget_border_color,.1)}`,scrollbarWidth:"thin"},children:[w.map((e,r)=>/* @__PURE__ */b(Rd,{message:e,index:r,isLastMessage:r===w.length-1,onScreenAccessAllow:t,onScreenAccessDeny:n},`message-${e.id}-${r}`)),s.length>0&&/* @__PURE__ */b(Fa,{justify:"center",style:{marginTop:"12px",marginBottom:"4px"},children:/* @__PURE__ */b(Da,{type:"button",variant:"bare",onClick:i.clearChatHistory,children:/* @__PURE__ */b(Va,{size:"xs",variant:"muted",style:{cursor:"pointer"},children:"Clear conversation"})})}),
48
+ /* @__PURE__ */b(La,{ref:e},"scroll-anchor")]},"message-list-container"),l&&/* @__PURE__ */b(Fa,{position:"absolute",justify:"center",style:{top:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */b(Wa,{variant:"secondary",size:"sm",label:"Scroll to top",onClick:()=>{g.current?.scrollTo({top:0,behavior:"smooth"})},style:Od,children:/* @__PURE__ */b(Ba,{name:"arrowUp",size:10,style:{color:r.widget_accent_color}})})}),f&&/* @__PURE__ */b(Fa,{position:"absolute",justify:"center",style:{bottom:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */b(Wa,{variant:"secondary",size:"sm",label:"Scroll to bottom",onClick:()=>{e.current&&!c&&e.current.scrollIntoView({behavior:"smooth"})},style:Od,children:/* @__PURE__ */b(Ba,{name:"arrowDown",size:10,style:{color:r.widget_accent_color}})})})]})},_d=[{id:"tell",icon:"chatBubble",flag:"widget_feature_tell"},{id:"show",icon:"mousePointerClick",flag:"widget_feature_show"},{id:"do",icon:"ticktick",flag:"widget_feature_do"}],Dd=({onScreenSharingChange:e,toggleScreenShareRef:t,messageInputRef:n})=>{const r=tl(),{state:o,actions:i}=nl(),{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=Gl(l),y=Gl(u),b=Gl(e),v=e=>{e&&o?.(e),n(rc("Stopped screenshare","show","user","stopped-sharing")),h(null)},w=Gl(v);a(()=>{const e=()=>{const e=null!==pr(),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[sc(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===Le.getContext().config?.use_screenshare)throw new Error("Screen sharing is disabled for this widget");const e=pr();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 ur=t,t.getVideoTracks()[0].addEventListener("ended",()=>{ur=null}),t}();d(!0),e?.(!0),k("allowed"),n(rc("Started screenshare","show","user","started-screenshare"));const r=((e,t="show")=>ec("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?(hr(),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)=>ec("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
+ return v(Ua,{height:"full",children:[w&&/* @__PURE__ */b(vd,{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
+ /* @__PURE__ */b(La,{grow:!0,overflow:"hidden",paddingY:"2xs",style:{display:"flex",flexDirection:"column",minHeight:0},children:/* @__PURE__ */b(ll,{label:"Chat",fallback:/* @__PURE__ */b(Va,{as:"div",size:"xs",align:"center",variant:"muted",style:{padding:"16px"},children:"Something went wrong displaying messages. Please refresh."}),children:/* @__PURE__ */b(Ad,{messagesEndRef:m,onScreenAccessAllow:k,onScreenAccessDeny:C})})}),
51
+ /* @__PURE__ */b(La,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px",marginTop:"auto"},children:/* @__PURE__ */b(Zl,{ref:n,value:h,onChange:f,onSubmit:()=>{if(!h.trim()||I)return;const e=h.trim();f(""),i.addMessage(tc(e,s)),!1===r.use_screenshare||"show"!==s&&"do"!==s||g?i.messageDispatch(e,s,!0):E(s,e)},modes:_d.filter(({flag:e})=>r[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:ic(e)})),activeMode:s,onModeChange:e=>{e!==s&&(i.addMessage(rc(`Switched to ${ic(e)} mode`,e,"agent","mode-change")),i.setMode(e))},disabled:I,taskRunning:l,onStop:()=>{vc.cleanup(),i.stopTask()}})})]})},Pd=[{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"}],Nd=({actions:e,onActionClick:t})=>{const n=tl();return 0===e.length?null:/* @__PURE__ */b(Ua,{gap:"sm",children:e.map((e,r)=>/* @__PURE__ */b(Da,{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(Va,{as:"span",weight:"normal",leading:"tight",children:e.text})},`welcome-chip-${e.id}-${r}`))})},Ld=({onNavigateToChat:e,onChipClick:t})=>{const n=tl(),{messages:r}=nl().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}):Pd}(n);/* @__PURE__ */
52
+ return v(Ua,{height:"full",overflow:"hidden",children:[/* @__PURE__ */v(Ua,{grow:!0,overflowY:"auto",padding:"lg",children:[/* @__PURE__ */v(La,{style:{textAlign:"center",paddingTop:"8px",paddingBottom:"16px"},children:[/* @__PURE__ */b(Va,{as:"h2",size:"lg",weight:"semibold",children:n.widget_greeting}),/* @__PURE__ */b(Va,{as:"p",variant:"muted",size:"sm",style:{marginTop:"2px"},children:n.widget_body})]}),/* @__PURE__ */v(Ua,{gap:"sm",children:[/* @__PURE__ */v(Da,{type:"button",variant:"primary",full:!0,onClick:e,"aria-label":"Ask a question",style:{paddingTop:"10px",paddingBottom:"10px"},children:[/* @__PURE__ */b(Ba,{name:"chat",size:16}),"Ask a question"]}),/* @__PURE__ */b(Nd,{actions:o,onActionClick:async(n,r)=>{r.preventDefault(),r.stopPropagation(),e(),t(n)}})]})]}),r.length>0&&/* @__PURE__ */v(La,{background:"card",border:!0,elevation:"card",paddingPreset:"card",rounded:"xl",style:{margin:"0 12px 12px 12px"},children:[
53
+ /* @__PURE__ */b(Va,{as:"p",size:"xs",weight:"semibold",style:{marginBottom:"2px"},children:"Recent conversation"}),
54
+ /* @__PURE__ */b(Va,{as:"p",size:"xs",variant:"muted",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:r[r.length-1].content||"Message"}),
55
+ /* @__PURE__ */b(Va,{as:"p",size:"xs",variant:"muted",onClick:e,style:{marginTop:"4px",cursor:"pointer"},children:"Continue conversation →"})]})]})},Fd=({grip:e,onMouseDown:t})=>/* @__PURE__ */b("div",{role:"separator","aria-label":`Resize widget from ${e.vertical} ${e.horizontal}`,title:"Drag to resize",style:{position:"absolute",[e.vertical]:0,[e.horizontal]:0,width:"20px",height:"20px",padding:"4px",touchAction:"none",zIndex:10,display:"flex",alignItems:"top"===e.vertical?"flex-start":"flex-end",justifyContent:"left"===e.horizontal?"flex-start":"flex-end",cursor:e.cursor},onMouseDown:t}),zd=[{id:"home",icon:"home",label:"Home"},{id:"chat",icon:"chat",label:"Chat"}],$d=()=>/* @__PURE__ */b(Hl,{render:/* @__PURE__ */b(Fa,{align:"center",justify:"around",shrink:!1,border:"top"}),style:{height:48},children:zd.map(e=>/* @__PURE__ */v(Tl,{value:e.id,render:/* @__PURE__ */b(Da,{stacked:!0,variant:"tab"}),children:[
56
56
  /* @__PURE__ */b("span",{className:"mtx-tab-underline"}),
57
- /* @__PURE__ */b(qa,{as:"span",inheritColor:!0,"aria-hidden":"true",children:/* @__PURE__ */b($a,{name:e.icon,size:20})}),
58
- /* @__PURE__ */b(qa,{as:"span",size:"xs",align:"center",inheritColor:!0,truncate:!0,block:!0,children:e.label})]},e.id))}),zd=()=>{const e=Qc(),{state:t,actions:n}=el(),{isOpen:r,activeView:o}=t,s=e.isPreviewMode??!1,{widthPx:c,heightPx:l,grip:h,onResizeStart:f,containerRef:m}=function(e,t,n,r,o){const s=`marketrix_widget_size_${r}`,a=u(null),c=d(()=>(e=>{const t=rl(e),n=il[t.vertical],r=il[t.horizontal];return{vertical:n,horizontal:r,growX:"left"===r?-1:1,growY:"top"===n?-1:1,cursor:"top"===n==("left"===r)?"nwse-resize":"nesw-resize"}})(n),[n]),[l,h]=p(()=>function(e){try{const t=JSON.parse(_e(e)??"null");return"number"!=typeof t?.width||"number"!=typeof t?.height?null:ql({width:t.width,height:t.height})}catch(t){return console.warn("[useResize] Ignoring an unparseable stored size:",t),null}}(s)??ql({width:Vl(e,360),height:Vl(t,450)})),f=u(l);f.current=l;const m=i(e=>{if(e.preventDefault(),e.stopPropagation(),o)return;const t=e.clientX,n=e.clientY,r=f.current.width,i=f.current.height,{growX:l,growY:d,cursor:u}=c;a.current&&(a.current.dataset.resizing="true");const p=e=>{const o=ql({width:r+(e.clientX-t)*l,height:i+(e.clientY-n)*d});f.current=o,a.current&&(a.current.style.width=`${o.width}px`,a.current.style.height=`${o.height}px`)},m=()=>{if(document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",m),document.body.style.cursor="",document.body.style.userSelect="",a.current&&delete a.current.dataset.resizing,h({...f.current}),!o){const{width:e,height:t}=f.current;De(s,JSON.stringify({width:e,height:t}))}};document.body.style.cursor=u,document.body.style.userSelect="none",document.addEventListener("mousemove",p),document.addEventListener("mouseup",m)},[o,s,c]);return{widthPx:`${l.width}px`,heightPx:`${l.height}px`,grip:c,onResizeStart:m,containerRef:a}}(e.widget_width,e.widget_height,e.widget_position,Oe(e),s),g=u(null),y="chat"===o?"forward":"back";!function(e,t,n){const r=u(!1),o=u(null),s=i(()=>{const t=e.current;if(!t)return;const r=n?.focusTargetRef?.current;if(r)return void r.focus({preventScroll:!0});const o=Hl(t);o[0]&&o[0].focus({preventScroll:!0})},[e,n?.focusTargetRef]);a(()=>{if(!t)return r.current&&(o.current?.focus({preventScroll:!0}),o.current=null),void(r.current=!1);const i=e.current;if(!i)return;r.current||(o.current=Ul(i)),r.current=!0,s();const a=e=>{const t=Ul(i);if(!t||!i.contains(t))return;if("Escape"===e.key)return void n?.onEscape?.();if("Tab"!==e.key)return;const r=Hl(i);if(0===r.length)return;const o=r.indexOf(t);-1!==o&&(e.shiftKey?0===o&&(e.preventDefault(),r[r.length-1].focus()):o===r.length-1&&(e.preventDefault(),r[0].focus()))};return document.addEventListener("keydown",a,!0),()=>document.removeEventListener("keydown",a,!0)},[t,e,s,n?.onEscape])}(m,r,{onEscape:n.closeWidget,focusTargetRef:"chat"===o?g:void 0});const w=ol(e.widget_position),[x,S]=p(!1),k=u(null);if(!r)return null;const C=e.widget_background_color.includes("gradient")?e.widget_background_color:`linear-gradient(135deg, ${e.widget_background_color} 0%, ${e.widget_background_color} 100%)`,{vertical:E,horizontal:I}=rl(e.widget_position),M="chat"===o&&!1!==e.use_screenshare?()=>k.current?.():void 0;/* @__PURE__ */
59
- return v(Wa,{ref:m,position:s?"absolute":"fixed",rounded:"lg",border:!0,overflow:"hidden",style:{zIndex:e.widget_position_z_index,backgroundImage:C,transformOrigin:`${E} ${I}`,width:c,height:l,fontSize:"14px",...w,pointerEvents:"auto",scrollbarWidth:"thin",animation:"messenger-entrance 300ms cubic-bezier(0, 1.2, 1, 1)",boxShadow:fa.panel},children:[
60
- /* @__PURE__ */b(Yl,{title:e.widget_header,subtitle:e.widget_body,onClose:n.closeWidget,controls:M&&/* @__PURE__ */v(Ba,{variant:"ghost",size:"sm",label:x?"Stop screen sharing":"Start screen sharing",onClick:M,children:[x&&/* @__PURE__ */v("span",{className:"mtx-screenshare-dot",children:[/* @__PURE__ */b("span",{className:"mtx-screenshare-dot-ping"}),/* @__PURE__ */b("span",{className:"mtx-screenshare-dot-core"})]}),/* @__PURE__ */b($a,{name:"screenShare",size:16})]})}),
61
- /* @__PURE__ */v(vl,{value:o,onValueChange:e=>n.setActiveView(e),style:{display:"flex",flexDirection:"column",flex:"1 1 0%",minHeight:0},children:[/* @__PURE__ */v(Na,{grow:!0,overflow:"hidden",style:{display:"flex",flexDirection:"column",minHeight:0},children:[/* @__PURE__ */b(Tl,{value:"home","data-view-transition":!0,"data-direction":y,style:{width:"100%",height:"100%"},children:/* @__PURE__ */b(Pd,{onNavigateToChat:()=>{n.setActiveView("chat")},onChipClick:e=>{n.addMessage(ec(e.text,e.type,"chip-message")),n.setMode(e.type),n.messageDispatch(e.text,e.type,!0)}})}),/* @__PURE__ */b(Tl,{value:"chat","data-view-transition":!0,"data-direction":y,style:{width:"100%",height:"100%"},children:/* @__PURE__ */b(Ad,{onScreenSharingChange:S,toggleScreenShareRef:k,messageInputRef:g})})]}),/* @__PURE__ */b(Fd,{})]}),!s&&/* @__PURE__ */b(Nd,{grip:h,onMouseDown:f})]})},$d=({config:e})=>{const[t,n]=p(!1),[r,o]=p(null),{state:i,actions:s}=el(),c=lr.getInstance(),l=e.isPreviewMode??!1,d=vr(e);var u;u=i.isOpen,a(()=>{if(!u)return;if(!window.matchMedia("(max-width: 767px)").matches)return;const e=document.documentElement,t=document.body,n=e.style.overflow,r=t.style.overflow;return e.style.overflow="hidden",t.style.overflow="hidden",()=>{e.style.overflow=n,t.style.overflow=r}},[u]);const[h,f]=p(e.widget_position??"bottom_right"),m=`marketrix_widget_position_${Oe(e)}`;a(()=>{const t=l?null:_e(m);(e=>nl.includes(e))(t)?f(t):f(e.widget_position??"bottom_right")},[l,m,e.widget_position]),a(()=>{if(i.isOpen||l||!e.widget_greeting_toast)return void n(!1);const t=setTimeout(()=>n(!0),2e3);return()=>clearTimeout(t)},[i.isOpen,l,e.widget_greeting_toast]);const g=d.invalidFields?wr(d.invalidFields):null;if(a(()=>{g&&console.error(`Marketrix Widget: ${g}`)},[g]),g)return null;const y=!e.widget_enabled||!1===e.show_widget||"hidden"===e.widget_appearance;if(!l&&y)return null;const w=Math.max(e.widget_position_z_index??0,2147483002),x={...e,widget_position:h,widget_position_z_index:w},S=i.isAwaitingReply||i.isTaskRunning,k={"--background":(C=Jc(e)).color.background,"--foreground":C.color.foreground,"--card":C.color.background,"--card-foreground":C.color.foreground,"--primary":C.color.primary,"--foreground-muted":C.color.foregroundMuted,"--foreground-faint":C.color.foregroundFaint,"--primary-foreground":C.color.primaryForeground,"--primary-hover":C.color.primaryHover,"--secondary":C.color.secondary,"--secondary-foreground":C.color.secondaryForeground,"--secondary-bg":C.color.secondaryBg,"--secondary-hover":C.color.secondaryHover,"--border":C.color.border,"--ring":C.color.primary,"--radius":C.radius,"--duration-animation":C.motion.durationAnimation,"--duration-fade":C.motion.durationFade};var C;/* @__PURE__ */
62
- return b(Zc,{value:x,children:/* @__PURE__ */b(Na,{ref:o,"data-marketrix-widget":!0,position:"relative",style:{...k,...l&&{width:"100%",height:"100%"}},children:/* @__PURE__ */b(Wc,{value:r,children:/* @__PURE__ */v(Ya,{container:r,offsetBottom:"top"===rl(h).vertical?20:90,children:[S&&/* @__PURE__ */b(Na,{"data-screen-edge-glow":!0,position:"fixed",inset:"0",style:{boxShadow:`inset 0 0 22px 2px ${Xc(x.widget_accent_color,.72)}, inset 0 0 46px 10px ${Xc(x.widget_accent_color,.28)}`,pointerEvents:"none",zIndex:2147483001}}),
63
- /* @__PURE__ */b(al,{label:"Widget",children:/* @__PURE__ */b(zd,{})}),
64
- /* @__PURE__ */b(ll,{onPositionCommit:e=>{f(e),l||De(m,e)}}),
65
- /* @__PURE__ */b(Xa,{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)})]})})})})},Bd={mount:null},Wd=null,Ud=(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}},Hd=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}=Ud(n,"marketrix-widget-root");return Object.assign(o.style,{pointerEvents:"auto",width:"100%",height:"100%",position:"relative"}),{container:n,shadowRoot:r,mountEl:o}},jd=(e,n,r=!1)=>{const o=m(e);return o.render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(jc,{previewMode:r,children:/* @__PURE__ */b($d,{config:n})})})),o},qd=()=>null!==Bd.mount,Vd=()=>Bd.mount?.config??null,Yd=(e,n="neutral")=>{if("undefined"==typeof window||"undefined"==typeof document)return;Kd();const r=document.createElement("div");r.id="marketrix-widget-notice-container",r.className="marketrix-widget-notice-container",document.body.appendChild(r);const{mountEl:o}=Ud(r,"marketrix-widget-notice-root");(Wd=m(o)).render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(Ya,{container:o,children:/* @__PURE__ */b(Xa,{error:"error"===n?e:void 0,onClearError:Kd,greeting:"error"===n?void 0:e,onGreetingDismiss:Kd})})}))},Kd=()=>{Wd?.unmount(),Wd=null,document.getElementById("marketrix-widget-notice-container")?.remove()},Xd=null,Gd=0,Jd=null;function Zd(e,t,n=!1){const{container:r,mountEl:o}=Hd(t),i=jd(o,e,n);Bd.mount={instance:i,config:e,container:r,host:t,previewMode:n}}var Qd=(e,t)=>{if(Xd)return Xd;if(window.__mtx?.state)return Promise.resolve();if(qd())return console.warn("Marketrix Widget: already initialized"),Promise.resolve();const n=async function(e,t,n){let r;window.__mtx={state:"initializing"},Yd("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=Sr(e);return n.includes("Failed to fetch")||n.includes("ERR_CONNECTION_REFUSED")||n.includes("NetworkError")||n.includes("Network request failed")?kr(`Cannot connect to API server. Please ensure the API server is running at ${t.mtxApiHost||"configured API server"}. Error: ${n}`,e):kr(`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 kr(`Failed to validate application: ${Sr(a)}`,a)}let i;try{i=await Te.widgetDefaultGet({type:"widget"})}catch(a){throw kr(`Failed to fetch widget settings from API: ${Sr(a)}`,a)}const s=vr({...i,...o.settings});if(s.invalidFields)throw new Error(wr(s.invalidFields));return{...xr(s.settings,e),mtxId:t,mtxKey:n,mtxApp:o.application_id}}(e)}catch(o){if(n!==Gd)return;return console.error("Marketrix Widget initialization failed:",o),Yd(o instanceof Error?o.message:"Failed to initialize widget","error"),void(window.__mtx=void 0)}n===Gd&&(Kd(),Le.setConfig(r),Zd(r,t),window.__mtx={state:"active"},r.widget_recording&&r.mtxApp&&(async()=>{try{const e=await Fe.getOrCreateChatId();if(n!==Gd)return;const t=new dr(e,r.mtxApp);Jd=t,await t.start(),n!==Gd&&(t.stop(),Jd===t&&(Jd=null))}catch(o){n===Gd&&console.error("Failed to start session recording:",o)}})())}(e,t,++Gd);return Xd=n,n.then(()=>{Xd===n&&(Xd=null)},()=>{Xd===n&&(Xd=null)}),n},eu=()=>{Gd++,lr.getInstance().disconnect(),Jd?.stop(),Jd=null,hr();const e=Bd.mount;Bd.mount=null,e&&(e.instance.unmount(),e.container.remove()),Xd=null,window.__mtx=void 0,Kd()},tu=async e=>{const t=Bd.mount;if(!t)return;const{config:n,host:r,previewMode:o}=t,i={...n,...e};eu(),o?Zd(i,r,!0):await Qd(i,r)},nu=({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{container:a,mountEl:c}=Hd(i);return o.current=a,r.current=jd(c,{...xr(e),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"}})},ru=async e=>{const t=e.container;if(void 0!==e.settings){eu();const{settings:n,container:r,...o}=e;Zd({...xr(n,o),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 Qd(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(qd())return;return console.error("[AutoInit] Missing required attributes:",{hasMtxId:!!o,hasMtxKey:!!i,hasMtxApiHost:!!s}),void Yd("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))})(Qd)}catch(e){console.error("Marketrix Widget: Auto-init registration failed",e)}},0);var ou={MarketrixWidget:nu,mountWidget:ru,initWidget:Qd,unmountWidget:eu,updateMarketrixConfig:tu,getCurrentConfig:Vd};export{nu as MarketrixWidget,ou as default,Vd as getCurrentConfig,Qd as initWidget,ru as mountWidget,eu as unmountWidget,tu as updateMarketrixConfig};
57
+ /* @__PURE__ */b(Va,{as:"span",inheritColor:!0,"aria-hidden":"true",children:/* @__PURE__ */b(Ba,{name:e.icon,size:20})}),
58
+ /* @__PURE__ */b(Va,{as:"span",size:"xs",align:"center",inheritColor:!0,truncate:!0,block:!0,children:e.label})]},e.id))}),Bd=()=>{const e=tl(),{state:t,actions:n}=nl(),{isOpen:r,activeView:o}=t,s=e.isPreviewMode??!1,{widthPx:c,heightPx:l,grip:h,onResizeStart:f,containerRef:m}=function(e,t,n,r,o){const s=`marketrix_widget_size_${r}`,a=u(null),c=d(()=>(e=>{const t=il(e),n=al[t.vertical],r=al[t.horizontal];return{vertical:n,horizontal:r,growX:"left"===r?-1:1,growY:"top"===n?-1:1,cursor:"top"===n==("left"===r)?"nwse-resize":"nesw-resize"}})(n),[n]),[l,h]=p(()=>function(e){try{const t=JSON.parse(_e(e)??"null");return"number"!=typeof t?.width||"number"!=typeof t?.height?null:Yl({width:t.width,height:t.height})}catch(t){return console.warn("[useResize] Ignoring an unparseable stored size:",t),null}}(s)??Yl({width:Kl(e,360),height:Kl(t,450)})),f=u(l);f.current=l;const m=i(e=>{if(e.preventDefault(),e.stopPropagation(),o)return;const t=e.clientX,n=e.clientY,r=f.current.width,i=f.current.height,{growX:l,growY:d,cursor:u}=c;a.current&&(a.current.dataset.resizing="true");const p=e=>{const o=Yl({width:r+(e.clientX-t)*l,height:i+(e.clientY-n)*d});f.current=o,a.current&&(a.current.style.width=`${o.width}px`,a.current.style.height=`${o.height}px`)},m=()=>{if(document.removeEventListener("mousemove",p),document.removeEventListener("mouseup",m),document.body.style.cursor="",document.body.style.userSelect="",a.current&&delete a.current.dataset.resizing,h({...f.current}),!o){const{width:e,height:t}=f.current;De(s,JSON.stringify({width:e,height:t}))}};document.body.style.cursor=u,document.body.style.userSelect="none",document.addEventListener("mousemove",p),document.addEventListener("mouseup",m)},[o,s,c]);return{widthPx:`${l.width}px`,heightPx:`${l.height}px`,grip:c,onResizeStart:m,containerRef:a}}(e.widget_width,e.widget_height,e.widget_position,Oe(e),s),g=u(null),y="chat"===o?"forward":"back";!function(e,t,n){const r=u(!1),o=u(null),s=i(()=>{const t=e.current;if(!t)return;const r=n?.focusTargetRef?.current;if(r)return void r.focus({preventScroll:!0});const o=ql(t);o[0]&&o[0].focus({preventScroll:!0})},[e,n?.focusTargetRef]);a(()=>{if(!t)return r.current&&(o.current?.focus({preventScroll:!0}),o.current=null),void(r.current=!1);const i=e.current;if(!i)return;r.current||(o.current=jl(i)),r.current=!0,s();const a=e=>{const t=jl(i);if(!t||!i.contains(t))return;if("Escape"===e.key)return void n?.onEscape?.();if("Tab"!==e.key)return;const r=ql(i);if(0===r.length)return;const o=r.indexOf(t);-1!==o&&(e.shiftKey?0===o&&(e.preventDefault(),r[r.length-1].focus()):o===r.length-1&&(e.preventDefault(),r[0].focus()))};return document.addEventListener("keydown",a,!0),()=>document.removeEventListener("keydown",a,!0)},[t,e,s,n?.onEscape])}(m,r,{onEscape:n.closeWidget,focusTargetRef:"chat"===o?g:void 0});const w=sl(e.widget_position),[x,S]=p(!1),k=u(null);if(!r)return null;const C=e.widget_background_color.includes("gradient")?e.widget_background_color:`linear-gradient(135deg, ${e.widget_background_color} 0%, ${e.widget_background_color} 100%)`,{vertical:E,horizontal:I}=il(e.widget_position),M="chat"===o&&!1!==e.use_screenshare?()=>k.current?.():void 0;/* @__PURE__ */
59
+ return v(Ua,{ref:m,position:s?"absolute":"fixed",rounded:"lg",border:!0,overflow:"hidden",style:{zIndex:e.widget_position_z_index,backgroundImage:C,transformOrigin:`${E} ${I}`,width:c,height:l,fontSize:"14px",...w,pointerEvents:"auto",scrollbarWidth:"thin",animation:"messenger-entrance 300ms cubic-bezier(0, 1.2, 1, 1)",boxShadow:ma.panel},children:[
60
+ /* @__PURE__ */b(Xl,{title:e.widget_header,subtitle:e.widget_body,onClose:n.closeWidget,controls:M&&/* @__PURE__ */v(Wa,{variant:"ghost",size:"sm",label:x?"Stop screen sharing":"Start screen sharing",onClick:M,children:[x&&/* @__PURE__ */v("span",{className:"mtx-screenshare-dot",children:[/* @__PURE__ */b("span",{className:"mtx-screenshare-dot-ping"}),/* @__PURE__ */b("span",{className:"mtx-screenshare-dot-core"})]}),/* @__PURE__ */b(Ba,{name:"screenShare",size:16})]})}),
61
+ /* @__PURE__ */v(xl,{value:o,onValueChange:e=>n.setActiveView(e),style:{display:"flex",flexDirection:"column",flex:"1 1 0%",minHeight:0},children:[/* @__PURE__ */v(La,{grow:!0,overflow:"hidden",style:{display:"flex",flexDirection:"column",minHeight:0},children:[/* @__PURE__ */b(Ol,{value:"home","data-view-transition":!0,"data-direction":y,style:{width:"100%",height:"100%"},children:/* @__PURE__ */b(Ld,{onNavigateToChat:()=>{n.setActiveView("chat")},onChipClick:e=>{n.addMessage(tc(e.text,e.type,"chip-message")),n.setMode(e.type),n.messageDispatch(e.text,e.type,!0)}})}),/* @__PURE__ */b(Ol,{value:"chat","data-view-transition":!0,"data-direction":y,style:{width:"100%",height:"100%"},children:/* @__PURE__ */b(Dd,{onScreenSharingChange:S,toggleScreenShareRef:k,messageInputRef:g})})]}),/* @__PURE__ */b($d,{})]}),!s&&/* @__PURE__ */b(Fd,{grip:h,onMouseDown:f})]})},Wd=({config:e})=>{const[t,n]=p(!1),[r,o]=p(null),{state:i,actions:s}=nl(),c=lr.getInstance(),l=e.isPreviewMode??!1,d=wr(e);var u;u=i.isOpen,a(()=>{if(!u)return;if(!window.matchMedia("(max-width: 767px)").matches)return;const e=document.documentElement,t=document.body,n=e.style.overflow,r=t.style.overflow;return e.style.overflow="hidden",t.style.overflow="hidden",()=>{e.style.overflow=n,t.style.overflow=r}},[u]);const[h,f]=p(e.widget_position??"bottom_right"),m=`marketrix_widget_position_${Oe(e)}`;a(()=>{const t=l?null:_e(m);(e=>ol.includes(e))(t)?f(t):f(e.widget_position??"bottom_right")},[l,m,e.widget_position]),a(()=>{if(i.isOpen||l||!e.widget_greeting_toast)return void n(!1);const t=setTimeout(()=>n(!0),2e3);return()=>clearTimeout(t)},[i.isOpen,l,e.widget_greeting_toast]);const g=d.invalidFields?xr(d.invalidFields):null;if(a(()=>{g&&console.error(`Marketrix Widget: ${g}`)},[g]),g)return null;const y=!1===e.show_widget||"hidden"===e.widget_appearance;if(!l&&y)return null;const w=Math.max(e.widget_position_z_index??0,2147483002),x={...e,widget_position:h,widget_position_z_index:w},S=i.isAwaitingReply||i.isTaskRunning,k={"--background":(C=Qc(e)).color.background,"--foreground":C.color.foreground,"--card":C.color.background,"--card-foreground":C.color.foreground,"--primary":C.color.primary,"--foreground-muted":C.color.foregroundMuted,"--foreground-faint":C.color.foregroundFaint,"--primary-foreground":C.color.primaryForeground,"--primary-hover":C.color.primaryHover,"--secondary":C.color.secondary,"--secondary-foreground":C.color.secondaryForeground,"--secondary-bg":C.color.secondaryBg,"--secondary-hover":C.color.secondaryHover,"--border":C.color.border,"--ring":C.color.primary,"--radius":C.radius,"--duration-animation":C.motion.durationAnimation,"--duration-fade":C.motion.durationFade};var C;/* @__PURE__ */
62
+ return b(el,{value:x,children:/* @__PURE__ */b(La,{ref:o,"data-marketrix-widget":!0,position:"relative",style:{...k,...l&&{width:"100%",height:"100%"}},children:/* @__PURE__ */b(Hc,{value:r,children:/* @__PURE__ */v(Ka,{container:r,offsetBottom:"top"===il(h).vertical?20:90,children:[S&&/* @__PURE__ */b(La,{"data-screen-edge-glow":!0,position:"fixed",inset:"0",style:{boxShadow:`inset 0 0 22px 2px ${Jc(x.widget_accent_color,.72)}, inset 0 0 46px 10px ${Jc(x.widget_accent_color,.28)}`,pointerEvents:"none",zIndex:2147483001}}),
63
+ /* @__PURE__ */b(ll,{label:"Widget",children:/* @__PURE__ */b(Bd,{})}),
64
+ /* @__PURE__ */b(ul,{onPositionCommit:e=>{f(e),l||De(m,e)}}),
65
+ /* @__PURE__ */b(Ga,{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)})]})})})})},Ud={mount:null},Hd=null,jd=(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}},qd=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}=jd(n,"marketrix-widget-root");return Object.assign(o.style,{pointerEvents:"auto",width:"100%",height:"100%",position:"relative"}),{container:n,shadowRoot:r,mountEl:o}},Vd=(e,n,r=!1)=>{const o=m(e);return o.render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(Vc,{previewMode:r,children:/* @__PURE__ */b(Wd,{config:n})})})),o},Yd=()=>null!==Ud.mount,Kd=()=>Ud.mount?.config??null,Xd=(e,n="neutral")=>{if("undefined"==typeof window||"undefined"==typeof document)return;Gd();const r=document.createElement("div");r.id="marketrix-widget-notice-container",r.className="marketrix-widget-notice-container",document.body.appendChild(r);const{mountEl:o}=jd(r,"marketrix-widget-notice-root");(Hd=m(o)).render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(Ka,{container:o,children:/* @__PURE__ */b(Ga,{error:"error"===n?e:void 0,onClearError:Gd,greeting:"error"===n?void 0:e,onGreetingDismiss:Gd})})}))},Gd=()=>{Hd?.unmount(),Hd=null,document.getElementById("marketrix-widget-notice-container")?.remove()},Jd=null,Zd=0,Qd=null;function eu(e,t,n=!1){const{container:r,mountEl:o}=qd(t),i=Vd(o,e,n);Ud.mount={instance:i,config:e,container:r,host:t,previewMode:n}}var tu=(e,t)=>{if(Jd)return Jd;if(window.__mtx?.state)return Promise.resolve();if(Yd())return console.warn("Marketrix Widget: already initialized"),Promise.resolve();const n=async function(e,t,n){let r;window.__mtx={state:"initializing"},Xd("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=kr(e);return n.includes("Failed to fetch")||n.includes("ERR_CONNECTION_REFUSED")||n.includes("NetworkError")||n.includes("Network request failed")?Cr(`Cannot connect to API server. Please ensure the API server is running at ${t.mtxApiHost||"configured API server"}. Error: ${n}`,e):Cr(`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 Cr(`Failed to validate application: ${kr(a)}`,a)}let i;try{i=await Te.widgetDefaultGet({type:"widget"})}catch(a){throw Cr(`Failed to fetch widget settings from API: ${kr(a)}`,a)}const s=wr({...i,...o.settings});if(s.invalidFields)throw new Error(xr(s.invalidFields));return{...Sr(s.settings,e),mtxId:t,mtxKey:n,mtxApp:o.application_id}}(e)}catch(o){if(n!==Zd)return;return console.error("Marketrix Widget initialization failed:",o),Xd(o instanceof Error?o.message:"Failed to initialize widget","error"),void(window.__mtx=void 0)}n===Zd&&(Gd(),r.widget_enabled?(Le.setConfig(r),eu(r,t),window.__mtx={state:"active"},r.widget_recording&&r.mtxApp&&(async()=>{try{const e=await Fe.getOrCreateChatId();if(n!==Zd)return;const t=new dr(e,r.mtxApp);Qd=t,await t.start(),n!==Zd&&(t.stop(),Qd===t&&(Qd=null))}catch(o){n===Zd&&console.error("Failed to start session recording:",o)}})()):window.__mtx=void 0)}(e,t,++Zd);return Jd=n,n.then(()=>{Jd===n&&(Jd=null)},()=>{Jd===n&&(Jd=null)}),n},nu=()=>{Zd++,lr.getInstance().disconnect(),Qd?.stop(),Qd=null,hr();const e=Ud.mount;Ud.mount=null,e&&(e.instance.unmount(),e.container.remove()),Jd=null,window.__mtx=void 0,Gd()},ru=async e=>{const t=Ud.mount;if(!t)return;const{config:n,host:r,previewMode:o}=t,i={...n,...e};nu(),o?eu(i,r,!0):await tu(i,r)},ou=({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{container:a,mountEl:c}=qd(i);return o.current=a,r.current=Vd(c,{...Sr(e),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"}})},iu=async e=>{const t=e.container;if(void 0!==e.settings){nu();const{settings:n,container:r,...o}=e;eu({...Sr(n,o),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 tu(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(Yd())return;return console.error("[AutoInit] Missing required attributes:",{hasMtxId:!!o,hasMtxKey:!!i,hasMtxApiHost:!!s}),void Xd("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))})(tu)}catch(e){console.error("Marketrix Widget: Auto-init registration failed",e)}},0);var su={MarketrixWidget:ou,mountWidget:iu,initWidget:tu,unmountWidget:nu,updateMarketrixConfig:ru,getCurrentConfig:Kd};export{ou as MarketrixWidget,su as default,Kd as getCurrentConfig,tu as initWidget,iu as mountWidget,nu as unmountWidget,ru as updateMarketrixConfig};