surf-cli 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,7 +23,7 @@ Surf takes a different approach:
23
23
 
24
24
  **Smart Defaults** - Screenshots auto-resize to 1200px (saves tokens). Actions auto-capture screenshots (saves round-trips). Errors on restricted pages warn instead of fail.
25
25
 
26
- **AI Without API Keys** - Query ChatGPT, Gemini, and Perplexity using your browser's logged-in session. No API keys, no rate limits, no cost.
26
+ **AI Without API Keys** - Query ChatGPT, Gemini, Perplexity, and Grok using your existing browser logins. No API keys needed.
27
27
 
28
28
  **Network Capture** - Automatically logs all network requests while active. Filter, search, and replay API calls without manually setting up request interception.
29
29
 
@@ -168,6 +168,29 @@ surf key Escape # Press key
168
168
  surf scroll.bottom # Scroll to bottom
169
169
  ```
170
170
 
171
+ ### Forms
172
+
173
+ Select options in dropdown menus:
174
+
175
+ ```bash
176
+ surf select e5 "US" # Select by value
177
+ surf select "#country" "US" # Select by CSS selector
178
+ surf select e5 "opt1" "opt2" # Multi-select
179
+ surf select e5 --by label "United States" # Select by visible text
180
+ surf select e5 --by index 0 # Select first option
181
+ ```
182
+
183
+ ### Element Inspection
184
+
185
+ Get computed styles from elements:
186
+
187
+ ```bash
188
+ surf element.styles e5 # Get styles by ref
189
+ surf element.styles ".header" # Get styles by CSS selector (can return multiple)
190
+ ```
191
+
192
+ Returns font, color, background, border, padding, and bounding box for design debugging.
193
+
171
194
  ### Screenshots
172
195
 
173
196
  Screenshots auto-save to `/tmp` by default (optimized for AI agents):
@@ -275,9 +298,20 @@ surf perplexity "what is quantum computing"
275
298
  surf perplexity "explain this page" --with-page # Include page context
276
299
  surf perplexity "deep dive" --mode research # Research mode (Pro)
277
300
  surf perplexity "latest news" --model sonar # Model selection (Pro)
301
+
302
+ # Grok (queries x.com/i/grok using your X.com login)
303
+ surf grok "what are the latest AI agent trends on X" # Search X posts
304
+ surf grok "analyze @username recent activity" # Profile analysis
305
+ surf grok "summarize this page" --with-page # Include page context
306
+ surf grok "find viral AI posts" --deep-search # DeepSearch mode
307
+ surf grok "quick question" --model fast # Models: auto, fast, expert, thinking
308
+ surf grok --validate # Check UI and available models
309
+ surf grok --validate --save-models # Save discovered models to settings
278
310
  ```
279
311
 
280
- Requires being logged into chatgpt.com, gemini.google.com, or perplexity.ai in Chrome.
312
+ Each AI tool uses your existing browser login - no API keys needed. Just be logged into the respective service in Chrome (chatgpt.com, gemini.google.com, perplexity.ai, or x.com).
313
+
314
+ **Grok troubleshooting:** If queries fail, run `surf grok --validate` to check if the UI structure changed. Use `--save-models` to update the model cache in `surf.json`. Default model is "thinking" (Grok 4.1 Thinking).
281
315
 
282
316
  ### Waiting
283
317
 
@@ -360,6 +394,7 @@ echo '{"type":"tool_request","method":"execute_tool","params":{"tool":"tab.list"
360
394
  | `scroll.*` | `top`, `bottom`, `to`, `info` |
361
395
  | `page.*` | `read`, `text`, `state` |
362
396
  | `locate.*` | `role`, `text`, `label` |
397
+ | `element.*` | `styles` |
363
398
  | `frame.*` | `list`, `switch`, `main`, `js` |
364
399
  | `wait.*` | `element`, `network`, `url`, `dom`, `load` |
365
400
  | `cookie.*` | `list`, `get`, `set`, `clear` |
@@ -1,11 +1,11 @@
1
- const J=new Set(["alert","alertdialog","application","article","banner","blockquote","button","caption","cell","checkbox","code","columnheader","combobox","complementary","contentinfo","definition","deletion","dialog","directory","document","emphasis","feed","figure","form","generic","grid","gridcell","group","heading","img","insertion","link","list","listbox","listitem","log","main","mark","marquee","math","menu","menubar","menuitem","menuitemcheckbox","menuitemradio","meter","navigation","none","note","option","paragraph","presentation","progressbar","radio","radiogroup","region","row","rowgroup","rowheader","scrollbar","search","searchbox","separator","slider","spinbutton","status","strong","subscript","superscript","switch","tab","table","tablist","tabpanel","term","textbox","time","timer","toolbar","tooltip","tree","treegrid","treeitem"]);function Q(r){const h=r.tagName.toLowerCase();if(["button","input","select","textarea"].includes(h))return!r.disabled;if(h==="a"&&r.hasAttribute("href"))return!0;if(r.hasAttribute("tabindex")){const i=parseInt(r.getAttribute("tabindex")||"",10);return!isNaN(i)&&i>=0}return r.getAttribute("contenteditable")==="true"}function Z(r){const h=r.getAttribute("role");if(!h)return null;const i=h.split(/\s+/).filter(m=>m);for(const m of i)if(J.has(m))return m;return null}function X(r){const h=r.tagName.toLowerCase(),i=r.getAttribute("type"),m={a:p=>p.hasAttribute("href")?"link":"generic",article:"article",aside:"complementary",button:"button",datalist:"listbox",dd:"definition",details:"group",dialog:"dialog",dt:"term",fieldset:"group",figure:"figure",footer:p=>p.closest("article, aside, main, nav, section")?"generic":"contentinfo",form:p=>p.hasAttribute("aria-label")||p.hasAttribute("aria-labelledby")?"form":"generic",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",header:p=>p.closest("article, aside, main, nav, section")?"generic":"banner",hr:"separator",img:p=>p.getAttribute("alt")===""?"presentation":"img",li:"listitem",main:"main",math:"math",menu:"list",meter:"meter",nav:"navigation",ol:"list",optgroup:"group",option:"option",output:"status",p:"paragraph",progress:"progressbar",search:"search",section:p=>p.hasAttribute("aria-label")||p.hasAttribute("aria-labelledby")?"region":"generic",select:p=>{const e=p;return e.hasAttribute("multiple")||e.size&&e.size>1?"listbox":"combobox"},table:"table",tbody:"rowgroup",td:"cell",textarea:"textbox",tfoot:"rowgroup",th:"columnheader",thead:"rowgroup",time:"time",tr:"row",ul:"list"};if(h==="input")return{button:"button",checkbox:"checkbox",email:"textbox",file:"button",image:"button",number:"spinbutton",radio:"radio",range:"slider",reset:"button",search:"searchbox",submit:"button",tel:"textbox",text:"textbox",url:"textbox"}[i||""]||"textbox";const g=m[h];return typeof g=="function"?g(r):g||"generic"}function U(r){const h=Z(r);return!h||(h==="none"||h==="presentation")&&Q(r)?X(r):h}window.__piElementMap||(window.__piElementMap={});let ee=0;function q(r,h,i){const m=r._piRef;if(m&&m.role===h&&m.name===i)return m.ref;const g=`e${++ee}`;return r._piRef={role:h,name:i,ref:g},g}function Y(){const r=[];return document.querySelectorAll('[role="dialog"], [role="alertdialog"], dialog[open]').forEach(i=>{var s,c;const m=window.getComputedStyle(i);if(!(m.display!=="none"&&m.visibility!=="hidden"&&m.opacity!=="0"&&i.offsetWidth>0&&i.offsetHeight>0))return;const p=i.getAttribute("role")||"dialog";let e=i.getAttribute("aria-label")||((c=(s=i.querySelector('[role="heading"], h1, h2, h3'))==null?void 0:s.textContent)==null?void 0:c.trim())||"Dialog";e.length>100&&(e=e.substring(0,100)+"..."),r.push({type:p,description:`${p}: ${e}`,clearedBy:"computer(action=key, text=Escape)"})}),r}const j={wait(r){return new Promise(h=>setTimeout(h,r))},async waitForSelector(r,h={}){const{state:i="visible",timeout:m=2e4}=h,g=e=>{if(!e)return!1;const s=window.getComputedStyle(e);return s.display!=="none"&&s.visibility!=="hidden"&&s.opacity!=="0"&&e.offsetWidth>0&&e.offsetHeight>0},p=()=>{const e=document.querySelector(r);switch(i){case"attached":return e;case"detached":return e?null:document.body;case"hidden":return e?g(e)?null:e:document.body;case"visible":default:return g(e)?e:null}};return new Promise((e,s)=>{const c=p();if(c){e(i==="detached"||i==="hidden"?null:c);return}const a=new MutationObserver(()=>{const u=p();u&&(a.disconnect(),clearTimeout(w),e(i==="detached"||i==="hidden"?null:u))}),w=setTimeout(()=>{a.disconnect(),s(new Error(`Timeout waiting for "${r}" to be ${i}`))},m);a.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","hidden"]})})},async waitForText(r,h={}){const{selector:i,timeout:m=2e4}=h,g=()=>{var s;const p=i?document.querySelector(i):document.body;if(!p)return null;const e=document.createTreeWalker(p,NodeFilter.SHOW_TEXT);for(;e.nextNode();)if((s=e.currentNode.textContent)!=null&&s.includes(r))return e.currentNode.parentElement;return null};return new Promise((p,e)=>{const s=g();if(s){p(s);return}const c=new MutationObserver(()=>{const w=g();w&&(c.disconnect(),clearTimeout(a),p(w))}),a=setTimeout(()=>{c.disconnect(),e(new Error(`Timeout waiting for text "${r}"`))},m);c.observe(document.documentElement,{childList:!0,subtree:!0,characterData:!0})})},async waitForHidden(r,h=2e4){await j.waitForSelector(r,{state:"hidden",timeout:h})},getByRole(r,h={}){var s,c,a,w;const{name:i}=h,m={button:["button",'input[type="button"]','input[type="submit"]','input[type="reset"]'],link:["a[href]"],textbox:["input:not([type])",'input[type="text"]','input[type="email"]','input[type="password"]','input[type="search"]','input[type="tel"]','input[type="url"]',"textarea"],checkbox:['input[type="checkbox"]'],radio:['input[type="radio"]'],combobox:["select"],heading:["h1","h2","h3","h4","h5","h6"],list:["ul","ol"],listitem:["li"],navigation:["nav"],main:["main"],banner:["header"],contentinfo:["footer"],form:["form"],img:["img"],table:["table"]},g=[];g.push(...document.querySelectorAll(`[role="${r}"]`));const p=m[r];if(p)for(const u of p)g.push(...document.querySelectorAll(`${u}:not([role])`));if(!i)return g[0]||null;const e=i.toLowerCase().trim();for(const u of g){const f=(s=u.getAttribute("aria-label"))==null?void 0:s.toLowerCase().trim(),b=(c=u.textContent)==null?void 0:c.toLowerCase().trim(),l=(a=u.getAttribute("title"))==null?void 0:a.toLowerCase().trim(),t=(w=u.getAttribute("placeholder"))==null?void 0:w.toLowerCase().trim();if(f===e||b===e||l===e||t===e||f!=null&&f.includes(e)||b!=null&&b.includes(e))return u}return null}};window.__piHelpers||(window.__piHelpers=j,window.piHelpers=j);function H(){return window.__piElementMap}function B(r="interactive",h=15,i,m=!1,g=!1){try{let p=function(n){return U(n)},e=function(n){var F,W;const d=n.tagName.toLowerCase(),_=n.getAttribute("aria-labelledby");if(_){const E=_.split(/\s+/).map(C=>{var P;const I=document.getElementById(C);return((P=I==null?void 0:I.textContent)==null?void 0:P.trim())||""}).filter(Boolean);if(E.length){const C=E.join(" ");return C.length>100?C.substring(0,100)+"...":C}}if(d==="select"){const E=n,C=E.querySelector("option[selected]")||(E.selectedIndex>=0?E.options[E.selectedIndex]:null);if((F=C==null?void 0:C.textContent)!=null&&F.trim())return C.textContent.trim()}const $=n.getAttribute("aria-label");if($!=null&&$.trim())return $.trim();const M=n.getAttribute("placeholder");if(M!=null&&M.trim())return M.trim();const O=n.getAttribute("title");if(O!=null&&O.trim())return O.trim();const T=n.getAttribute("alt");if(T!=null&&T.trim())return T.trim();if(n.id){const E=document.querySelector(`label[for="${n.id}"]`);if((W=E==null?void 0:E.textContent)!=null&&W.trim())return E.textContent.trim()}if(d==="input"){const E=n,C=n.getAttribute("type")||"",I=n.getAttribute("value");if(C==="submit"&&(I!=null&&I.trim()))return I.trim();if(E.value&&E.value.length<50&&E.value.trim())return E.value.trim()}if(["button","a","summary"].includes(d)){let E="";for(const C of n.childNodes)C.nodeType===Node.TEXT_NODE&&(E+=C.textContent);if(E.trim())return E.trim()}if(/^h[1-6]$/.test(d)){const E=n.textContent;if(E!=null&&E.trim()){const C=E.trim();return C.length>100?C.substring(0,100)+"...":C}}if(d==="img")return"";let N="";for(const E of n.childNodes)E.nodeType===Node.TEXT_NODE&&(N+=E.textContent);if(N!=null&&N.trim()&&N.trim().length>=3){const E=N.trim();return E.length>100?E.substring(0,100)+"...":E}return""},s=function(n){const d={},_=n.getAttribute("aria-checked");_==="true"?d.checked=!0:_==="false"?d.checked=!1:_==="mixed"?d.checked="mixed":n instanceof HTMLInputElement&&(n.type==="checkbox"||n.type==="radio")&&(n.type==="checkbox"&&n.indeterminate?d.checked="mixed":d.checked=n.checked);const $=n instanceof HTMLButtonElement||n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement;(n.getAttribute("aria-disabled")==="true"||$&&n.disabled||n.closest("fieldset:disabled"))&&(d.disabled=!0);const M=n.getAttribute("aria-expanded");M==="true"?d.expanded=!0:M==="false"&&(d.expanded=!1);const O=n.getAttribute("aria-pressed");O==="true"?d.pressed=!0:O==="false"?d.pressed=!1:O==="mixed"&&(d.pressed="mixed");const T=n.getAttribute("aria-selected");T==="true"?d.selected=!0:T==="false"&&(d.selected=!1);const N=n.getAttribute("aria-current");N&&N!=="false"&&(d.active=!0);const F=n.tagName.toLowerCase();if(/^h[1-6]$/.test(F))d.level=parseInt(F[1],10);else{const W=n.getAttribute("aria-level");W&&(d.level=parseInt(W,10))}return d},c=function(n){const d=[];return n.checked!==void 0&&d.push(n.checked==="mixed"?"[checked=mixed]":n.checked?"[checked]":"[unchecked]"),n.disabled&&d.push("[disabled]"),n.expanded!==void 0&&d.push(n.expanded?"[expanded]":"[collapsed]"),n.pressed!==void 0&&d.push(n.pressed==="mixed"?"[pressed=mixed]":n.pressed?"[pressed]":"[not-pressed]"),n.selected!==void 0&&d.push(n.selected?"[selected]":"[not-selected]"),n.active&&d.push("[active]"),n.level!==void 0&&d.push(`[level=${n.level}]`),d.join(" ")},a=function(n){const d=window.getComputedStyle(n);return d.display!=="none"&&d.visibility!=="hidden"&&d.opacity!=="0"&&n.offsetWidth>0&&n.offsetHeight>0},w=function(n){const d=n.tagName.toLowerCase();return["a","button","input","select","textarea","details","summary"].includes(d)||n.hasAttribute("onclick")||n.hasAttribute("tabindex")||n.getAttribute("role")==="button"||n.getAttribute("role")==="link"||n.getAttribute("contenteditable")==="true"},u=function(n){const d=n.tagName.toLowerCase();return["h1","h2","h3","h4","h5","h6","nav","main","header","footer","section","article","aside"].includes(d)||n.hasAttribute("role")},f=function(n){return window.getComputedStyle(n).cursor==="pointer"},b=function(n,d){const _=n.tagName.toLowerCase();if(["script","style","meta","link","title","noscript"].includes(_)||d.filter!=="all"&&n.getAttribute("aria-hidden")==="true"||d.filter!=="all"&&!a(n))return!1;if(d.filter!=="all"&&!d.refId){const M=n.getBoundingClientRect();if(!(M.top<window.innerHeight&&M.bottom>0&&M.left<window.innerWidth&&M.right>0))return!1}if(d.filter==="interactive")return w(n);if(w(n)||u(n)||e(n).length>0)return!0;const $=p(n);return d.compact&&new Set(["generic","group","region","article","section","complementary"]).has($)&&e(n).length===0?!1:$!=="generic"&&$!=="img"},l=function(n,d){const _=[],$={filter:r,refId:i||null,compact:g},M=H(),O=b(n,$)||i&&d===0;if(O){const T=p(n),N=e(n),F=s(n),W=q(n,T,N);window.__piRefs[W]=n,M[W]={element:new WeakRef(n),role:T,name:N};let C=`${" ".repeat(d)}${T}`;if(N){const K=N.replace(/\s+/g," ").replace(/"/g,'\\"');C+=` "${K}"`}C+=` [${W}]`;const I=c(F);I&&(C+=` ${I}`),f(n)&&(C+=" [cursor=pointer]");const P=n.getAttribute("href");P&&(C+=` href="${P}"`);const G=n.getAttribute("type");G&&(C+=` type="${G}"`);const V=n.getAttribute("placeholder");V&&(C+=` placeholder="${V}"`),_.push(C)}if(d<h)for(const T of n.children)_.push(...l(T,O?d+1:d));return _},t=function(n){return n.replace(/\[e\d+\]/g,"[REF]")},o=function(n){const d=new Map;for(const _ of n){if(!_.trim())continue;const $=t(_);d.set($,(d.get($)||0)+1)}return d},y=function(n,d){const _=n.split(`
2
- `),$=d.split(`
3
- `),M=o(_),O=o($),T=[],N=[];for(const E of $){if(!E.trim())continue;const C=t(E),I=M.get(C)||0;(O.get(C)||0)>I&&(T.push(E),M.set(C,I+1))}const F=o(_);for(const E of _){if(!E.trim())continue;const C=t(E),I=F.get(C)||0,P=O.get(C)||0;I>P&&(N.push(E),F.set(C,I-1))}if(T.length===0&&N.length===0)return{diff:"[NO CHANGES]",hasChanges:!1};const W=[];return N.length>0&&W.push(...N.map(E=>`- ${E}`)),T.length>0&&W.push(...T.map(E=>`+ ${E}`)),{diff:W.join(`
4
- `),hasChanges:!0}};window.__piRefs={};const v=H();let A=null;if(i){const n=v[i];if(!n)return{error:`Element with ref_id '${i}' not found. Use read_page without ref_id to get current elements.`,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}};const d=n.element.deref();if(!d)return delete v[i],{error:`Element with ref_id '${i}' no longer exists. Use read_page without ref_id to get current elements.`,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}};A=d}else A=document.body;const S=A?l(A,0):[];for(const n of Object.keys(v))v[n].element.deref()||delete v[n];const k=S.join(`
5
- `);if(k.length>5e4)return{error:`Output exceeds 50000 character limit (${k.length} characters). Try using filter="interactive" or specify a ref_id.`,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}};const L=Y();let D,R=!1;const x=window.__piLastSnapshot;return!m&&!i&&x&&Date.now()-x.timestamp<5e3&&(D=y(x.content,k).diff,R=!0),window.__piLastSnapshot={content:k,timestamp:Date.now()},{pageContent:k+`
1
+ const J=new Set(["alert","alertdialog","application","article","banner","blockquote","button","caption","cell","checkbox","code","columnheader","combobox","complementary","contentinfo","definition","deletion","dialog","directory","document","emphasis","feed","figure","form","generic","grid","gridcell","group","heading","img","insertion","link","list","listbox","listitem","log","main","mark","marquee","math","menu","menubar","menuitem","menuitemcheckbox","menuitemradio","meter","navigation","none","note","option","paragraph","presentation","progressbar","radio","radiogroup","region","row","rowgroup","rowheader","scrollbar","search","searchbox","separator","slider","spinbutton","status","strong","subscript","superscript","switch","tab","table","tablist","tabpanel","term","textbox","time","timer","toolbar","tooltip","tree","treegrid","treeitem"]);function Q(i){const m=i.tagName.toLowerCase();if(["button","input","select","textarea"].includes(m))return!i.disabled;if(m==="a"&&i.hasAttribute("href"))return!0;if(i.hasAttribute("tabindex")){const r=parseInt(i.getAttribute("tabindex")||"",10);return!isNaN(r)&&r>=0}return i.getAttribute("contenteditable")==="true"}function Z(i){const m=i.getAttribute("role");if(!m)return null;const r=m.split(/\s+/).filter(w=>w);for(const w of r)if(J.has(w))return w;return null}function X(i){const m=i.tagName.toLowerCase(),r=i.getAttribute("type"),w={a:g=>g.hasAttribute("href")?"link":"generic",article:"article",aside:"complementary",button:"button",datalist:"listbox",dd:"definition",details:"group",dialog:"dialog",dt:"term",fieldset:"group",figure:"figure",footer:g=>g.closest("article, aside, main, nav, section")?"generic":"contentinfo",form:g=>g.hasAttribute("aria-label")||g.hasAttribute("aria-labelledby")?"form":"generic",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",header:g=>g.closest("article, aside, main, nav, section")?"generic":"banner",hr:"separator",img:g=>g.getAttribute("alt")===""?"presentation":"img",li:"listitem",main:"main",math:"math",menu:"list",meter:"meter",nav:"navigation",ol:"list",optgroup:"group",option:"option",output:"status",p:"paragraph",progress:"progressbar",search:"search",section:g=>g.hasAttribute("aria-label")||g.hasAttribute("aria-labelledby")?"region":"generic",select:g=>{const e=g;return e.hasAttribute("multiple")||e.size&&e.size>1?"listbox":"combobox"},table:"table",tbody:"rowgroup",td:"cell",textarea:"textbox",tfoot:"rowgroup",th:"columnheader",thead:"rowgroup",time:"time",tr:"row",ul:"list"};if(m==="input")return{button:"button",checkbox:"checkbox",email:"textbox",file:"button",image:"button",number:"spinbutton",radio:"radio",range:"slider",reset:"button",search:"searchbox",submit:"button",tel:"textbox",text:"textbox",url:"textbox"}[r||""]||"textbox";const y=w[m];return typeof y=="function"?y(i):y||"generic"}function U(i){const m=Z(i);return!m||(m==="none"||m==="presentation")&&Q(i)?X(i):m}window.__piElementMap||(window.__piElementMap={});let ee=0;function q(i,m,r){const w=i._piRef;if(w&&w.role===m&&w.name===r)return w.ref;const y=`e${++ee}`;return i._piRef={role:m,name:r,ref:y},y}function Y(){const i=[];return document.querySelectorAll('[role="dialog"], [role="alertdialog"], dialog[open]').forEach(r=>{var c,l;const w=window.getComputedStyle(r);if(!(w.display!=="none"&&w.visibility!=="hidden"&&w.opacity!=="0"&&r.offsetWidth>0&&r.offsetHeight>0))return;const g=r.getAttribute("role")||"dialog";let e=r.getAttribute("aria-label")||((l=(c=r.querySelector('[role="heading"], h1, h2, h3'))==null?void 0:c.textContent)==null?void 0:l.trim())||"Dialog";e.length>100&&(e=e.substring(0,100)+"..."),i.push({type:g,description:`${g}: ${e}`,clearedBy:"computer(action=key, text=Escape)"})}),i}const j={wait(i){return new Promise(m=>setTimeout(m,i))},async waitForSelector(i,m={}){const{state:r="visible",timeout:w=2e4}=m,y=e=>{if(!e)return!1;const c=window.getComputedStyle(e);return c.display!=="none"&&c.visibility!=="hidden"&&c.opacity!=="0"&&e.offsetWidth>0&&e.offsetHeight>0},g=()=>{const e=document.querySelector(i);switch(r){case"attached":return e;case"detached":return e?null:document.body;case"hidden":return e?y(e)?null:e:document.body;case"visible":default:return y(e)?e:null}};return new Promise((e,c)=>{const l=g();if(l){e(r==="detached"||r==="hidden"?null:l);return}const s=new MutationObserver(()=>{const u=g();u&&(s.disconnect(),clearTimeout(d),e(r==="detached"||r==="hidden"?null:u))}),d=setTimeout(()=>{s.disconnect(),c(new Error(`Timeout waiting for "${i}" to be ${r}`))},w);s.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","hidden"]})})},async waitForText(i,m={}){const{selector:r,timeout:w=2e4}=m,y=()=>{var c;const g=r?document.querySelector(r):document.body;if(!g)return null;const e=document.createTreeWalker(g,NodeFilter.SHOW_TEXT);for(;e.nextNode();)if((c=e.currentNode.textContent)!=null&&c.includes(i))return e.currentNode.parentElement;return null};return new Promise((g,e)=>{const c=y();if(c){g(c);return}const l=new MutationObserver(()=>{const d=y();d&&(l.disconnect(),clearTimeout(s),g(d))}),s=setTimeout(()=>{l.disconnect(),e(new Error(`Timeout waiting for text "${i}"`))},w);l.observe(document.documentElement,{childList:!0,subtree:!0,characterData:!0})})},async waitForHidden(i,m=2e4){await j.waitForSelector(i,{state:"hidden",timeout:m})},getByRole(i,m={}){var c,l,s,d;const{name:r}=m,w={button:["button",'input[type="button"]','input[type="submit"]','input[type="reset"]'],link:["a[href]"],textbox:["input:not([type])",'input[type="text"]','input[type="email"]','input[type="password"]','input[type="search"]','input[type="tel"]','input[type="url"]',"textarea"],checkbox:['input[type="checkbox"]'],radio:['input[type="radio"]'],combobox:["select"],heading:["h1","h2","h3","h4","h5","h6"],list:["ul","ol"],listitem:["li"],navigation:["nav"],main:["main"],banner:["header"],contentinfo:["footer"],form:["form"],img:["img"],table:["table"]},y=[];y.push(...document.querySelectorAll(`[role="${i}"]`));const g=w[i];if(g)for(const u of g)y.push(...document.querySelectorAll(`${u}:not([role])`));if(!r)return y[0]||null;const e=r.toLowerCase().trim();for(const u of y){const h=(c=u.getAttribute("aria-label"))==null?void 0:c.toLowerCase().trim(),b=(l=u.textContent)==null?void 0:l.toLowerCase().trim(),a=(s=u.getAttribute("title"))==null?void 0:s.toLowerCase().trim(),t=(d=u.getAttribute("placeholder"))==null?void 0:d.toLowerCase().trim();if(h===e||b===e||a===e||t===e||h!=null&&h.includes(e)||b!=null&&b.includes(e))return u}return null}};window.__piHelpers||(window.__piHelpers=j,window.piHelpers=j);function O(){return window.__piElementMap}function B(i="interactive",m=15,r,w=!1,y=!1){try{let g=function(n){return U(n)},e=function(n){var R,F;const f=n.tagName.toLowerCase(),k=n.getAttribute("aria-labelledby");if(k){const E=k.split(/\s+/).map(C=>{var P;const I=document.getElementById(C);return((P=I==null?void 0:I.textContent)==null?void 0:P.trim())||""}).filter(Boolean);if(E.length){const C=E.join(" ");return C.length>100?C.substring(0,100)+"...":C}}if(f==="select"){const E=n,C=E.querySelector("option[selected]")||(E.selectedIndex>=0?E.options[E.selectedIndex]:null);if((R=C==null?void 0:C.textContent)!=null&&R.trim())return C.textContent.trim()}const $=n.getAttribute("aria-label");if($!=null&&$.trim())return $.trim();const M=n.getAttribute("placeholder");if(M!=null&&M.trim())return M.trim();const H=n.getAttribute("title");if(H!=null&&H.trim())return H.trim();const T=n.getAttribute("alt");if(T!=null&&T.trim())return T.trim();if(n.id){const E=document.querySelector(`label[for="${n.id}"]`);if((F=E==null?void 0:E.textContent)!=null&&F.trim())return E.textContent.trim()}if(f==="input"){const E=n,C=n.getAttribute("type")||"",I=n.getAttribute("value");if(C==="submit"&&(I!=null&&I.trim()))return I.trim();if(E.value&&E.value.length<50&&E.value.trim())return E.value.trim()}if(["button","a","summary"].includes(f)){let E="";for(const C of n.childNodes)C.nodeType===Node.TEXT_NODE&&(E+=C.textContent);if(E.trim())return E.trim()}if(/^h[1-6]$/.test(f)){const E=n.textContent;if(E!=null&&E.trim()){const C=E.trim();return C.length>100?C.substring(0,100)+"...":C}}if(f==="img")return"";let N="";for(const E of n.childNodes)E.nodeType===Node.TEXT_NODE&&(N+=E.textContent);if(N!=null&&N.trim()&&N.trim().length>=3){const E=N.trim();return E.length>100?E.substring(0,100)+"...":E}return""},c=function(n){const f={},k=n.getAttribute("aria-checked");k==="true"?f.checked=!0:k==="false"?f.checked=!1:k==="mixed"?f.checked="mixed":n instanceof HTMLInputElement&&(n.type==="checkbox"||n.type==="radio")&&(n.type==="checkbox"&&n.indeterminate?f.checked="mixed":f.checked=n.checked);const $=n instanceof HTMLButtonElement||n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement;(n.getAttribute("aria-disabled")==="true"||$&&n.disabled||n.closest("fieldset:disabled"))&&(f.disabled=!0);const M=n.getAttribute("aria-expanded");M==="true"?f.expanded=!0:M==="false"&&(f.expanded=!1);const H=n.getAttribute("aria-pressed");H==="true"?f.pressed=!0:H==="false"?f.pressed=!1:H==="mixed"&&(f.pressed="mixed");const T=n.getAttribute("aria-selected");T==="true"?f.selected=!0:T==="false"&&(f.selected=!1);const N=n.getAttribute("aria-current");N&&N!=="false"&&(f.active=!0);const R=n.tagName.toLowerCase();if(/^h[1-6]$/.test(R))f.level=parseInt(R[1],10);else{const F=n.getAttribute("aria-level");F&&(f.level=parseInt(F,10))}return f},l=function(n){const f=[];return n.checked!==void 0&&f.push(n.checked==="mixed"?"[checked=mixed]":n.checked?"[checked]":"[unchecked]"),n.disabled&&f.push("[disabled]"),n.expanded!==void 0&&f.push(n.expanded?"[expanded]":"[collapsed]"),n.pressed!==void 0&&f.push(n.pressed==="mixed"?"[pressed=mixed]":n.pressed?"[pressed]":"[not-pressed]"),n.selected!==void 0&&f.push(n.selected?"[selected]":"[not-selected]"),n.active&&f.push("[active]"),n.level!==void 0&&f.push(`[level=${n.level}]`),f.join(" ")},s=function(n){const f=window.getComputedStyle(n);return f.display!=="none"&&f.visibility!=="hidden"&&f.opacity!=="0"&&n.offsetWidth>0&&n.offsetHeight>0},d=function(n){const f=n.tagName.toLowerCase();return["a","button","input","select","textarea","details","summary"].includes(f)||n.hasAttribute("onclick")||n.hasAttribute("tabindex")||n.getAttribute("role")==="button"||n.getAttribute("role")==="link"||n.getAttribute("contenteditable")==="true"},u=function(n){const f=n.tagName.toLowerCase();return["h1","h2","h3","h4","h5","h6","nav","main","header","footer","section","article","aside"].includes(f)||n.hasAttribute("role")},h=function(n){return window.getComputedStyle(n).cursor==="pointer"},b=function(n,f){const k=n.tagName.toLowerCase();if(["script","style","meta","link","title","noscript"].includes(k)||f.filter!=="all"&&n.getAttribute("aria-hidden")==="true"||f.filter!=="all"&&!s(n))return!1;if(f.filter!=="all"&&!f.refId){const M=n.getBoundingClientRect();if(!(M.top<window.innerHeight&&M.bottom>0&&M.left<window.innerWidth&&M.right>0))return!1}if(f.filter==="interactive")return d(n);if(d(n)||u(n)||e(n).length>0)return!0;const $=g(n);return f.compact&&new Set(["generic","group","region","article","section","complementary"]).has($)&&e(n).length===0?!1:$!=="generic"&&$!=="img"},a=function(n,f){const k=[],$={filter:i,refId:r||null,compact:y},M=O(),H=b(n,$)||r&&f===0;if(H){const T=g(n),N=e(n),R=c(n),F=q(n,T,N);window.__piRefs[F]=n,M[F]={element:new WeakRef(n),role:T,name:N};let C=`${" ".repeat(f)}${T}`;if(N){const K=N.replace(/\s+/g," ").replace(/"/g,'\\"');C+=` "${K}"`}C+=` [${F}]`;const I=l(R);I&&(C+=` ${I}`),h(n)&&(C+=" [cursor=pointer]");const P=n.getAttribute("href");P&&(C+=` href="${P}"`);const G=n.getAttribute("type");G&&(C+=` type="${G}"`);const V=n.getAttribute("placeholder");V&&(C+=` placeholder="${V}"`),k.push(C)}if(f<m)for(const T of n.children)k.push(...a(T,H?f+1:f));return k},t=function(n){return n.replace(/\[e\d+\]/g,"[REF]")},o=function(n){const f=new Map;for(const k of n){if(!k.trim())continue;const $=t(k);f.set($,(f.get($)||0)+1)}return f},p=function(n,f){const k=n.split(`
2
+ `),$=f.split(`
3
+ `),M=o(k),H=o($),T=[],N=[];for(const E of $){if(!E.trim())continue;const C=t(E),I=M.get(C)||0;(H.get(C)||0)>I&&(T.push(E),M.set(C,I+1))}const R=o(k);for(const E of k){if(!E.trim())continue;const C=t(E),I=R.get(C)||0,P=H.get(C)||0;I>P&&(N.push(E),R.set(C,I-1))}if(T.length===0&&N.length===0)return{diff:"[NO CHANGES]",hasChanges:!1};const F=[];return N.length>0&&F.push(...N.map(E=>`- ${E}`)),T.length>0&&F.push(...T.map(E=>`+ ${E}`)),{diff:F.join(`
4
+ `),hasChanges:!0}};window.__piRefs={};const v=O();let _=null;if(r){const n=v[r];if(!n)return{error:`Element with ref_id '${r}' not found. Use read_page without ref_id to get current elements.`,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}};const f=n.element.deref();if(!f)return delete v[r],{error:`Element with ref_id '${r}' no longer exists. Use read_page without ref_id to get current elements.`,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}};_=f}else _=document.body;const S=_?a(_,0):[];for(const n of Object.keys(v))v[n].element.deref()||delete v[n];const A=S.join(`
5
+ `);if(A.length>5e4)return{error:`Output exceeds 50000 character limit (${A.length} characters). Try using filter="interactive" or specify a ref_id.`,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}};const L=Y();let D,W=!1;const x=window.__piLastSnapshot;return!w&&!r&&x&&Date.now()-x.timestamp<5e3&&(D=p(x.content,A).diff,W=!0),window.__piLastSnapshot={content:A,timestamp:Date.now()},{pageContent:A+`
6
6
 
7
- [Viewport: ${window.innerWidth}x${window.innerHeight}]`,diff:R?D:void 0,viewport:{width:window.innerWidth,height:window.innerHeight},modalStates:L.length>0?L:void 0,modalLimitations:"Only custom modals ([role=dialog]) detected. Native alert/confirm/prompt dialogs and system file choosers cannot be detected from content scripts.",isIncremental:R}}catch(p){return{error:`Error generating accessibility tree: ${p instanceof Error?p.message:"Unknown error"}`,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}}}}function z(r){return r.length?/[\n\r]/.test(r)||/^[\s]/.test(r)||/[\s]$/.test(r)||/[:"{}[\]]/.test(r)?'"'+r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r")+'"':r:'""'}function te(r="interactive",h=15){try{let i=function(t){return U(t)},m=function(t){var D,R;const o=t.tagName.toLowerCase(),y=t.getAttribute("aria-labelledby");if(y){const x=y.split(/\s+/).map(n=>{var _;const d=document.getElementById(n);return((_=d==null?void 0:d.textContent)==null?void 0:_.trim())||""}).filter(Boolean);if(x.length){const n=x.join(" ");return n.length>100?n.substring(0,100)+"...":n}}if(o==="select"){const x=t,n=x.querySelector("option[selected]")||(x.selectedIndex>=0?x.options[x.selectedIndex]:null);if((D=n==null?void 0:n.textContent)!=null&&D.trim())return n.textContent.trim()}const v=t.getAttribute("aria-label");if(v!=null&&v.trim())return v.trim();const A=t.getAttribute("placeholder");if(A!=null&&A.trim())return A.trim();const S=t.getAttribute("title");if(S!=null&&S.trim())return S.trim();const k=t.getAttribute("alt");if(k!=null&&k.trim())return k.trim();if(t.id){const x=document.querySelector(`label[for="${t.id}"]`);if((R=x==null?void 0:x.textContent)!=null&&R.trim())return x.textContent.trim()}if(o==="input"){const x=t,n=t.getAttribute("type")||"",d=t.getAttribute("value");if(n==="submit"&&(d!=null&&d.trim()))return d.trim();if(x.value&&x.value.length<50&&x.value.trim())return x.value.trim()}if(["button","a","summary"].includes(o)){let x="";for(const n of t.childNodes)n.nodeType===Node.TEXT_NODE&&(x+=n.textContent);if(x.trim())return x.trim()}if(/^h[1-6]$/.test(o)){const x=t.textContent;if(x!=null&&x.trim()){const n=x.trim();return n.length>100?n.substring(0,100)+"...":n}}if(o==="img")return"";let L="";for(const x of t.childNodes)x.nodeType===Node.TEXT_NODE&&(L+=x.textContent);if(L!=null&&L.trim()&&L.trim().length>=3){const x=L.trim();return x.length>100?x.substring(0,100)+"...":x}return""},g=function(t){const o={},y=t.getAttribute("aria-checked");y==="true"?o.checked=!0:y==="false"?o.checked=!1:y==="mixed"?o.checked="mixed":t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")&&(t.type==="checkbox"&&t.indeterminate?o.checked="mixed":o.checked=t.checked);const v=t instanceof HTMLButtonElement||t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement;(t.getAttribute("aria-disabled")==="true"||v&&t.disabled||t.closest("fieldset:disabled"))&&(o.disabled=!0);const A=t.getAttribute("aria-expanded");A==="true"?o.expanded=!0:A==="false"&&(o.expanded=!1);const S=t.getAttribute("aria-pressed");S==="true"?o.pressed=!0:S==="false"?o.pressed=!1:S==="mixed"&&(o.pressed="mixed");const k=t.getAttribute("aria-selected");k==="true"?o.selected=!0:k==="false"&&(o.selected=!1);const L=t.getAttribute("aria-current");L&&L!=="false"&&(o.active=!0);const D=t.tagName.toLowerCase();if(/^h[1-6]$/.test(D))o.level=parseInt(D[1],10);else{const R=t.getAttribute("aria-level");R&&(o.level=parseInt(R,10))}return o},p=function(t){const o=[];return t.checked!==void 0&&o.push(t.checked==="mixed"?"[checked=mixed]":t.checked?"[checked]":"[unchecked]"),t.disabled&&o.push("[disabled]"),t.expanded!==void 0&&o.push(t.expanded?"[expanded]":"[collapsed]"),t.pressed!==void 0&&o.push(t.pressed==="mixed"?"[pressed=mixed]":t.pressed?"[pressed]":"[not-pressed]"),t.selected!==void 0&&o.push(t.selected?"[selected]":"[not-selected]"),t.active&&o.push("[active]"),t.level!==void 0&&o.push(`[level=${t.level}]`),o.join(" ")},e=function(t){const o=window.getComputedStyle(t);return o.display!=="none"&&o.visibility!=="hidden"&&o.opacity!=="0"&&t.offsetWidth>0&&t.offsetHeight>0},s=function(t){const o=t.tagName.toLowerCase();return["a","button","input","select","textarea","details","summary"].includes(o)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")||t.getAttribute("role")==="button"||t.getAttribute("role")==="link"||t.getAttribute("contenteditable")==="true"},c=function(t){const o=t.tagName.toLowerCase();return["h1","h2","h3","h4","h5","h6","nav","main","header","footer","section","article","aside"].includes(o)||t.hasAttribute("role")},a=function(t){return window.getComputedStyle(t).cursor==="pointer"},w=function(t,o,y,v){let A=t;o&&(A+=" "+z(o));const S=q(y,t,o);window.__piRefs[S]=y,A+=` [ref=${S}]`;const k=p(v);return k&&(A+=` ${k}`),a(y)&&(A+=" [cursor=pointer]"),A},u=function(t){const o={},y=t.getAttribute("href");y&&(o.url=y);const v=t.getAttribute("placeholder");return v&&(o.placeholder=v),o},f=function(t,o,y){if(o>h)return;const v=t.tagName.toLowerCase();if(["script","style","meta","link","title","noscript"].includes(v)||r!=="all"&&t.getAttribute("aria-hidden")==="true"||r!=="all"&&!e(t))return;if(r!=="all"){const n=t.getBoundingClientRect();if(!(n.top<window.innerHeight&&n.bottom>0&&n.left<window.innerWidth&&n.right>0))return}const A=i(t),S=m(t),k=g(t),L=s(t),D=c(t),R=S.length>0;let x;if(r==="interactive"?x=L:r==="all"?x=!0:x=L||D||R||A!=="generic"&&A!=="img",x){const n=" ".repeat(o),d=w(A,S,t,k),_=u(t),$=[];for(const T of t.children)$.push(T);const M=$.length>0,O=Object.keys(_).length>0;if(!M&&!O)b.push(`${n}- ${d}`);else{b.push(`${n}- ${d}:`);for(const[T,N]of Object.entries(_))b.push(`${n} - /${T}: ${z(N)}`);for(const T of $)f(T,o+1,!0)}}else for(const n of t.children)f(n,o,y)};window.__piRefs={};const b=[];f(document.body,0,!1);const l=b.join(`
8
- `);return l.length>5e4?{error:`Output exceeds 50000 character limit (${l.length} characters). Try using filter="interactive".`,yaml:"",viewport:{width:window.innerWidth,height:window.innerHeight}}:{yaml:l+`
7
+ [Viewport: ${window.innerWidth}x${window.innerHeight}]`,diff:W?D:void 0,viewport:{width:window.innerWidth,height:window.innerHeight},modalStates:L.length>0?L:void 0,modalLimitations:"Only custom modals ([role=dialog]) detected. Native alert/confirm/prompt dialogs and system file choosers cannot be detected from content scripts.",isIncremental:W}}catch(g){return{error:`Error generating accessibility tree: ${g instanceof Error?g.message:"Unknown error"}`,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}}}}function z(i){return i.length?/[\n\r]/.test(i)||/^[\s]/.test(i)||/[\s]$/.test(i)||/[:"{}[\]]/.test(i)?'"'+i.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r")+'"':i:'""'}function te(i="interactive",m=15){try{let r=function(t){return U(t)},w=function(t){var D,W;const o=t.tagName.toLowerCase(),p=t.getAttribute("aria-labelledby");if(p){const x=p.split(/\s+/).map(n=>{var k;const f=document.getElementById(n);return((k=f==null?void 0:f.textContent)==null?void 0:k.trim())||""}).filter(Boolean);if(x.length){const n=x.join(" ");return n.length>100?n.substring(0,100)+"...":n}}if(o==="select"){const x=t,n=x.querySelector("option[selected]")||(x.selectedIndex>=0?x.options[x.selectedIndex]:null);if((D=n==null?void 0:n.textContent)!=null&&D.trim())return n.textContent.trim()}const v=t.getAttribute("aria-label");if(v!=null&&v.trim())return v.trim();const _=t.getAttribute("placeholder");if(_!=null&&_.trim())return _.trim();const S=t.getAttribute("title");if(S!=null&&S.trim())return S.trim();const A=t.getAttribute("alt");if(A!=null&&A.trim())return A.trim();if(t.id){const x=document.querySelector(`label[for="${t.id}"]`);if((W=x==null?void 0:x.textContent)!=null&&W.trim())return x.textContent.trim()}if(o==="input"){const x=t,n=t.getAttribute("type")||"",f=t.getAttribute("value");if(n==="submit"&&(f!=null&&f.trim()))return f.trim();if(x.value&&x.value.length<50&&x.value.trim())return x.value.trim()}if(["button","a","summary"].includes(o)){let x="";for(const n of t.childNodes)n.nodeType===Node.TEXT_NODE&&(x+=n.textContent);if(x.trim())return x.trim()}if(/^h[1-6]$/.test(o)){const x=t.textContent;if(x!=null&&x.trim()){const n=x.trim();return n.length>100?n.substring(0,100)+"...":n}}if(o==="img")return"";let L="";for(const x of t.childNodes)x.nodeType===Node.TEXT_NODE&&(L+=x.textContent);if(L!=null&&L.trim()&&L.trim().length>=3){const x=L.trim();return x.length>100?x.substring(0,100)+"...":x}return""},y=function(t){const o={},p=t.getAttribute("aria-checked");p==="true"?o.checked=!0:p==="false"?o.checked=!1:p==="mixed"?o.checked="mixed":t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")&&(t.type==="checkbox"&&t.indeterminate?o.checked="mixed":o.checked=t.checked);const v=t instanceof HTMLButtonElement||t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement;(t.getAttribute("aria-disabled")==="true"||v&&t.disabled||t.closest("fieldset:disabled"))&&(o.disabled=!0);const _=t.getAttribute("aria-expanded");_==="true"?o.expanded=!0:_==="false"&&(o.expanded=!1);const S=t.getAttribute("aria-pressed");S==="true"?o.pressed=!0:S==="false"?o.pressed=!1:S==="mixed"&&(o.pressed="mixed");const A=t.getAttribute("aria-selected");A==="true"?o.selected=!0:A==="false"&&(o.selected=!1);const L=t.getAttribute("aria-current");L&&L!=="false"&&(o.active=!0);const D=t.tagName.toLowerCase();if(/^h[1-6]$/.test(D))o.level=parseInt(D[1],10);else{const W=t.getAttribute("aria-level");W&&(o.level=parseInt(W,10))}return o},g=function(t){const o=[];return t.checked!==void 0&&o.push(t.checked==="mixed"?"[checked=mixed]":t.checked?"[checked]":"[unchecked]"),t.disabled&&o.push("[disabled]"),t.expanded!==void 0&&o.push(t.expanded?"[expanded]":"[collapsed]"),t.pressed!==void 0&&o.push(t.pressed==="mixed"?"[pressed=mixed]":t.pressed?"[pressed]":"[not-pressed]"),t.selected!==void 0&&o.push(t.selected?"[selected]":"[not-selected]"),t.active&&o.push("[active]"),t.level!==void 0&&o.push(`[level=${t.level}]`),o.join(" ")},e=function(t){const o=window.getComputedStyle(t);return o.display!=="none"&&o.visibility!=="hidden"&&o.opacity!=="0"&&t.offsetWidth>0&&t.offsetHeight>0},c=function(t){const o=t.tagName.toLowerCase();return["a","button","input","select","textarea","details","summary"].includes(o)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")||t.getAttribute("role")==="button"||t.getAttribute("role")==="link"||t.getAttribute("contenteditable")==="true"},l=function(t){const o=t.tagName.toLowerCase();return["h1","h2","h3","h4","h5","h6","nav","main","header","footer","section","article","aside"].includes(o)||t.hasAttribute("role")},s=function(t){return window.getComputedStyle(t).cursor==="pointer"},d=function(t,o,p,v){let _=t;o&&(_+=" "+z(o));const S=q(p,t,o);window.__piRefs[S]=p,_+=` [ref=${S}]`;const A=g(v);return A&&(_+=` ${A}`),s(p)&&(_+=" [cursor=pointer]"),_},u=function(t){const o={},p=t.getAttribute("href");p&&(o.url=p);const v=t.getAttribute("placeholder");return v&&(o.placeholder=v),o},h=function(t,o,p){if(o>m)return;const v=t.tagName.toLowerCase();if(["script","style","meta","link","title","noscript"].includes(v)||i!=="all"&&t.getAttribute("aria-hidden")==="true"||i!=="all"&&!e(t))return;if(i!=="all"){const n=t.getBoundingClientRect();if(!(n.top<window.innerHeight&&n.bottom>0&&n.left<window.innerWidth&&n.right>0))return}const _=r(t),S=w(t),A=y(t),L=c(t),D=l(t),W=S.length>0;let x;if(i==="interactive"?x=L:i==="all"?x=!0:x=L||D||W||_!=="generic"&&_!=="img",x){const n=" ".repeat(o),f=d(_,S,t,A),k=u(t),$=[];for(const T of t.children)$.push(T);const M=$.length>0,H=Object.keys(k).length>0;if(!M&&!H)b.push(`${n}- ${f}`);else{b.push(`${n}- ${f}:`);for(const[T,N]of Object.entries(k))b.push(`${n} - /${T}: ${z(N)}`);for(const T of $)h(T,o+1,!0)}}else for(const n of t.children)h(n,o,p)};window.__piRefs={};const b=[];h(document.body,0,!1);const a=b.join(`
8
+ `);return a.length>5e4?{error:`Output exceeds 50000 character limit (${a.length} characters). Try using filter="interactive".`,yaml:"",viewport:{width:window.innerWidth,height:window.innerHeight}}:{yaml:a+`
9
9
 
10
- [Viewport: ${window.innerWidth}x${window.innerHeight}]`,viewport:{width:window.innerWidth,height:window.innerHeight}}}catch(i){return{error:`Error generating YAML tree: ${i instanceof Error?i.message:"Unknown error"}`,yaml:"",viewport:{width:window.innerWidth,height:window.innerHeight}}}}function ne(r){const h=H(),i=h[r];let m;if(i&&(m=i.element.deref(),m||delete h[r]),!m&&window.__piRefs&&(m=window.__piRefs[r]),!m)return{x:0,y:0,error:`Element ${r} not found. Use read_page to get current elements.`};const g=m.getBoundingClientRect(),p=Math.round(g.left+g.width/2),e=Math.round(g.top+g.height/2);return{x:p,y:e}}function re(r,h){var e;const i=H(),m=i[r];let g;if(m&&(g=m.element.deref(),g||delete i[r]),!g&&window.__piRefs&&(g=window.__piRefs[r]),!g)return{success:!1,error:`Element ${r} not found. Use read_page to get current elements.`};const p=g.tagName.toLowerCase();try{if(p==="input"){const s=g,c=s.type.toLowerCase();c==="checkbox"||c==="radio"?(s.checked=!!h,s.dispatchEvent(new Event("change",{bubbles:!0}))):(s.value=String(h),s.dispatchEvent(new Event("input",{bubbles:!0})),s.dispatchEvent(new Event("change",{bubbles:!0})))}else if(p==="textarea"){const s=g;s.value=String(h),s.dispatchEvent(new Event("input",{bubbles:!0})),s.dispatchEvent(new Event("change",{bubbles:!0}))}else if(p==="select"){const s=g,c=String(h);let a=!1;for(const w of s.options)if(w.value===c||((e=w.textContent)==null?void 0:e.trim())===c){s.value=w.value,a=!0;break}if(!a)return{success:!1,error:`Option "${h}" not found in select element ${r}`};s.dispatchEvent(new Event("change",{bubbles:!0}))}else if(g.getAttribute("contenteditable")==="true")g.textContent=String(h),g.dispatchEvent(new Event("input",{bubbles:!0}));else return{success:!1,error:`Element ${r} (${p}) is not a form field`};return{success:!0}}catch(s){return{success:!1,error:`Failed to set value: ${s instanceof Error?s.message:"Unknown error"}`}}}function ie(){var r;try{const h=document.querySelector("article"),i=document.querySelector("main");return{text:((r=(h||i||document.body).textContent)==null?void 0:r.replace(/\s+/g," ").trim().substring(0,5e4))||"",title:document.title,url:window.location.href}}catch(h){return{text:"",title:"",url:"",error:`Failed to extract text: ${h instanceof Error?h.message:"Unknown error"}`}}}function oe(r){const h=H(),i=h[r];let m;return i&&(m=i.element.deref(),m||delete h[r]),!m&&window.__piRefs&&(m=window.__piRefs[r]),m?(m.scrollIntoView({behavior:"smooth",block:"center"}),{success:!0}):{success:!1,error:`Element ${r} not found. Run read_page to get current element refs.`}}function se(r,h,i,m="screenshot.png"){try{const g=atob(r),p=new ArrayBuffer(g.length),e=new Uint8Array(p);for(let f=0;f<g.length;f++)e[f]=g.charCodeAt(f);const s=new Blob([p],{type:"image/png"}),c=new File([s],m,{type:"image/png"});let a=null;if(h){const f=H(),b=f[h];if(b&&(a=b.element.deref(),a||delete f[h]),!a&&window.__piRefs&&(a=window.__piRefs[h]),!a)return{success:!1,error:`Element ${h} not found. Run read_page to get current element refs.`}}else if(i&&(a=document.elementFromPoint(i[0],i[1]),!a))return{success:!1,error:`No element at (${i[0]}, ${i[1]})`};if(!a)return{success:!1,error:"No target element"};if(a.tagName==="INPUT"&&a.type==="file"){const f=a,b=new DataTransfer;return b.items.add(c),f.files=b.files,f.dispatchEvent(new Event("change",{bubbles:!0})),{success:!0}}const w=new DataTransfer;w.items.add(c);const u=new DragEvent("drop",{bubbles:!0,cancelable:!0,dataTransfer:w});return a.dispatchEvent(u),{success:!0}}catch(g){return{success:!1,error:g instanceof Error?g.message:"Upload failed"}}}chrome.runtime.onMessage.addListener((r,h,i)=>{var m,g,p;switch(r.type){case"GENERATE_ACCESSIBILITY_TREE":{const e=r.options||{};if(e.format==="yaml"){const s=te(e.filter||"interactive",e.depth??15),c=Y();s.error?i({error:s.error,pageContent:"",viewport:s.viewport}):i({pageContent:s.yaml,viewport:s.viewport,modalStates:c.length>0?c:void 0,modalLimitations:"Only custom modals ([role=dialog]) detected. Native alert/confirm/prompt dialogs and system file choosers cannot be detected from content scripts."})}else{const s=B(e.filter||"interactive",e.depth??15,e.refId,e.forceFullSnapshot??!1,e.compact??!1);i(s)}break}case"GET_ELEMENT_COORDINATES":{const e=ne(r.ref);i(e);break}case"CLICK_ELEMENT":{const e=H(),s=e[r.ref];let c;if(s&&(c=s.element.deref(),c||delete e[r.ref]),!c&&window.__piRefs&&(c=window.__piRefs[r.ref]),!c){i({error:`Element ${r.ref} not found. Use read_page to get current elements.`});break}if(r.button==="triple"){const a=new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window,detail:3});c.dispatchEvent(a)}else r.button==="double"?c.dispatchEvent(new MouseEvent("dblclick",{bubbles:!0,cancelable:!0,view:window})):r.button==="right"?c.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,view:window})):c.click();i({success:!0});break}case"FORM_INPUT":{const e=re(r.ref,r.value);i(e);break}case"EVAL_IN_PAGE":{try{const e=document.createElement("script");e.textContent=`(function() { ${r.code} })();`,document.documentElement.appendChild(e),e.remove(),i({success:!0})}catch(e){i({success:!1,error:e instanceof Error?e.message:String(e)})}break}case"GET_PAGE_TEXT":{const e=ie();i(e);break}case"GET_FRAME_BY_SELECTOR":{try{const e=document.querySelector(r.selector);if(!e||e.tagName.toLowerCase()!=="iframe"){i({error:`No iframe found with selector "${r.selector}"`});break}i({url:e.src,name:e.name||void 0})}catch(e){i({error:e instanceof Error?e.message:String(e)})}break}case"GET_FRAME_NAME":{try{i({name:window.name||null})}catch{i({name:null})}break}case"LOCATE_ROLE":{try{const{role:e,name:s,all:c}=r,a=H(),u={button:["button",'input[type="button"]','input[type="submit"]','input[type="reset"]','[role="button"]'],link:["a[href]",'[role="link"]'],textbox:["input:not([type])",'input[type="text"]','input[type="email"]','input[type="password"]','input[type="search"]','input[type="tel"]','input[type="url"]',"textarea",'[role="textbox"]'],checkbox:['input[type="checkbox"]','[role="checkbox"]'],radio:['input[type="radio"]','[role="radio"]'],combobox:["select",'[role="combobox"]'],listbox:['[role="listbox"]',"select[multiple]"],option:["option",'[role="option"]'],heading:["h1","h2","h3","h4","h5","h6",'[role="heading"]'],navigation:["nav",'[role="navigation"]'],main:["main",'[role="main"]'],img:["img[alt]",'[role="img"]'],dialog:["dialog",'[role="dialog"]','[role="alertdialog"]'],tab:['[role="tab"]'],tabpanel:['[role="tabpanel"]'],menu:['[role="menu"]'],menuitem:['[role="menuitem"]']}[e]||[`[role="${e}"]`],f=[];for(const o of u)try{f.push(...document.querySelectorAll(o))}catch{}const b=f.filter(o=>{const y=window.getComputedStyle(o);return y.display!=="none"&&y.visibility!=="hidden"&&o.offsetWidth>0&&o.offsetHeight>0});let l=b;if(s){const o=s.toLowerCase();l=b.filter(y=>{var D,R,x,n,d;const v=(D=y.getAttribute("aria-label"))==null?void 0:D.toLowerCase(),A=(R=y.textContent)==null?void 0:R.trim().toLowerCase(),S=(x=y.getAttribute("title"))==null?void 0:x.toLowerCase(),k=(n=y.placeholder)==null?void 0:n.toLowerCase(),L=(d=y.value)==null?void 0:d.toLowerCase();return(v==null?void 0:v.includes(o))||(A==null?void 0:A.includes(o))||(S==null?void 0:S.includes(o))||(k==null?void 0:k.includes(o))||(L==null?void 0:L.includes(o))})}if(l.length===0){i({error:`No element found with role "${e}"${s?` and name "${s}"`:""}`});break}const t=l.map(o=>{var v;const y=q(o,e,s||"");return window.__piRefs=window.__piRefs||{},window.__piRefs[y]=o,a[y]={element:new WeakRef(o),role:e,name:s||""},{ref:y,text:(v=o.textContent)==null?void 0:v.trim().slice(0,50)}});i(c?{matches:t}:{ref:t[0].ref,text:t[0].text})}catch(e){i({error:e instanceof Error?e.message:String(e)})}break}case"LOCATE_TEXT":{try{const{text:e,exact:s}=r,c=H(),a=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),w=[];for(;a.nextNode();){const l=a.currentNode.textContent||"";if(s?l.trim()===e:l.toLowerCase().includes(e.toLowerCase())){const o=a.currentNode.parentElement;if(o&&!w.includes(o)){const y=window.getComputedStyle(o);y.display!=="none"&&y.visibility!=="hidden"&&w.push(o)}}}if(w.length===0){i({error:`No element found with text "${e}"`});break}const u=w.sort((l,t)=>{var o,y;return(((o=l.textContent)==null?void 0:o.length)||0)-(((y=t.textContent)==null?void 0:y.length)||0)})[0],f=U(u),b=q(u,f,e);window.__piRefs=window.__piRefs||{},window.__piRefs[b]=u,c[b]={element:new WeakRef(u),role:f,name:e},i({ref:b,text:(m=u.textContent)==null?void 0:m.trim().slice(0,50)})}catch(e){i({error:e instanceof Error?e.message:String(e)})}break}case"LOCATE_LABEL":{try{const{label:e}=r,s=H(),c=document.querySelectorAll("label");let a=null;for(const f of c){const b=(g=f.textContent)==null?void 0:g.trim().toLowerCase();if(b!=null&&b.includes(e.toLowerCase())){const l=f.getAttribute("for");if(l&&(a=document.getElementById(l)),a||(a=f.querySelector("input, select, textarea")),a)break}}if(!a){const f=e.toLowerCase();a=document.querySelector(`input[aria-label*="${e}" i], input[placeholder*="${e}" i], textarea[aria-label*="${e}" i], textarea[placeholder*="${e}" i], select[aria-label*="${e}" i]`)}if(!a){i({error:`No form field found with label "${e}"`});break}const w=U(a),u=q(a,w,e);window.__piRefs=window.__piRefs||{},window.__piRefs[u]=a,s[u]={element:new WeakRef(a),role:w,name:e},i({ref:u,label:e})}catch(e){i({error:e instanceof Error?e.message:String(e)})}break}case"GET_ELEMENT_TEXT":{try{const{ref:e}=r,s=H(),c=s[e];let a;if(c&&(a=c.element.deref(),a||delete s[e]),!a&&window.__piRefs&&(a=window.__piRefs[e]),!a){i({error:`Element ${e} not found`});break}i({text:((p=a.textContent)==null?void 0:p.trim())||""})}catch(e){i({error:e instanceof Error?e.message:String(e)})}break}case"SCROLL_TO_ELEMENT":{const e=oe(r.ref);i(e);break}case"UPLOAD_IMAGE":{const e=se(r.base64,r.ref,r.coordinate,r.filename);i(e);break}case"WAIT_FOR_ELEMENT":{const{selector:e,state:s="visible",timeout:c=2e4}=r,a=Math.min(c,6e4),w=l=>{if(!l)return!1;const t=window.getComputedStyle(l);return t.display!=="none"&&t.visibility!=="hidden"&&t.opacity!=="0"&&l.offsetWidth>0&&l.offsetHeight>0},u=()=>{const l=document.querySelector(e);switch(s){case"attached":return!!l;case"detached":return!l;case"hidden":return!l||!w(l);case"visible":default:return w(l)}},f=Date.now();return new Promise(l=>{if(u()){l({success:!0,waited:Date.now()-f});return}const t=new MutationObserver(()=>{u()&&(t.disconnect(),clearTimeout(o),l({success:!0,waited:Date.now()-f}))}),o=setTimeout(()=>{t.disconnect(),l({success:!1,waited:Date.now()-f,error:`Timeout waiting for "${e}" to be ${s}`})},a);t.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","hidden","disabled"]})}).then(l=>{if(!l.success){i({error:l.error,waited:l.waited,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}});return}const t=B("interactive",15,void 0,!0);i({...t,waited:l.waited})}),!0}case"WAIT_FOR_URL":{const{pattern:e,timeout:s=2e4}=r,c=Math.min(s,6e4),a=f=>{if(e.includes("*")){const b=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*");return new RegExp(`^${b}$`).test(f)}return f.includes(e)},w=Date.now();return new Promise(f=>{if(a(window.location.href)){f({success:!0,waited:Date.now()-w});return}let b=!1;const l=()=>{b||a(window.location.href)&&(b=!0,clearInterval(t),clearTimeout(o),window.removeEventListener("popstate",l),window.removeEventListener("hashchange",l),f({success:!0,waited:Date.now()-w}))},t=setInterval(l,100),o=setTimeout(()=>{b||(b=!0,clearInterval(t),window.removeEventListener("popstate",l),window.removeEventListener("hashchange",l),f({success:!1,waited:Date.now()-w,error:`Timeout waiting for URL to match "${e}". Current: ${window.location.href}`}))},c);window.addEventListener("popstate",l),window.addEventListener("hashchange",l)}).then(f=>{if(!f.success){i({error:f.error,waited:f.waited,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}});return}const b=B("interactive",15,void 0,!0);i({...b,waited:f.waited})}),!0}case"WAIT_FOR_DOM_STABLE":{const{stable:e=100,timeout:s=5e3}=r,c=Math.min(s,3e4),a=Date.now();return new Promise(u=>{let f=Date.now(),b=!1;const l=()=>{if(b)return;Date.now()-f>=e&&(b=!0,t.disconnect(),clearTimeout(o),clearInterval(y),u({success:!0,waited:Date.now()-a}))},t=new MutationObserver(()=>{f=Date.now()}),o=setTimeout(()=>{b||(b=!0,t.disconnect(),clearInterval(y),u({success:!1,waited:Date.now()-a,error:`Timeout: DOM did not stabilize within ${c}ms`}))},c),y=setInterval(l,Math.max(10,Math.min(50,e/2)));t.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),l()}).then(u=>{if(!u.success){i({error:u.error,waited:u.waited,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}});return}const f=B("interactive",15,void 0,!0);i({...f,waited:u.waited})}),!0}case"FORM_FILL":{const{data:e}=r;if(!Array.isArray(e))return i({error:"data must be an array of {ref, value} pairs"}),!0;const s=H(),c=[];for(const w of e){const{ref:u,value:f}=w;if(!u){c.push({ref:u||"unknown",success:!1,error:"Missing ref"});continue}const b=s[u];if(!b){c.push({ref:u,success:!1,error:"Element not found (run page.read first)"});continue}const l=b.element.deref();if(!l){delete s[u],c.push({ref:u,success:!1,error:"Element no longer exists"});continue}try{if(l instanceof HTMLInputElement){const t=l.type.toLowerCase();if(t==="checkbox"||t==="radio"){const o=f===!0||f==="true"||f==="1"||f==="checked";l.checked=o,l.dispatchEvent(new Event("change",{bubbles:!0}))}else l.focus(),l.value=String(f),l.dispatchEvent(new Event("input",{bubbles:!0})),l.dispatchEvent(new Event("change",{bubbles:!0}));c.push({ref:u,success:!0})}else l instanceof HTMLTextAreaElement?(l.focus(),l.value=String(f),l.dispatchEvent(new Event("input",{bubbles:!0})),l.dispatchEvent(new Event("change",{bubbles:!0})),c.push({ref:u,success:!0})):l instanceof HTMLSelectElement?(l.value=String(f),l.dispatchEvent(new Event("change",{bubbles:!0})),c.push({ref:u,success:!0})):l.isContentEditable?(l.focus(),l.textContent=String(f),l.dispatchEvent(new Event("input",{bubbles:!0})),c.push({ref:u,success:!0})):c.push({ref:u,success:!1,error:"Element is not fillable"})}catch(t){c.push({ref:u,success:!1,error:t instanceof Error?t.message:String(t)})}}const a=c.filter(w=>!w.success);return i({success:a.length===0,filled:c.filter(w=>w.success).length,failed:a.length,results:c}),!0}case"GET_FILE_INPUT_SELECTOR":{const{ref:e}=r;if(!e)return i({error:"No ref provided"}),!0;const s=H(),c=s[e];if(!c)return i({error:"Element not found (run page.read first)"}),!0;const a=c.element.deref();if(!a)return delete s[e],i({error:"Element no longer exists"}),!0;if(!(a instanceof HTMLInputElement)||a.type!=="file")return i({error:"Element is not a file input"}),!0;const w=`__pi_file_${Date.now()}`;return a.setAttribute("data-pi-file-id",w),i({selector:`[data-pi-file-id="${w}"]`}),!0}case"WAIT_FOR_NETWORK_IDLE":{const{timeout:e=1e4}=r,s=Math.min(e,6e4),c=["doubleclick.net","googlesyndication.com","googletagmanager.com","google-analytics.com","facebook.net","connect.facebook.net","analytics","ads","tracking","pixel","hotjar.com","clarity.ms","mixpanel.com","segment.com","newrelic.com","nr-data.net","/tracker/","/collector/","/beacon/","/telemetry/","/log/","/events/","/track.","/metrics/"],a=["img","image","font","icon"],w=t=>c.some(o=>t.includes(o)),u=t=>{const o=t.initiatorType||"unknown";return!!(a.includes(o)||/\.(jpg|jpeg|png|gif|webp|svg|ico|woff|woff2|ttf|eot)(\?|$)/i.test(t.name))},f=()=>{const t=performance.now();return performance.getEntriesByType("resource").filter(y=>{if(y.responseEnd!==0||y.name.startsWith("data:")||y.name.length>500||w(y.name))return!1;const v=t-y.startTime;return!(v>1e4||u(y)&&v>3e3)})},b=Date.now();return new Promise(t=>{const o=()=>{const y=f(),v=Date.now()-b;if(y.length===0){t({success:!0,waited:v});return}if(v>=s){t({success:!1,waited:v,pendingCount:y.length});return}setTimeout(o,100)};o()}).then(t=>{if(!t.success){i({error:`Network not idle after ${t.waited}ms (${t.pendingCount} requests pending)`,waited:t.waited,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}});return}const o=B("interactive",15,void 0,!0);i({...o,waited:t.waited})}),!0}case"SEARCH_PAGE":{const{term:e,caseSensitive:s,limit:c}=r,a=ce(e,s||!1,c||10);i({query:e,count:a.length,matches:a});break}case"GET_ELEMENT_BOUNDS_FOR_ANNOTATION":{const e=H(),s=[];for(const[c,a]of Object.entries(e)){const w=a.element.deref();if(!w)continue;const u=w.getBoundingClientRect();u.width<=0||u.height<=0||u.bottom<0||u.top>window.innerHeight||u.right<0||u.left>window.innerWidth||s.push({ref:c,tag:w.tagName.toLowerCase(),bounds:{x:u.x,y:u.y,width:u.width,height:u.height}})}i({elements:s});break}default:return!1}return!1});function ce(r,h,i){const m=[],g=h?r:r.toLowerCase(),p=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),e=H();let s=0;for(;p.nextNode()&&m.length<i;){const c=p.currentNode,a=c.textContent||"",w=h?a:a.toLowerCase();let u=0;for(;(u=w.indexOf(g,u))!==-1&&m.length<i;){const f=c.parentElement;if(!f){u++;continue}const b=document.createRange();b.setStart(c,u),b.setEnd(c,Math.min(u+r.length,a.length));const l=b.getBoundingClientRect();if(l.width===0||l.height===0){u++;continue}const t=c.textContent||"",o=Math.max(0,u-30),y=Math.min(t.length,u+r.length+30),v=t.slice(o,y).trim();let A=null;for(const[S,k]of Object.entries(e)){const L=k.element.deref();if(L&&(L===f||L.contains(f))){A=S;break}}m.push({ref:`m${++s}`,text:t.slice(u,u+r.length),context:v,bounds:{x:Math.round(l.x),y:Math.round(l.y),width:Math.round(l.width),height:Math.round(l.height)},elementRef:A}),u++}}return m}
10
+ [Viewport: ${window.innerWidth}x${window.innerHeight}]`,viewport:{width:window.innerWidth,height:window.innerHeight}}}catch(r){return{error:`Error generating YAML tree: ${r instanceof Error?r.message:"Unknown error"}`,yaml:"",viewport:{width:window.innerWidth,height:window.innerHeight}}}}function ne(i){const m=O(),r=m[i];let w;if(r&&(w=r.element.deref(),w||delete m[i]),!w&&window.__piRefs&&(w=window.__piRefs[i]),!w)return{x:0,y:0,error:`Element ${i} not found. Use read_page to get current elements.`};const y=w.getBoundingClientRect(),g=Math.round(y.left+y.width/2),e=Math.round(y.top+y.height/2);return{x:g,y:e}}function re(i,m){var e;const r=O(),w=r[i];let y;if(w&&(y=w.element.deref(),y||delete r[i]),!y&&window.__piRefs&&(y=window.__piRefs[i]),!y)return{success:!1,error:`Element ${i} not found. Use read_page to get current elements.`};const g=y.tagName.toLowerCase();try{if(g==="input"){const c=y,l=c.type.toLowerCase();l==="checkbox"||l==="radio"?(c.checked=!!m,c.dispatchEvent(new Event("change",{bubbles:!0}))):(c.value=String(m),c.dispatchEvent(new Event("input",{bubbles:!0})),c.dispatchEvent(new Event("change",{bubbles:!0})))}else if(g==="textarea"){const c=y;c.value=String(m),c.dispatchEvent(new Event("input",{bubbles:!0})),c.dispatchEvent(new Event("change",{bubbles:!0}))}else if(g==="select"){const c=y,l=String(m);let s=!1;for(const d of c.options)if(d.value===l||((e=d.textContent)==null?void 0:e.trim())===l){c.value=d.value,s=!0;break}if(!s)return{success:!1,error:`Option "${m}" not found in select element ${i}`};c.dispatchEvent(new Event("change",{bubbles:!0}))}else if(y.getAttribute("contenteditable")==="true")y.textContent=String(m),y.dispatchEvent(new Event("input",{bubbles:!0}));else return{success:!1,error:`Element ${i} (${g}) is not a form field`};return{success:!0}}catch(c){return{success:!1,error:`Failed to set value: ${c instanceof Error?c.message:"Unknown error"}`}}}function ie(){var i;try{const m=document.querySelector("article"),r=document.querySelector("main");return{text:((i=(m||r||document.body).textContent)==null?void 0:i.replace(/\s+/g," ").trim().substring(0,5e4))||"",title:document.title,url:window.location.href}}catch(m){return{text:"",title:"",url:"",error:`Failed to extract text: ${m instanceof Error?m.message:"Unknown error"}`}}}function oe(i){const m=O(),r=m[i];let w;return r&&(w=r.element.deref(),w||delete m[i]),!w&&window.__piRefs&&(w=window.__piRefs[i]),w?(w.scrollIntoView({behavior:"smooth",block:"center"}),{success:!0}):{success:!1,error:`Element ${i} not found. Run read_page to get current element refs.`}}function se(i,m,r,w="screenshot.png"){try{const y=atob(i),g=new ArrayBuffer(y.length),e=new Uint8Array(g);for(let h=0;h<y.length;h++)e[h]=y.charCodeAt(h);const c=new Blob([g],{type:"image/png"}),l=new File([c],w,{type:"image/png"});let s=null;if(m){const h=O(),b=h[m];if(b&&(s=b.element.deref(),s||delete h[m]),!s&&window.__piRefs&&(s=window.__piRefs[m]),!s)return{success:!1,error:`Element ${m} not found. Run read_page to get current element refs.`}}else if(r&&(s=document.elementFromPoint(r[0],r[1]),!s))return{success:!1,error:`No element at (${r[0]}, ${r[1]})`};if(!s)return{success:!1,error:"No target element"};if(s.tagName==="INPUT"&&s.type==="file"){const h=s,b=new DataTransfer;return b.items.add(l),h.files=b.files,h.dispatchEvent(new Event("change",{bubbles:!0})),{success:!0}}const d=new DataTransfer;d.items.add(l);const u=new DragEvent("drop",{bubbles:!0,cancelable:!0,dataTransfer:d});return s.dispatchEvent(u),{success:!0}}catch(y){return{success:!1,error:y instanceof Error?y.message:"Upload failed"}}}chrome.runtime.onMessage.addListener((i,m,r)=>{var w,y,g;switch(i.type){case"GENERATE_ACCESSIBILITY_TREE":{const e=i.options||{};if(e.format==="yaml"){const c=te(e.filter||"interactive",e.depth??15),l=Y();c.error?r({error:c.error,pageContent:"",viewport:c.viewport}):r({pageContent:c.yaml,viewport:c.viewport,modalStates:l.length>0?l:void 0,modalLimitations:"Only custom modals ([role=dialog]) detected. Native alert/confirm/prompt dialogs and system file choosers cannot be detected from content scripts."})}else{const c=B(e.filter||"interactive",e.depth??15,e.refId,e.forceFullSnapshot??!1,e.compact??!1);r(c)}break}case"GET_ELEMENT_COORDINATES":{const e=ne(i.ref);r(e);break}case"CLICK_ELEMENT":{const e=O(),c=e[i.ref];let l;if(c&&(l=c.element.deref(),l||delete e[i.ref]),!l&&window.__piRefs&&(l=window.__piRefs[i.ref]),!l){r({error:`Element ${i.ref} not found. Use read_page to get current elements.`});break}if(i.button==="triple"){const s=new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window,detail:3});l.dispatchEvent(s)}else i.button==="double"?l.dispatchEvent(new MouseEvent("dblclick",{bubbles:!0,cancelable:!0,view:window})):i.button==="right"?l.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,view:window})):l.click();r({success:!0});break}case"FORM_INPUT":{const e=re(i.ref,i.value);r(e);break}case"EVAL_IN_PAGE":{try{const e=document.createElement("script");e.textContent=`(function() { ${i.code} })();`,document.documentElement.appendChild(e),e.remove(),r({success:!0})}catch(e){r({success:!1,error:e instanceof Error?e.message:String(e)})}break}case"GET_PAGE_TEXT":{const e=ie();r(e);break}case"GET_FRAME_BY_SELECTOR":{try{const e=document.querySelector(i.selector);if(!e||e.tagName.toLowerCase()!=="iframe"){r({error:`No iframe found with selector "${i.selector}"`});break}r({url:e.src,name:e.name||void 0})}catch(e){r({error:e instanceof Error?e.message:String(e)})}break}case"GET_FRAME_NAME":{try{r({name:window.name||null})}catch{r({name:null})}break}case"LOCATE_ROLE":{try{const{role:e,name:c,all:l}=i,s=O(),u={button:["button",'input[type="button"]','input[type="submit"]','input[type="reset"]','[role="button"]'],link:["a[href]",'[role="link"]'],textbox:["input:not([type])",'input[type="text"]','input[type="email"]','input[type="password"]','input[type="search"]','input[type="tel"]','input[type="url"]',"textarea",'[role="textbox"]'],checkbox:['input[type="checkbox"]','[role="checkbox"]'],radio:['input[type="radio"]','[role="radio"]'],combobox:["select",'[role="combobox"]'],listbox:['[role="listbox"]',"select[multiple]"],option:["option",'[role="option"]'],heading:["h1","h2","h3","h4","h5","h6",'[role="heading"]'],navigation:["nav",'[role="navigation"]'],main:["main",'[role="main"]'],img:["img[alt]",'[role="img"]'],dialog:["dialog",'[role="dialog"]','[role="alertdialog"]'],tab:['[role="tab"]'],tabpanel:['[role="tabpanel"]'],menu:['[role="menu"]'],menuitem:['[role="menuitem"]']}[e]||[`[role="${e}"]`],h=[];for(const o of u)try{h.push(...document.querySelectorAll(o))}catch{}const b=h.filter(o=>{const p=window.getComputedStyle(o);return p.display!=="none"&&p.visibility!=="hidden"&&o.offsetWidth>0&&o.offsetHeight>0});let a=b;if(c){const o=c.toLowerCase();a=b.filter(p=>{var D,W,x,n,f;const v=(D=p.getAttribute("aria-label"))==null?void 0:D.toLowerCase(),_=(W=p.textContent)==null?void 0:W.trim().toLowerCase(),S=(x=p.getAttribute("title"))==null?void 0:x.toLowerCase(),A=(n=p.placeholder)==null?void 0:n.toLowerCase(),L=(f=p.value)==null?void 0:f.toLowerCase();return(v==null?void 0:v.includes(o))||(_==null?void 0:_.includes(o))||(S==null?void 0:S.includes(o))||(A==null?void 0:A.includes(o))||(L==null?void 0:L.includes(o))})}if(a.length===0){r({error:`No element found with role "${e}"${c?` and name "${c}"`:""}`});break}const t=a.map(o=>{var v;const p=q(o,e,c||"");return window.__piRefs=window.__piRefs||{},window.__piRefs[p]=o,s[p]={element:new WeakRef(o),role:e,name:c||""},{ref:p,text:(v=o.textContent)==null?void 0:v.trim().slice(0,50)}});r(l?{matches:t}:{ref:t[0].ref,text:t[0].text})}catch(e){r({error:e instanceof Error?e.message:String(e)})}break}case"LOCATE_TEXT":{try{const{text:e,exact:c}=i,l=O(),s=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),d=[];for(;s.nextNode();){const a=s.currentNode.textContent||"";if(c?a.trim()===e:a.toLowerCase().includes(e.toLowerCase())){const o=s.currentNode.parentElement;if(o&&!d.includes(o)){const p=window.getComputedStyle(o);p.display!=="none"&&p.visibility!=="hidden"&&d.push(o)}}}if(d.length===0){r({error:`No element found with text "${e}"`});break}const u=d.sort((a,t)=>{var o,p;return(((o=a.textContent)==null?void 0:o.length)||0)-(((p=t.textContent)==null?void 0:p.length)||0)})[0],h=U(u),b=q(u,h,e);window.__piRefs=window.__piRefs||{},window.__piRefs[b]=u,l[b]={element:new WeakRef(u),role:h,name:e},r({ref:b,text:(w=u.textContent)==null?void 0:w.trim().slice(0,50)})}catch(e){r({error:e instanceof Error?e.message:String(e)})}break}case"LOCATE_LABEL":{try{const{label:e}=i,c=O(),l=document.querySelectorAll("label");let s=null;for(const h of l){const b=(y=h.textContent)==null?void 0:y.trim().toLowerCase();if(b!=null&&b.includes(e.toLowerCase())){const a=h.getAttribute("for");if(a&&(s=document.getElementById(a)),s||(s=h.querySelector("input, select, textarea")),s)break}}if(!s){const h=e.toLowerCase();s=document.querySelector(`input[aria-label*="${e}" i], input[placeholder*="${e}" i], textarea[aria-label*="${e}" i], textarea[placeholder*="${e}" i], select[aria-label*="${e}" i]`)}if(!s){r({error:`No form field found with label "${e}"`});break}const d=U(s),u=q(s,d,e);window.__piRefs=window.__piRefs||{},window.__piRefs[u]=s,c[u]={element:new WeakRef(s),role:d,name:e},r({ref:u,label:e})}catch(e){r({error:e instanceof Error?e.message:String(e)})}break}case"GET_ELEMENT_STYLES":{try{const{selector:e}=i,c=O(),l=s=>{var h;const d=getComputedStyle(s),u=s.getBoundingClientRect();return{tag:s.tagName.toLowerCase(),text:((h=s.innerText)==null?void 0:h.trim().slice(0,80))||null,box:{x:Math.round(u.x),y:Math.round(u.y),width:Math.round(u.width),height:Math.round(u.height)},styles:{fontSize:d.fontSize,fontWeight:d.fontWeight,fontFamily:d.fontFamily.split(",")[0].trim().replace(/"/g,""),color:d.color,backgroundColor:d.backgroundColor,borderRadius:d.borderRadius,border:d.border!=="none"&&d.borderWidth!=="0px"?d.border:null,boxShadow:d.boxShadow!=="none"?d.boxShadow:null,padding:d.padding}}};if(/^e\d+$/.test(e)){const s=c[e];let d;if(s&&(d=s.element.deref(),d||delete c[e]),!d&&window.__piRefs&&(d=window.__piRefs[e]),!d){r({error:`Element ${e} not found`});break}r({styles:[l(d)]})}else{const s=document.querySelectorAll(e);if(s.length===0){r({error:`No elements found matching "${e}"`});break}const d=Array.from(s).map(l);r({styles:d})}}catch(e){r({error:e instanceof Error?e.message:String(e)})}break}case"SELECT_OPTION":{try{const{selector:e,values:c,by:l}=i,s=O();let d=null;if(/^e\d+$/.test(e)){const a=s[e];let t;if(a&&(t=a.element.deref(),t||delete s[e]),!t&&window.__piRefs&&(t=window.__piRefs[e]),!t){r({error:`Element ${e} not found`});break}if(t.tagName!=="SELECT"){r({error:`Element ${e} is not a <select>`});break}d=t}else{if(d=document.querySelector(e),!d){r({error:`No element found matching "${e}"`});break}if(d.tagName!=="SELECT"){r({error:`Element "${e}" is not a <select>`});break}}if(d.multiple)for(const a of d.options)a.selected=!1;const u=[],h=[],b=d.multiple?c:[c[0]];for(const a of b){let t=!1;for(const o of d.options){let p=!1;if(l==="index"?p=o.index===parseInt(a,10):l==="label"?p=o.text.toLowerCase().includes(a.toLowerCase()):p=o.value===a,p){o.selected=!0,u.push(o.value),t=!0;break}}t||h.push(a)}d.dispatchEvent(new Event("change",{bubbles:!0})),h.length>0?r({selected:u,warning:`Values not found: ${h.join(", ")}`}):r({selected:u})}catch(e){r({error:e instanceof Error?e.message:String(e)})}break}case"GET_ELEMENT_TEXT":{try{const{ref:e}=i,c=O(),l=c[e];let s;if(l&&(s=l.element.deref(),s||delete c[e]),!s&&window.__piRefs&&(s=window.__piRefs[e]),!s){r({error:`Element ${e} not found`});break}r({text:((g=s.textContent)==null?void 0:g.trim())||""})}catch(e){r({error:e instanceof Error?e.message:String(e)})}break}case"SCROLL_TO_ELEMENT":{const e=oe(i.ref);r(e);break}case"UPLOAD_IMAGE":{const e=se(i.base64,i.ref,i.coordinate,i.filename);r(e);break}case"WAIT_FOR_ELEMENT":{const{selector:e,state:c="visible",timeout:l=2e4}=i,s=Math.min(l,6e4),d=a=>{if(!a)return!1;const t=window.getComputedStyle(a);return t.display!=="none"&&t.visibility!=="hidden"&&t.opacity!=="0"&&a.offsetWidth>0&&a.offsetHeight>0},u=()=>{const a=document.querySelector(e);switch(c){case"attached":return!!a;case"detached":return!a;case"hidden":return!a||!d(a);case"visible":default:return d(a)}},h=Date.now();return new Promise(a=>{if(u()){a({success:!0,waited:Date.now()-h});return}const t=new MutationObserver(()=>{u()&&(t.disconnect(),clearTimeout(o),a({success:!0,waited:Date.now()-h}))}),o=setTimeout(()=>{t.disconnect(),a({success:!1,waited:Date.now()-h,error:`Timeout waiting for "${e}" to be ${c}`})},s);t.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","hidden","disabled"]})}).then(a=>{if(!a.success){r({error:a.error,waited:a.waited,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}});return}const t=B("interactive",15,void 0,!0);r({...t,waited:a.waited})}),!0}case"WAIT_FOR_URL":{const{pattern:e,timeout:c=2e4}=i,l=Math.min(c,6e4),s=h=>{if(e.includes("*")){const b=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*");return new RegExp(`^${b}$`).test(h)}return h.includes(e)},d=Date.now();return new Promise(h=>{if(s(window.location.href)){h({success:!0,waited:Date.now()-d});return}let b=!1;const a=()=>{b||s(window.location.href)&&(b=!0,clearInterval(t),clearTimeout(o),window.removeEventListener("popstate",a),window.removeEventListener("hashchange",a),h({success:!0,waited:Date.now()-d}))},t=setInterval(a,100),o=setTimeout(()=>{b||(b=!0,clearInterval(t),window.removeEventListener("popstate",a),window.removeEventListener("hashchange",a),h({success:!1,waited:Date.now()-d,error:`Timeout waiting for URL to match "${e}". Current: ${window.location.href}`}))},l);window.addEventListener("popstate",a),window.addEventListener("hashchange",a)}).then(h=>{if(!h.success){r({error:h.error,waited:h.waited,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}});return}const b=B("interactive",15,void 0,!0);r({...b,waited:h.waited})}),!0}case"WAIT_FOR_DOM_STABLE":{const{stable:e=100,timeout:c=5e3}=i,l=Math.min(c,3e4),s=Date.now();return new Promise(u=>{let h=Date.now(),b=!1;const a=()=>{if(b)return;Date.now()-h>=e&&(b=!0,t.disconnect(),clearTimeout(o),clearInterval(p),u({success:!0,waited:Date.now()-s}))},t=new MutationObserver(()=>{h=Date.now()}),o=setTimeout(()=>{b||(b=!0,t.disconnect(),clearInterval(p),u({success:!1,waited:Date.now()-s,error:`Timeout: DOM did not stabilize within ${l}ms`}))},l),p=setInterval(a,Math.max(10,Math.min(50,e/2)));t.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),a()}).then(u=>{if(!u.success){r({error:u.error,waited:u.waited,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}});return}const h=B("interactive",15,void 0,!0);r({...h,waited:u.waited})}),!0}case"FORM_FILL":{const{data:e}=i;if(!Array.isArray(e))return r({error:"data must be an array of {ref, value} pairs"}),!0;const c=O(),l=[];for(const d of e){const{ref:u,value:h}=d;if(!u){l.push({ref:u||"unknown",success:!1,error:"Missing ref"});continue}const b=c[u];if(!b){l.push({ref:u,success:!1,error:"Element not found (run page.read first)"});continue}const a=b.element.deref();if(!a){delete c[u],l.push({ref:u,success:!1,error:"Element no longer exists"});continue}try{if(a instanceof HTMLInputElement){const t=a.type.toLowerCase();if(t==="checkbox"||t==="radio"){const o=h===!0||h==="true"||h==="1"||h==="checked";a.checked=o,a.dispatchEvent(new Event("change",{bubbles:!0}))}else a.focus(),a.value=String(h),a.dispatchEvent(new Event("input",{bubbles:!0})),a.dispatchEvent(new Event("change",{bubbles:!0}));l.push({ref:u,success:!0})}else a instanceof HTMLTextAreaElement?(a.focus(),a.value=String(h),a.dispatchEvent(new Event("input",{bubbles:!0})),a.dispatchEvent(new Event("change",{bubbles:!0})),l.push({ref:u,success:!0})):a instanceof HTMLSelectElement?(a.value=String(h),a.dispatchEvent(new Event("change",{bubbles:!0})),l.push({ref:u,success:!0})):a.isContentEditable?(a.focus(),a.textContent=String(h),a.dispatchEvent(new Event("input",{bubbles:!0})),l.push({ref:u,success:!0})):l.push({ref:u,success:!1,error:"Element is not fillable"})}catch(t){l.push({ref:u,success:!1,error:t instanceof Error?t.message:String(t)})}}const s=l.filter(d=>!d.success);return r({success:s.length===0,filled:l.filter(d=>d.success).length,failed:s.length,results:l}),!0}case"GET_FILE_INPUT_SELECTOR":{const{ref:e}=i;if(!e)return r({error:"No ref provided"}),!0;const c=O(),l=c[e];if(!l)return r({error:"Element not found (run page.read first)"}),!0;const s=l.element.deref();if(!s)return delete c[e],r({error:"Element no longer exists"}),!0;if(!(s instanceof HTMLInputElement)||s.type!=="file")return r({error:"Element is not a file input"}),!0;const d=`__pi_file_${Date.now()}`;return s.setAttribute("data-pi-file-id",d),r({selector:`[data-pi-file-id="${d}"]`}),!0}case"WAIT_FOR_NETWORK_IDLE":{const{timeout:e=1e4}=i,c=Math.min(e,6e4),l=["doubleclick.net","googlesyndication.com","googletagmanager.com","google-analytics.com","facebook.net","connect.facebook.net","analytics","ads","tracking","pixel","hotjar.com","clarity.ms","mixpanel.com","segment.com","newrelic.com","nr-data.net","/tracker/","/collector/","/beacon/","/telemetry/","/log/","/events/","/track.","/metrics/"],s=["img","image","font","icon"],d=t=>l.some(o=>t.includes(o)),u=t=>{const o=t.initiatorType||"unknown";return!!(s.includes(o)||/\.(jpg|jpeg|png|gif|webp|svg|ico|woff|woff2|ttf|eot)(\?|$)/i.test(t.name))},h=()=>{const t=performance.now();return performance.getEntriesByType("resource").filter(p=>{if(p.responseEnd!==0||p.name.startsWith("data:")||p.name.length>500||d(p.name))return!1;const v=t-p.startTime;return!(v>1e4||u(p)&&v>3e3)})},b=Date.now();return new Promise(t=>{const o=()=>{const p=h(),v=Date.now()-b;if(p.length===0){t({success:!0,waited:v});return}if(v>=c){t({success:!1,waited:v,pendingCount:p.length});return}setTimeout(o,100)};o()}).then(t=>{if(!t.success){r({error:`Network not idle after ${t.waited}ms (${t.pendingCount} requests pending)`,waited:t.waited,pageContent:"",viewport:{width:window.innerWidth,height:window.innerHeight}});return}const o=B("interactive",15,void 0,!0);r({...o,waited:t.waited})}),!0}case"SEARCH_PAGE":{const{term:e,caseSensitive:c,limit:l}=i,s=ce(e,c||!1,l||10);r({query:e,count:s.length,matches:s});break}case"GET_ELEMENT_BOUNDS_FOR_ANNOTATION":{const e=O(),c=[];for(const[l,s]of Object.entries(e)){const d=s.element.deref();if(!d)continue;const u=d.getBoundingClientRect();u.width<=0||u.height<=0||u.bottom<0||u.top>window.innerHeight||u.right<0||u.left>window.innerWidth||c.push({ref:l,tag:d.tagName.toLowerCase(),bounds:{x:u.x,y:u.y,width:u.width,height:u.height}})}r({elements:c});break}default:return!1}return!1});function ce(i,m,r){const w=[],y=m?i:i.toLowerCase(),g=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),e=O();let c=0;for(;g.nextNode()&&w.length<r;){const l=g.currentNode,s=l.textContent||"",d=m?s:s.toLowerCase();let u=0;for(;(u=d.indexOf(y,u))!==-1&&w.length<r;){const h=l.parentElement;if(!h){u++;continue}const b=document.createRange();b.setStart(l,u),b.setEnd(l,Math.min(u+i.length,s.length));const a=b.getBoundingClientRect();if(a.width===0||a.height===0){u++;continue}const t=l.textContent||"",o=Math.max(0,u-30),p=Math.min(t.length,u+i.length+30),v=t.slice(o,p).trim();let _=null;for(const[S,A]of Object.entries(e)){const L=A.element.deref();if(L&&(L===h||L.contains(h))){_=S;break}}w.push({ref:`m${++c}`,text:t.slice(u,u+i.length),context:v,bounds:{x:Math.round(a.x),y:Math.round(a.y),width:Math.round(a.width),height:Math.round(a.height)},elementRef:_}),u++}}return w}
11
11
  //# sourceMappingURL=accessibility-tree.js.map