@usecrow/client 0.1.27 → 0.1.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,79 @@
1
+ (function(){"use strict";try{if(typeof document<"u"){var e=document.createElement("style");e.appendChild(document.createTextNode(`._wrapper_7c7fs_1{position:fixed;top:0;right:0;bottom:0;left:0;z-index:2147483641;cursor:wait;overflow:hidden;display:none}._animatedBorder_7c7fs_14{position:absolute;top:0;right:0;bottom:0;left:0;--border-width: 3px;--glow-size: 8px;--animation-speed: 3s;opacity:0;transition:opacity .3s ease-out}._animatedBorderVisible_7c7fs_27{opacity:1}._animatedBorder_7c7fs_14:before{content:"";position:absolute;top:0;right:0;bottom:0;left:0;border:var(--border-width) solid transparent;background:linear-gradient(90deg,#1e3a5f,#2563eb,#3b82f6,#60a5fa,#3b82f6,#2563eb,#1e3a5f) border-box;background-size:300% 100%;-webkit-mask:linear-gradient(#fff 0 0) padding-box,linear-gradient(#fff 0 0);-webkit-mask-composite:xor;mask:linear-gradient(#fff 0 0) padding-box,linear-gradient(#fff 0 0);mask-composite:exclude;animation:_shimmerBorder_7c7fs_1 var(--animation-speed) linear infinite}._animatedBorder_7c7fs_14:after{content:"";position:absolute;inset:calc(-1 * var(--glow-size));border:calc(var(--border-width) + var(--glow-size)) solid transparent;background:linear-gradient(90deg,#1e3a5f,#2563eb,#3b82f6,#60a5fa,#3b82f6,#2563eb,#1e3a5f) border-box;background-size:300% 100%;-webkit-mask:linear-gradient(#fff 0 0) padding-box,linear-gradient(#fff 0 0);-webkit-mask-composite:xor;mask:linear-gradient(#fff 0 0) padding-box,linear-gradient(#fff 0 0);mask-composite:exclude;animation:_shimmerBorder_7c7fs_1 var(--animation-speed) linear infinite;filter:blur(var(--glow-size));opacity:.6}@keyframes _shimmerBorder_7c7fs_1{0%{background-position:0% 50%}to{background-position:300% 50%}}._cursor_o2dvz_2{position:absolute;width:32px;height:32px;pointer-events:none;z-index:10000;background:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='48'%20height='48'%20viewBox='0%200%2024%2024'%3e%3cpath%20fill='%23000'%20d='M4.5.79v22.42l6.56-6.57h9.29L4.5.79z'%3e%3c/path%3e%3c/svg%3e");background-size:contain;background-repeat:no-repeat}._cursorRipple_o2dvz_14{position:absolute;width:48px;height:48px;pointer-events:none;top:8px;left:8px}._cursorRipple_o2dvz_14:after{content:"";opacity:0;position:absolute;top:0;right:0;bottom:0;left:0;border:3px solid rgba(59,130,246,.8);border-radius:50%}._cursor_o2dvz_2._clicking_o2dvz_32 ._cursorRipple_o2dvz_14:after{animation:_cursor-ripple_o2dvz_1 .3s ease-out forwards}@keyframes _cursor-ripple_o2dvz_1{0%{transform:scale(0);opacity:1}to{transform:scale(1.5);opacity:0}}`)),document.head.appendChild(e)}}catch(o){console.error("vite-plugin-css-injected-by-js",o)}})();
2
+ var C = (i) => {
3
+ throw TypeError(i);
4
+ };
5
+ var g = (i, t, s) => t.has(i) || C("Cannot " + s);
6
+ var e = (i, t, s) => (g(i, t, "read from private field"), s ? s.call(i) : t.get(i)), d = (i, t, s) => t.has(i) ? C("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(i) : t.set(i, s), r = (i, t, s, l) => (g(i, t, "write to private field"), l ? l.call(i, s) : t.set(i, s), s), w = (i, t, s) => (g(i, t, "access private method"), s);
7
+ const y = "_wrapper_7c7fs_1", E = "_animatedBorder_7c7fs_14", L = "_animatedBorderVisible_7c7fs_27", v = {
8
+ wrapper: y,
9
+ animatedBorder: E,
10
+ animatedBorderVisible: L
11
+ }, P = "_cursor_o2dvz_2", b = "_cursorRipple_o2dvz_14", B = "_clicking_o2dvz_32", m = {
12
+ cursor: P,
13
+ cursorRipple: b,
14
+ clicking: B
15
+ };
16
+ var c, a, o, n, p, h, u, k, f;
17
+ class x {
18
+ constructor() {
19
+ d(this, u);
20
+ d(this, c);
21
+ d(this, a);
22
+ d(this, o);
23
+ d(this, n);
24
+ d(this, p);
25
+ d(this, h);
26
+ this.shown = !1, this.wrapper = document.createElement("div"), r(this, c, document.createElement("div")), r(this, a, document.createElement("div")), r(this, o, 0), r(this, n, 0), r(this, p, 0), r(this, h, 0), this.wrapper.id = "page-agent-runtime_simulator-mask", this.wrapper.className = v.wrapper, this.wrapper.setAttribute("data-browser-use-ignore", "true"), e(this, c).className = v.animatedBorder, this.wrapper.appendChild(e(this, c)), this.wrapper.addEventListener("click", (t) => {
27
+ t.stopPropagation(), t.preventDefault();
28
+ }), this.wrapper.addEventListener("mousedown", (t) => {
29
+ t.stopPropagation(), t.preventDefault();
30
+ }), this.wrapper.addEventListener("mouseup", (t) => {
31
+ t.stopPropagation(), t.preventDefault();
32
+ }), this.wrapper.addEventListener("mousemove", (t) => {
33
+ t.stopPropagation(), t.preventDefault();
34
+ }), this.wrapper.addEventListener("wheel", (t) => {
35
+ t.stopPropagation(), t.preventDefault();
36
+ }), this.wrapper.addEventListener("keydown", (t) => {
37
+ t.stopPropagation(), t.preventDefault();
38
+ }), this.wrapper.addEventListener("keyup", (t) => {
39
+ t.stopPropagation(), t.preventDefault();
40
+ }), w(this, u, k).call(this), document.body.appendChild(this.wrapper), w(this, u, f).call(this), window.addEventListener("PageAgent::MovePointerTo", (t) => {
41
+ const { x: s, y: l } = t.detail;
42
+ this.setCursorPosition(s, l);
43
+ }), window.addEventListener("PageAgent::ClickPointer", () => {
44
+ this.triggerClickAnimation();
45
+ });
46
+ }
47
+ setCursorPosition(t, s) {
48
+ r(this, p, t), r(this, h, s);
49
+ }
50
+ triggerClickAnimation() {
51
+ e(this, a).classList.remove(m.clicking), e(this, a).offsetHeight, e(this, a).classList.add(m.clicking);
52
+ }
53
+ show() {
54
+ this.shown || (this.shown = !0, this.wrapper.style.display = "block", requestAnimationFrame(() => {
55
+ e(this, c).classList.add(v.animatedBorderVisible);
56
+ }), r(this, o, window.innerWidth / 2), r(this, n, window.innerHeight / 2), r(this, p, e(this, o)), r(this, h, e(this, n)), e(this, a).style.left = `${e(this, o)}px`, e(this, a).style.top = `${e(this, n)}px`);
57
+ }
58
+ hide() {
59
+ this.shown && (this.shown = !1, e(this, c).classList.remove(v.animatedBorderVisible), e(this, a).classList.remove(m.clicking), setTimeout(() => {
60
+ this.wrapper.style.display = "none";
61
+ }, 300));
62
+ }
63
+ dispose() {
64
+ this.wrapper.remove();
65
+ }
66
+ }
67
+ c = new WeakMap(), a = new WeakMap(), o = new WeakMap(), n = new WeakMap(), p = new WeakMap(), h = new WeakMap(), u = new WeakSet(), k = function() {
68
+ e(this, a).className = m.cursor;
69
+ const t = document.createElement("div");
70
+ t.className = m.cursorRipple, e(this, a).appendChild(t), this.wrapper.appendChild(e(this, a));
71
+ }, f = function() {
72
+ const t = e(this, o) + (e(this, p) - e(this, o)) * 0.2, s = e(this, n) + (e(this, h) - e(this, n)) * 0.2, l = Math.abs(t - e(this, p));
73
+ l > 0 && (l < 2 ? r(this, o, e(this, p)) : r(this, o, t), e(this, a).style.left = `${e(this, o)}px`);
74
+ const _ = Math.abs(s - e(this, h));
75
+ _ > 0 && (_ < 2 ? r(this, n, e(this, h)) : r(this, n, s), e(this, a).style.top = `${e(this, n)}px`), requestAnimationFrame(() => w(this, u, f).call(this));
76
+ };
77
+ export {
78
+ x as SimulatorMask
79
+ };
@@ -0,0 +1,2 @@
1
+ (function(){"use strict";try{if(typeof document<"u"){var e=document.createElement("style");e.appendChild(document.createTextNode(`._wrapper_7c7fs_1{position:fixed;top:0;right:0;bottom:0;left:0;z-index:2147483641;cursor:wait;overflow:hidden;display:none}._animatedBorder_7c7fs_14{position:absolute;top:0;right:0;bottom:0;left:0;--border-width: 3px;--glow-size: 8px;--animation-speed: 3s;opacity:0;transition:opacity .3s ease-out}._animatedBorderVisible_7c7fs_27{opacity:1}._animatedBorder_7c7fs_14:before{content:"";position:absolute;top:0;right:0;bottom:0;left:0;border:var(--border-width) solid transparent;background:linear-gradient(90deg,#1e3a5f,#2563eb,#3b82f6,#60a5fa,#3b82f6,#2563eb,#1e3a5f) border-box;background-size:300% 100%;-webkit-mask:linear-gradient(#fff 0 0) padding-box,linear-gradient(#fff 0 0);-webkit-mask-composite:xor;mask:linear-gradient(#fff 0 0) padding-box,linear-gradient(#fff 0 0);mask-composite:exclude;animation:_shimmerBorder_7c7fs_1 var(--animation-speed) linear infinite}._animatedBorder_7c7fs_14:after{content:"";position:absolute;inset:calc(-1 * var(--glow-size));border:calc(var(--border-width) + var(--glow-size)) solid transparent;background:linear-gradient(90deg,#1e3a5f,#2563eb,#3b82f6,#60a5fa,#3b82f6,#2563eb,#1e3a5f) border-box;background-size:300% 100%;-webkit-mask:linear-gradient(#fff 0 0) padding-box,linear-gradient(#fff 0 0);-webkit-mask-composite:xor;mask:linear-gradient(#fff 0 0) padding-box,linear-gradient(#fff 0 0);mask-composite:exclude;animation:_shimmerBorder_7c7fs_1 var(--animation-speed) linear infinite;filter:blur(var(--glow-size));opacity:.6}@keyframes _shimmerBorder_7c7fs_1{0%{background-position:0% 50%}to{background-position:300% 50%}}._cursor_o2dvz_2{position:absolute;width:32px;height:32px;pointer-events:none;z-index:10000;background:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='48'%20height='48'%20viewBox='0%200%2024%2024'%3e%3cpath%20fill='%23000'%20d='M4.5.79v22.42l6.56-6.57h9.29L4.5.79z'%3e%3c/path%3e%3c/svg%3e");background-size:contain;background-repeat:no-repeat}._cursorRipple_o2dvz_14{position:absolute;width:48px;height:48px;pointer-events:none;top:8px;left:8px}._cursorRipple_o2dvz_14:after{content:"";opacity:0;position:absolute;top:0;right:0;bottom:0;left:0;border:3px solid rgba(59,130,246,.8);border-radius:50%}._cursor_o2dvz_2._clicking_o2dvz_32 ._cursorRipple_o2dvz_14:after{animation:_cursor-ripple_o2dvz_1 .3s ease-out forwards}@keyframes _cursor-ripple_o2dvz_1{0%{transform:scale(0);opacity:1}to{transform:scale(1.5);opacity:0}}`)),document.head.appendChild(e)}}catch(o){console.error("vite-plugin-css-injected-by-js",o)}})();
2
+ "use strict";var y=i=>{throw TypeError(i)};var g=(i,t,s)=>t.has(i)||y("Cannot "+s);var e=(i,t,s)=>(g(i,t,"read from private field"),s?s.call(i):t.get(i)),d=(i,t,s)=>t.has(i)?y("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,s),r=(i,t,s,l)=>(g(i,t,"write to private field"),l?l.call(i,s):t.set(i,s),s),w=(i,t,s)=>(g(i,t,"access private method"),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C="_wrapper_7c7fs_1",b="_animatedBorder_7c7fs_14",E="_animatedBorderVisible_7c7fs_27",v={wrapper:C,animatedBorder:b,animatedBorderVisible:E},L="_cursor_o2dvz_2",P="_cursorRipple_o2dvz_14",B="_clicking_o2dvz_32",m={cursor:L,cursorRipple:P,clicking:B};var c,a,o,n,p,h,u,k,f;class D{constructor(){d(this,u);d(this,c);d(this,a);d(this,o);d(this,n);d(this,p);d(this,h);this.shown=!1,this.wrapper=document.createElement("div"),r(this,c,document.createElement("div")),r(this,a,document.createElement("div")),r(this,o,0),r(this,n,0),r(this,p,0),r(this,h,0),this.wrapper.id="page-agent-runtime_simulator-mask",this.wrapper.className=v.wrapper,this.wrapper.setAttribute("data-browser-use-ignore","true"),e(this,c).className=v.animatedBorder,this.wrapper.appendChild(e(this,c)),this.wrapper.addEventListener("click",t=>{t.stopPropagation(),t.preventDefault()}),this.wrapper.addEventListener("mousedown",t=>{t.stopPropagation(),t.preventDefault()}),this.wrapper.addEventListener("mouseup",t=>{t.stopPropagation(),t.preventDefault()}),this.wrapper.addEventListener("mousemove",t=>{t.stopPropagation(),t.preventDefault()}),this.wrapper.addEventListener("wheel",t=>{t.stopPropagation(),t.preventDefault()}),this.wrapper.addEventListener("keydown",t=>{t.stopPropagation(),t.preventDefault()}),this.wrapper.addEventListener("keyup",t=>{t.stopPropagation(),t.preventDefault()}),w(this,u,k).call(this),document.body.appendChild(this.wrapper),w(this,u,f).call(this),window.addEventListener("PageAgent::MovePointerTo",t=>{const{x:s,y:l}=t.detail;this.setCursorPosition(s,l)}),window.addEventListener("PageAgent::ClickPointer",()=>{this.triggerClickAnimation()})}setCursorPosition(t,s){r(this,p,t),r(this,h,s)}triggerClickAnimation(){e(this,a).classList.remove(m.clicking),e(this,a).offsetHeight,e(this,a).classList.add(m.clicking)}show(){this.shown||(this.shown=!0,this.wrapper.style.display="block",requestAnimationFrame(()=>{e(this,c).classList.add(v.animatedBorderVisible)}),r(this,o,window.innerWidth/2),r(this,n,window.innerHeight/2),r(this,p,e(this,o)),r(this,h,e(this,n)),e(this,a).style.left=`${e(this,o)}px`,e(this,a).style.top=`${e(this,n)}px`)}hide(){this.shown&&(this.shown=!1,e(this,c).classList.remove(v.animatedBorderVisible),e(this,a).classList.remove(m.clicking),setTimeout(()=>{this.wrapper.style.display="none"},300))}dispose(){this.wrapper.remove()}}c=new WeakMap,a=new WeakMap,o=new WeakMap,n=new WeakMap,p=new WeakMap,h=new WeakMap,u=new WeakSet,k=function(){e(this,a).className=m.cursor;const t=document.createElement("div");t.className=m.cursorRipple,e(this,a).appendChild(t),this.wrapper.appendChild(e(this,a))},f=function(){const t=e(this,o)+(e(this,p)-e(this,o))*.2,s=e(this,n)+(e(this,h)-e(this,n))*.2,l=Math.abs(t-e(this,p));l>0&&(l<2?r(this,o,e(this,p)):r(this,o,t),e(this,a).style.left=`${e(this,o)}px`);const _=Math.abs(s-e(this,h));_>0&&(_<2?r(this,n,e(this,h)):r(this,n,s),e(this,a).style.top=`${e(this,n)}px`),requestAnimationFrame(()=>w(this,u,f).call(this))};exports.SimulatorMask=D;
package/dist/browser.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./PageController-GcMFZYwU.cjs"),r=require("./browserUse-BOc9kyBK.cjs");r.setPageController(s.PageController);function n(e){return async o=>{const t=o.instruction||o.instruction;return t?new r.CrowBrowserUse({productId:e.productId,apiUrl:e.apiUrl}).execute(t):{status:"error",error:"Missing instruction parameter for browser_use tool"}}}exports.PageController=s.PageController;exports.CrowBrowserUse=r.CrowBrowserUse;exports.createBrowserUseTool=n;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./browserUse-B-b3zqW1.cjs");e.setPageController(e.PageController);let r=null;function w(){r&&(console.log("[Crow] Stopping active browser-use automation"),r.stop(),r=null)}function a(t,u){return async n=>{const s=n.instruction||n.instruction;if(!s)return{status:"error",error:"Missing instruction parameter for browser_use tool"};const l=window.__crow_browser_callbacks,o=u||l,i=new e.CrowBrowserUse({productId:t.productId,apiUrl:t.apiUrl,onConfirmation:o==null?void 0:o.onConfirmation,onQuestion:o==null?void 0:o.onQuestion,onProgress:o==null?void 0:o.onProgress});r=i;try{return await i.execute(s)}finally{r=null}}}exports.CrowBrowserUse=e.CrowBrowserUse;exports.PageController=e.PageController;exports.createBrowserUseTool=a;exports.stopActiveBrowserUse=w;
package/dist/browser.d.ts CHANGED
@@ -17,9 +17,18 @@ declare interface BrowserState {
17
17
  footer: string;
18
18
  }
19
19
 
20
+ export declare interface BrowserUseCallbacks {
21
+ onConfirmation?: (instruction: string) => Promise<boolean>;
22
+ onQuestion?: (question: string) => Promise<string>;
23
+ onProgress?: (step: number, maxSteps: number, action?: string) => void;
24
+ }
25
+
20
26
  declare interface BrowserUseConfig {
21
27
  productId: string;
22
28
  apiUrl: string;
29
+ onConfirmation?: (instruction: string) => Promise<boolean>;
30
+ onQuestion?: (question: string) => Promise<string>;
31
+ onProgress?: (step: number, maxSteps: number, action?: string) => void;
23
32
  }
24
33
 
25
34
  export declare interface BrowserUseToolArgs {
@@ -37,12 +46,20 @@ declare function cleanUpHighlights(): void;
37
46
  * Create a browser_use tool handler for registration with CrowClient or widget.
38
47
  *
39
48
  * @param config - Configuration with productId and apiUrl
49
+ * @param callbacks - Optional callbacks for user interaction (confirmation, questions, progress)
40
50
  * @returns Async function that executes browser automation tasks
41
51
  *
42
52
  * @example
43
53
  * ```typescript
44
- * // Widget usage
45
- * window.__crow_client_tools.browser_use = createBrowserUseTool({ productId, apiUrl });
54
+ * // Widget usage with callbacks
55
+ * window.__crow_client_tools.browser_use = createBrowserUseTool(
56
+ * { productId, apiUrl },
57
+ * {
58
+ * onConfirmation: (instruction) => showConfirmDialog(instruction),
59
+ * onQuestion: (question) => showQuestionDialog(question),
60
+ * onProgress: (step, maxSteps) => updateProgress(step, maxSteps),
61
+ * }
62
+ * );
46
63
  *
47
64
  * // SDK usage
48
65
  * client.registerTools({
@@ -50,13 +67,14 @@ declare function cleanUpHighlights(): void;
50
67
  * });
51
68
  * ```
52
69
  */
53
- export declare function createBrowserUseTool(config: BrowserUseToolConfig): (args: BrowserUseToolArgs | Record<string, unknown>) => Promise<ToolResult>;
70
+ export declare function createBrowserUseTool(config: BrowserUseToolConfig, callbacks?: BrowserUseCallbacks): (args: BrowserUseToolArgs | Record<string, unknown>) => Promise<ToolResult>;
54
71
 
55
72
  export declare class CrowBrowserUse {
56
73
  private config;
57
74
  private pageController;
58
75
  private sessionId;
59
76
  private maxSteps;
77
+ private aborted;
60
78
  constructor(config: BrowserUseConfig);
61
79
  /**
62
80
  * Initialize PageController with non-blocking pointer
@@ -308,6 +326,12 @@ declare interface PageControllerConfig extends dom.DomConfig {
308
326
  enableMask?: boolean;
309
327
  }
310
328
 
329
+ /**
330
+ * Stop any currently running browser-use automation.
331
+ * Safe to call even if no automation is running.
332
+ */
333
+ export declare function stopActiveBrowserUse(): void;
334
+
311
335
  declare interface TextDomNode {
312
336
  type: 'TEXT_NODE';
313
337
  text: string;
@@ -316,7 +340,7 @@ declare interface TextDomNode {
316
340
  }
317
341
 
318
342
  declare interface ToolResult {
319
- status: 'success' | 'error';
343
+ status: 'success' | 'error' | 'needs_input';
320
344
  data?: unknown;
321
345
  error?: string;
322
346
  }
package/dist/browser.js CHANGED
@@ -1,20 +1,35 @@
1
- import { PageController as t } from "./PageController-KoeqDxMP.js";
2
- import { C as s, s as n } from "./browserUse-BbPG4pH1.js";
3
- n(t);
4
- function a(r) {
5
- return async (o) => {
6
- const e = o.instruction || o.instruction;
7
- return e ? new s({
8
- productId: r.productId,
9
- apiUrl: r.apiUrl
10
- }).execute(e) : {
11
- status: "error",
12
- error: "Missing instruction parameter for browser_use tool"
13
- };
1
+ import { C as a, s as l, P as w } from "./browserUse-D5NUCzN4.js";
2
+ l(w);
3
+ let r = null;
4
+ function p() {
5
+ r && (console.log("[Crow] Stopping active browser-use automation"), r.stop(), r = null);
6
+ }
7
+ function U(n, i) {
8
+ return async (t) => {
9
+ const s = t.instruction || t.instruction;
10
+ if (!s)
11
+ return {
12
+ status: "error",
13
+ error: "Missing instruction parameter for browser_use tool"
14
+ };
15
+ const u = window.__crow_browser_callbacks, o = i || u, e = new a({
16
+ productId: n.productId,
17
+ apiUrl: n.apiUrl,
18
+ onConfirmation: o == null ? void 0 : o.onConfirmation,
19
+ onQuestion: o == null ? void 0 : o.onQuestion,
20
+ onProgress: o == null ? void 0 : o.onProgress
21
+ });
22
+ r = e;
23
+ try {
24
+ return await e.execute(s);
25
+ } finally {
26
+ r = null;
27
+ }
14
28
  };
15
29
  }
16
30
  export {
17
- s as CrowBrowserUse,
18
- t as PageController,
19
- a as createBrowserUseTool
31
+ a as CrowBrowserUse,
32
+ w as PageController,
33
+ U as createBrowserUseTool,
34
+ p as stopActiveBrowserUse
20
35
  };
@@ -0,0 +1,9 @@
1
+ "use strict";async function waitFor(o){await new Promise(e=>setTimeout(e,o*1e3))}async function movePointerToElement(o){const e=o.getBoundingClientRect(),n=e.left+e.width/2,r=e.top+e.height/2;window.dispatchEvent(new CustomEvent("PageAgent::MovePointerTo",{detail:{x:n,y:r}})),await waitFor(.3)}function getElementByIndex(o,e){const n=o.get(e);if(!n)throw new Error(`No interactive element found at index ${e}`);const r=n.ref;if(!r)throw new Error(`Element at index ${e} does not have a reference`);if(!(r instanceof HTMLElement))throw new Error(`Element at index ${e} is not an HTMLElement`);return r}let lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&(lastClickedElement.blur(),lastClickedElement.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0,cancelable:!0})),lastClickedElement=null)}async function clickElement(o){blurLastClickedElement(),lastClickedElement=o,await scrollIntoViewIfNeeded(o),await movePointerToElement(o),window.dispatchEvent(new CustomEvent("PageAgent::ClickPointer")),await waitFor(.1),o.dispatchEvent(new MouseEvent("mouseenter",{bubbles:!0,cancelable:!0})),o.dispatchEvent(new MouseEvent("mouseover",{bubbles:!0,cancelable:!0})),o.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,cancelable:!0})),o.focus(),o.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0})),o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),await waitFor(.1)}const nativeInputValueSetter=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value").set,nativeTextAreaValueSetter=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value").set;async function inputTextElement(o,e){if(!(o instanceof HTMLInputElement||o instanceof HTMLTextAreaElement))throw new Error("Element is not an input or textarea");await clickElement(o),o instanceof HTMLTextAreaElement?nativeTextAreaValueSetter.call(o,e):nativeInputValueSetter.call(o,e);const n=new Event("input",{bubbles:!0});o.dispatchEvent(n),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(o,e){if(!(o instanceof HTMLSelectElement))throw new Error("Element is not a select element");const r=Array.from(o.options).find(d=>{var h;return((h=d.textContent)==null?void 0:h.trim())===e.trim()});if(!r)throw new Error(`Option with text "${e}" not found in select element`);o.value=r.value,o.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(o){const e=o;e.scrollIntoViewIfNeeded?e.scrollIntoViewIfNeeded():e.scrollIntoView({behavior:"auto",block:"center",inline:"nearest"})}async function scrollVertically(o,e,n){if(n){const l=n;console.log("[SCROLL DEBUG] Starting direct container scroll for element:",l.tagName);let f=l,v=!1,m=null,c=0,g=0;const C=e;for(;f&&g<10;){const B=window.getComputedStyle(f),D=/(auto|scroll|overlay)/.test(B.overflowY),S=f.scrollHeight>f.clientHeight;if(console.log("[SCROLL DEBUG] Checking element:",f.tagName,"hasScrollableY:",D,"canScrollVertically:",S,"scrollHeight:",f.scrollHeight,"clientHeight:",f.clientHeight),D&&S){const R=f.scrollTop,U=f.scrollHeight-f.clientHeight;let k=C/3;k>0?k=Math.min(k,U-R):k=Math.max(k,-R),f.scrollTop=R+k;const V=f.scrollTop,$=V-R;if(console.log("[SCROLL DEBUG] Scroll attempt:",f.tagName,"before:",R,"after:",V,"delta:",$),Math.abs($)>.5){v=!0,m=f,c=$,console.log("[SCROLL DEBUG] Successfully scrolled container:",f.tagName,"delta:",$);break}}if(f===document.body||f===document.documentElement)break;f=f.parentElement,g++}return v?`Scrolled container (${m==null?void 0:m.tagName}) by ${c}px`:`No scrollable container found for element (${l.tagName})`}const r=e,d=l=>l.clientHeight>=window.innerHeight*.5,h=l=>l&&/(auto|scroll|overlay)/.test(getComputedStyle(l).overflowY)&&l.scrollHeight>l.clientHeight&&d(l);let s=document.activeElement;for(;s&&!h(s)&&s!==document.body;)s=s.parentElement;if(s=h(s)?s:Array.from(document.querySelectorAll("*")).find(h)||document.scrollingElement||document.documentElement,s===document.scrollingElement||s===document.documentElement||s===document.body){const l=window.scrollY,f=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,r);const v=window.scrollY,m=v-l;if(Math.abs(m)<1)return r>0?"⚠️ Already at the bottom of the page, cannot scroll down further.":"⚠️ Already at the top of the page, cannot scroll up further.";const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled page by ${m}px. Reached the bottom of the page.`:g?`✅ Scrolled page by ${m}px. Reached the top of the page.`:`✅ Scrolled page by ${m}px.`}else{const l=s.scrollTop,f=s.scrollHeight-s.clientHeight;s.scrollBy({top:r,behavior:"smooth"}),await waitFor(.1);const v=s.scrollTop,m=v-l;if(Math.abs(m)<1)return r>0?`⚠️ Already at the bottom of container (${s.tagName}), cannot scroll down further.`:`⚠️ Already at the top of container (${s.tagName}), cannot scroll up further.`;const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the bottom.`:g?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the top.`:`✅ Scrolled container (${s.tagName}) by ${m}px.`}}async function scrollHorizontally(o,e,n){if(n){const l=n;console.log("[SCROLL DEBUG] Starting direct container scroll for element:",l.tagName);let f=l,v=!1,m=null,c=0,g=0;const C=o?e:-e;for(;f&&g<10;){const B=window.getComputedStyle(f),D=/(auto|scroll|overlay)/.test(B.overflowX),S=f.scrollWidth>f.clientWidth;if(console.log("[SCROLL DEBUG] Checking element:",f.tagName,"hasScrollableX:",D,"canScrollHorizontally:",S,"scrollWidth:",f.scrollWidth,"clientWidth:",f.clientWidth),D&&S){const R=f.scrollLeft,U=f.scrollWidth-f.clientWidth;let k=C/3;k>0?k=Math.min(k,U-R):k=Math.max(k,-R),f.scrollLeft=R+k;const V=f.scrollLeft,$=V-R;if(console.log("[SCROLL DEBUG] Scroll attempt:",f.tagName,"before:",R,"after:",V,"delta:",$),Math.abs($)>.5){v=!0,m=f,c=$,console.log("[SCROLL DEBUG] Successfully scrolled container:",f.tagName,"delta:",$);break}}if(f===document.body||f===document.documentElement)break;f=f.parentElement,g++}return v?`Scrolled container (${m==null?void 0:m.tagName}) horizontally by ${c}px`:`No horizontally scrollable container found for element (${l.tagName})`}const r=o?e:-e,d=l=>l.clientWidth>=window.innerWidth*.5,h=l=>l&&/(auto|scroll|overlay)/.test(getComputedStyle(l).overflowX)&&l.scrollWidth>l.clientWidth&&d(l);let s=document.activeElement;for(;s&&!h(s)&&s!==document.body;)s=s.parentElement;if(s=h(s)?s:Array.from(document.querySelectorAll("*")).find(h)||document.scrollingElement||document.documentElement,s===document.scrollingElement||s===document.documentElement||s===document.body){const l=window.scrollX,f=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(r,0);const v=window.scrollX,m=v-l;if(Math.abs(m)<1)return r>0?"⚠️ Already at the right edge of the page, cannot scroll right further.":"⚠️ Already at the left edge of the page, cannot scroll left further.";const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled page by ${m}px. Reached the right edge of the page.`:g?`✅ Scrolled page by ${m}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${m}px.`}else{const l=s.scrollLeft,f=s.scrollWidth-s.clientWidth;s.scrollBy({left:r,behavior:"smooth"}),await waitFor(.1);const v=s.scrollLeft,m=v-l;if(Math.abs(m)<1)return r>0?`⚠️ Already at the right edge of container (${s.tagName}), cannot scroll right further.`:`⚠️ Already at the left edge of container (${s.tagName}), cannot scroll left further.`;const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the right edge.`:g?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the left edge.`:`✅ Scrolled container (${s.tagName}) horizontally by ${m}px.`}}const VIEWPORT_EXPANSION=-1,domTree=(o={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:e,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:d}=o,{doHighlightElements:h,focusHighlightIndex:s,viewportExpansion:l,debugMode:f}=o;let v=0;const m=new WeakMap;function c(t,i){!t||t.nodeType!==Node.ELEMENT_NODE||m.set(t,{...m.get(t),...i})}const g={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{g.boundingRects=new WeakMap,g.clientRects=new WeakMap,g.computedStyles=new WeakMap}};function C(t){if(!t)return null;if(g.boundingRects.has(t))return g.boundingRects.get(t);const i=t.getBoundingClientRect();return i&&g.boundingRects.set(t,i),i}function B(t){if(!t)return null;if(g.computedStyles.has(t))return g.computedStyles.get(t);const i=window.getComputedStyle(t);return i&&g.computedStyles.set(t,i),i}function D(t){if(!t)return null;if(g.clientRects.has(t))return g.clientRects.get(t);const i=t.getClientRects();return i&&g.clientRects.set(t,i),i}const S={},R={current:0},U="playwright-highlight-container";function k(t,i,w=null){if(!t)return i;const u=[];let a=null,x=20,E=16,H=null;try{let b=document.getElementById(U);b||(b=document.createElement("div"),b.id=U,b.style.position="fixed",b.style.pointerEvents="none",b.style.top="0",b.style.left="0",b.style.width="100%",b.style.height="100%",b.style.zIndex="2147483640",b.style.backgroundColor="transparent",document.body.appendChild(b));const P=t.getClientRects();if(!P||P.length===0)return i;const O=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"],p=i%O.length;let y=O[p];const I=y+Math.floor(r*255).toString(16).padStart(2,"0");y=y+Math.floor(d*255).toString(16).padStart(2,"0");let L={x:0,y:0};if(w){const N=w.getBoundingClientRect();L.x=N.left,L.y=N.top}const j=document.createDocumentFragment();for(const N of P){if(N.width===0||N.height===0)continue;const M=document.createElement("div");M.style.position="fixed",M.style.border=`2px solid ${y}`,M.style.backgroundColor=I,M.style.pointerEvents="none",M.style.boxSizing="border-box";const T=N.top+L.y,W=N.left+L.x;M.style.top=`${T}px`,M.style.left=`${W}px`,M.style.width=`${N.width}px`,M.style.height=`${N.height}px`,j.appendChild(M),u.push({element:M,initialRect:N})}const G=P[0];if(d>0){a=document.createElement("div"),a.className="playwright-highlight-label",a.style.position="fixed",a.style.background=y,a.style.color="white",a.style.padding="1px 4px",a.style.borderRadius="4px",a.style.fontSize=`${Math.min(12,Math.max(8,G.height/2))}px`,a.textContent=i.toString(),x=a.offsetWidth>0?a.offsetWidth:x,E=a.offsetHeight>0?a.offsetHeight:E;const N=G.top+L.y,M=G.left+L.x;let T=N+2,W=M+G.width-x-2;(G.width<x+4||G.height<E+4)&&(T=N-E-2,W=M+G.width-x,W<L.x&&(W=M)),T=Math.max(0,Math.min(T,window.innerHeight-E)),W=Math.max(0,Math.min(W,window.innerWidth-x)),a.style.top=`${T}px`,a.style.left=`${W}px`,j.appendChild(a)}const q=((N,M)=>{let T=0;return(...W)=>{const X=performance.now();if(!(X-T<M))return T=X,N(...W)}})(()=>{const N=t.getClientRects();let M={x:0,y:0};if(w){const T=w.getBoundingClientRect();M.x=T.left,M.y=T.top}if(u.forEach((T,W)=>{if(W<N.length){const X=N[W],tt=X.top+M.y,Q=X.left+M.x;T.element.style.top=`${tt}px`,T.element.style.left=`${Q}px`,T.element.style.width=`${X.width}px`,T.element.style.height=`${X.height}px`,T.element.style.display=X.width===0||X.height===0?"none":"block"}else T.element.style.display="none"}),N.length<u.length)for(let T=N.length;T<u.length;T++)u[T].element.style.display="none";if(a&&N.length>0){const T=N[0],W=T.top+M.y,X=T.left+M.x;let tt=W+2,Q=X+T.width-x-2;(T.width<x+4||T.height<E+4)&&(tt=W-E-2,Q=X+T.width-x,Q<M.x&&(Q=X)),tt=Math.max(0,Math.min(tt,window.innerHeight-E)),Q=Math.max(0,Math.min(Q,window.innerWidth-x)),a.style.top=`${tt}px`,a.style.left=`${Q}px`,a.style.display="block"}else a&&(a.style.display="none")},16);return window.addEventListener("scroll",q,!0),window.addEventListener("resize",q),H=()=>{window.removeEventListener("scroll",q,!0),window.removeEventListener("resize",q),u.forEach(N=>N.element.remove()),a&&a.remove()},b.appendChild(j),i+1}finally{H&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(H)}}function V(t){if(!t||t.nodeType!==Node.ELEMENT_NODE)return null;const i=B(t);if(!i)return null;const w=i.display;if(w==="inline"||w==="inline-block")return null;const u=i.overflowX,a=i.overflowY,x=u==="auto"||u==="scroll",E=a==="auto"||a==="scroll";if(!x&&!E)return null;const H=t.scrollWidth-t.clientWidth,b=t.scrollHeight-t.clientHeight,P=4;if(H<P&&b<P||!E&&H<P||!x&&b<P)return null;const O=t.scrollTop,p=t.scrollLeft,y=t.scrollWidth-t.clientWidth-t.scrollLeft,I=t.scrollHeight-t.clientHeight-t.scrollTop,L={top:O,right:y,bottom:I,left:p};return c(t,{scrollable:!0,scrollData:L}),L}function $(t){try{if(l===-1){const E=t.parentElement;if(!E)return!1;try{return E.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const b=window.getComputedStyle(E);return b.display!=="none"&&b.visibility!=="hidden"&&b.opacity!=="0"}}const i=document.createRange();i.selectNodeContents(t);const w=i.getClientRects();if(!w||w.length===0)return!1;let u=!1,a=!1;for(const E of w)if(E.width>0&&E.height>0&&(u=!0,!(E.bottom<-l||E.top>window.innerHeight+l||E.right<-l||E.left>window.innerWidth+l))){a=!0;break}if(!u||!a)return!1;const x=t.parentElement;if(!x)return!1;try{return x.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const H=window.getComputedStyle(x);return H.display!=="none"&&H.visibility!=="hidden"&&H.opacity!=="0"}}catch(i){return console.warn("Error checking text node visibility:",i),!1}}function _(t){if(!t||!t.tagName)return!1;const i=new Set(["body","div","main","article","section","nav","header","footer"]),w=t.tagName.toLowerCase();return i.has(w)?!0:!new Set(["svg","script","style","link","meta","noscript","template"]).has(w)}function F(t){const i=B(t);return t.offsetWidth>0&&t.offsetHeight>0&&(i==null?void 0:i.visibility)!=="hidden"&&(i==null?void 0:i.display)!=="none"}function A(t){var I,L;if(!t||t.nodeType!==Node.ELEMENT_NODE||e.includes(t))return!1;if(n.includes(t))return!0;const i=t.tagName.toLowerCase(),w=B(t),u=new Set(["pointer","move","text","grab","grabbing","cell","copy","alias","all-scroll","col-resize","context-menu","crosshair","e-resize","ew-resize","help","n-resize","ne-resize","nesw-resize","ns-resize","nw-resize","nwse-resize","row-resize","s-resize","se-resize","sw-resize","vertical-text","w-resize","zoom-in","zoom-out"]),a=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);function x(j){return j.tagName.toLowerCase()==="html"?!1:!!(w!=null&&w.cursor&&u.has(w.cursor))}if(x(t))return!0;const H=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),b=new Set(["disabled","readonly"]);if(H.has(i)){if(w!=null&&w.cursor&&a.has(w.cursor))return!1;for(const j of b)if(t.hasAttribute(j)||t.getAttribute(j)==="true"||t.getAttribute(j)==="")return!1;return!(t.disabled||t.readOnly||t.inert)}const P=t.getAttribute("role"),O=t.getAttribute("aria-role");if(t.getAttribute("contenteditable")==="true"||t.isContentEditable||t.classList&&(t.classList.contains("button")||t.classList.contains("dropdown-toggle")||t.getAttribute("data-index")||t.getAttribute("data-toggle")==="dropdown"||t.getAttribute("aria-haspopup")==="true"))return!0;const p=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(H.has(i)||P&&p.has(P)||O&&p.has(O))return!0;try{if(typeof getEventListeners=="function"){const J=getEventListeners(t),nt=["click","mousedown","mouseup","dblclick"];for(const q of nt)if(J[q]&&J[q].length>0)return!0}const j=((L=(I=t==null?void 0:t.ownerDocument)==null?void 0:I.defaultView)==null?void 0:L.getEventListenersForNode)||window.getEventListenersForNode;if(typeof j=="function"){const J=j(t),nt=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const q of nt)for(const N of J)if(N.type===q)return!0}const G=["onclick","onmousedown","onmouseup","ondblclick"];for(const J of G)if(t.hasAttribute(J)||typeof t[J]=="function")return!0}catch{}return!!V(t)}function ot(t){if(l===-1)return!0;const i=D(t);if(!i||i.length===0)return!1;let w=!1;for(const b of i)if(b.width>0&&b.height>0&&!(b.bottom<-l||b.top>window.innerHeight+l||b.right<-l||b.left>window.innerWidth+l)){w=!0;break}if(!w)return!1;if(t.ownerDocument!==window.document)return!0;let a=Array.from(i).find(b=>b.width>0&&b.height>0);if(!a)return!1;const x=t.getRootNode();if(x instanceof ShadowRoot){const b=a.left+a.width/2,P=a.top+a.height/2;try{const O=x.elementFromPoint(b,P);if(!O)return!1;let p=O;for(;p&&p!==x;){if(p===t)return!0;p=p.parentElement}return!1}catch{return!0}}const E=5;return[{x:a.left+a.width/2,y:a.top+a.height/2},{x:a.left+E,y:a.top+E},{x:a.right-E,y:a.bottom-E}].some(({x:b,y:P})=>{try{const O=document.elementFromPoint(b,P);if(!O)return!1;let p=O;for(;p&&p!==document.documentElement;){if(p===t)return!0;p=p.parentElement}return!1}catch{return!0}})}function rt(t,i){if(i===-1)return!0;const w=t.getClientRects();if(!w||w.length===0){const u=C(t);return!u||u.width===0||u.height===0?!1:!(u.bottom<-i||u.top>window.innerHeight+i||u.right<-i||u.left>window.innerWidth+i)}for(const u of w)if(!(u.width===0||u.height===0)&&!(u.bottom<-i||u.top>window.innerHeight+i||u.right<-i||u.left>window.innerWidth+i))return!0;return!1}function z(t){if(!t||t.nodeType!==Node.ELEMENT_NODE)return!1;const i=t.tagName.toLowerCase();return new Set(["a","button","input","select","textarea","details","summary","label"]).has(i)?!0:t.hasAttribute("onclick")||t.hasAttribute("role")||t.hasAttribute("tabindex")||t.hasAttribute("aria-")||t.hasAttribute("data-action")||t.getAttribute("contenteditable")==="true"}const Y=new Set(["a","button","input","select","textarea","summary","details","label","option"]),K=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);function et(t){if(!t||t.nodeType!==Node.ELEMENT_NODE||!F(t))return!1;const i=t.hasAttribute("role")||t.hasAttribute("tabindex")||t.hasAttribute("onclick")||typeof t.onclick=="function",w=/\b(btn|clickable|menu|item|entry|link)\b/i.test(t.className||""),u=!!t.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar'),a=[...t.children].some(F),x=t.parentElement&&t.parentElement.isSameNode(document.body);return(A(t)||i||w)&&a&&u&&!x}function it(t){var u,a;if(!t||t.nodeType!==Node.ELEMENT_NODE)return!1;const i=t.tagName.toLowerCase(),w=t.getAttribute("role");if(i==="iframe"||Y.has(i)||w&&K.has(w)||t.isContentEditable||t.getAttribute("contenteditable")==="true"||t.hasAttribute("data-testid")||t.hasAttribute("data-cy")||t.hasAttribute("data-test")||t.hasAttribute("onclick")||typeof t.onclick=="function")return!0;try{const x=((a=(u=t==null?void 0:t.ownerDocument)==null?void 0:u.defaultView)==null?void 0:a.getEventListenersForNode)||window.getEventListenersForNode;if(typeof x=="function"){const H=x(t),b=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const P of b)for(const O of H)if(O.type===P)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(H=>t.hasAttribute(H)))return!0}catch{}return!!et(t)}function st(t,i,w,u){if(!t.isInteractive)return!1;let a=!1;return u?it(i)?a=!0:a=!1:a=!0,a&&(t.isInViewport=rt(i,l),(t.isInViewport||l===-1)&&(t.highlightIndex=v++,h))?(s>=0?s===t.highlightIndex&&k(i,t.highlightIndex,w):k(i,t.highlightIndex,w),!0):!1}function Z(t,i=null,w=!1){var E,H,b,P,O;if(!t||t.id===U||t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE||!t||t.id===U||((E=t.dataset)==null?void 0:E.browserUseIgnore)==="true"||t.getAttribute&&t.getAttribute("aria-hidden")==="true")return null;if(t===document.body){const p={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const I of t.childNodes){const L=Z(I,i,!1);L&&p.children.push(L)}const y=`${R.current++}`;return S[y]=p,y}if(t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE)return null;if(t.nodeType===Node.TEXT_NODE){const p=(H=t.textContent)==null?void 0:H.trim();if(!p)return null;const y=t.parentElement;if(!y||y.tagName.toLowerCase()==="script")return null;const I=`${R.current++}`;return S[I]={type:"TEXT_NODE",text:p,isVisible:$(t)},I}if(t.nodeType===Node.ELEMENT_NODE&&!_(t))return null;if(l!==-1&&!t.shadowRoot){const p=C(t),y=B(t),I=y&&(y.position==="fixed"||y.position==="sticky"),L=t.offsetWidth>0||t.offsetHeight>0;if(!p||!I&&!L&&(p.bottom<-l||p.top>window.innerHeight+l||p.right<-l||p.left>window.innerWidth+l))return null}const u={tagName:t.tagName.toLowerCase(),attributes:{},children:[]};if(z(t)||t.tagName.toLowerCase()==="iframe"||t.tagName.toLowerCase()==="body"){const p=((b=t.getAttributeNames)==null?void 0:b.call(t))||[];for(const y of p){const I=t.getAttribute(y);u.attributes[y]=I}t.tagName.toLowerCase()==="input"&&(t.type==="checkbox"||t.type==="radio")&&(u.attributes.checked=t.checked?"true":"false")}let a=!1;if(t.nodeType===Node.ELEMENT_NODE&&(u.isVisible=F(t),u.isVisible)){u.isTopElement=ot(t);const p=t.getAttribute("role"),y=p==="menu"||p==="menubar"||p==="listbox";(u.isTopElement||y)&&(u.isInteractive=A(t),a=st(u,t,i,w),u.ref=t)}if(t.tagName){const p=t.tagName.toLowerCase();if(p==="iframe")try{const y=t.contentDocument||((P=t.contentWindow)==null?void 0:P.document);if(y)for(const I of y.childNodes){const L=Z(I,t,!1);L&&u.children.push(L)}}catch(y){console.warn("Unable to access iframe:",y)}else if(t.isContentEditable||t.getAttribute("contenteditable")==="true"||t.id==="tinymce"||t.classList.contains("mce-content-body")||p==="body"&&((O=t.getAttribute("data-id"))!=null&&O.startsWith("mce_")))for(const y of t.childNodes){const I=Z(y,i,a);I&&u.children.push(I)}else{if(t.shadowRoot){u.shadowRoot=!0;for(const y of t.shadowRoot.childNodes){const I=Z(y,i,a);I&&u.children.push(I)}}for(const y of t.childNodes){const L=Z(y,i,a||w);L&&u.children.push(L)}}}if(u.tagName==="a"&&u.children.length===0&&!u.attributes.href){const p=C(t);if(!(p&&p.width>0&&p.height>0||t.offsetWidth>0||t.offsetHeight>0))return null}u.extra=m.get(t)||null;const x=`${R.current++}`;return S[x]=u,x}const lt=Z(document.body);return g.clearCache(),{rootId:lt,map:S}},newElementsCache=new WeakMap;function getFlatTree(o){const e=[];for(const h of o.interactiveBlacklist||[])typeof h=="function"?e.push(h()):e.push(h);const n=[];for(const h of o.interactiveWhitelist||[])typeof h=="function"?n.push(h()):n.push(h);const r=domTree({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:VIEWPORT_EXPANSION,interactiveBlacklist:e,interactiveWhitelist:n,highlightOpacity:o.highlightOpacity??0,highlightLabelOpacity:o.highlightLabelOpacity??.1}),d=window.location.href;for(const h in r.map){const s=r.map[h];if(s.isInteractive&&s.ref){const l=s.ref;newElementsCache.has(l)||(newElementsCache.set(l,d),s.isNew=!0)}}return r}function flatTreeToString(o,e){const n=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns"],r=[...e||[],...n],d=(c,g)=>c.length>g?c.substring(0,g)+"...":c,h=c=>{const g=o.map[c];if(!g)return null;if(g.type==="TEXT_NODE"){const C=g;return{type:"text",text:C.text,isVisible:C.isVisible,parent:null,children:[]}}else{const C=g,B=[];if(C.children)for(const D of C.children){const S=h(D);S&&(S.parent=null,B.push(S))}return{type:"element",tagName:C.tagName,attributes:C.attributes??{},isVisible:C.isVisible??!1,isInteractive:C.isInteractive??!1,isTopElement:C.isTopElement??!1,isNew:C.isNew??!1,highlightIndex:C.highlightIndex,parent:null,children:B,extra:C.extra??{}}}},s=(c,g=null)=>{c.parent=g;for(const C of c.children)s(C,c)},l=h(o.rootId);if(!l)return"";s(l);const f=c=>{let g=c.parent;for(;g;){if(g.type==="element"&&g.highlightIndex!==void 0)return!0;g=g.parent}return!1},v=(c,g,C)=>{var S,R,U,k;let B=g;const D=" ".repeat(g);if(c.type==="element"){if(c.highlightIndex!==void 0){B+=1;const V=getAllTextTillNextClickableElement(c);let $="";if(r.length>0&&c.attributes){const A={};for(const z of r){const Y=c.attributes[z];Y&&Y.trim()!==""&&(A[z]=Y.trim())}const ot=r.filter(z=>z in A);if(ot.length>1){const z=new Set,Y={};for(const K of ot){const et=A[K];et.length>5&&(et in Y?z.add(K):Y[et]=K)}for(const K of z)delete A[K]}A.role===c.tagName&&delete A.role;const rt=["aria-label","placeholder","title"];for(const z of rt)A[z]&&A[z].toLowerCase().trim()===V.toLowerCase().trim()&&delete A[z];Object.keys(A).length>0&&($=Object.entries(A).map(([z,Y])=>`${z}=${d(Y,20)}`).join(" "))}const _=c.isNew?`*[${c.highlightIndex}]`:`[${c.highlightIndex}]`;let F=`${D}${_}<${c.tagName??""}`;if($&&(F+=` ${$}`),c.extra&&c.extra.scrollable){let A="";(S=c.extra.scrollData)!=null&&S.left&&(A+=`left=${c.extra.scrollData.left}, `),(R=c.extra.scrollData)!=null&&R.top&&(A+=`top=${c.extra.scrollData.top}, `),(U=c.extra.scrollData)!=null&&U.right&&(A+=`right=${c.extra.scrollData.right}, `),(k=c.extra.scrollData)!=null&&k.bottom&&(A+=`bottom=${c.extra.scrollData.bottom}`),F+=` data-scrollable="${A}"`}if(V){const A=V.trim();$||(F+=" "),F+=`>${A}`}else $||(F+=" ");F+=" />",C.push(F)}for(const V of c.children)v(V,B,C)}else if(c.type==="text"){if(f(c))return;c.parent&&c.parent.type==="element"&&c.parent.isVisible&&c.parent.isTopElement&&C.push(`${D}${c.text??""}`)}},m=[];return v(l,0,m),m.join(`
2
+ `)}const getAllTextTillNextClickableElement=(o,e=-1)=>{const n=[],r=(d,h)=>{if(!(e!==-1&&h>e)&&!(d.type==="element"&&d!==o&&d.highlightIndex!==void 0)){if(d.type==="text"&&d.text)n.push(d.text);else if(d.type==="element")for(const s of d.children)r(s,h+1)}};return r(o,0),n.join(`
3
+ `).trim()};function getSelectorMap(o){const e=new Map,n=Object.keys(o.map);for(const r of n){const d=o.map[r];d.isInteractive&&typeof d.highlightIndex=="number"&&e.set(d.highlightIndex,d)}return e}function getElementTextMap(o){const e=o.split(`
4
+ `).map(r=>r.trim()).filter(r=>r.length>0),n=new Map;for(const r of e){const h=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(r);if(h){const s=parseInt(h[1],10);n.set(s,r)}}return n}function cleanUpHighlights(){const o=window._highlightCleanupFunctions||[];for(const e of o)typeof e=="function"&&e();window._highlightCleanupFunctions=[]}window.addEventListener("popstate",()=>{cleanUpHighlights()});window.addEventListener("hashchange",()=>{cleanUpHighlights()});window.addEventListener("beforeunload",()=>{cleanUpHighlights()});const navigation=window.navigation;if(navigation&&typeof navigation.addEventListener=="function")navigation.addEventListener("navigate",()=>{cleanUpHighlights()});else{let o=window.location.href;setInterval(()=>{window.location.href!==o&&(o=window.location.href,cleanUpHighlights())},500)}function getPageInfo(){const o=window.innerWidth,e=window.innerHeight,n=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),r=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),d=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,h=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,s=Math.max(0,r-(window.innerHeight+h)),l=Math.max(0,n-(window.innerWidth+d));return{viewport_width:o,viewport_height:e,page_width:n,page_height:r,scroll_x:d,scroll_y:h,pixels_above:h,pixels_below:s,pages_above:e>0?h/e:0,pages_below:e>0?s/e:0,total_pages:e>0?r/e:0,current_page_position:h/Math.max(1,r-e),pixels_left:d,pixels_right:l}}function patchReact(o){const e=document.querySelectorAll('[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root');for(const n of e)n.setAttribute("data-page-agent-not-interactive","true")}class PageController extends EventTarget{constructor(o={}){super(),this.flatTree=null,this.selectorMap=new Map,this.elementTextMap=new Map,this.simplifiedHTML="<EMPTY>",this.lastTimeUpdate=0,this.isIndexed=!1,this.mask=null,this.maskReady=null,this.config=o,patchReact(),o.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{const{SimulatorMask:o}=await Promise.resolve().then(()=>require("./SimulatorMask-jCkPs2Tt.cjs"));this.mask=new o})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){const o=window.location.href,e=document.title,n=getPageInfo(),r=this.config.viewportExpansion??VIEWPORT_EXPANSION;await this.updateTree();const d=this.simplifiedHTML,h=`Current Page: [${e}](${o})`,s=`Page info: ${n.viewport_width}x${n.viewport_height}px viewport, ${n.page_width}x${n.page_height}px total page size, ${n.pages_above.toFixed(1)} pages above, ${n.pages_below.toFixed(1)} pages below, ${n.total_pages.toFixed(1)} total pages, at ${(n.current_page_position*100).toFixed(0)}% of page`,l=r===-1?"Interactive elements from top layer of the current page (full page):":"Interactive elements from top layer of the current page inside the viewport:",v=n.pixels_above>4&&r!==-1?`... ${n.pixels_above} pixels above (${n.pages_above.toFixed(1)} pages) - scroll to see more ...`:"[Start of page]",m=`${h}
5
+ ${s}
6
+
7
+ ${l}
8
+
9
+ ${v}`,g=n.pixels_below>4&&r!==-1?`... ${n.pixels_below} pixels below (${n.pages_below.toFixed(1)} pages) - scroll to see more ...`:"[End of page]";return{url:o,title:e,header:m,content:d,footer:g}}async updateTree(){this.dispatchEvent(new Event("beforeUpdate")),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents="none"),cleanUpHighlights();const o=[...this.config.interactiveBlacklist||[],...document.querySelectorAll("[data-page-agent-not-interactive]").values()];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:o}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.include_attributes),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.mask&&(this.mask.wrapper.style.pointerEvents="auto"),this.dispatchEvent(new Event("afterUpdate")),this.simplifiedHTML}async cleanUpHighlights(){cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw new Error("DOM tree not indexed yet. Can not perform actions on elements.")}async clickElement(o){try{this.assertIndexed();const e=getElementByIndex(this.selectorMap,o),n=this.elementTextMap.get(o);return await clickElement(e),e instanceof HTMLAnchorElement&&e.target==="_blank"?{success:!0,message:`✅ Clicked element (${n??o}). ⚠️ Link opens in a new tab. You are not capable of reading new tabs.`}:{success:!0,message:`✅ Clicked element (${n??o}).`}}catch(e){return{success:!1,message:`❌ Failed to click element: ${e}`}}}async inputText(o,e){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,o),r=this.elementTextMap.get(o);return await inputTextElement(n,e),{success:!0,message:`✅ Input text (${e}) into element (${r??o}).`}}catch(n){return{success:!1,message:`❌ Failed to input text: ${n}`}}}async selectOption(o,e){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,o),r=this.elementTextMap.get(o);return await selectOptionElement(n,e),{success:!0,message:`✅ Selected option (${e}) in element (${r??o}).`}}catch(n){return{success:!1,message:`❌ Failed to select option: ${n}`}}}async scroll(o){try{const{down:e,numPages:n,pixels:r,index:d}=o;this.assertIndexed();const h=r??n*(e?1:-1)*window.innerHeight,s=d!==void 0?getElementByIndex(this.selectorMap,d):null;return{success:!0,message:await scrollVertically(e,h,s)}}catch(e){return{success:!1,message:`❌ Failed to scroll: ${e}`}}}async scrollHorizontally(o){try{const{right:e,pixels:n,index:r}=o;this.assertIndexed();const d=n*(e?1:-1),h=r!==void 0?getElementByIndex(this.selectorMap,r):null;return{success:!0,message:await scrollHorizontally(e,d,h)}}catch(e){return{success:!1,message:`❌ Failed to scroll horizontally: ${e}`}}}async executeJavascript(script){try{const asyncFunction=eval(`(async () => { ${script} })`),result=await asyncFunction();return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(o){return{success:!1,message:`❌ Error executing JavaScript: ${o}`}}}async showMask(){var o;await this.maskReady,(o=this.mask)==null||o.show()}async hideMask(){var o;await this.maskReady,(o=this.mask)==null||o.hide()}dispose(){var o;cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="<EMPTY>",this.isIndexed=!1,(o=this.mask)==null||o.dispose(),this.mask=null}}const PageController$1=Object.freeze(Object.defineProperty({__proto__:null,PageController},Symbol.toStringTag,{value:"Module"}));let injectedPageController=null,PageControllerModule=null;function setPageController(o){injectedPageController=o}async function getPageController(){if(injectedPageController)return injectedPageController;if(!PageControllerModule)try{PageControllerModule=await Promise.resolve().then(()=>PageController$1)}catch{throw new Error('PageController not available. Either import from "@usecrow/client/browser" or use the bundled version.')}return PageControllerModule.PageController}class CrowBrowserUse{constructor(e){this.pageController=null,this.sessionId=null,this.maxSteps=20,this.aborted=!1,this.config=e}async initPageController(){if(this.pageController)return this.pageController;try{const e=await getPageController();this.pageController=new e({enableMask:!0,viewportExpansion:500,highlightLabelOpacity:0,highlightOpacity:0}),await this.pageController.showMask();const n=this.pageController.mask;return n!=null&&n.wrapper&&(n.wrapper.style.pointerEvents="none"),console.log("[CrowBrowserUse] PageController initialized with non-blocking pointer"),this.pageController}catch(e){throw console.error("[CrowBrowserUse] Failed to initialize PageController:",e),new Error("Failed to initialize browser automation. Please import from @usecrow/client/browser.")}}async execute(e){var n,r,d,h,s,l,f,v,m,c,g,C,B,D;if(console.log("[CrowBrowserUse] Starting task:",e),this.config.onConfirmation&&!await this.config.onConfirmation(e))return console.log("[CrowBrowserUse] User declined browser automation"),(r=(n=this.config).onProgress)==null||r.call(n,-1,this.maxSteps),{status:"error",error:"User declined browser automation",data:{declined:!0}};try{const S=await this.initPageController(),R=await this.startSession(e);this.sessionId=R.session_id,this.maxSteps=R.max_steps,console.log("[CrowBrowserUse] Session started:",this.sessionId);let U=0,k;for(;U<this.maxSteps;){if(this.aborted)return console.log("[CrowBrowserUse] Task cancelled by user"),await this.cleanup(),(h=(d=this.config).onProgress)==null||h.call(d,-1,this.maxSteps),{status:"error",error:"Task cancelled by user"};U++;const V=await S.getBrowserState(),$=S.mask;$!=null&&$.wrapper&&($.wrapper.style.pointerEvents="none");const _=await this.processStep(V,k);if(_.needs_user_input&&_.question){if(console.log("[CrowBrowserUse] Asking user:",_.question),!this.config.onQuestion){k="User input not available - no callback provided",console.warn("[CrowBrowserUse] No onQuestion callback provided");continue}try{const F=await this.config.onQuestion(_.question);k=`User answered: ${F}`,console.log("[CrowBrowserUse] User answered:",F)}catch(F){if(k="User cancelled or failed to respond",console.log("[CrowBrowserUse] User cancelled or error:",F),this.aborted)return console.log("[CrowBrowserUse] Aborted after user cancelled"),await this.cleanup(),(l=(s=this.config).onProgress)==null||l.call(s,-1,this.maxSteps),{status:"error",error:"Task cancelled by user"}}continue}if(_.done)return console.log("[CrowBrowserUse] Task completed:",_.message),await this.cleanup(),(v=(f=this.config).onProgress)==null||v.call(f,U,this.maxSteps),{status:_.success?"success":"error",data:{message:_.message,steps:U},error:_.success?void 0:_.message};if(_.error)return console.error("[CrowBrowserUse] Error:",_.error),await this.cleanup(),(c=(m=this.config).onProgress)==null||c.call(m,-1,this.maxSteps),{status:"error",error:_.error};_.action&&(k=await this.executeAction(S,_.action),console.log(`[CrowBrowserUse] Step ${U}:`,k)),_.reflection&&console.log("[CrowBrowserUse] Reflection:",_.reflection.next_goal)}return await this.cleanup(),(C=(g=this.config).onProgress)==null||C.call(g,-1,this.maxSteps),{status:"error",error:`Task incomplete after ${this.maxSteps} steps`}}catch(S){return console.error("[CrowBrowserUse] Error:",S),await this.cleanup(),(D=(B=this.config).onProgress)==null||D.call(B,-1,this.maxSteps),{status:"error",error:S instanceof Error?S.message:String(S)}}}async startSession(e){const n=await fetch(`${this.config.apiUrl}/api/browser-use/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({product_id:this.config.productId,task:e})});if(!n.ok){const r=await n.json().catch(()=>({detail:"Unknown error"}));throw new Error(r.detail||`Failed to start session: ${n.status}`)}return n.json()}async processStep(e,n){const r=await fetch(`${this.config.apiUrl}/api/browser-use/step`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.sessionId,product_id:this.config.productId,browser_state:e,action_result:n})});if(!r.ok){const d=await r.json().catch(()=>({detail:"Unknown error"}));throw new Error(d.detail||`Failed to process step: ${r.status}`)}return r.json()}async executeAction(e,n){const r=Object.keys(n)[0],d=n[r];try{switch(r){case"click_element_by_index":return(await e.clickElement(d.index)).message;case"input_text":return(await e.inputText(d.index,d.text)).message;case"select_dropdown_option":return(await e.selectOption(d.index,d.text)).message;case"scroll":return(await e.scroll({down:d.down,numPages:d.num_pages,pixels:d.pixels,index:d.index})).message;case"scroll_horizontally":return(await e.scrollHorizontally({right:d.right,pixels:d.pixels,index:d.index})).message;case"wait":{const h=d.seconds||1;return await new Promise(s=>setTimeout(s,h*1e3)),`Waited ${h} seconds`}case"done":return"Task completed";default:return`Unknown action: ${r}`}}catch(h){return`Action failed: ${h instanceof Error?h.message:String(h)}`}}async cleanup(){if(this.pageController){try{await this.pageController.hideMask(),await this.pageController.cleanUpHighlights(),this.pageController.dispose()}catch(e){console.warn("[CrowBrowserUse] Cleanup error:",e)}this.pageController=null}if(this.sessionId){try{await fetch(`${this.config.apiUrl}/api/browser-use/end`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.sessionId,product_id:this.config.productId})})}catch{}this.sessionId=null}}async stop(){this.aborted=!0,await this.cleanup()}}exports.CrowBrowserUse=CrowBrowserUse;exports.PageController=PageController;exports.setPageController=setPageController;