@inbrowser/driver 0.0.0-stage → 0.5.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/AGENTS.md +20 -0
- package/LICENSE +21 -0
- package/README.md +112 -2
- package/THIRD_PARTY_NOTICES.txt +216 -0
- package/dist/LICENSE +21 -0
- package/dist/THIRD_PARTY_NOTICES.txt +216 -0
- package/dist/index.js +1631 -0
- package/dist/index.js.map +7 -0
- package/dist/preload.iife.js +5 -0
- package/dist/preload.js +2 -0
- package/dist/puppeteer.js +2569 -0
- package/dist/puppeteer.js.map +7 -0
- package/dist/tools.js +1283 -0
- package/dist/tools.js.map +7 -0
- package/dist/types/host/capture-seam.d.ts +17 -0
- package/dist/types/host/preview-backend.d.ts +9 -0
- package/dist/types/host/sandbox-connect.d.ts +38 -0
- package/dist/types/host/viewport-capture.d.ts +2 -0
- package/dist/types/index.d.ts +5 -0
- package/dist/types/preload/act.d.ts +4 -0
- package/dist/types/preload/capture-seam.d.ts +1 -0
- package/dist/types/preload/cursor-overlay.d.ts +5 -0
- package/dist/types/preload/diagnostics.d.ts +13 -0
- package/dist/types/preload/diff.d.ts +3 -0
- package/dist/types/preload/entry.d.ts +1 -0
- package/dist/types/preload/eval.d.ts +7 -0
- package/dist/types/preload/export.d.ts +11 -0
- package/dist/types/preload/intrinsics.d.ts +255 -0
- package/dist/types/preload/observe.d.ts +27 -0
- package/dist/types/preload/ref-registry.d.ts +44 -0
- package/dist/types/preload/silent-capture.d.ts +3 -0
- package/dist/types/protocol.d.ts +103 -0
- package/dist/types/puppeteer/cdp-driver.d.ts +11 -0
- package/dist/types/puppeteer/index.d.ts +2 -0
- package/dist/types/tools/format.d.ts +7 -0
- package/dist/types/tools/index.d.ts +9 -0
- package/dist/types/tools/schemas.d.ts +36 -0
- package/dist/types/types.d.ts +268 -0
- package/package.json +70 -4
|
@@ -0,0 +1,2569 @@
|
|
|
1
|
+
// src/puppeteer/cdp-driver.ts
|
|
2
|
+
import {
|
|
3
|
+
connect
|
|
4
|
+
} from "puppeteer-core";
|
|
5
|
+
|
|
6
|
+
// dist/preload.js
|
|
7
|
+
var DRIVER_PRELOAD_SOURCE = '"use strict";(()=>{var je="@inbrowser/driver:v1";var L=class extends Error{code;candidates;constructor(t,n,r){super(n,r?.cause!==void 0?{cause:r.cause}:void 0),this.name="DriverError",this.code=t,r?.candidates!==void 0&&(this.candidates=r.candidates)}};var x=Reflect.apply,F=Reflect.get,st=Reflect.set,un=Reflect.has,fn=Reflect.defineProperty,pn=Object.getOwnPropertyDescriptor,lt=WeakRef,ze=WeakMap,Ke=WeakSet,z=Map,P=Set;function B(e){return new P(e.split(" "))}function Se(e){let t={};for(let n of e.split(" ")){let r=n.indexOf(":");r>0&&(t[n.slice(0,r)]=n.slice(r+1))}return t}function m(e,t){return t!==void 0&&e instanceof t}var E=globalThis,b=E.window,S=E.document,dt=E.MessageEvent,mn=E.ErrorEvent,gn=E.PromiseRejectionEvent,ct=E.MutationObserver,Y=E.Event,yn=E.MouseEvent,hn=E.PointerEvent,ut=E.KeyboardEvent,ft=E.InputEvent,pt=E.Node,v=E.Element,V=E.HTMLElement,ne=E.ShadowRoot,Re=E.Document,Hr=E.HTMLSlotElement,N=E.HTMLInputElement,Q=E.HTMLTextAreaElement,re=E.HTMLSelectElement,ve=E.HTMLOptionElement,Pe=E.HTMLFormElement,bn=E.HTMLLabelElement,En=E.HTMLButtonElement,mt=E.HTMLAnchorElement,gt=E.HTMLDialogElement,me=E.HTMLMediaElement,qe=E.HTMLVideoElement,Z=E.HTMLCanvasElement,Sn=E.CanvasRenderingContext2D,We=E.Image,yt=E.XMLSerializer,oe=E.URL,ht=E.Request,xe=E.XMLHttpRequest;function we(e,t){let n=e?pn(e.prototype,t):void 0;return[r=>n?.get?x(n.get,r,[]):F(r,t),(r,i)=>{n?.set?x(n.set,r,[i]):st(r,t,i)}]}function $(e,t){let n=e?.prototype,r=n!==void 0?n[t]:void 0;return(i,...o)=>x(r,i,o)}var rn=b?.getComputedStyle,Fr=b?.setTimeout??setTimeout,Br=b?.clearTimeout??clearTimeout,on=b?.requestAnimationFrame,at=E.performance,an=at?.now,sn=Y?pn(new Y("x"),"isTrusted")?.get:void 0,Xe=(e,t)=>x(Fr,b,[e,t]),Je=e=>{x(Br,b,[e])},Rn=e=>on&&b?x(on,b,[e]):null,H=()=>at&&an?x(an,at,[]):Date.now(),vn=e=>sn?!!x(sn,e,[]):e.isTrusted===!0,K=$(E.EventTarget,"addEventListener"),Ye=$(E.EventTarget,"removeEventListener"),ge=$(E.EventTarget,"dispatchEvent"),ie=e=>rn?x(rn,window,[e]):null,xn=$(E.MessagePort,"postMessage"),wn=$(E.MessagePort,"start"),bt=$(E.MessagePort,"close"),kn=v?.prototype,ln=kn?.scrollIntoView,dn=kn?.attachShadow,cn=V?.prototype.focus,$r=Pe?.prototype.requestSubmit,Ur=Pe?.prototype.submit,W=$(v,"getBoundingClientRect"),ye=we(v,"shadowRoot")[0],Tn=e=>{try{return dn?x(dn,e,[{mode:"open"}]):null}catch{return ye(e)}},Gr=[Re,ne].map(e=>e?.prototype.elementFromPoint),Et=(e,t,n)=>{let r=Gr[m(e,Re)?0:1];return r?x(r,e,[t,n]):null},Cn=e=>{ln&&x(ln,e,[{block:"nearest",inline:"nearest"}])},he=e=>{cn&&x(cn,e,[{preventScroll:!0}])},Dn=$(V,"click"),On=e=>{let t=$r??Ur;t&&x(t,e,[])},ae=$(v,"setAttribute"),In=$(pt,"cloneNode"),jr=[v,Re,ne].map(e=>e?.prototype.querySelector),Qe=(e,t)=>{let n=jr[m(e,v)?0:m(e,Re)?1:m(e,ne)?2:3];return n?x(n,e,[t]):null},[St,Mn]=we(N,"value"),[zr,An]=we(Q,"value"),[Kr,Nn]=we(re,"value");var Rt=we(ve,"selected")[1],ke=e=>m(e,N)?St(e):m(e,Q)?zr(e):m(e,re)?Kr(e):null,Pn=we(me,"currentTime")[1],_e=Z?.prototype.getContext,vt=Z?.prototype.transferControlToOffscreen,xt=E.console?.error,wt=b?.fetch,kt=xe?.prototype.open,Tt=xe?.prototype.send,_n=b?.alert,Ln=b?.confirm,Vn=b?.prompt,ee="data-inbrowser-driver-ui",k=e=>e.replace(/\\s+/g," ").trim(),T=e=>e.tagName.toLowerCase(),C=$(v,"getAttribute"),I=(e,t)=>k(C(e,t)??""),A=$(v,"hasAttribute");function X(e){if(m(e,v)){if(m(e,Hr)){let n=e.assignedNodes({flatten:!1});if(n.length)return n}let t=ye(e);if(t)return[...t.childNodes];if(m(e,re))return[...e.childNodes].slice(0,50)}return[...e.childNodes]}var qr="pointerdown mousedown keydown touchstart wheel".split(" "),be=null,Ze=e=>`${Math.round(e)}px`,Le=(e,t,n,r="")=>{e.style.cssText=`display:block;left:${Ze(t)};top:${Ze(n)}${r}`},Ct=e=>{e&&(e.style.display="none")};function Hn(){if(!S?.documentElement)return null;if(!be){let e=S.createElement("div");ae(e,ee,"cursor"),ae(e,"aria-hidden","true");let t=Tn(e);if(!t)return null;let n=S.createElement("style");n.textContent=":host,[data-part]{all:initial;position:fixed;pointer-events:none;box-sizing:border-box}:host{inset:0;z-index:2147483647}[data-part=box]{border:2px solid #2563eb;background:#2563eb14}[data-part=dot]{width:10px;height:10px;margin:-5px 0 0 -5px;border-radius:9px;background:#2563eb}[data-part=badge]{padding:2px 5px;background:#0f172a;color:#fff;font:600 11px sans-serif;white-space:nowrap}";let r=["box","dot","badge"].map(i=>{let o=S.createElement("div");return ae(o,"data-part",i),o});t.append(n,...r),be=[e,r[0],r[1],r[2]]}return be[0].isConnected||S.documentElement.appendChild(be[0]),be[0].style.display="block",be}function Fn(e,t){let n=Hn();n&&Le(n[2],e,t)}function Dt(e,t,n,r,i,o){let a=Hn();if(!a)return;let[,f,u,c]=a;c.textContent=`${e+1}/${t} ${n}`,Le(c,r?Math.max(4,r.left):8,r?Math.max(4,r.top-22):8),r?(Le(f,r.left,r.top,`;width:${Ze(Math.max(2,r.width))};height:${Ze(Math.max(2,r.height))}`),Le(u,i??r.left+r.width/2,o??r.top+r.height/2)):(Ct(f),i!==void 0&&o!==void 0?Le(u,i,o):Ct(u))}function Bn(){Ct(be?.[0])}function $n(){let e=r=>{!n[0]&&vn(r)&&(n[0]=!0,n[1]?.(),n[1]=null)},t=(r,i)=>{if(b)for(let o of qr)r(b,o,e,i)},n=[!1,null,()=>{n[1]=null,t(Ye,!0)}];return t(K,{capture:!0,passive:!0}),n}function U(e,t,n){throw new L(e,t,n!==void 0?{candidates:n}:void 0)}function le(e,t){return U("DRIVER_TARGET_NOT_FOUND",e,t)}function Un(e,t){return U("DRIVER_TARGET_AMBIGUOUS",e,t)}function jn(e,t,n=8){let r=t.role?e.filter(o=>o.fingerprint.role===t.role):[],i=(o,a,f)=>{if(!o||!a)return 0;let u=o.toLowerCase(),c=a.toLowerCase();return c===u?f:c.includes(u)||u.includes(c)?f/2:0};return(r.length?r:e).map(({fingerprint:o},a)=>[o,a,(t.role&&o.role===t.role?100:0)+(t.landmark!==void 0&&o.landmark===t.landmark?30:0)+i(t.driverId,o.driverId,80)+i(t.name,o.name,50)]).sort((o,a)=>a[2]-o[2]||o[1]-a[1]).slice(0,n).map(o=>o[0])}var zn=(e,t)=>e.role===t.role&&e.name===t.name&&e.landmark===t.landmark&&e.driverId===t.driverId;function Wr(e,t){let n=t.filter(r=>zn(r.fingerprint,e.fingerprint));if(n.length===0)return{status:"not_found",candidates:jn(t,e.fingerprint)};if(n.length===e.cohortSize){let r=n[n.length===1?0:e.fingerprint.nth];if(r!==void 0)return{status:"matched",candidate:r}}return{status:"ambiguous",candidates:n.map(r=>r.fingerprint)}}function Ve(e){return/^e\\d+$/.test(e)}var Gn=2e3,et=0,Xr=1,Ot=new ze,se=new z,Kn=()=>et,It=e=>{e>et&&(et=e)},qn=()=>++et,Wn=e=>se.get(e);function Xn(e,t,n,r){let i=c=>(Ot.set(e,c),se.set(c,[new lt(e),t,n,r]),c),o=Ot.get(e);if(o!==void 0)return i(o);let a,f=-1;for(let[c,[d,l,s,p]]of se)s===n&&zn(l,t)&&l.nth===t.nth&&!d.deref()?.isConnected&&p>f&&(a=c,f=p);if(a)return i(a);let u=i(`e${Xr++}`);if(se.size>Gn){for(let[c,[d]]of se)if(!d.deref()?.isConnected&&(se.delete(c),se.size<=Gn))break}return u}function Mt(e,t,n="",r="",i,o){return le(e,jn(i??q(t,!1),{role:n,name:r,...o?{driverId:o}:{}}))}function de(e,t){let n=t??S??le("No root.");function r(d,l="",s="",p,y){return Mt(d,n,l,s,p,y)}if(typeof e=="string"){Ve(e)||r(e,"",e);let d=se.get(e);d||r(e);let l=d[0].deref();if(l&&At(l,n))return l;let s=Wr({fingerprint:d[1],cohortSize:d[2]},q(n,!1));return s.status==="matched"?(d[0]=new lt(s.candidate.target),Ot.set(s.candidate.target,e),s.candidate.target):s.status==="ambiguous"?Un(e,s.candidates):le(e,s.candidates)}let i=(d,l,s)=>{let p=()=>d.map(y=>y.fingerprint);return l!==void 0?d[l]?.target??le(`nth=${String(l)}`,p()):d.length>1?Un(s,p()):d[0].target};if("role"in e||"driver"in e){let d=q(n,!1);if("role"in e){let p=e.role.trim().toLowerCase(),y=e.name!==void 0?k(e.name):void 0,g=d.filter(({fingerprint:h})=>h.role===p&&(y===void 0||h.name===y));return g.length||r(e.role,p,y??"",d),i(g,e.nth,e.role)}let l=k(e.driver),s=l?d.filter(({fingerprint:p})=>p.driverId===l):[];return s.length||r(e.driver,"",l,d,l),i(s,e.nth,l)}let o=k(e.text),a=e.exact===!0,f=o.toLowerCase(),u=o?q(n,!0).filter(d=>[d.text,d.fingerprint.name].some(l=>a?l===o:l.toLowerCase().includes(f))):[];u.length||r(e.text,"",o);let c=u.filter(d=>!u.some(l=>l.target!==d.target&&Te(d.target,l.target)));return i(c,void 0,e.text)}var nr=B("script style noscript template head meta link base title param track source wbr br"),Jr=B("article aside main nav section"),tt=B("main navigation banner contentinfo region form toolbar dialog complementary"),rr=B("checkbox switch radio menuitemcheckbox menuitemradio"),Vt=B("textbox searchbox combobox listbox slider spinbutton"),Yr=B("video audio canvas textbox option"),Ht=new P([...rr,...Vt,...B("button link option tab menuitem")]),Jn=Se("main:main form:form dialog:dialog button:button option:option nav:navigation aside:complementary output:status ul:list ol:list menu:list li:listitem summary:button textarea:textbox"),Qr=Se("button:button checkbox:checkbox radio:radio submit:button reset:button image:button range:slider number:spinbutton"),Nt=new Ke,Yn=!1;function or(){Yn||!Z||!_e||(Yn=!0,Z.prototype.getContext=function(e,...t){let n=x(_e,this,[e,...t]);return n&&e!=="2d"&&Nt.add(this),n},vt&&(Z.prototype.transferControlToOffscreen=function(){return Nt.add(this),x(vt,this,[])}))}function Pt(e){if(m(e,v)&&e.assignedSlot)return e.assignedSlot;let t=e.parentNode;return m(t,ne)?t.host:t}function He(e){let t=Pt(e);for(;t&&!m(t,v);)t=Pt(t);return t}function Te(e,t){for(let n=t;n;n=Pt(n))if(n===e||n.parentNode===e)return!0;return!1}function At(e,t){if(!e.isConnected||!Te(t,e))return!1;for(let n=e;n;n=He(n)){if(G(n))return!1;if(n===t)break}return!0}function ue(e,t,n=!1){for(let r=n?e:e?He(e):null;r;r=He(r))if(t(r))return r;return null}var Ft=(e,t)=>ue(e,t)!==null;function G(e,t=!0){if(A(e,ee)||A(e,"hidden")||t&&I(e,"aria-hidden")==="true")return!0;let n=T(e);if(nr.has(n)||m(e,N)&&e.type.toLowerCase()==="hidden"||n==="dialog"&&!A(e,"open"))return!0;let r=ie(e);if(r){if(r.visibility==="hidden"||r.visibility==="collapse")return!0;if(r.display==="none")return n==="audio"&&!A(e,"controls")||n==="option"?m(e,V)&&e.style.display==="none":!0}return!1}function Fe(e){return I(e,"aria-disabled")==="true"?!0:m(e,ve)?e.disabled:"disabled"in e&&typeof e.disabled=="boolean"?e.disabled||Ft(e,t=>T(t)==="fieldset"&&"disabled"in t&&!!t.disabled):!1}function _t(e,t,n,r,i){let o=[];function a(f,u){if(f.nodeType===3){f.nodeValue&&o.push(f.nodeValue);return}if(!m(f,v)||f===r||!u&&t.has(f))return;let c=T(f);if(!u||!n){if(G(f))return}else if(nr.has(c)||A(f,ee))return;if(!u&&i){let d=Ee(f);if(d&&Lt(f,d))return}if(c==="img"){let d=C(f,"alt");d&&o.push(d);return}if(!u){let d=I(f,"aria-label");if(d){o.push(d);return}}for(let d of X(f))a(d,!1)}return a(e,!0),k(o.join(" "))}var Qn=e=>!!(I(e,"aria-label")||I(e,"aria-labelledby")||I(e,"title")),ir=e=>e==="heading"||Ht.has(e)&&!Vt.has(e),Zr=/^[A-Za-z0-9_.:/-]{1,80}$/,eo=/(?:^|\\.)(?:panel|section|region|list|nav|group)$/i,ar="button,a[href],input:not([type=hidden]),select,textarea,[tabindex]",nt=e=>{let t=I(e,"data-driver").slice(0,80);return Zr.test(t)?t:""},sr=e=>(I(e,"data-driver-intent")||I(e,"data-driver-description")).slice(0,140);function Zn(e){let t=T(e);if(t==="video"||t==="audio"||t==="canvas")return t;let n=I(e,"role");if(n){let o=n.split(" ")[0]?.toLowerCase()??"";return o==="none"||o==="presentation"?null:o||null}if(Jn[t])return Jn[t];if(/^h[1-6]$/.test(t))return"heading";let r=nt(e);if(t==="header"||t==="footer")return Ft(e,o=>Jr.has(T(o)))?r?"region":null:t==="header"?"banner":"contentinfo";if(t==="section")return Qn(e)||r?"region":null;if(t==="a"||t==="area")return A(e,"href")?"link":r?"button":null;if(t==="select")return m(e,re)&&(e.multiple||e.size>1)?"listbox":"combobox";if(t==="input"){let o=m(e,N)?e.type.toLowerCase():I(e,"type").toLowerCase()||"text";return o==="hidden"?null:Qr[o]??"textbox"}if(t==="img")return Qn(e)||I(e,"alt")||r?"img":null;let i=C(e,"contenteditable");return i===""||i?.toLowerCase()==="true"?"textbox":A(e,"onclick")?"button":r?eo.test(r)||!sr(e)&&ie(e)?.cursor!=="pointer"&&Qe(e,ar)?"region":"button":null}function Ee(e){let t=Zn(e);if(t)return t;let n=T(e);if(n==="html"||n==="body"||n==="main"||n==="label"||ie(e)?.cursor!=="pointer")return null;let r=He(e);if(r&&ie(r)?.cursor==="pointer"||Qe(e,ar)||Ft(e,o=>{let a=Zn(o);return!!(a&&Ht.has(a))}))return null;let i=k(e.textContent??"");return i.length>0&&i.length<=240?"button":null}function Bt(e,t,n=new P){if(n.has(e))return"";let r=new P(n);r.add(e);let i=(l,s,p)=>k([...l].map(y=>_t(y,r,s,p)).filter(Boolean).join(" ")),o=I(e,"aria-labelledby");if(o){let l=e.getRootNode(),s=[];for(let y of o.split(" ")){let g=m(l,ne)&&l.getElementById(y)||S?.getElementById(y);g&&s.push(g)}let p=i(s,!0);if(p)return p}let a=I(e,"aria-label");if(a)return a;if(m(e,N)){let l=e.type.toLowerCase(),s=k(St(e));if(l==="image")return I(e,"alt")||s||"Submit";if(l==="submit"||l==="reset"||l==="button")return s||(l==="submit"?"Submit":l==="reset"?"Reset":"")}let f=m(e,N)||m(e,Q),u=f||m(e,re)?e.labels:null;if(u?.length){let l=i(u,!1,e);if(l)return l}if(m(e,ve)){let l=k(e.label||e.text);if(l)return l}if(T(e)==="img"){let l=I(e,"alt");if(l)return l}let c=ir(t)&&!((t==="checkbox"||t==="radio")&&m(e,N))?!1:t==="alert"||t==="status"||t==="listitem"?!0:null;if(c!==null){let l=_t(e,r,!1,void 0,c);if(l)return l}return(f?k(e.placeholder):I(e,"aria-placeholder"))||I(e,"title")}function Lt(e,t){return!!nt(e)||tt.has(t)||Ht.has(t)||t==="video"||t==="audio"||t==="canvas"||m(e,V)&&A(e,"tabindex")&&e.tabIndex>=0}var $t=(e,t,n)=>tt.has(e)?t?`${e}:${t}`:e:n;function lr(e){let t;return ue(e,n=>{let r=Ee(n);return r&&tt.has(r)?(t=$t(r,Bt(n,r)),!0):!1}),t}var dr=(e,t,n,r)=>`${e}\\0${t}\\0${n??""}\\0${r??""}`;function cr(e,t,n,r,i){let o=dr(t,n,r,i),a=e.get(o)??0;return e.set(o,a+1),{role:t,name:n,nth:a,...r!==void 0?{landmark:r}:{},...i?{driverId:i}:{}}}function q(e,t){let n=m(e,Re)?e.body??e.documentElement:e;if(!n)return[];let r=new z,i=[];function o(a,f){let u=f;if(m(a,v)){if(G(a))return;let c=Ee(a),d=c??(t?T(a):null);if(d){let l=Bt(a,d);u=$t(d,l,f);let s=t?_t(a,new P,!1):"";(c||s||l)&&i.push({target:a,text:s,fingerprint:cr(r,d,c?l:l||s,f,nt(a)||void 0)})}}for(let c of X(a))o(c,u)}return o(n,m(n,v)?lr(n):void 0),i}function er(e){function t(n){try{let r=Qe(n,e);if(r&&At(r,S))return r}catch{return null}for(let r of X(n))if(m(r,v)&&!G(r)){let i=t(ye(r)??r);if(i)return i}return null}return S?t(S):null}function to(e){let t=e.trim(),n=(o,a,f)=>Mt(t,S,o,a,void 0,f);if(t||le("Empty scope."),Ve(t))return[de(t,S)];if(/^driver:/i.test(t)){let o=k(t.slice(7)),a=o?q(S,!1).filter(({fingerprint:u})=>u.driverId===o||!!u.driverId?.startsWith(`${o}.`)).map(u=>u.target):[],f=a.filter(u=>!a.some(c=>c!==u&&Te(c,u)));return f.length||n("",o,o),f}let r=/^([a-z]+)(?::(.+))?$/i.exec(t),i=r?.[2]!==void 0?k(r[2]):void 0;if(r&&i!=="")try{return[de({role:r[1].toLowerCase(),...i?{name:i}:{}},S)]}catch(o){if(!(o instanceof L&&o.code==="DRIVER_TARGET_NOT_FOUND"))throw o;let a=er(t);if(a)return[a];throw o}return[er(t)??n(t.toLowerCase(),t)]}function no(e,t){let{currentTime:n,duration:r,error:i}=e,o=t==="video"&&m(e,qe)?e:null,a=o?W(o):null;return{kind:t,paused:e.paused,currentTime:Number.isFinite(n)&&n>0?n:0,duration:Number.isFinite(r)&&r>=0?r:null,width:a&&o?Math.max(0,o.videoWidth||Math.round(a.width)):0,height:a&&o?Math.max(0,o.videoHeight||Math.round(a.height)):0,ready:e.readyState>=2,error:i?i.message||`MEDIA_ERR_${i.code}`:null}}var ce=null;function ro(e){let t=Math.max(0,e.width),n=Math.max(0,e.height),r=!!(t&&n);if(r&&!Nt.has(e)&&_e){let i=Math.min(64,t),o=Math.min(64,n);try{if(!ce){let a=x(_e,S.createElement("canvas"),["2d",{willReadFrequently:!0}]);m(a,Sn)&&(ce=a)}ce&&(ce.canvas.width=i,ce.canvas.height=o,ce.drawImage(e,0,0,i,o),r=ce.getImageData(0,0,i,o).data.some((a,f)=>(f&3)===3&&a>0))}catch{ce=null}}return{width:t,height:n,nonBlank:r}}var tr=(e,t)=>{let n=C(e,t);return n==="true"||n==="false"?n==="true":void 0};function oo(e,t,n){if((n==="video"||n==="audio")&&m(t,me)){e.media=no(t,n);return}if(n==="canvas"&&m(t,Z)){e.canvas=ro(t);return}let r=tr(t,"aria-expanded");if(r!==void 0)e.expanded=r;else if(T(t)==="summary"){let a=He(t);a&&T(a)==="details"&&(e.expanded=A(a,"open"))}else n==="combobox"&&(e.expanded=!1);let i=Fe(t),o=!0;if(rr.has(n))e.checked=m(t,N)?t.checked:C(t,"aria-checked")==="true";else if(n==="option"||n==="tab")if(n==="option"&&m(t,ve))e.value=t.value,e.checked=t.selected;else{let a=tr(t,"aria-selected");a!==void 0&&(e.checked=a)}else if(Vt.has(n)){let a=ke(t)??(n==="textbox"||n==="searchbox"?t.textContent??"":C(t,"aria-valuenow")??C(t,"aria-valuetext")??C(t,"value"));if(a!==null&&(e.value=a),n==="slider"||n==="spinbutton"){let f=n==="slider",u=m(t,N)?t.min||(f?"0":""):I(t,"aria-valuemin"),c=m(t,N)?t.max||(f?"100":""):I(t,"aria-valuemax");u!==""&&Number.isFinite(+u)&&(e.min=+u),c!==""&&Number.isFinite(+c)&&(e.max=+c)}}else o=!1;(o||i)&&(e.disabled=i)}var ur=null;function fr(){return ur}function Be(e,t=!1){let n=e?.includeAllText===!0,r=e?.scope!==void 0?to(e.scope):null,i=t?Kn():qn(),o=Ce(t),a=S.body??S.documentElement,f=new z,u=[];function c(p,y,g){let h=[];for(let R of X(p)){if(R.nodeType===3){if(n&&!g){let D=k(R.nodeValue??"");D&&h.push({role:"text",name:D})}continue}m(R,v)&&h.push(...d(R,y))}return h}function d(p,y){if(G(p))return[];if(T(p)==="label"&&!n)return c(p,y,!0);let g=Ee(p);if(!g)return c(p,y,!1);let h=Lt(p,g)&&!tt.has(g);if((g==="list"||g==="listitem"||g==="img")&&!n&&!h)return g==="img"?[]:c(p,y,!0);let R=Bt(p,g),D=nt(p),w=sr(p),O={role:g,name:R};if(D&&(O.driverId=D),w&&(O.intent=w),oo(O,p,g),Lt(p,g)&&u.push([O,p,cr(f,g,R,y,D||void 0)]),!Yr.has(g)&&!m(p,ve)){let M=ir(g)||g==="alert"||g==="status"||g==="listitem",_=c(p,$t(g,R,y),M);_.length>0&&(O.children=_)}return[O]}let l=r?r.flatMap(p=>d(p,lr(p))):a?c(a,void 0,!1):[];for(let[p,y,g]of u)p.ref=Xn(y,g,f.get(dr(g.role,g.name,g.landmark,g.driverId))??1,i);let s={rev:i,url:b.location.href,title:S.title,viewport:{width:Math.max(0,b.innerWidth),height:Math.max(0,b.innerHeight)},diagnostics:o,elements:l};return!t&&r===null&&!n&&(ur=s),s}var pr=50,io=B("script img video audio source link");function zt(e=pr){let t=e>=1?e:pr,n=[];return{push(r){n.length>=t&&n.shift(),n.push(r)},drain(){let r=n;return n=[],r}}}var rt=(e,t=1e3)=>e.length<=t?e:`${e.slice(0,t-1)}\\u2026`;function Ut(e){if(typeof e=="string")return e;if(e instanceof Error)return e.stack??`${e.name}: ${e.message}`;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e);if(typeof t=="string")return t}catch{}return String(e)}function gr(e){if(e.nodeType===3)return e.nodeValue?.trim()??"";if(m(e,v)&&(T(e)==="svg"||G(e)))return"";let t=X(e).map(gr).filter(Boolean).join(`\n`);return t?rt(t.replace(/[ \\t]+/g," ").trim(),2e3):""}function Kt(){if(!S?.documentElement)return null;function e(t){if(m(t,v)){if(A(t,ee)||A(t,"hidden"))return null;let n=T(t);if(n==="vite-error-overlay"||n==="nextjs-portal"||A(t,"data-nextjs-dialog")){let r=gr(t);if(r)return r}}for(let n of X(t)){let r=e(n);if(r)return r}return null}return e(S.documentElement)}var mr=!1,Gt=zt(),yr=zt(),hr=zt(),br=new P,jt=new P,$e=0;function De(){if(mr)return;mr=!0;let e=(r,i)=>{let o=rt(r);if(yr.push(o),i)for(let a of br)a(o)},t=(r,i,o,a)=>{hr.push({method:r,url:i,status:o,statusText:a})},n=()=>{$e>0&&($e-=1)};if(b){if(xt){let i=xt;console.error=function(...o){try{let a=rt(o.map(Ut).join(" ").trim());a&&Gt.push(a)}catch{}x(i,this,o)}}K(b,"error",i=>{let o=i.target;if(m(o,v)){let a=T(o);if(io.has(a)){let f=(m(o,me)?o.currentSrc:"")||C(o,"src")||C(o,"href")||"";e(`Resource error: <${a}${f?` src="${f}"`:""}>`,!1)}return}if(m(i,mn)){let a=i.error;e(a instanceof Error?Ut(a):i.message||"Page error",!0)}},!0),K(b,"unhandledrejection",i=>{let o=m(i,gn)?i.reason:F(i,"reason");e(`Unhandled rejection: ${Ut(o)}`,!0)});let r=(i,o)=>{if(jt.size===0)return!1;let a=o!==void 0?String(o):"",f=rt(a?`[dialog:${i}] ${a}`:`[dialog:${i}]`);Gt.push(f);for(let u of jt)u(i,f);return!0};for(let[i,o,a]of[["alert",_n,void 0],["confirm",Ln,!1],["prompt",Vn,null]])o&&st(b,i,(...f)=>r(i,f[0])?a:x(o,b,f));if(wt){let i=wt;b.fetch=function(...o){let[a,f]=o,u=m(a,ht)?a.url:String(a),c=(f?.method||(m(a,ht)?a.method:"GET")).toUpperCase();return $e+=1,x(i,this,o).then(d=>(n(),d.status>=400&&t(c,d.url||u,d.status,d.statusText),d),d=>{throw n(),d instanceof Error&&d.name==="AbortError"||t(c,u,0,d instanceof Error?d.message:String(d)),d})}}if(xe&&kt&&Tt){let i=kt,o=Tt,a=new ze;xe.prototype.open=function(f,u,...c){a.set(this,[String(f).toUpperCase(),String(u)]),x(i,this,[f,u,...c])},xe.prototype.send=function(...f){let u=!1;$e+=1,K(this,"abort",()=>{u=!0},{once:!0}),K(this,"loadend",()=>{n();let c=a.get(this),d=this.status;!u&&c&&(!d||d>=400)&&t(c[0],this.responseURL||c[1],d,this.statusText||(d?"":"Network Error"))},{once:!0}),x(o,this,f)}}}}var Oe=()=>$e,Er=(e,t)=>(De(),e.add(t),()=>{e.delete(t)}),Sr=e=>Er(br,e),Rr=e=>Er(jt,e);function Ce(e=!1){return e||De(),{compileOverlay:e?null:Kt(),consoleErrors:e?[]:Gt.drain(),pageErrors:e?[]:yr.drain(),networkFailures:e?[]:hr.drain()}}function Ue(e){if(oe)try{let t=new oe(e);return`${t.origin!=="null"?t.origin:t.protocol}${t.pathname}`}catch{}return e.split(/[?#]/)[0]}var vr=(e,t)=>{if(e===t)return!0;if(!e||!t)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>F(e,r)===F(t,r))},ao="role name ref driverId intent value checked disabled expanded min max".split(" ");function so(e,t){return ao.every(n=>F(e,n)===F(t,n))&&vr(e.media,t.media)&&vr(e.canvas,t.canvas)}function lo(e){if(!e.children)return e;let{children:t,...n}=e;return n}function xr(e,t){let n=e===null||Ue(e.url)!==Ue(t.url),r=new z,i=[],o=new z,a=new P,f=[],u=[];function c(d,l,s,p){let y=new z;for(let g of d){let h=g.ref;if(g.ref!==void 0)p?(r.set(g.ref,g),i.push(g.ref)):a.add(g.ref);else{let R=y.get(g.role)??0;y.set(g.role,R+1),h=`${l}/${g.role}[${R}]`,p&&o.set(h,g)}if(p)g.children&&c(g.children,h,!1,!0);else{let R=g.ref!==void 0?r.get(g.ref):o.get(h);R?(so(R,g)||u.push(lo(g)),g.children&&c(g.children,h,s,!1)):(s||f.push(g),g.children&&c(g.children,h,!0,!1))}}}return n||(c(e.elements,"root",!1,!0),c(t.elements,"root",!1,!1)),{fromRev:e?.rev??0,toRev:t.rev,fullReset:n,added:f,removed:i.filter(d=>!a.has(d)),changed:u,...n?{elements:t.elements}:{}}}var Cr={bubbles:!0,cancelable:!0,composed:!0},co=B("button link"),uo=B("button checkbox switch"),fo=Se("space:Space esc:Escape escape:Escape enter:Enter tab:Tab"),po=Se("control:Control ctrl:Control shift:Shift alt:Alt option:Alt meta:Meta command:Meta cmd:Meta"),Ne={};function fe(e,t,n){return e[0]?Promise.reject(Ne):new Promise((r,i)=>{let o=!1,a=c=>{o||(o=!0,Je(u),e[1]===f&&(e[1]=null),c?i(Ne):r())},f=()=>a(!0),u=Xe(()=>a(!1),t);n&&Rn(()=>a(!1)),e[1]=f})}var Me=(e,t,n,r,i=0,o=0,a=1,f=!1)=>{let u=f?hn:yn,c={...Cr,clientX:n,clientY:r,button:i,buttons:o};return!u||ge(e,new u(t,f?{...c,pointerId:1,isPrimary:!0}:{...c,view:b??null,detail:a}))},Ae=(e,t,n,r,i,o=0,a=0,f=1)=>(Me(e,t,r,i,t==="pointermove"?-1:o,a,1,!0),Me(e,n,r,i,o,a,f));function Ie(e,t,n,r,i){return!ut||ge(e,new ut(t,{...Cr,key:n,code:r,...i}))}function qt(e,t){if(!S)return null;let n=Et(S,e,t);for(;n;){let r=ye(n),i=r?Et(r,e,t):null;if(!i||i===n)break;n=i}return n}function wr(){if(!S)return null;let e=S.activeElement;for(;e;){let t=ye(e)?.activeElement;if(!t||t===e)break;e=t}return e}function Dr(e){let t=ue(e,r=>m(r,Pe),!0),n=(m(e,N)||m(e,Q)?e.form:null)??(m(t,Pe)?t:null);n&&On(n)}function Or(e,t){if(!m(e,N)&&!m(e,Q))return!1;let n=ke(e),r=F(e,"_valueTracker");if(typeof r=="object"&&r!==null){let i=F(r,"setValue");if(typeof i=="function")try{x(i,r,[n])}catch{}}return m(e,N)?Mn(e,t):An(e,t),!0}function Jt(e,t,n="insertText"){let r={bubbles:!0,composed:!0};ft?ge(e,new ft("input",{...r,...t!==void 0?{data:t}:{},inputType:n})):Y&&ge(e,new Y("input",r)),Y&&ge(e,new Y("change",{bubbles:!0}))}async function Wt(e,t,n,r=!1){let i=null,o="not actionable",a=null,f=0,u=!1;for(;;){if(n[0])throw Ne;let c=null;try{c=de(e)}catch(d){if(i=d,d instanceof L&&d.code==="DRIVER_TARGET_AMBIGUOUS"){if(u)throw d;u=!0}}if(c){u=!1;let d=T(c),l=d==="audio"||d==="option";if(!c.isConnected||G(c))o="hidden",f=0;else{let s=W(c);if(!(r&&d==="audio")&&(s.width<=0||s.height<=0))o="zero size",f=0;else{let p=b.innerWidth,y=b.innerHeight;if(!l&&(s.bottom<=0||s.top>=y||s.right<=0||s.left>=p)&&(Cn(c),s=W(c)),a&&Math.hypot(a.left-s.left,a.top-s.top,a.width-s.width,a.height-s.height)<.5?f+=1:(a=s,f=0),f>=2)if(Fe(c))o="disabled";else{if(l)return[c,c,s,s.left+s.width/2,s.top+s.height/2];{let g=Math.max(0,s.left),h=Math.max(0,s.top),R=Math.min(p,s.right),D=Math.min(y,s.bottom);if(R>g&&D>h){let w=(g+R)/2,O=(h+D)/2,M=qt(w,O);if(M&&(M===c||Te(c,M)||ue(M,_=>m(_,bn)&&_.control===c,!0)))return[c,M,s,w,O];o=`obscured at (${Math.round(w)}, ${Math.round(O)})`}else o="outside viewport"}}}}}if(H()>=t){if(i instanceof L)throw i;U("DRIVER_TIMEOUT",`Target ${o}.`)}await fe(n,16,!0)}}var Ir=e=>!!e.hash&&e.href.split("#")[0]===b.location.href.split("#")[0];function mo(e,t){if(!t)return!1;let n=ue(e,o=>m(o,mt)&&A(o,"href"),!0);if(!n||A(n,"download"))return!1;let r=(C(n,"target")??"").trim().toLowerCase();if(r&&r!=="_self")return!1;let i=C(n,"href")??"";if(!oe)return!!i&&!i.startsWith("#");try{let o=new oe(i,b.location.href);return(o.protocol==="http:"||o.protocol==="https:")&&!Ir(o)}catch{return!1}}function Xt(e,t,n,r,i){let o=i.button==="middle"?1:i.button==="right"?2:0,a=o===1?4:o||1,f=i.clickCount??1,u=!1;Ae(t,"pointerover","mouseover",n,r);for(let c=1;c<=f;c+=1)Ae(t,"pointerdown","mousedown",n,r,o,a,c)&&m(e,V)&&he(e),Ae(t,"pointerup","mouseup",n,r,o,0,c),o===2?Me(t,"contextmenu",n,r,2,0,c):o===0&&(mo(t,Me(t,"click",n,r,0,0,c))&&(u=!0),c===2&&Me(t,"dblclick",n,r,0,0,2));return u}function go(e,t){m(e,V)&&he(e);let n=C(e,"contenteditable");Or(e,t.value)||(n===""||n?.toLowerCase()==="true"||m(e,V)&&e.isContentEditable?e.textContent=t.value:U("DRIVER_PROTOCOL","Not fillable.")),Jt(e,t.value,"insertText"),t.submit===!0&&(Ie(e,"keydown","Enter","Enter")&&Dr(e),Ie(e,"keyup","Enter","Enter"))}function yo(e,t){if(m(e,me)){let r=Number(t.value);if((!Number.isFinite(r)||r<0)&&U("DRIVER_PROTOCOL","Invalid time."),Pn(e,r),Y)for(let i of"input timeupdate seeked".split(" "))ge(e,new Y(i,i==="input"?{bubbles:!0,composed:!0}:void 0));return}let n=String(t.value);m(e,V)&&he(e),Or(e,n)||ae(e,"aria-valuenow",n),Jt(e,n,"insertReplacementText")}function kr(e,t,n){return e||le(`Option "${n}" not found.`),t&&U("DRIVER_PROTOCOL",`Option "${n}" disabled.`),e}async function ho(e,t,n){let[r,i,,o,a]=e,f=typeof t.value=="string"?[t.value]:[...t.value];if(m(r,re)){he(r);let u=[...r.options],c=f.map(d=>{let l=k(d),s=u.find(p=>p.value===d||k(p.label||p.text)===l);return kr(s,!!s?.disabled,d)});if(r.multiple){let d=new P(c);for(let l of u)Rt(l,d.has(l))}else c[0]&&(Nn(r,c[0].value),Rt(c[0],!0));Jt(r);return}Ee(r)==="combobox"&&C(r,"aria-expanded")!=="true"&&(Xt(r,i,o,a,{}),await fe(n,16,!0));for(let u of f){let c=k(u),d=q(S,!0).find(p=>p.fingerprint.role==="option"&&(p.fingerprint.name===c||p.text===c||C(p.target,"data-value")===u||C(p.target,"value")===u)),l=kr(d,!!(d&&Fe(d.target)),u),s=W(l.target);Xt(l.target,l.target,s.left+s.width/2,s.top+s.height/2,{}),await Promise.resolve()}}function bo(e,t){let n=t??wr()??S?.body??S?.documentElement;if(!n)return;let r=e.key==="+"?["+"]:e.key.split("+").filter(Boolean),i={},o=[];for(let s=0;s<r.length-1;s+=1){let p=po[(r[s]??"").trim().toLowerCase()];p&&(i[`${p==="Control"?"ctrl":p.toLowerCase()}Key`]=!0,o.push(p))}let a=(r.at(-1)??e.key).trim(),f=e.key===" "?"Space":fo[a.toLowerCase()],u=f==="Space"?" ":f??a,c=f??a;!f&&a.length===1&&(/^[a-z]$/i.test(a)?(u=i.shiftKey?a.toUpperCase():a,c=`Key${a.toUpperCase()}`):/^[0-9]$/.test(a)&&(c=`Digit${a}`));for(let s of o)Ie(n,"keydown",s,`${s}Left`,i);if(Ie(n,"keydown",u,c,i)&&!i.ctrlKey&&!i.altKey&&!i.metaKey&&m(n,v)){let s=Ee(n)??"";if(u==="Tab"){let p=q(S,!1).map(y=>y.target).filter(y=>m(y,V)&&!Fe(y)&&y.tabIndex>=0);if(p.length>0){let y=m(n,V)?p.indexOf(n):-1,g=p.at(y<0?i.shiftKey?-1:0:(y+(i.shiftKey?-1:1))%p.length);g&&he(g)}}else if(u==="Enter"||u===" ")m(n,En)||T(n)==="summary"||(u==="Enter"?m(n,mt)&&A(n,"href")||co.has(s):m(n,N)&&(n.type==="checkbox"||n.type==="radio")||uo.has(s))?m(n,V)&&Dn(n):u==="Enter"&&m(n,N)&&Dr(n);else if(u==="Escape"){let p=ue(n,y=>m(y,gt)&&y.open,!0);m(p,gt)&&p.close()}}let l=wr()??n;Ie(l,"keyup",u,c,i);for(let s of o.reverse())Ie(l,"keyup",s,`${s}Left`)}async function Eo(e,t,n,r,i){let[,o,a,f,u]=await Wt(e.from,r,i),[c,d]="target"in e.to?(await Wt(e.to.target,r,i)).slice(3):"deltaX"in e.to?[f+e.to.deltaX,u+e.to.deltaY]:[e.to.clientX,e.to.clientY],l=Math.max(1,e.steps??5);Dt(t,n,"drag",a,f,u),Me(o,"pointerover",f,u,0,0,1,!0),Ae(o,"pointerdown","mousedown",f,u,0,1);for(let s=1;s<=l;s+=1){if(i[0])throw Ne;let p=f+(c-f)*s/l,y=u+(d-u)*s/l;Fn(p,y),Ae(qt(p,y)??o,"pointermove","mousemove",p,y,0,1),await Promise.resolve()}Ae(qt(c,d)??o,"pointerup","mouseup",c,d)}function So(e){let t=b.location;if("url"in e){let n=oe?new oe(e.url,t.href):null,r=n!==null&&Ir(n);return t.assign(n?n.href:e.url),r?"none":"unload"}return e.action==="reload"?(t.reload(),"unload"):(e.action==="back"?b.history.back():b.history.forward(),"history")}function Ro(e,t){if(typeof e=="string"&&Ve(e)&&Wn(e)?.[0].deref()?.isConnected&&(t==="detached"||t==="attached"))return t==="attached";try{let n=de(e);if(t==="detached")return!1;if(t==="attached")return n.isConnected;let r=W(n),i=n.isConnected&&!G(n)&&(T(n)==="audio"||r.width>0&&r.height>0);return t==="visible"?i:!i}catch(n){return(t==="detached"||t==="hidden")&&n instanceof L&&n.code==="DRIVER_TARGET_NOT_FOUND"}}async function vo(e,t,n,r){let i=e.timeoutMs!==void 0?Math.min(n?t:1/0,H()+e.timeoutMs):t,o=e.state??"visible",a=e.text!==void 0?k(e.text).toLowerCase():void 0,f=H(),u=null;e.idleMs!==void 0&&ct&&S?.documentElement&&(u=new ct(c=>{c.some(d=>{let l=d.target,s=m(l,v)?l:m(l,ne)?l.host:l.parentElement;return!ue(s,p=>A(p,ee),!0)})&&(f=H())}),u.observe(S.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}));try{for(;;){if(r[0])throw Ne;let c=e.target===void 0||Ro(e.target,o),d=!a||q(S,!0).some(p=>[p.text,p.fingerprint.name].some(y=>y.toLowerCase().includes(a))),l=a===void 0||(o==="hidden"||o==="detached"?!d:d);Oe()>0&&(f=H());let s=e.idleMs===void 0||!Oe()&&H()-f>=e.idleMs;if(c&&l&&s)return;H()>=i&&U("DRIVER_TIMEOUT","waitFor timeout."),await fe(r,Math.min(20,Math.max(4,i-H())),!1)}}finally{u?.disconnect()}}var Tr=()=>S?q(S,!1).filter(e=>e.fingerprint.role==="dialog"||e.fingerprint.role==="alertdialog").map(e=>e.target):[];async function xo(e,t){if(await fe(t,0,!1),await fe(t,16,!0),Oe()>0){let n=Math.min(e,H()+250);for(;Oe()>0&&H()<n;)await fe(t,12,!1);Oe()||await fe(t,16,!0)}}function wo(e){if(e instanceof L){let t=e.candidates?.length?` (candidates: ${e.candidates.slice(0,5).map(n=>`${n.role}${n.name?` "${n.name}"`:""}`).join(", ")})`:"";return`${e.code}: ${e.message}${t}`}return e instanceof Error?e.message:String(e)}async function Mr(e,t){let n=$n(),r=e.timeoutMs!==void 0,i=H()+(e.timeoutMs??5e3),o=fr()??Be(void 0,!0);t?.(o.rev,0);let a=e.steps.length,f=0,u,c,d=null,l=!1,s=Sr(g=>{d??=g}),p=Rr(()=>{l=!0});try{for(let g=0;g<a;g+=1){let h=e.steps[g];if(!h)break;if(n[0]){u="user_takeover";break}d=null,l=!1;let R=new P(Tr()),D=b.location,w=D.href,O=Ue(w),M="none";try{let _=h.kind==="press"?`press ${h.key}`:h.kind,j="target"in h&&h.target!==void 0&&h.kind!=="waitFor"?await Wt(h.target,i,n,h.kind==="setValue"):null,J=j?.[0]??null;switch(h.kind!=="drag"&&Dt(g,a,_,j?.[2],j?.[3],j?.[4]),t?.(o.rev,g+1),h.kind){case"click":Xt(J,j[1],j[3],j[4],h)&&(M="unload");break;case"fill":go(J,h);break;case"setValue":yo(J,h);break;case"select":await ho(j,h,n);break;case"press":J&&m(J,V)&&he(J),bo(h,J);break;case"drag":await Eo(h,g,a,i,n);break;case"navigate":M=So(h);break;case"waitFor":t?.(o.rev,g),await vo(h,i,r,n);break;default:U("DRIVER_PROTOCOL","Unsupported step.")}if(f=g+1,await xo(i,n),M!=="none"&&D.href===w){let ot=M==="history"?Math.min(i,H()+2e3):i;for(;D.href===w&&H()<ot;)await fe(n,20,!1)}}catch(_){_===Ne||n[0]?u="user_takeover":(u="step_error",c=wo(_));break}if(n[0]?u="user_takeover":d!==null?(c=d,u="step_error"):Kt()!==null?u="compile_error":l||g<a-1&&Tr().some(_=>!R.has(_))?u="dialog_opened":g<a-1&&Ue(D.href)!==O&&(u="navigation"),u)break}}finally{s(),p(),n[2](),Bn()}let y=Be();return{completedSteps:f,totalSteps:a,...u!==void 0?{interruptedReason:u}:{},...c!==void 0?{error:c}:{},rev:y.rev,url:y.url,title:y.title,diff:xr(o,y),diagnostics:y.diagnostics}}function Ar(e,t){let n=ie(e);n&&ae(t,"style",`${C(e,"style")??""};color:${n.color};fill:${n.fill};stroke:${n.stroke};stroke-width:${n.strokeWidth};opacity:${n.opacity}`);for(let r=0;r<e.children.length;r++)Ar(e.children[r],t.children[r])}async function Yt(e){let t=e,n=t.target?W(de(t.target)):new DOMRect(0,0,innerWidth,innerHeight),r=S.createElement("canvas"),i=r.width=Math.round(n.width)||1,o=r.height=Math.round(n.height)||1,a=r.getContext("2d");a.translate(-n.x,-n.y),a.fillStyle="#fff",a.fillRect(n.x,n.y,i,o);let f=S.documentElement,u=async d=>{let l=!G(d,!1)&&ie(d);if(!l||!+l.opacity)return;let s=d===f||d===S.body?n:W(d),p=parseInt(l.borderWidth),y=T(d);if(a.fillStyle=l.backgroundColor,a.fillRect(s.x,s.y,s.width,s.height),p&&(a.strokeStyle=l.borderColor,a.lineWidth=p,a.strokeRect(s.x,s.y,s.width,s.height)),m(d,Z)||m(d,qe)||m(d,We)||y==="svg"){try{let w=d;if(y==="svg"&&We&&yt){let O=In(d,!0);Ar(d,O);let M=new We;M.src="data:image/svg+xml,"+encodeURIComponent(new yt().serializeToString(O)),await M.decode(),w=M}a.drawImage(w,s.x,s.y,s.width,s.height)}catch{}return}let g=ke(d),h=m(d,Q)||l.whiteSpace.startsWith("pre"),R=g??"",D=g===null?X(d):[];for(let w of D)w.nodeType===3&&(R+=(h?"":" ")+w.nodeValue);if(h||(R=k(R)),R.trim()&&s.width>0&&s.height>0){a.save(),a.beginPath(),a.rect(s.x,s.y,s.width,s.height),a.clip(),a.font=l.font,a.fillStyle=l.color;let w=(pe,te)=>parseFloat(pe)||te,O=w(l.fontSize,14),M=w(l.lineHeight,O*1.3),_=w(l.paddingLeft,6),j=s.width-2*p-_-w(l.paddingRight,6),J=j>8&&l.whiteSpace!=="pre"&&l.whiteSpace!=="nowrap",ot=s.x+p+_-d.scrollLeft,Ge=s.y+p+w(l.paddingTop,4)+O-d.scrollTop,nn=pe=>{Ge+M>s.y&&Ge-O<s.y+s.height&&a.fillText(pe,ot,Ge),Ge+=M};for(let pe of h?R.split(`\n`):[R]){let te="";for(let it of J&&pe?pe.split(/(\\s+)/):[pe])te&&a.measureText(te+it).width>j?(nn(te.trimEnd()),te=it.trimStart()):te+=it;nn(te)}a.restore()}for(let w of D)m(w,v)&&await u(w)};f&&await u(f);let c=await new Promise(d=>r.toBlob(d,"image/"+(t.format==="png"?"png":"webp"),t.quality??.85));return{mimeType:c.type,bytes:await c.bytes(),width:i,height:o,modeUsed:"silent"}}var ko=Object.getPrototypeOf(async function(){}).constructor;function To(e){let t;for(let n of[`return (\n${e}\n);`,e])try{return ko(n)}catch(r){t??=r}throw t}function Nr(e,t=new Ke,n=0){if(e==null)return null;if(typeof e=="boolean"||typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="bigint")return`${e}n`;if(typeof e=="function")return`[Function: ${e.name||"anon"}]`;if(typeof e!="object")return String(e);if(m(e,pt)){let r=k(e.textContent??"").slice(0,120),i=m(e,v)&&C(e,"id"),o=m(e,v)&&C(e,"class");return{...m(e,v)?{tag:T(e)}:{nodeName:e.nodeName},...i?{id:i}:{},...o?{className:o}:{},...r?{text:r}:{}}}if(e instanceof Error)return{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{}};if(e instanceof Date)return Number.isFinite(e.getTime())?e.toISOString():null;if(e instanceof RegExp)return String(e);if(t.has(e))return"[Circular]";if(n>=12)return"[MaxDepth]";t.add(e);try{let r=o=>Nr(o,t,n+1);if(Array.isArray(e)||m(e,P))return[...e].map(r);if(m(e,z))return[...e].map(([o,a])=>[r(o),r(a)]);let i={};for(let o of Object.keys(e))try{i[o]=r(F(e,o))}catch(a){i[o]=`[GetterError: ${String(a)}]`}return i}finally{t.delete(e)}}async function Pr(e){De();let t=e.timeoutMs??5e3,n=To(e.expression),r;try{let i=await Promise.race([Promise.resolve().then(()=>x(n,b??globalThis,[])),new Promise((o,a)=>{r=Xe(()=>a(new L("DRIVER_TIMEOUT","Eval timeout.")),t)})]);return{value:Nr(i),diagnostics:Ce()}}finally{r!==void 0&&Je(r)}}var _r=Symbol.for("@inbrowser/driver:preload-installed:v1"),Zt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),en=(e,t=0)=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=t,tn=e=>Zt(e)&&e.channel===je&&e.protocolVersion===1&&typeof e.kind=="string"?e.kind:"",Lr=(e,t)=>e===void 0||typeof e===t;function Vr(e){if(tn(e)!=="hello")return!1;let t=e;return typeof t.allowEval=="boolean"&&Lr(t.sessionId,"string")&&Lr(t.rebindOnlyIfUnbound,"boolean")&&(t.minRev===void 0||en(t.minRev))}function Co(){if(!b||typeof MessagePort>"u"||un(b,_r))return;fn(b,_r,{value:!0}),De(),or();let e=null,t=!1,n,r=null,i=null,o=(l,s)=>{xn(l,{channel:je,protocolVersion:1,...s})},a=(l,s)=>{o(l,{kind:"hello_ack",capabilities:{protocolVersion:1,allowEval:s,captureModes:["silent"],trustedInput:!1}})};async function f(l,s,p,y){try{let g=Zt(y)?y:null,h;if(p==="observe"&&(y===void 0||g))h=Be(y);else if(p==="act"&&g&&en(g.rev)&&Array.isArray(g.steps)){let R=g,D=[s,R.rev,0,R.steps.length];i=D;try{h=await Mr(R,(w,O)=>{D[1]=w,D[2]=O})}finally{i===D&&(i=null)}}else p==="capture"&&typeof g?.mode=="string"?h=await Yt(g):p==="eval"&&typeof g?.expression=="string"?(t||U("DRIVER_EVAL_DISABLED","allowEval is false."),h=await Pr(g)):U("DRIVER_PROTOCOL","Bad RPC.");e===l&&o(l,{kind:"rpc_response",id:s,ok:!0,result:h})}catch(g){if(e===l){let h=g instanceof L?g:null,R={code:h?h.code:"DRIVER_PROTOCOL",message:h?h.message:g instanceof Error?g.message:String(g),...h?.candidates?{candidates:h.candidates}:{}};o(l,{kind:"rpc_response",id:s,ok:!1,error:R})}}}let u=l=>{let s=e;if(s)return e=null,r&&Ye(s,"message",r),r=null,l&&bt(s),s},c=(l,s)=>{s.minRev!==void 0&&It(s.minRev),t=s.allowEval,n=s.sessionId,a(l,s.allowEval)};function d(l,s){s?.minRev!==void 0&&It(s.minRev),u(!0),e=l,t=!1,n=void 0,r=p=>{if(!m(p,dt))return;let y=p.data;Vr(y)?c(l,y):Zt(y)&&y.channel===je&&en(y.id,1)&&f(l,y.id,tn(y)==="rpc_request"?y.method:"",y.params)},K(l,"message",r),wn(l),s&&c(l,s)}K(b,"pagehide",()=>{let l=u(!1);if(l&&i){let[s,p,y,g]=i;i=null,o(l,{kind:"navigating",id:s,fromRev:p,completedSteps:y,totalSteps:g,diagnostics:Ce()})}}),K(b,"message",l=>{if(!m(l,dt))return;let s=l.ports[0];if(!s)return;let p=l.data;if(Vr(p)){if(p.rebindOnlyIfUnbound===!0&&e!==null&&p.sessionId!==void 0&&n===p.sessionId){bt(s);return}d(s,p)}else tn(p)==="bind_port"&&d(s)})}Co();})();\n';
|
|
8
|
+
|
|
9
|
+
// src/preload/intrinsics.ts
|
|
10
|
+
var reflectApply = Reflect.apply;
|
|
11
|
+
var reflectGet = Reflect.get;
|
|
12
|
+
var reflectSet = Reflect.set;
|
|
13
|
+
var getOwnDescriptor = Object.getOwnPropertyDescriptor;
|
|
14
|
+
var HostMap = Map;
|
|
15
|
+
var HostSet = Set;
|
|
16
|
+
var g = globalThis;
|
|
17
|
+
var win = g.window;
|
|
18
|
+
var doc = g.document;
|
|
19
|
+
var HostMessageEvent = g.MessageEvent;
|
|
20
|
+
var HostErrorEvent = g.ErrorEvent;
|
|
21
|
+
var HostPromiseRejectionEvent = g.PromiseRejectionEvent;
|
|
22
|
+
var HostMutationObserver = g.MutationObserver;
|
|
23
|
+
var HostEvent = g.Event;
|
|
24
|
+
var HostMouseEvent = g.MouseEvent;
|
|
25
|
+
var HostPointerEvent = g.PointerEvent;
|
|
26
|
+
var HostKeyboardEvent = g.KeyboardEvent;
|
|
27
|
+
var HostInputEvent = g.InputEvent;
|
|
28
|
+
var NodeCtor = g.Node;
|
|
29
|
+
var El = g.Element;
|
|
30
|
+
var HtmlEl = g.HTMLElement;
|
|
31
|
+
var ShadowEl = g.ShadowRoot;
|
|
32
|
+
var DocEl = g.Document;
|
|
33
|
+
var SlotEl = g.HTMLSlotElement;
|
|
34
|
+
var InputEl = g.HTMLInputElement;
|
|
35
|
+
var TextAreaEl = g.HTMLTextAreaElement;
|
|
36
|
+
var SelectEl = g.HTMLSelectElement;
|
|
37
|
+
var OptionEl = g.HTMLOptionElement;
|
|
38
|
+
var FormEl = g.HTMLFormElement;
|
|
39
|
+
var LabelEl = g.HTMLLabelElement;
|
|
40
|
+
var ButtonEl = g.HTMLButtonElement;
|
|
41
|
+
var AnchorEl = g.HTMLAnchorElement;
|
|
42
|
+
var DialogEl = g.HTMLDialogElement;
|
|
43
|
+
var MediaEl = g.HTMLMediaElement;
|
|
44
|
+
var VideoEl = g.HTMLVideoElement;
|
|
45
|
+
var CanvasEl = g.HTMLCanvasElement;
|
|
46
|
+
var Ctx2dEl = g.CanvasRenderingContext2D;
|
|
47
|
+
var HostImage = g.Image;
|
|
48
|
+
var HostXMLSerializer = g.XMLSerializer;
|
|
49
|
+
var UrlCtor = g.URL;
|
|
50
|
+
var ReqCtor = g.Request;
|
|
51
|
+
var XhrCtor = g.XMLHttpRequest;
|
|
52
|
+
// @__NO_SIDE_EFFECTS__
|
|
53
|
+
function protoProp(ctor, prop) {
|
|
54
|
+
const d = ctor ? getOwnDescriptor(ctor.prototype, prop) : void 0;
|
|
55
|
+
return [
|
|
56
|
+
(s) => d?.get ? reflectApply(d.get, s, []) : reflectGet(s, prop),
|
|
57
|
+
(s, v) => {
|
|
58
|
+
if (d?.set) reflectApply(d.set, s, [v]);
|
|
59
|
+
else reflectSet(s, prop, v);
|
|
60
|
+
}
|
|
61
|
+
];
|
|
62
|
+
}
|
|
63
|
+
// @__NO_SIDE_EFFECTS__
|
|
64
|
+
function protoMethod(ctor, key) {
|
|
65
|
+
const proto = ctor?.prototype;
|
|
66
|
+
const fn = proto !== void 0 ? proto[key] : void 0;
|
|
67
|
+
return (self, ...args) => reflectApply(fn, self, args);
|
|
68
|
+
}
|
|
69
|
+
var winStyleRaw = win?.getComputedStyle;
|
|
70
|
+
var rawSetTimeout = win?.setTimeout ?? setTimeout;
|
|
71
|
+
var rawClearTimeout = win?.clearTimeout ?? clearTimeout;
|
|
72
|
+
var rawRaf = win?.requestAnimationFrame;
|
|
73
|
+
var rawPerf = g.performance;
|
|
74
|
+
var rawPerfNow = rawPerf?.now;
|
|
75
|
+
var onEvent = /* @__PURE__ */ protoMethod(g.EventTarget, "addEventListener");
|
|
76
|
+
var offEvent = /* @__PURE__ */ protoMethod(g.EventTarget, "removeEventListener");
|
|
77
|
+
var targetDispatchEvent = /* @__PURE__ */ protoMethod(
|
|
78
|
+
g.EventTarget,
|
|
79
|
+
"dispatchEvent"
|
|
80
|
+
);
|
|
81
|
+
var portPostMessage = /* @__PURE__ */ protoMethod(
|
|
82
|
+
g.MessagePort,
|
|
83
|
+
"postMessage"
|
|
84
|
+
);
|
|
85
|
+
var portStart = /* @__PURE__ */ protoMethod(g.MessagePort, "start");
|
|
86
|
+
var portClose = /* @__PURE__ */ protoMethod(g.MessagePort, "close");
|
|
87
|
+
var elProto = El?.prototype;
|
|
88
|
+
var elScrollIntoView = elProto?.scrollIntoView;
|
|
89
|
+
var elAttachShadow = elProto?.attachShadow;
|
|
90
|
+
var htmlFocus = HtmlEl?.prototype.focus;
|
|
91
|
+
var formReqSubmit = FormEl?.prototype.requestSubmit;
|
|
92
|
+
var formSubmit = FormEl?.prototype.submit;
|
|
93
|
+
var getOpenShadowRoot = (/* @__PURE__ */ protoProp(El, "shadowRoot"))[0];
|
|
94
|
+
var elFromPt = [DocEl, ShadowEl].map((c) => c?.prototype.elementFromPoint);
|
|
95
|
+
var qSels = [El, DocEl, ShadowEl].map((c) => c?.prototype.querySelector);
|
|
96
|
+
var [getInputValue, setInputValue] = /* @__PURE__ */ protoProp(InputEl, "value");
|
|
97
|
+
var [getTextAreaValue, setTextAreaValue] = /* @__PURE__ */ protoProp(TextAreaEl, "value");
|
|
98
|
+
var [getSelectValue, setSelectValue] = /* @__PURE__ */ protoProp(SelectEl, "value");
|
|
99
|
+
var setOptionSelected = (/* @__PURE__ */ protoProp(OptionEl, "selected"))[1];
|
|
100
|
+
var setMediaCurrentTime = (/* @__PURE__ */ protoProp(MediaEl, "currentTime"))[1];
|
|
101
|
+
var origCanvasGetContext = CanvasEl?.prototype.getContext;
|
|
102
|
+
var origCanvasTransferOffscreen = CanvasEl?.prototype.transferControlToOffscreen;
|
|
103
|
+
var origConsoleError = g.console?.error;
|
|
104
|
+
var origFetch = win?.fetch;
|
|
105
|
+
var origXhrOpen = XhrCtor?.prototype.open;
|
|
106
|
+
var origXhrSend = XhrCtor?.prototype.send;
|
|
107
|
+
var origAlert = win?.alert;
|
|
108
|
+
var origConfirm = win?.confirm;
|
|
109
|
+
var origPrompt = win?.prompt;
|
|
110
|
+
|
|
111
|
+
// src/preload/diff.ts
|
|
112
|
+
function originAndPathname(rawUrl) {
|
|
113
|
+
if (UrlCtor) {
|
|
114
|
+
try {
|
|
115
|
+
const p = new UrlCtor(rawUrl);
|
|
116
|
+
return `${p.origin !== "null" ? p.origin : p.protocol}${p.pathname}`;
|
|
117
|
+
} catch {
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return rawUrl.split(/[?#]/)[0];
|
|
121
|
+
}
|
|
122
|
+
var sameFlat = (a, b) => {
|
|
123
|
+
if (a === b) return true;
|
|
124
|
+
if (!a || !b) return false;
|
|
125
|
+
const ka = Object.keys(a);
|
|
126
|
+
return ka.length === Object.keys(b).length && ka.every((k) => reflectGet(a, k) === reflectGet(b, k));
|
|
127
|
+
};
|
|
128
|
+
var NODE_SCALAR_KEYS = "role name ref driverId intent value checked disabled expanded min max".split(" ");
|
|
129
|
+
function sameNodeShallow(a, b) {
|
|
130
|
+
return NODE_SCALAR_KEYS.every((k) => reflectGet(a, k) === reflectGet(b, k)) && sameFlat(a.media, b.media) && sameFlat(a.canvas, b.canvas);
|
|
131
|
+
}
|
|
132
|
+
function shallowCopy(node) {
|
|
133
|
+
if (!node.children) return node;
|
|
134
|
+
const { children: _omitted, ...shallow } = node;
|
|
135
|
+
void _omitted;
|
|
136
|
+
return shallow;
|
|
137
|
+
}
|
|
138
|
+
function diffSnapshots(prev, next) {
|
|
139
|
+
const fullReset = prev === null || originAndPathname(prev.url) !== originAndPathname(next.url);
|
|
140
|
+
const prevRefs = new HostMap();
|
|
141
|
+
const prevOrder = [];
|
|
142
|
+
const prevUnreffed = new HostMap();
|
|
143
|
+
const nextRefs = new HostSet();
|
|
144
|
+
const added = [];
|
|
145
|
+
const changed = [];
|
|
146
|
+
function walkTree(nodes, parentKey, inAdded, indexOnly) {
|
|
147
|
+
const counts = new HostMap();
|
|
148
|
+
for (const n of nodes) {
|
|
149
|
+
let key = n.ref;
|
|
150
|
+
if (n.ref !== void 0) {
|
|
151
|
+
if (indexOnly) {
|
|
152
|
+
prevRefs.set(n.ref, n);
|
|
153
|
+
prevOrder.push(n.ref);
|
|
154
|
+
} else {
|
|
155
|
+
nextRefs.add(n.ref);
|
|
156
|
+
}
|
|
157
|
+
} else {
|
|
158
|
+
const ord = counts.get(n.role) ?? 0;
|
|
159
|
+
counts.set(n.role, ord + 1);
|
|
160
|
+
key = `${parentKey}/${n.role}[${ord}]`;
|
|
161
|
+
if (indexOnly) prevUnreffed.set(key, n);
|
|
162
|
+
}
|
|
163
|
+
if (indexOnly) {
|
|
164
|
+
if (n.children) walkTree(n.children, key, false, true);
|
|
165
|
+
} else {
|
|
166
|
+
const old = n.ref !== void 0 ? prevRefs.get(n.ref) : prevUnreffed.get(key);
|
|
167
|
+
if (!old) {
|
|
168
|
+
if (!inAdded) added.push(n);
|
|
169
|
+
if (n.children) walkTree(n.children, key, true, false);
|
|
170
|
+
} else {
|
|
171
|
+
if (!sameNodeShallow(old, n)) changed.push(shallowCopy(n));
|
|
172
|
+
if (n.children) walkTree(n.children, key, inAdded, false);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (!fullReset) {
|
|
178
|
+
walkTree(prev.elements, "root", false, true);
|
|
179
|
+
walkTree(next.elements, "root", false, false);
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
fromRev: prev?.rev ?? 0,
|
|
183
|
+
toRev: next.rev,
|
|
184
|
+
fullReset,
|
|
185
|
+
added,
|
|
186
|
+
removed: prevOrder.filter((ref) => !nextRefs.has(ref)),
|
|
187
|
+
changed,
|
|
188
|
+
...fullReset ? { elements: next.elements } : {}
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// src/protocol.ts
|
|
193
|
+
var PROTOCOL_VERSION = 1;
|
|
194
|
+
var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
195
|
+
var isStr = (v) => typeof v === "string";
|
|
196
|
+
var isBool = (v) => typeof v === "boolean";
|
|
197
|
+
var isOptStr = (v) => v === void 0 || isStr(v);
|
|
198
|
+
var isOptBool = (v) => v === void 0 || isBool(v);
|
|
199
|
+
var isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
|
|
200
|
+
var isNonNegFinite = (v) => isFiniteNumber(v) && v >= 0;
|
|
201
|
+
var isNonNegSafeInt = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
|
|
202
|
+
var isRefId = (v) => isStr(v) && /^e\d+$/.test(v);
|
|
203
|
+
function isDiagnosticsDelta(v) {
|
|
204
|
+
return isRecord(v) && (v["compileOverlay"] === null || isStr(v["compileOverlay"])) && Array.isArray(v["consoleErrors"]) && v["consoleErrors"].every(isStr) && Array.isArray(v["pageErrors"]) && v["pageErrors"].every(isStr) && Array.isArray(v["networkFailures"]) && v["networkFailures"].every(
|
|
205
|
+
(e) => isRecord(e) && isStr(e["method"]) && isStr(e["url"]) && isNonNegSafeInt(e["status"]) && isStr(e["statusText"])
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
function isSnapshotMediaState(v) {
|
|
209
|
+
return isRecord(v) && (v["kind"] === "video" || v["kind"] === "audio") && isBool(v["paused"]) && isNonNegFinite(v["currentTime"]) && (v["duration"] === null || isNonNegFinite(v["duration"])) && isNonNegFinite(v["width"]) && isNonNegFinite(v["height"]) && isBool(v["ready"]) && (v["error"] === null || isStr(v["error"]));
|
|
210
|
+
}
|
|
211
|
+
function isSnapshotCanvasState(v) {
|
|
212
|
+
return isRecord(v) && isNonNegFinite(v["width"]) && isNonNegFinite(v["height"]) && isBool(v["nonBlank"]);
|
|
213
|
+
}
|
|
214
|
+
function isSnapshotNode(v) {
|
|
215
|
+
return isRecord(v) && isStr(v["role"]) && isStr(v["name"]) && (v["ref"] === void 0 || isRefId(v["ref"])) && isOptStr(v["driverId"]) && isOptStr(v["intent"]) && isOptStr(v["value"]) && isOptBool(v["checked"]) && isOptBool(v["disabled"]) && isOptBool(v["expanded"]) && (v["min"] === void 0 || isFiniteNumber(v["min"])) && (v["max"] === void 0 || isFiniteNumber(v["max"])) && (v["media"] === void 0 || isSnapshotMediaState(v["media"])) && (v["canvas"] === void 0 || isSnapshotCanvasState(v["canvas"])) && (v["children"] === void 0 || Array.isArray(v["children"]) && v["children"].every(isSnapshotNode));
|
|
216
|
+
}
|
|
217
|
+
function isObservationSnapshot(value) {
|
|
218
|
+
if (!isRecord(value) || !isNonNegSafeInt(value["rev"])) return false;
|
|
219
|
+
if (!isStr(value["url"]) || !isStr(value["title"])) return false;
|
|
220
|
+
const vp = value["viewport"];
|
|
221
|
+
return isRecord(vp) && isNonNegFinite(vp["width"]) && isNonNegFinite(vp["height"]) && isDiagnosticsDelta(value["diagnostics"]) && Array.isArray(value["elements"]) && value["elements"].every(isSnapshotNode);
|
|
222
|
+
}
|
|
223
|
+
function isEvalResult(value) {
|
|
224
|
+
return isRecord(value) && "value" in value && isDiagnosticsDelta(value["diagnostics"]);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// src/types.ts
|
|
228
|
+
var DriverError = class extends Error {
|
|
229
|
+
code;
|
|
230
|
+
candidates;
|
|
231
|
+
constructor(code, message, options) {
|
|
232
|
+
super(message, options?.cause !== void 0 ? { cause: options.cause } : void 0);
|
|
233
|
+
this.name = "DriverError";
|
|
234
|
+
this.code = code;
|
|
235
|
+
if (options?.candidates !== void 0) {
|
|
236
|
+
this.candidates = options.candidates;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
// src/puppeteer/cdp-driver.ts
|
|
242
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
243
|
+
var DEFAULT_ACT_TIMEOUT_MS = 5e3;
|
|
244
|
+
var nextCdpSessionSeq = 1;
|
|
245
|
+
function getPreloadSource() {
|
|
246
|
+
const raw = DRIVER_PRELOAD_SOURCE;
|
|
247
|
+
if (typeof raw !== "string" || raw.length === 0) {
|
|
248
|
+
throw new DriverError(
|
|
249
|
+
"DRIVER_PROTOCOL",
|
|
250
|
+
"Preload source bundle is unavailable; build @inbrowser/driver before connecting."
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
return raw;
|
|
254
|
+
}
|
|
255
|
+
function toDriverError(err, fallbackMessage) {
|
|
256
|
+
if (err instanceof DriverError) {
|
|
257
|
+
return err;
|
|
258
|
+
}
|
|
259
|
+
const message = err instanceof Error ? err.message : fallbackMessage;
|
|
260
|
+
if (/timed?\s*out|timeout/i.test(message)) {
|
|
261
|
+
return new DriverError("DRIVER_TIMEOUT", message, { cause: err });
|
|
262
|
+
}
|
|
263
|
+
return new DriverError("DRIVER_PROTOCOL", message || fallbackMessage, { cause: err });
|
|
264
|
+
}
|
|
265
|
+
function formatStepError(err) {
|
|
266
|
+
if (err instanceof DriverError) {
|
|
267
|
+
const cands = err.candidates?.length ? ` (candidates: ${err.candidates.slice(0, 5).map((c) => `${c.role}${c.name ? ` "${c.name}"` : ""}`).join(", ")})` : "";
|
|
268
|
+
return `${err.code}: ${err.message}${cands}`;
|
|
269
|
+
}
|
|
270
|
+
return err instanceof Error ? err.message : String(err);
|
|
271
|
+
}
|
|
272
|
+
function isExecutionContextDestroyed(err) {
|
|
273
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
274
|
+
return /Execution context was destroyed|Cannot find context with specified id|Target closed|Session closed|Inspected target navigated/i.test(
|
|
275
|
+
msg
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
function raceWithAbortAndTimeout(work, timeoutMs, operationLabel, signal) {
|
|
279
|
+
if (signal?.aborted) {
|
|
280
|
+
return Promise.reject(
|
|
281
|
+
new DriverError("DRIVER_TIMEOUT", `Driver '${operationLabel}' operation aborted by signal.`, {
|
|
282
|
+
cause: signal.reason
|
|
283
|
+
})
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
return new Promise((resolve, reject) => {
|
|
287
|
+
let settled = false;
|
|
288
|
+
const cleanup = () => {
|
|
289
|
+
clearTimeout(timer);
|
|
290
|
+
signal?.removeEventListener("abort", onAbort);
|
|
291
|
+
};
|
|
292
|
+
const onAbort = () => {
|
|
293
|
+
if (settled) return;
|
|
294
|
+
settled = true;
|
|
295
|
+
cleanup();
|
|
296
|
+
reject(
|
|
297
|
+
new DriverError(
|
|
298
|
+
"DRIVER_TIMEOUT",
|
|
299
|
+
`Driver '${operationLabel}' operation aborted by signal.`,
|
|
300
|
+
{ cause: signal?.reason }
|
|
301
|
+
)
|
|
302
|
+
);
|
|
303
|
+
};
|
|
304
|
+
const timer = setTimeout(() => {
|
|
305
|
+
if (settled) return;
|
|
306
|
+
settled = true;
|
|
307
|
+
cleanup();
|
|
308
|
+
reject(
|
|
309
|
+
new DriverError(
|
|
310
|
+
"DRIVER_TIMEOUT",
|
|
311
|
+
`Driver '${operationLabel}' timed out after ${String(timeoutMs)}ms.`
|
|
312
|
+
)
|
|
313
|
+
);
|
|
314
|
+
}, timeoutMs);
|
|
315
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
316
|
+
work().then(
|
|
317
|
+
(value) => {
|
|
318
|
+
if (settled) return;
|
|
319
|
+
settled = true;
|
|
320
|
+
cleanup();
|
|
321
|
+
resolve(value);
|
|
322
|
+
},
|
|
323
|
+
(err) => {
|
|
324
|
+
if (settled) return;
|
|
325
|
+
settled = true;
|
|
326
|
+
cleanup();
|
|
327
|
+
reject(toDriverError(err, `Driver '${operationLabel}' failed.`));
|
|
328
|
+
}
|
|
329
|
+
);
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
function isNavigableUrl(candidate) {
|
|
333
|
+
return /^https?:\/\//i.test(candidate) || candidate.startsWith("data:") || candidate === "about:blank";
|
|
334
|
+
}
|
|
335
|
+
async function resolveTargetPage(browser, targetUrl, preloadSource, timeoutMs) {
|
|
336
|
+
const pages = await browser.pages();
|
|
337
|
+
if (targetUrl !== void 0) {
|
|
338
|
+
const matched = pages.find((p) => {
|
|
339
|
+
const currentUrl = p.url();
|
|
340
|
+
return currentUrl === targetUrl || currentUrl.startsWith(targetUrl);
|
|
341
|
+
});
|
|
342
|
+
if (matched !== void 0) {
|
|
343
|
+
return { page: matched, preloadRegisteredOnNewDoc: false };
|
|
344
|
+
}
|
|
345
|
+
if (!isNavigableUrl(targetUrl)) {
|
|
346
|
+
throw new DriverError(
|
|
347
|
+
"DRIVER_TARGET_NOT_FOUND",
|
|
348
|
+
`No open page matched targetUrl "${targetUrl}".`
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
const blankPage = pages.find((p) => p.url() === "" || p.url() === "about:blank");
|
|
352
|
+
const page = blankPage ?? await browser.newPage();
|
|
353
|
+
await page.evaluateOnNewDocument(preloadSource);
|
|
354
|
+
await page.goto(targetUrl, { waitUntil: "domcontentloaded", timeout: timeoutMs });
|
|
355
|
+
return { page, preloadRegisteredOnNewDoc: true };
|
|
356
|
+
}
|
|
357
|
+
const preferred = pages.find((p) => p.url() !== "" && p.url() !== "about:blank") ?? pages[0];
|
|
358
|
+
if (preferred === void 0) {
|
|
359
|
+
throw new DriverError(
|
|
360
|
+
"DRIVER_TARGET_NOT_FOUND",
|
|
361
|
+
"No open page targets available in connected browser."
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
return { page: preferred, preloadRegisteredOnNewDoc: false };
|
|
365
|
+
}
|
|
366
|
+
function isBridgeError(v) {
|
|
367
|
+
return isRecord(v) && typeof v["code"] === "string" && typeof v["message"] === "string" && (v["code"] === "DRIVER_TIMEOUT" || v["code"] === "DRIVER_DISPOSED" || v["code"] === "DRIVER_PROTOCOL" || v["code"] === "DRIVER_UNSUPPORTED" || v["code"] === "DRIVER_TARGET_NOT_FOUND" || v["code"] === "DRIVER_TARGET_AMBIGUOUS" || v["code"] === "DRIVER_EVAL_DISABLED");
|
|
368
|
+
}
|
|
369
|
+
function unwrapBridgeEnvelope(rawOutcome) {
|
|
370
|
+
if (!isRecord(rawOutcome)) {
|
|
371
|
+
throw new DriverError("DRIVER_PROTOCOL", "Malformed response from in-page CDP bridge.");
|
|
372
|
+
}
|
|
373
|
+
if (rawOutcome["ok"] === true) {
|
|
374
|
+
return rawOutcome["result"];
|
|
375
|
+
}
|
|
376
|
+
if (rawOutcome["ok"] === false && isBridgeError(rawOutcome["error"])) {
|
|
377
|
+
const errInfo = rawOutcome["error"];
|
|
378
|
+
throw new DriverError(errInfo.code, errInfo.message, {
|
|
379
|
+
...errInfo.candidates !== void 0 ? { candidates: errInfo.candidates } : {}
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
throw new DriverError("DRIVER_PROTOCOL", "Unexpected bridge response envelope.");
|
|
383
|
+
}
|
|
384
|
+
function readImageDimensions(bytes, format, fallbackWidth, fallbackHeight) {
|
|
385
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
386
|
+
if (format === "png" && bytes.byteLength >= 24 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) {
|
|
387
|
+
const w = view.getUint32(16, false);
|
|
388
|
+
const h = view.getUint32(20, false);
|
|
389
|
+
if (w > 0 && h > 0) {
|
|
390
|
+
return { width: w, height: h };
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
if (format === "webp" && bytes.byteLength >= 30 && bytes[0] === 82 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 70 && bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80) {
|
|
394
|
+
const chunk = String.fromCharCode(
|
|
395
|
+
bytes[12] ?? 0,
|
|
396
|
+
bytes[13] ?? 0,
|
|
397
|
+
bytes[14] ?? 0,
|
|
398
|
+
bytes[15] ?? 0
|
|
399
|
+
);
|
|
400
|
+
if (chunk === "VP8X") {
|
|
401
|
+
const w = 1 + ((bytes[24] ?? 0) | (bytes[25] ?? 0) << 8 | (bytes[26] ?? 0) << 16);
|
|
402
|
+
const h = 1 + ((bytes[27] ?? 0) | (bytes[28] ?? 0) << 8 | (bytes[29] ?? 0) << 16);
|
|
403
|
+
if (w > 0 && h > 0) {
|
|
404
|
+
return { width: w, height: h };
|
|
405
|
+
}
|
|
406
|
+
} else if (chunk === "VP8 " && bytes[23] === 157 && bytes[24] === 1 && bytes[25] === 42) {
|
|
407
|
+
const w = view.getUint16(26, true) & 16383;
|
|
408
|
+
const h = view.getUint16(28, true) & 16383;
|
|
409
|
+
if (w > 0 && h > 0) {
|
|
410
|
+
return { width: w, height: h };
|
|
411
|
+
}
|
|
412
|
+
} else if (chunk === "VP8L" && bytes[20] === 47) {
|
|
413
|
+
const bits = view.getUint32(21, true);
|
|
414
|
+
const w = (bits & 16383) + 1;
|
|
415
|
+
const h = (bits >>> 14 & 16383) + 1;
|
|
416
|
+
if (w > 0 && h > 0) {
|
|
417
|
+
return { width: w, height: h };
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return {
|
|
422
|
+
width: Math.max(1, Math.round(fallbackWidth)),
|
|
423
|
+
height: Math.max(1, Math.round(fallbackHeight))
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
async function encodeFramesToWebmInPage(arg) {
|
|
427
|
+
const decodeImage = (b64) => new Promise((resolve, reject) => {
|
|
428
|
+
const img = new Image();
|
|
429
|
+
img.onload = () => resolve(img);
|
|
430
|
+
img.onerror = () => reject(new Error("Failed to decode recorded frame"));
|
|
431
|
+
img.src = `data:image/jpeg;base64,${b64}`;
|
|
432
|
+
});
|
|
433
|
+
const decoded = [];
|
|
434
|
+
for (const frame of arg.frames) {
|
|
435
|
+
try {
|
|
436
|
+
decoded.push(await decodeImage(frame));
|
|
437
|
+
} catch {
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const first = decoded[0];
|
|
441
|
+
const width = Math.max(2, Math.round(first?.naturalWidth || arg.fallbackWidth || 640));
|
|
442
|
+
const height = Math.max(2, Math.round(first?.naturalHeight || arg.fallbackHeight || 480));
|
|
443
|
+
const canvas = document.createElement("canvas");
|
|
444
|
+
canvas.width = width;
|
|
445
|
+
canvas.height = height;
|
|
446
|
+
const ctx = canvas.getContext("2d");
|
|
447
|
+
if (!ctx) {
|
|
448
|
+
throw new Error("2D canvas context unavailable for WebM encoding.");
|
|
449
|
+
}
|
|
450
|
+
const preferredMime = typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported("video/webm;codecs=vp8") ? "video/webm;codecs=vp8" : "video/webm";
|
|
451
|
+
const stream = canvas.captureStream(0);
|
|
452
|
+
const track = stream.getVideoTracks()[0];
|
|
453
|
+
const requestFrame = () => {
|
|
454
|
+
if (track && "requestFrame" in track) {
|
|
455
|
+
const fn = Reflect.get(track, "requestFrame");
|
|
456
|
+
if (typeof fn === "function") {
|
|
457
|
+
fn.call(track);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
const chunks = [];
|
|
462
|
+
const recorder = new MediaRecorder(stream, { mimeType: preferredMime });
|
|
463
|
+
const stoppedPromise = new Promise((resolve, reject) => {
|
|
464
|
+
recorder.ondataavailable = (ev) => {
|
|
465
|
+
if (ev.data.size > 0) {
|
|
466
|
+
chunks.push(ev.data);
|
|
467
|
+
}
|
|
468
|
+
};
|
|
469
|
+
recorder.onerror = () => reject(new Error("MediaRecorder encoding failed."));
|
|
470
|
+
recorder.onstop = () => resolve(new Blob(chunks, { type: "video/webm" }));
|
|
471
|
+
});
|
|
472
|
+
recorder.start();
|
|
473
|
+
const framesToRender = decoded.length > 0 ? decoded : [null];
|
|
474
|
+
const sequence = framesToRender.length === 1 ? [framesToRender[0], framesToRender[0]] : framesToRender;
|
|
475
|
+
for (const img of sequence) {
|
|
476
|
+
if (img) {
|
|
477
|
+
ctx.drawImage(img, 0, 0, width, height);
|
|
478
|
+
} else {
|
|
479
|
+
ctx.fillStyle = "#0f172a";
|
|
480
|
+
ctx.fillRect(0, 0, width, height);
|
|
481
|
+
}
|
|
482
|
+
requestFrame();
|
|
483
|
+
await new Promise((r) => setTimeout(r, 25));
|
|
484
|
+
}
|
|
485
|
+
recorder.stop();
|
|
486
|
+
const blob = await stoppedPromise;
|
|
487
|
+
for (const t of stream.getTracks()) {
|
|
488
|
+
t.stop();
|
|
489
|
+
}
|
|
490
|
+
const buf = await blob.arrayBuffer();
|
|
491
|
+
return {
|
|
492
|
+
mimeType: "video/webm",
|
|
493
|
+
bytesArray: Array.from(new Uint8Array(buf)),
|
|
494
|
+
width,
|
|
495
|
+
height
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
async function executeInPageBridgeCommand(cmd) {
|
|
499
|
+
const CHANNEL = "@inbrowser/driver:v1";
|
|
500
|
+
const BRIDGE_KEY = Symbol.for("@inbrowser/driver:cdp-bridge:v1");
|
|
501
|
+
const DRIVER_UI_ATTR = "data-inbrowser-driver-ui";
|
|
502
|
+
class CodedBridgeError extends Error {
|
|
503
|
+
code;
|
|
504
|
+
candidates;
|
|
505
|
+
constructor(code, message, candidates) {
|
|
506
|
+
super(message);
|
|
507
|
+
this.code = code;
|
|
508
|
+
this.candidates = candidates;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
const normSpace = (s) => s.replace(/\s+/g, " ").trim();
|
|
512
|
+
const tag = (el) => el.tagName.toLowerCase();
|
|
513
|
+
const attr = (el, name) => normSpace(el.getAttribute(name) ?? "");
|
|
514
|
+
const IGNORED_TAGS = /* @__PURE__ */ new Set([
|
|
515
|
+
"script",
|
|
516
|
+
"style",
|
|
517
|
+
"noscript",
|
|
518
|
+
"template",
|
|
519
|
+
"head",
|
|
520
|
+
"meta",
|
|
521
|
+
"link",
|
|
522
|
+
"base",
|
|
523
|
+
"title",
|
|
524
|
+
"param",
|
|
525
|
+
"track",
|
|
526
|
+
"source",
|
|
527
|
+
"wbr",
|
|
528
|
+
"br"
|
|
529
|
+
]);
|
|
530
|
+
const SECTION_TAGS = /* @__PURE__ */ new Set(["article", "aside", "main", "nav", "section"]);
|
|
531
|
+
const LANDMARK_ROLES = /* @__PURE__ */ new Set([
|
|
532
|
+
"main",
|
|
533
|
+
"navigation",
|
|
534
|
+
"banner",
|
|
535
|
+
"contentinfo",
|
|
536
|
+
"region",
|
|
537
|
+
"form",
|
|
538
|
+
"toolbar",
|
|
539
|
+
"dialog",
|
|
540
|
+
"complementary"
|
|
541
|
+
]);
|
|
542
|
+
const TOGGLE_ROLES = /* @__PURE__ */ new Set([
|
|
543
|
+
"checkbox",
|
|
544
|
+
"switch",
|
|
545
|
+
"radio",
|
|
546
|
+
"menuitemcheckbox",
|
|
547
|
+
"menuitemradio"
|
|
548
|
+
]);
|
|
549
|
+
const VALUE_ROLES = /* @__PURE__ */ new Set([
|
|
550
|
+
"textbox",
|
|
551
|
+
"searchbox",
|
|
552
|
+
"combobox",
|
|
553
|
+
"listbox",
|
|
554
|
+
"slider",
|
|
555
|
+
"spinbutton"
|
|
556
|
+
]);
|
|
557
|
+
const INTERACTIVE_ROLES = /* @__PURE__ */ new Set([
|
|
558
|
+
...TOGGLE_ROLES,
|
|
559
|
+
...VALUE_ROLES,
|
|
560
|
+
"button",
|
|
561
|
+
"link",
|
|
562
|
+
"option",
|
|
563
|
+
"tab",
|
|
564
|
+
"menuitem"
|
|
565
|
+
]);
|
|
566
|
+
const DIRECT_ROLES = {
|
|
567
|
+
main: "main",
|
|
568
|
+
form: "form",
|
|
569
|
+
dialog: "dialog",
|
|
570
|
+
button: "button",
|
|
571
|
+
option: "option",
|
|
572
|
+
nav: "navigation",
|
|
573
|
+
aside: "complementary",
|
|
574
|
+
output: "status",
|
|
575
|
+
ul: "list",
|
|
576
|
+
ol: "list",
|
|
577
|
+
menu: "list",
|
|
578
|
+
li: "listitem",
|
|
579
|
+
summary: "button",
|
|
580
|
+
textarea: "textbox",
|
|
581
|
+
h1: "heading",
|
|
582
|
+
h2: "heading",
|
|
583
|
+
h3: "heading",
|
|
584
|
+
h4: "heading",
|
|
585
|
+
h5: "heading",
|
|
586
|
+
h6: "heading"
|
|
587
|
+
};
|
|
588
|
+
const INPUT_ROLES = {
|
|
589
|
+
button: "button",
|
|
590
|
+
checkbox: "checkbox",
|
|
591
|
+
radio: "radio",
|
|
592
|
+
submit: "button",
|
|
593
|
+
reset: "button",
|
|
594
|
+
image: "button",
|
|
595
|
+
range: "slider",
|
|
596
|
+
number: "spinbutton"
|
|
597
|
+
};
|
|
598
|
+
function getComposedChildren(node) {
|
|
599
|
+
if (node instanceof Element) {
|
|
600
|
+
if (node instanceof HTMLSlotElement) {
|
|
601
|
+
const assigned = node.assignedNodes({ flatten: false });
|
|
602
|
+
if (assigned.length > 0) return [...assigned];
|
|
603
|
+
}
|
|
604
|
+
if (node.shadowRoot) return Array.from(node.shadowRoot.childNodes);
|
|
605
|
+
if (node instanceof HTMLSelectElement) return Array.from(node.childNodes).slice(0, 50);
|
|
606
|
+
}
|
|
607
|
+
return Array.from(node.childNodes);
|
|
608
|
+
}
|
|
609
|
+
function composedParent(node) {
|
|
610
|
+
if (node instanceof Element && node.assignedSlot) return node.assignedSlot;
|
|
611
|
+
const p = node.parentNode;
|
|
612
|
+
return p instanceof ShadowRoot ? p.host : p;
|
|
613
|
+
}
|
|
614
|
+
function getComposedParentElement(node) {
|
|
615
|
+
let cur = composedParent(node);
|
|
616
|
+
while (cur && !(cur instanceof Element)) cur = composedParent(cur);
|
|
617
|
+
return cur;
|
|
618
|
+
}
|
|
619
|
+
function isComposedDescendant(ancestor, candidate) {
|
|
620
|
+
for (let cur = candidate; cur; cur = composedParent(cur)) {
|
|
621
|
+
if (cur === ancestor || cur.parentNode === ancestor) return true;
|
|
622
|
+
}
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
function findComposedAncestor(el, pred, includeSelf = false) {
|
|
626
|
+
for (let cur = includeSelf ? el : el ? getComposedParentElement(el) : null; cur; cur = getComposedParentElement(cur)) {
|
|
627
|
+
if (pred(cur)) return cur;
|
|
628
|
+
}
|
|
629
|
+
return null;
|
|
630
|
+
}
|
|
631
|
+
function isElementHidden(el) {
|
|
632
|
+
if (el.hasAttribute(DRIVER_UI_ATTR) || el.hasAttribute("hidden") || attr(el, "aria-hidden") === "true") {
|
|
633
|
+
return true;
|
|
634
|
+
}
|
|
635
|
+
const t = tag(el);
|
|
636
|
+
if (IGNORED_TAGS.has(t)) return true;
|
|
637
|
+
if (el instanceof HTMLInputElement && el.type.toLowerCase() === "hidden") return true;
|
|
638
|
+
if (t === "dialog" && !el.hasAttribute("open")) return true;
|
|
639
|
+
const style = window.getComputedStyle(el);
|
|
640
|
+
if (style.visibility === "hidden" || style.visibility === "collapse") return true;
|
|
641
|
+
if (style.display === "none") {
|
|
642
|
+
return t === "audio" && !el.hasAttribute("controls") || t === "option" ? el instanceof HTMLElement && el.style.display === "none" : true;
|
|
643
|
+
}
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
646
|
+
function isElementDisabled(el) {
|
|
647
|
+
if (attr(el, "aria-disabled") === "true") return true;
|
|
648
|
+
if (el instanceof HTMLOptionElement) return el.disabled;
|
|
649
|
+
if ("disabled" in el && typeof el.disabled === "boolean") {
|
|
650
|
+
return el.disabled || findComposedAncestor(
|
|
651
|
+
el,
|
|
652
|
+
(a) => tag(a) === "fieldset" && "disabled" in a && Boolean(a.disabled)
|
|
653
|
+
) !== null;
|
|
654
|
+
}
|
|
655
|
+
return false;
|
|
656
|
+
}
|
|
657
|
+
const DRIVER_ID_RE = /^[A-Za-z0-9_.:/-]{1,80}$/;
|
|
658
|
+
const DRIVER_REGION_RE = /(?:^|\.)(?:panel|section|region|list|nav|group)$/i;
|
|
659
|
+
const NATIVE_CTRL_SEL = "button,a[href],input:not([type=hidden]),select,textarea,[tabindex]";
|
|
660
|
+
function readDriverId(el) {
|
|
661
|
+
const v = attr(el, "data-driver").slice(0, 80);
|
|
662
|
+
return DRIVER_ID_RE.test(v) ? v : "";
|
|
663
|
+
}
|
|
664
|
+
function shouldAssignRef(el, role) {
|
|
665
|
+
return Boolean(readDriverId(el)) || LANDMARK_ROLES.has(role) || INTERACTIVE_ROLES.has(role) || role === "video" || role === "audio" || role === "canvas" || el instanceof HTMLElement && el.hasAttribute("tabindex") && el.tabIndex >= 0;
|
|
666
|
+
}
|
|
667
|
+
function computeBaseRole(el) {
|
|
668
|
+
const t = tag(el);
|
|
669
|
+
if (t === "video" || t === "audio" || t === "canvas") return t;
|
|
670
|
+
const explicit = attr(el, "role");
|
|
671
|
+
if (explicit) {
|
|
672
|
+
const token = explicit.split(" ")[0]?.toLowerCase() ?? "";
|
|
673
|
+
return token === "none" || token === "presentation" ? null : token || null;
|
|
674
|
+
}
|
|
675
|
+
if (DIRECT_ROLES[t]) return DIRECT_ROLES[t];
|
|
676
|
+
const drv = readDriverId(el);
|
|
677
|
+
if (t === "header" || t === "footer") {
|
|
678
|
+
return findComposedAncestor(el, (a) => SECTION_TAGS.has(tag(a))) !== null ? drv ? "region" : null : t === "header" ? "banner" : "contentinfo";
|
|
679
|
+
}
|
|
680
|
+
if (t === "section") {
|
|
681
|
+
return attr(el, "aria-label") || attr(el, "aria-labelledby") || attr(el, "title") || drv ? "region" : null;
|
|
682
|
+
}
|
|
683
|
+
if (t === "a" || t === "area") return el.hasAttribute("href") ? "link" : drv ? "button" : null;
|
|
684
|
+
if (t === "select") {
|
|
685
|
+
return el instanceof HTMLSelectElement && (el.multiple || el.size > 1) ? "listbox" : "combobox";
|
|
686
|
+
}
|
|
687
|
+
if (t === "input") {
|
|
688
|
+
const it = el instanceof HTMLInputElement ? el.type.toLowerCase() : attr(el, "type").toLowerCase() || "text";
|
|
689
|
+
return it === "hidden" ? null : INPUT_ROLES[it] ?? "textbox";
|
|
690
|
+
}
|
|
691
|
+
if (t === "img") {
|
|
692
|
+
return attr(el, "aria-label") || attr(el, "aria-labelledby") || attr(el, "title") || attr(el, "alt") || drv ? "img" : null;
|
|
693
|
+
}
|
|
694
|
+
const ce = el.getAttribute("contenteditable");
|
|
695
|
+
if (ce === "" || ce?.toLowerCase() === "true") return "textbox";
|
|
696
|
+
if (el.hasAttribute("onclick")) return "button";
|
|
697
|
+
if (drv) {
|
|
698
|
+
return DRIVER_REGION_RE.test(drv) || !attr(el, "data-driver-intent") && !attr(el, "data-driver-description") && window.getComputedStyle(el).cursor !== "pointer" && Boolean(el.querySelector(NATIVE_CTRL_SEL)) ? "region" : "button";
|
|
699
|
+
}
|
|
700
|
+
return null;
|
|
701
|
+
}
|
|
702
|
+
function computeElementRole(el) {
|
|
703
|
+
const base = computeBaseRole(el);
|
|
704
|
+
if (base) return base;
|
|
705
|
+
const t = tag(el);
|
|
706
|
+
if (t === "html" || t === "body" || t === "main" || t === "label") return null;
|
|
707
|
+
if (window.getComputedStyle(el).cursor !== "pointer") return null;
|
|
708
|
+
const parent = getComposedParentElement(el);
|
|
709
|
+
if (parent && window.getComputedStyle(parent).cursor === "pointer") return null;
|
|
710
|
+
if (el.querySelector(NATIVE_CTRL_SEL) || findComposedAncestor(el, (a) => {
|
|
711
|
+
const r = computeBaseRole(a);
|
|
712
|
+
return Boolean(r && INTERACTIVE_ROLES.has(r));
|
|
713
|
+
}) !== null) {
|
|
714
|
+
return null;
|
|
715
|
+
}
|
|
716
|
+
const txt = normSpace(el.textContent ?? "");
|
|
717
|
+
return txt.length > 0 && txt.length <= 240 ? "button" : null;
|
|
718
|
+
}
|
|
719
|
+
function extractText(root, visited, allowHiddenRoot, exclude, skipControls) {
|
|
720
|
+
const parts = [];
|
|
721
|
+
function walk(cur, isRoot) {
|
|
722
|
+
if (cur.nodeType === 3) {
|
|
723
|
+
if (cur.nodeValue) parts.push(cur.nodeValue);
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
if (!(cur instanceof Element) || cur === exclude || !isRoot && visited.has(cur)) return;
|
|
727
|
+
const t = tag(cur);
|
|
728
|
+
if (!isRoot || !allowHiddenRoot) {
|
|
729
|
+
if (isElementHidden(cur)) return;
|
|
730
|
+
} else if (IGNORED_TAGS.has(t) || cur.hasAttribute(DRIVER_UI_ATTR)) return;
|
|
731
|
+
if (!isRoot && skipControls) {
|
|
732
|
+
const r = computeElementRole(cur);
|
|
733
|
+
if (r && shouldAssignRef(cur, r)) return;
|
|
734
|
+
}
|
|
735
|
+
if (t === "img") {
|
|
736
|
+
const alt = cur.getAttribute("alt");
|
|
737
|
+
if (alt) parts.push(alt);
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
if (!isRoot) {
|
|
741
|
+
const aria = attr(cur, "aria-label");
|
|
742
|
+
if (aria) {
|
|
743
|
+
parts.push(aria);
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
for (const c of getComposedChildren(cur)) walk(c, false);
|
|
748
|
+
}
|
|
749
|
+
walk(root, true);
|
|
750
|
+
return normSpace(parts.join(" "));
|
|
751
|
+
}
|
|
752
|
+
function computeAccessibleName(el, role, visited = /* @__PURE__ */ new Set()) {
|
|
753
|
+
if (visited.has(el)) return "";
|
|
754
|
+
const next = new Set(visited);
|
|
755
|
+
next.add(el);
|
|
756
|
+
const lb = attr(el, "aria-labelledby");
|
|
757
|
+
if (lb) {
|
|
758
|
+
const root = el.getRootNode();
|
|
759
|
+
const parts = [];
|
|
760
|
+
for (const id of lb.split(" ")) {
|
|
761
|
+
const refEl = root instanceof ShadowRoot ? root.getElementById(id) ?? document.getElementById(id) : document.getElementById(id);
|
|
762
|
+
if (refEl) {
|
|
763
|
+
const txt = extractText(refEl, next, true);
|
|
764
|
+
if (txt) parts.push(txt);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
const joined = normSpace(parts.join(" "));
|
|
768
|
+
if (joined) return joined;
|
|
769
|
+
}
|
|
770
|
+
const aria = attr(el, "aria-label");
|
|
771
|
+
if (aria) return aria;
|
|
772
|
+
if (el instanceof HTMLInputElement) {
|
|
773
|
+
const it = el.type.toLowerCase();
|
|
774
|
+
if (it === "image") return attr(el, "alt") || normSpace(el.value) || "Submit";
|
|
775
|
+
if (it === "submit" || it === "reset" || it === "button") {
|
|
776
|
+
return normSpace(el.value) || (it === "submit" ? "Submit" : it === "reset" ? "Reset" : "");
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
const labels = el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement ? el.labels : null;
|
|
780
|
+
if (labels && labels.length > 0) {
|
|
781
|
+
const parts = [];
|
|
782
|
+
for (const lbl of Array.from(labels)) {
|
|
783
|
+
const txt = extractText(lbl, next, false, el);
|
|
784
|
+
if (txt) parts.push(txt);
|
|
785
|
+
}
|
|
786
|
+
const joined = normSpace(parts.join(" "));
|
|
787
|
+
if (joined) return joined;
|
|
788
|
+
}
|
|
789
|
+
if (el instanceof HTMLOptionElement) {
|
|
790
|
+
const opt = normSpace(el.label || el.text);
|
|
791
|
+
if (opt) return opt;
|
|
792
|
+
}
|
|
793
|
+
if (tag(el) === "img") {
|
|
794
|
+
const alt = attr(el, "alt");
|
|
795
|
+
if (alt) return alt;
|
|
796
|
+
}
|
|
797
|
+
const usesContent = role === "heading" || INTERACTIVE_ROLES.has(role) && !VALUE_ROLES.has(role);
|
|
798
|
+
if (usesContent && !((role === "checkbox" || role === "radio") && el instanceof HTMLInputElement)) {
|
|
799
|
+
const txt = extractText(el, next, false);
|
|
800
|
+
if (txt) return txt;
|
|
801
|
+
}
|
|
802
|
+
if (role === "alert" || role === "status" || role === "listitem") {
|
|
803
|
+
const txt = extractText(el, next, false, void 0, true);
|
|
804
|
+
if (txt) return txt;
|
|
805
|
+
}
|
|
806
|
+
const placeholder = el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement ? normSpace(el.placeholder) : attr(el, "aria-placeholder");
|
|
807
|
+
return placeholder || attr(el, "title");
|
|
808
|
+
}
|
|
809
|
+
const formatLm = (role, name) => name ? `${role}:${name}` : role;
|
|
810
|
+
function findEnclosingLandmark(el) {
|
|
811
|
+
let out;
|
|
812
|
+
findComposedAncestor(el, (cur) => {
|
|
813
|
+
const r = computeElementRole(cur);
|
|
814
|
+
if (r && LANDMARK_ROLES.has(r)) {
|
|
815
|
+
out = formatLm(r, computeAccessibleName(cur, r));
|
|
816
|
+
return true;
|
|
817
|
+
}
|
|
818
|
+
return false;
|
|
819
|
+
});
|
|
820
|
+
return out;
|
|
821
|
+
}
|
|
822
|
+
function scanLiveDom(withText) {
|
|
823
|
+
const start = document.body ?? document.documentElement;
|
|
824
|
+
const counts = /* @__PURE__ */ new Map();
|
|
825
|
+
const items = [];
|
|
826
|
+
if (!start) return { items, cohortCounts: counts };
|
|
827
|
+
function visit(node, landmark) {
|
|
828
|
+
if (node instanceof Element) {
|
|
829
|
+
if (isElementHidden(node)) return;
|
|
830
|
+
const computedRole = computeElementRole(node);
|
|
831
|
+
const role = computedRole ?? (withText ? tag(node) : null);
|
|
832
|
+
let childLm = landmark;
|
|
833
|
+
if (role) {
|
|
834
|
+
const name = computeAccessibleName(node, role);
|
|
835
|
+
if (LANDMARK_ROLES.has(role)) childLm = formatLm(role, name);
|
|
836
|
+
const text = withText ? extractText(node, /* @__PURE__ */ new Set(), false) : "";
|
|
837
|
+
if (computedRole || text || name) {
|
|
838
|
+
const fpName = computedRole ? name : name || text;
|
|
839
|
+
const drv = readDriverId(node);
|
|
840
|
+
const key = `${role}\0${fpName}\0${landmark ?? ""}\0${drv}`;
|
|
841
|
+
const nth = counts.get(key) ?? 0;
|
|
842
|
+
counts.set(key, nth + 1);
|
|
843
|
+
const fingerprint = {
|
|
844
|
+
role,
|
|
845
|
+
name: fpName,
|
|
846
|
+
nth,
|
|
847
|
+
...landmark !== void 0 ? { landmark } : {},
|
|
848
|
+
...drv ? { driverId: drv } : {}
|
|
849
|
+
};
|
|
850
|
+
items.push({ target: node, text, fingerprint });
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
for (const c of getComposedChildren(node)) visit(c, childLm);
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
for (const c of getComposedChildren(node)) visit(c, landmark);
|
|
857
|
+
}
|
|
858
|
+
visit(start, start instanceof Element ? findEnclosingLandmark(start) : void 0);
|
|
859
|
+
return { items, cohortCounts: counts };
|
|
860
|
+
}
|
|
861
|
+
function isElementObservable(el) {
|
|
862
|
+
if (!el.isConnected || !isComposedDescendant(document, el)) return false;
|
|
863
|
+
for (let cur = el; cur; cur = getComposedParentElement(cur)) {
|
|
864
|
+
if (isElementHidden(cur)) return false;
|
|
865
|
+
}
|
|
866
|
+
return true;
|
|
867
|
+
}
|
|
868
|
+
function rankCandidates(pool, role, name, landmark, driverId) {
|
|
869
|
+
if (pool.length === 0) return [];
|
|
870
|
+
const sameRole = role ? pool.filter((c) => c.fingerprint.role === role) : [];
|
|
871
|
+
const activePool = sameRole.length > 0 ? sameRole : pool;
|
|
872
|
+
const qName = name.toLowerCase();
|
|
873
|
+
const qDrv = driverId?.toLowerCase() ?? "";
|
|
874
|
+
return activePool.map((item, idx) => {
|
|
875
|
+
const fp = item.fingerprint;
|
|
876
|
+
let s = role && fp.role === role ? 100 : 0;
|
|
877
|
+
if (landmark !== void 0 && fp.landmark === landmark) s += 30;
|
|
878
|
+
const cDrv = fp.driverId?.toLowerCase() ?? "";
|
|
879
|
+
if (qDrv && cDrv) {
|
|
880
|
+
if (cDrv === qDrv) s += 80;
|
|
881
|
+
else if (cDrv.includes(qDrv) || qDrv.includes(cDrv)) s += 40;
|
|
882
|
+
}
|
|
883
|
+
const cName = fp.name.toLowerCase();
|
|
884
|
+
if (qName && cName) {
|
|
885
|
+
if (cName === qName) s += 50;
|
|
886
|
+
else if (cName.includes(qName) || qName.includes(cName)) s += 25;
|
|
887
|
+
}
|
|
888
|
+
return { fp, s, idx };
|
|
889
|
+
}).sort((a, b) => b.s - a.s || a.idx - b.idx).slice(0, 8).map((x) => x.fp);
|
|
890
|
+
}
|
|
891
|
+
function sameCohort(a, b) {
|
|
892
|
+
return a.role === b.role && a.name === b.name && a.landmark === b.landmark && a.driverId === b.driverId;
|
|
893
|
+
}
|
|
894
|
+
function resolveTarget(spec, state2) {
|
|
895
|
+
if (typeof spec === "string") {
|
|
896
|
+
if (!/^e\d+$/.test(spec)) {
|
|
897
|
+
const { items: items3 } = scanLiveDom(false);
|
|
898
|
+
throw new CodedBridgeError(
|
|
899
|
+
"DRIVER_TARGET_NOT_FOUND",
|
|
900
|
+
`Invalid ref "${spec}".`,
|
|
901
|
+
rankCandidates(items3, "", spec)
|
|
902
|
+
);
|
|
903
|
+
}
|
|
904
|
+
const entry = state2.refs.get(spec);
|
|
905
|
+
if (!entry) {
|
|
906
|
+
const { items: items3 } = scanLiveDom(false);
|
|
907
|
+
throw new CodedBridgeError(
|
|
908
|
+
"DRIVER_TARGET_NOT_FOUND",
|
|
909
|
+
`Unknown ref "${spec}".`,
|
|
910
|
+
rankCandidates(items3, "", "")
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
const liveEl = entry.weakEl.deref();
|
|
914
|
+
if (liveEl && isElementObservable(liveEl)) return liveEl;
|
|
915
|
+
const { items: items2 } = scanLiveDom(false);
|
|
916
|
+
const cohort = items2.filter((c) => sameCohort(c.fingerprint, entry.fingerprint));
|
|
917
|
+
if (cohort.length === 0) {
|
|
918
|
+
throw new CodedBridgeError(
|
|
919
|
+
"DRIVER_TARGET_NOT_FOUND",
|
|
920
|
+
`Detached "${spec}".`,
|
|
921
|
+
rankCandidates(
|
|
922
|
+
items2,
|
|
923
|
+
entry.fingerprint.role,
|
|
924
|
+
entry.fingerprint.name,
|
|
925
|
+
entry.fingerprint.landmark,
|
|
926
|
+
entry.fingerprint.driverId
|
|
927
|
+
)
|
|
928
|
+
);
|
|
929
|
+
}
|
|
930
|
+
if (cohort.length === entry.cohortSize) {
|
|
931
|
+
const picked = cohort[cohort.length === 1 ? 0 : entry.fingerprint.nth];
|
|
932
|
+
if (picked !== void 0) {
|
|
933
|
+
entry.weakEl = new WeakRef(picked.target);
|
|
934
|
+
return picked.target;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
throw new CodedBridgeError(
|
|
938
|
+
"DRIVER_TARGET_AMBIGUOUS",
|
|
939
|
+
`Ambiguous "${spec}".`,
|
|
940
|
+
cohort.map((c) => c.fingerprint)
|
|
941
|
+
);
|
|
942
|
+
}
|
|
943
|
+
if ("role" in spec) {
|
|
944
|
+
const { items: items2 } = scanLiveDom(false);
|
|
945
|
+
const r = spec.role.trim().toLowerCase();
|
|
946
|
+
const n = spec.name !== void 0 ? normSpace(spec.name) : void 0;
|
|
947
|
+
const matches = items2.filter(
|
|
948
|
+
({ fingerprint: f }) => f.role === r && (n === void 0 || f.name === n)
|
|
949
|
+
);
|
|
950
|
+
if (matches.length === 0) {
|
|
951
|
+
throw new CodedBridgeError(
|
|
952
|
+
"DRIVER_TARGET_NOT_FOUND",
|
|
953
|
+
`No "${spec.role}".`,
|
|
954
|
+
rankCandidates(items2, r, n ?? "")
|
|
955
|
+
);
|
|
956
|
+
}
|
|
957
|
+
if (spec.nth !== void 0) {
|
|
958
|
+
const picked = matches[spec.nth];
|
|
959
|
+
if (!picked) {
|
|
960
|
+
throw new CodedBridgeError(
|
|
961
|
+
"DRIVER_TARGET_NOT_FOUND",
|
|
962
|
+
`nth=${String(spec.nth)} out of range.`,
|
|
963
|
+
matches.map((m) => m.fingerprint)
|
|
964
|
+
);
|
|
965
|
+
}
|
|
966
|
+
return picked.target;
|
|
967
|
+
}
|
|
968
|
+
if (matches.length > 1) {
|
|
969
|
+
throw new CodedBridgeError(
|
|
970
|
+
"DRIVER_TARGET_AMBIGUOUS",
|
|
971
|
+
`Ambiguous "${spec.role}".`,
|
|
972
|
+
matches.map((m) => m.fingerprint)
|
|
973
|
+
);
|
|
974
|
+
}
|
|
975
|
+
return matches[0].target;
|
|
976
|
+
}
|
|
977
|
+
if ("driver" in spec) {
|
|
978
|
+
const { items: items2 } = scanLiveDom(false);
|
|
979
|
+
const drv = normSpace(spec.driver);
|
|
980
|
+
const matches = drv ? items2.filter(({ fingerprint: f }) => f.driverId === drv) : [];
|
|
981
|
+
if (matches.length === 0) {
|
|
982
|
+
throw new CodedBridgeError(
|
|
983
|
+
"DRIVER_TARGET_NOT_FOUND",
|
|
984
|
+
`No driver="${spec.driver}".`,
|
|
985
|
+
rankCandidates(items2, "", drv, void 0, drv)
|
|
986
|
+
);
|
|
987
|
+
}
|
|
988
|
+
if (spec.nth !== void 0) {
|
|
989
|
+
const picked = matches[spec.nth];
|
|
990
|
+
if (!picked) {
|
|
991
|
+
throw new CodedBridgeError(
|
|
992
|
+
"DRIVER_TARGET_NOT_FOUND",
|
|
993
|
+
`nth=${String(spec.nth)} out of range.`,
|
|
994
|
+
matches.map((m) => m.fingerprint)
|
|
995
|
+
);
|
|
996
|
+
}
|
|
997
|
+
return picked.target;
|
|
998
|
+
}
|
|
999
|
+
if (matches.length > 1) {
|
|
1000
|
+
throw new CodedBridgeError(
|
|
1001
|
+
"DRIVER_TARGET_AMBIGUOUS",
|
|
1002
|
+
`Ambiguous driver="${drv}".`,
|
|
1003
|
+
matches.map((m) => m.fingerprint)
|
|
1004
|
+
);
|
|
1005
|
+
}
|
|
1006
|
+
return matches[0].target;
|
|
1007
|
+
}
|
|
1008
|
+
const query = normSpace(spec.text);
|
|
1009
|
+
const exact = spec.exact === true;
|
|
1010
|
+
const lq = query.toLowerCase();
|
|
1011
|
+
const { items } = scanLiveDom(true);
|
|
1012
|
+
const matched = query ? items.filter(
|
|
1013
|
+
(c) => exact ? c.text === query || c.fingerprint.name === query : c.text.toLowerCase().includes(lq) || c.fingerprint.name.toLowerCase().includes(lq)
|
|
1014
|
+
) : [];
|
|
1015
|
+
if (matched.length === 0) {
|
|
1016
|
+
throw new CodedBridgeError(
|
|
1017
|
+
"DRIVER_TARGET_NOT_FOUND",
|
|
1018
|
+
`Text "${spec.text}" not found.`,
|
|
1019
|
+
rankCandidates(items, "", query)
|
|
1020
|
+
);
|
|
1021
|
+
}
|
|
1022
|
+
const deepest = matched.filter(
|
|
1023
|
+
(o) => !matched.some((i) => i.target !== o.target && isComposedDescendant(o.target, i.target))
|
|
1024
|
+
);
|
|
1025
|
+
if (deepest.length > 1) {
|
|
1026
|
+
throw new CodedBridgeError(
|
|
1027
|
+
"DRIVER_TARGET_AMBIGUOUS",
|
|
1028
|
+
`Ambiguous text "${spec.text}".`,
|
|
1029
|
+
deepest.map((m) => m.fingerprint)
|
|
1030
|
+
);
|
|
1031
|
+
}
|
|
1032
|
+
return deepest[0].target;
|
|
1033
|
+
}
|
|
1034
|
+
function deepElementFromPoint(x, y) {
|
|
1035
|
+
let hit = document.elementFromPoint(x, y);
|
|
1036
|
+
while (hit) {
|
|
1037
|
+
const inner = hit.shadowRoot ? hit.shadowRoot.elementFromPoint(x, y) : null;
|
|
1038
|
+
if (!inner || inner === hit) break;
|
|
1039
|
+
hit = inner;
|
|
1040
|
+
}
|
|
1041
|
+
return hit;
|
|
1042
|
+
}
|
|
1043
|
+
const sleepFrame = (ms, useRaf) => new Promise((resolve) => {
|
|
1044
|
+
let done = false;
|
|
1045
|
+
const finish = () => {
|
|
1046
|
+
if (!done) {
|
|
1047
|
+
done = true;
|
|
1048
|
+
clearTimeout(timer);
|
|
1049
|
+
resolve();
|
|
1050
|
+
}
|
|
1051
|
+
};
|
|
1052
|
+
const timer = setTimeout(finish, ms);
|
|
1053
|
+
if (useRaf) requestAnimationFrame(() => finish());
|
|
1054
|
+
});
|
|
1055
|
+
async function waitForActionable(spec, timeoutMs, state2, allowZeroSizeAudio = false) {
|
|
1056
|
+
const deadline = performance.now() + timeoutMs;
|
|
1057
|
+
let lastError = null;
|
|
1058
|
+
let lastReason = "Target not actionable before timeout.";
|
|
1059
|
+
let prevRect = null;
|
|
1060
|
+
let stableFrames = 0;
|
|
1061
|
+
let sawAmbiguous = false;
|
|
1062
|
+
while (true) {
|
|
1063
|
+
let el = null;
|
|
1064
|
+
try {
|
|
1065
|
+
el = resolveTarget(spec, state2);
|
|
1066
|
+
} catch (err) {
|
|
1067
|
+
lastError = err;
|
|
1068
|
+
if (err instanceof CodedBridgeError && err.code === "DRIVER_TARGET_AMBIGUOUS") {
|
|
1069
|
+
if (sawAmbiguous) throw err;
|
|
1070
|
+
sawAmbiguous = true;
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
if (el) {
|
|
1074
|
+
sawAmbiguous = false;
|
|
1075
|
+
const t = tag(el);
|
|
1076
|
+
const skipHit = t === "audio" || t === "option";
|
|
1077
|
+
if (!el.isConnected || isElementHidden(el)) {
|
|
1078
|
+
lastReason = "Target is hidden or detached.";
|
|
1079
|
+
stableFrames = 0;
|
|
1080
|
+
} else {
|
|
1081
|
+
let rect = el.getBoundingClientRect();
|
|
1082
|
+
if (!(allowZeroSizeAudio && t === "audio") && (rect.width <= 0 || rect.height <= 0)) {
|
|
1083
|
+
lastReason = "Target has zero size.";
|
|
1084
|
+
stableFrames = 0;
|
|
1085
|
+
} else {
|
|
1086
|
+
if (!skipHit && (rect.bottom <= 0 || rect.top >= window.innerHeight || rect.right <= 0 || rect.left >= window.innerWidth)) {
|
|
1087
|
+
el.scrollIntoView({ block: "nearest", inline: "nearest" });
|
|
1088
|
+
rect = el.getBoundingClientRect();
|
|
1089
|
+
}
|
|
1090
|
+
if (prevRect && Math.hypot(
|
|
1091
|
+
prevRect.left - rect.left,
|
|
1092
|
+
prevRect.top - rect.top,
|
|
1093
|
+
prevRect.width - rect.width,
|
|
1094
|
+
prevRect.height - rect.height
|
|
1095
|
+
) < 0.5) {
|
|
1096
|
+
stableFrames += 1;
|
|
1097
|
+
} else {
|
|
1098
|
+
prevRect = rect;
|
|
1099
|
+
stableFrames = 0;
|
|
1100
|
+
}
|
|
1101
|
+
if (stableFrames >= 2) {
|
|
1102
|
+
if (isElementDisabled(el)) {
|
|
1103
|
+
lastReason = "Target is disabled.";
|
|
1104
|
+
} else {
|
|
1105
|
+
const pageLeft = window.visualViewport?.pageLeft ?? window.scrollX;
|
|
1106
|
+
const pageTop = window.visualViewport?.pageTop ?? window.scrollY;
|
|
1107
|
+
const rRole = computeElementRole(el) ?? t;
|
|
1108
|
+
if (skipHit) {
|
|
1109
|
+
const cx = rect.left + rect.width / 2;
|
|
1110
|
+
const cy = rect.top + rect.height / 2;
|
|
1111
|
+
return {
|
|
1112
|
+
el,
|
|
1113
|
+
hitEl: el,
|
|
1114
|
+
cx,
|
|
1115
|
+
cy,
|
|
1116
|
+
docX: rect.left + pageLeft,
|
|
1117
|
+
docY: rect.top + pageTop,
|
|
1118
|
+
width: rect.width,
|
|
1119
|
+
height: rect.height,
|
|
1120
|
+
tagName: t,
|
|
1121
|
+
role: rRole,
|
|
1122
|
+
isCustomCombobox: rRole === "combobox" && !(el instanceof HTMLSelectElement),
|
|
1123
|
+
ariaExpanded: el.getAttribute("aria-expanded") === "true"
|
|
1124
|
+
};
|
|
1125
|
+
}
|
|
1126
|
+
const vx0 = Math.max(0, rect.left);
|
|
1127
|
+
const vy0 = Math.max(0, rect.top);
|
|
1128
|
+
const vx1 = Math.min(window.innerWidth, rect.right);
|
|
1129
|
+
const vy1 = Math.min(window.innerHeight, rect.bottom);
|
|
1130
|
+
if (vx1 > vx0 && vy1 > vy0) {
|
|
1131
|
+
const cx = (vx0 + vx1) / 2;
|
|
1132
|
+
const cy = (vy0 + vy1) / 2;
|
|
1133
|
+
const hit = deepElementFromPoint(cx, cy);
|
|
1134
|
+
const labelHit = findComposedAncestor(
|
|
1135
|
+
hit,
|
|
1136
|
+
(c) => c instanceof HTMLLabelElement && c.control === el,
|
|
1137
|
+
true
|
|
1138
|
+
) !== null;
|
|
1139
|
+
if (hit && (hit === el || isComposedDescendant(el, hit) || labelHit)) {
|
|
1140
|
+
return {
|
|
1141
|
+
el,
|
|
1142
|
+
hitEl: hit,
|
|
1143
|
+
cx,
|
|
1144
|
+
cy,
|
|
1145
|
+
docX: rect.left + pageLeft,
|
|
1146
|
+
docY: rect.top + pageTop,
|
|
1147
|
+
width: rect.width,
|
|
1148
|
+
height: rect.height,
|
|
1149
|
+
tagName: t,
|
|
1150
|
+
role: rRole,
|
|
1151
|
+
isCustomCombobox: rRole === "combobox" && !(el instanceof HTMLSelectElement),
|
|
1152
|
+
ariaExpanded: el.getAttribute("aria-expanded") === "true"
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
lastReason = `Target obscured at (${Math.round(cx)}, ${Math.round(cy)}).`;
|
|
1156
|
+
} else {
|
|
1157
|
+
lastReason = "Target outside viewport.";
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
if (performance.now() >= deadline) {
|
|
1165
|
+
if (lastError instanceof CodedBridgeError) throw lastError;
|
|
1166
|
+
throw new CodedBridgeError("DRIVER_TIMEOUT", lastReason);
|
|
1167
|
+
}
|
|
1168
|
+
await sleepFrame(16, true);
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
function collectVisibleDialogs() {
|
|
1172
|
+
const out = /* @__PURE__ */ new Set();
|
|
1173
|
+
const { items } = scanLiveDom(false);
|
|
1174
|
+
for (const item of items) {
|
|
1175
|
+
if (item.fingerprint.role === "dialog" || item.fingerprint.role === "alertdialog") {
|
|
1176
|
+
out.add(item.target);
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
return out;
|
|
1180
|
+
}
|
|
1181
|
+
function readCompileOverlay() {
|
|
1182
|
+
if (!document.documentElement) return null;
|
|
1183
|
+
const skip = /* @__PURE__ */ new Set(["style", "script", "noscript", "template", "svg"]);
|
|
1184
|
+
function overlayText(n) {
|
|
1185
|
+
if (n.nodeType === 3) return n.nodeValue?.trim() ?? "";
|
|
1186
|
+
if (n instanceof Element && (n.hasAttribute(DRIVER_UI_ATTR) || n.hasAttribute("hidden") || n.getAttribute("aria-hidden") === "true" || skip.has(tag(n)))) {
|
|
1187
|
+
return "";
|
|
1188
|
+
}
|
|
1189
|
+
const joined = getComposedChildren(n).map(overlayText).filter(Boolean).join("\n");
|
|
1190
|
+
return joined ? joined.replace(/[ \t]+/g, " ").trim().slice(0, 2e3) : "";
|
|
1191
|
+
}
|
|
1192
|
+
function scan(n) {
|
|
1193
|
+
if (n instanceof Element) {
|
|
1194
|
+
if (n.hasAttribute(DRIVER_UI_ATTR) || n.hasAttribute("hidden")) return null;
|
|
1195
|
+
const t = tag(n);
|
|
1196
|
+
if (t === "vite-error-overlay" || t === "nextjs-portal" || n.hasAttribute("data-nextjs-dialog")) {
|
|
1197
|
+
const txt = overlayText(n);
|
|
1198
|
+
if (txt) return txt;
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
for (const c of getComposedChildren(n)) {
|
|
1202
|
+
const hit = scan(c);
|
|
1203
|
+
if (hit) return hit;
|
|
1204
|
+
}
|
|
1205
|
+
return null;
|
|
1206
|
+
}
|
|
1207
|
+
return scan(document.documentElement);
|
|
1208
|
+
}
|
|
1209
|
+
function isCrossDocUrl(rawHref) {
|
|
1210
|
+
if (!rawHref) return false;
|
|
1211
|
+
try {
|
|
1212
|
+
const next = new URL(rawHref, window.location.href);
|
|
1213
|
+
if (next.protocol !== "http:" && next.protocol !== "https:") return false;
|
|
1214
|
+
const loc = window.location;
|
|
1215
|
+
const sameHashOnly = next.origin === loc.origin && next.pathname === loc.pathname && next.search === loc.search && next.hash !== "";
|
|
1216
|
+
return !sameHashOnly;
|
|
1217
|
+
} catch {
|
|
1218
|
+
return false;
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
function armNavigationTracker(state2) {
|
|
1222
|
+
state2.detachNavTrackers?.();
|
|
1223
|
+
state2.pendingUnload = false;
|
|
1224
|
+
const onClick = (ev) => {
|
|
1225
|
+
if (ev.defaultPrevented || ev.button !== 0) return;
|
|
1226
|
+
const targetNode = ev.composedPath()[0];
|
|
1227
|
+
const startEl = targetNode instanceof Element ? targetNode : null;
|
|
1228
|
+
const anchor = findComposedAncestor(
|
|
1229
|
+
startEl,
|
|
1230
|
+
(c) => c instanceof HTMLAnchorElement && c.hasAttribute("href"),
|
|
1231
|
+
true
|
|
1232
|
+
);
|
|
1233
|
+
if (!anchor || anchor.hasAttribute("download")) return;
|
|
1234
|
+
const tgt = (anchor.getAttribute("target") ?? "").trim().toLowerCase();
|
|
1235
|
+
if (tgt && tgt !== "_self") return;
|
|
1236
|
+
if (isCrossDocUrl(anchor.getAttribute("href") ?? "")) {
|
|
1237
|
+
state2.pendingUnload = true;
|
|
1238
|
+
}
|
|
1239
|
+
};
|
|
1240
|
+
const onSubmit = (ev) => {
|
|
1241
|
+
if (!ev.defaultPrevented) {
|
|
1242
|
+
state2.pendingUnload = true;
|
|
1243
|
+
}
|
|
1244
|
+
};
|
|
1245
|
+
window.addEventListener("click", onClick, false);
|
|
1246
|
+
window.addEventListener("submit", onSubmit, false);
|
|
1247
|
+
state2.detachNavTrackers = () => {
|
|
1248
|
+
window.removeEventListener("click", onClick, false);
|
|
1249
|
+
window.removeEventListener("submit", onSubmit, false);
|
|
1250
|
+
state2.detachNavTrackers = null;
|
|
1251
|
+
};
|
|
1252
|
+
}
|
|
1253
|
+
function setReactSafeValue(el, value) {
|
|
1254
|
+
if (!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)) {
|
|
1255
|
+
return false;
|
|
1256
|
+
}
|
|
1257
|
+
const proto = el instanceof HTMLInputElement ? HTMLInputElement.prototype : HTMLTextAreaElement.prototype;
|
|
1258
|
+
const desc = Object.getOwnPropertyDescriptor(proto, "value");
|
|
1259
|
+
const prev = desc?.get ? desc.get.call(el) : el.value;
|
|
1260
|
+
const vt = Reflect.get(el, "_valueTracker");
|
|
1261
|
+
if (typeof vt === "object" && vt !== null) {
|
|
1262
|
+
const setVal = Reflect.get(vt, "setValue");
|
|
1263
|
+
if (typeof setVal === "function") {
|
|
1264
|
+
try {
|
|
1265
|
+
setVal.call(vt, prev);
|
|
1266
|
+
} catch {
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
if (desc?.set) desc.set.call(el, value);
|
|
1271
|
+
else el.value = value;
|
|
1272
|
+
return true;
|
|
1273
|
+
}
|
|
1274
|
+
function getOrCreateState() {
|
|
1275
|
+
const existingRaw = Reflect.get(window, BRIDGE_KEY);
|
|
1276
|
+
if (typeof existingRaw === "object" && existingRaw !== null && "callRpc" in existingRaw) {
|
|
1277
|
+
return existingRaw;
|
|
1278
|
+
}
|
|
1279
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1280
|
+
const state2 = {
|
|
1281
|
+
sessionId: "",
|
|
1282
|
+
allowEval: false,
|
|
1283
|
+
nextId: 1,
|
|
1284
|
+
port: null,
|
|
1285
|
+
refs: /* @__PURE__ */ new Map(),
|
|
1286
|
+
lastTargetEl: null,
|
|
1287
|
+
dialogsBefore: /* @__PURE__ */ new Set(),
|
|
1288
|
+
pendingUnload: false,
|
|
1289
|
+
detachNavTrackers: null,
|
|
1290
|
+
async ensurePort(sessionId, allowEval, minRev) {
|
|
1291
|
+
if (this.port !== null && this.sessionId === sessionId && this.allowEval === allowEval) {
|
|
1292
|
+
if (minRev > 0) {
|
|
1293
|
+
this.port.postMessage({
|
|
1294
|
+
channel: CHANNEL,
|
|
1295
|
+
kind: "hello",
|
|
1296
|
+
protocolVersion: 1,
|
|
1297
|
+
allowEval,
|
|
1298
|
+
sessionId,
|
|
1299
|
+
minRev
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
return this.port;
|
|
1303
|
+
}
|
|
1304
|
+
const channel = new MessageChannel();
|
|
1305
|
+
const port = channel.port1;
|
|
1306
|
+
let ackResolve = null;
|
|
1307
|
+
const ackPromise = new Promise((resolve) => {
|
|
1308
|
+
ackResolve = resolve;
|
|
1309
|
+
});
|
|
1310
|
+
port.addEventListener("message", (ev) => {
|
|
1311
|
+
const d = ev.data;
|
|
1312
|
+
if (typeof d !== "object" || d === null) return;
|
|
1313
|
+
const rec = d;
|
|
1314
|
+
if (rec["channel"] !== CHANNEL) return;
|
|
1315
|
+
if (rec["kind"] === "hello_ack") {
|
|
1316
|
+
ackResolve?.();
|
|
1317
|
+
ackResolve = null;
|
|
1318
|
+
return;
|
|
1319
|
+
}
|
|
1320
|
+
if (rec["kind"] === "rpc_response" && typeof rec["id"] === "number") {
|
|
1321
|
+
const fn = pending.get(rec["id"]);
|
|
1322
|
+
if (fn !== void 0) {
|
|
1323
|
+
pending.delete(rec["id"]);
|
|
1324
|
+
fn(rec);
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
});
|
|
1328
|
+
port.start();
|
|
1329
|
+
window.postMessage(
|
|
1330
|
+
{
|
|
1331
|
+
channel: CHANNEL,
|
|
1332
|
+
kind: "hello",
|
|
1333
|
+
protocolVersion: 1,
|
|
1334
|
+
allowEval,
|
|
1335
|
+
sessionId,
|
|
1336
|
+
minRev
|
|
1337
|
+
},
|
|
1338
|
+
"*",
|
|
1339
|
+
[channel.port2]
|
|
1340
|
+
);
|
|
1341
|
+
await ackPromise;
|
|
1342
|
+
this.port = port;
|
|
1343
|
+
this.sessionId = sessionId;
|
|
1344
|
+
this.allowEval = allowEval;
|
|
1345
|
+
return port;
|
|
1346
|
+
},
|
|
1347
|
+
async callRpc(sessionId, allowEval, minRev, method, params) {
|
|
1348
|
+
const port = await this.ensurePort(sessionId, allowEval, minRev);
|
|
1349
|
+
const id = this.nextId;
|
|
1350
|
+
this.nextId += 1;
|
|
1351
|
+
const response = await new Promise((resolve) => {
|
|
1352
|
+
pending.set(id, resolve);
|
|
1353
|
+
port.postMessage({
|
|
1354
|
+
channel: CHANNEL,
|
|
1355
|
+
kind: "rpc_request",
|
|
1356
|
+
protocolVersion: 1,
|
|
1357
|
+
id,
|
|
1358
|
+
method,
|
|
1359
|
+
...params !== void 0 ? { params } : {}
|
|
1360
|
+
});
|
|
1361
|
+
});
|
|
1362
|
+
if (method === "observe" && typeof response === "object" && response !== null && response["ok"] === true) {
|
|
1363
|
+
this.indexSnapshot(response["result"]);
|
|
1364
|
+
}
|
|
1365
|
+
return response;
|
|
1366
|
+
},
|
|
1367
|
+
indexSnapshot(snap) {
|
|
1368
|
+
if (typeof snap !== "object" || snap === null) return;
|
|
1369
|
+
const elementsRaw = snap["elements"];
|
|
1370
|
+
if (!Array.isArray(elementsRaw)) return;
|
|
1371
|
+
const { items, cohortCounts } = scanLiveDom(false);
|
|
1372
|
+
const byTuple = /* @__PURE__ */ new Map();
|
|
1373
|
+
for (const item of items) {
|
|
1374
|
+
const fp = item.fingerprint;
|
|
1375
|
+
byTuple.set(
|
|
1376
|
+
`${fp.role}\0${fp.name}\0${fp.landmark ?? ""}\0${fp.driverId ?? ""}\0${String(fp.nth)}`,
|
|
1377
|
+
item
|
|
1378
|
+
);
|
|
1379
|
+
}
|
|
1380
|
+
const localCounts = /* @__PURE__ */ new Map();
|
|
1381
|
+
const walkSnap = (nodes, enclosingLm) => {
|
|
1382
|
+
for (const rawNode of nodes) {
|
|
1383
|
+
if (typeof rawNode !== "object" || rawNode === null) continue;
|
|
1384
|
+
const n = rawNode;
|
|
1385
|
+
const role = typeof n["role"] === "string" ? n["role"] : "";
|
|
1386
|
+
const name = typeof n["name"] === "string" ? n["name"] : "";
|
|
1387
|
+
const drv = typeof n["driverId"] === "string" ? n["driverId"] : "";
|
|
1388
|
+
const ref = typeof n["ref"] === "string" ? n["ref"] : void 0;
|
|
1389
|
+
if (ref !== void 0 && role) {
|
|
1390
|
+
const cKey = `${role}\0${name}\0${enclosingLm ?? ""}\0${drv}`;
|
|
1391
|
+
const nth = localCounts.get(cKey) ?? 0;
|
|
1392
|
+
localCounts.set(cKey, nth + 1);
|
|
1393
|
+
const exactCand = byTuple.get(`${cKey}\0${String(nth)}`) ?? items.find(
|
|
1394
|
+
(it) => it.fingerprint.role === role && it.fingerprint.name === name && (it.fingerprint.driverId ?? "") === drv && it.fingerprint.nth === nth
|
|
1395
|
+
);
|
|
1396
|
+
if (exactCand !== void 0) {
|
|
1397
|
+
const fp = exactCand.fingerprint;
|
|
1398
|
+
const cohortKey = `${fp.role}\0${fp.name}\0${fp.landmark ?? ""}\0${fp.driverId ?? ""}`;
|
|
1399
|
+
this.refs.set(ref, {
|
|
1400
|
+
weakEl: new WeakRef(exactCand.target),
|
|
1401
|
+
fingerprint: fp,
|
|
1402
|
+
cohortSize: cohortCounts.get(cohortKey) ?? 1
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
const nextLm = LANDMARK_ROLES.has(role) ? formatLm(role, name) : enclosingLm;
|
|
1407
|
+
if (Array.isArray(n["children"])) {
|
|
1408
|
+
walkSnap(n["children"], nextLm);
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
};
|
|
1412
|
+
walkSnap(elementsRaw, void 0);
|
|
1413
|
+
}
|
|
1414
|
+
};
|
|
1415
|
+
window.addEventListener("pagehide", () => {
|
|
1416
|
+
if (state2.port !== null) {
|
|
1417
|
+
state2.port.close();
|
|
1418
|
+
state2.port = null;
|
|
1419
|
+
}
|
|
1420
|
+
});
|
|
1421
|
+
Reflect.defineProperty(window, BRIDGE_KEY, {
|
|
1422
|
+
value: state2,
|
|
1423
|
+
configurable: true,
|
|
1424
|
+
enumerable: false,
|
|
1425
|
+
writable: true
|
|
1426
|
+
});
|
|
1427
|
+
return state2;
|
|
1428
|
+
}
|
|
1429
|
+
const state = getOrCreateState();
|
|
1430
|
+
try {
|
|
1431
|
+
switch (cmd.op) {
|
|
1432
|
+
case "rpc": {
|
|
1433
|
+
return await state.callRpc(
|
|
1434
|
+
cmd.sessionId,
|
|
1435
|
+
cmd.allowEval,
|
|
1436
|
+
cmd.minRev,
|
|
1437
|
+
cmd.method,
|
|
1438
|
+
cmd.params
|
|
1439
|
+
);
|
|
1440
|
+
}
|
|
1441
|
+
case "recordDialogsBefore": {
|
|
1442
|
+
state.dialogsBefore = collectVisibleDialogs();
|
|
1443
|
+
return { ok: true, result: null };
|
|
1444
|
+
}
|
|
1445
|
+
case "prepareActionTarget": {
|
|
1446
|
+
if (cmd.recordDialogsBefore) state.dialogsBefore = collectVisibleDialogs();
|
|
1447
|
+
const found = await waitForActionable(
|
|
1448
|
+
cmd.target,
|
|
1449
|
+
cmd.timeoutMs,
|
|
1450
|
+
state,
|
|
1451
|
+
cmd.allowZeroSizeAudio
|
|
1452
|
+
);
|
|
1453
|
+
state.lastTargetEl = found.el;
|
|
1454
|
+
if (cmd.armNavTracker) armNavigationTracker(state);
|
|
1455
|
+
const { el: _el, hitEl: _hit, ...clean } = found;
|
|
1456
|
+
void _el;
|
|
1457
|
+
void _hit;
|
|
1458
|
+
return { ok: true, result: clean };
|
|
1459
|
+
}
|
|
1460
|
+
case "prepareFill": {
|
|
1461
|
+
if (cmd.recordDialogsBefore) state.dialogsBefore = collectVisibleDialogs();
|
|
1462
|
+
const found = await waitForActionable(cmd.target, cmd.timeoutMs, state, false);
|
|
1463
|
+
const el = found.el;
|
|
1464
|
+
const ce = el.getAttribute("contenteditable");
|
|
1465
|
+
const isCe = ce === "" || ce?.toLowerCase() === "true" || el instanceof HTMLElement && el.isContentEditable;
|
|
1466
|
+
const nonTextInput = el instanceof HTMLInputElement && (/* @__PURE__ */ new Set(["button", "submit", "reset", "checkbox", "radio", "range", "file", "image"])).has(
|
|
1467
|
+
el.type.toLowerCase()
|
|
1468
|
+
);
|
|
1469
|
+
const isTextCtrl = el instanceof HTMLInputElement && !nonTextInput || el instanceof HTMLTextAreaElement;
|
|
1470
|
+
if (!isTextCtrl && !isCe) {
|
|
1471
|
+
throw new CodedBridgeError("DRIVER_PROTOCOL", `Target <${tag(el)}> is not fillable.`);
|
|
1472
|
+
}
|
|
1473
|
+
state.lastTargetEl = el;
|
|
1474
|
+
if (el instanceof HTMLElement) el.focus({ preventScroll: true });
|
|
1475
|
+
let hadContent = false;
|
|
1476
|
+
if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
|
|
1477
|
+
hadContent = el.value.length > 0;
|
|
1478
|
+
try {
|
|
1479
|
+
el.select();
|
|
1480
|
+
} catch {
|
|
1481
|
+
}
|
|
1482
|
+
if (hadContent && el.selectionStart === null) {
|
|
1483
|
+
setReactSafeValue(el, "");
|
|
1484
|
+
hadContent = false;
|
|
1485
|
+
}
|
|
1486
|
+
} else if (isCe) {
|
|
1487
|
+
hadContent = (el.textContent ?? "").length > 0;
|
|
1488
|
+
const sel = window.getSelection();
|
|
1489
|
+
if (sel) {
|
|
1490
|
+
sel.selectAllChildren(el);
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
const result = { cx: found.cx, cy: found.cy, hadContent };
|
|
1494
|
+
return { ok: true, result };
|
|
1495
|
+
}
|
|
1496
|
+
case "finalizeFill": {
|
|
1497
|
+
const el = state.lastTargetEl;
|
|
1498
|
+
if (el && el.isConnected) {
|
|
1499
|
+
const ce = el.getAttribute("contenteditable");
|
|
1500
|
+
const isCe = ce === "" || ce?.toLowerCase() === "true" || el instanceof HTMLElement && el.isContentEditable;
|
|
1501
|
+
if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
|
|
1502
|
+
if (el.value !== cmd.value) {
|
|
1503
|
+
setReactSafeValue(el, cmd.value);
|
|
1504
|
+
el.dispatchEvent(
|
|
1505
|
+
new InputEvent("input", {
|
|
1506
|
+
bubbles: true,
|
|
1507
|
+
composed: true,
|
|
1508
|
+
data: cmd.value,
|
|
1509
|
+
inputType: "insertText"
|
|
1510
|
+
})
|
|
1511
|
+
);
|
|
1512
|
+
}
|
|
1513
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
1514
|
+
} else if (isCe && (el.textContent ?? "") !== cmd.value) {
|
|
1515
|
+
el.textContent = cmd.value;
|
|
1516
|
+
el.dispatchEvent(
|
|
1517
|
+
new InputEvent("input", {
|
|
1518
|
+
bubbles: true,
|
|
1519
|
+
composed: true,
|
|
1520
|
+
data: cmd.value,
|
|
1521
|
+
inputType: "insertText"
|
|
1522
|
+
})
|
|
1523
|
+
);
|
|
1524
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
1525
|
+
}
|
|
1526
|
+
if (cmd.submit) {
|
|
1527
|
+
armNavigationTracker(state);
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
return { ok: true, result: null };
|
|
1531
|
+
}
|
|
1532
|
+
case "executeSetValue": {
|
|
1533
|
+
if (cmd.recordDialogsBefore) state.dialogsBefore = collectVisibleDialogs();
|
|
1534
|
+
const found = await waitForActionable(cmd.target, cmd.timeoutMs, state, true);
|
|
1535
|
+
const el = found.el;
|
|
1536
|
+
if (el instanceof HTMLMediaElement) {
|
|
1537
|
+
const nextTime = Number(cmd.value);
|
|
1538
|
+
if (!Number.isFinite(nextTime) || nextTime < 0) {
|
|
1539
|
+
throw new CodedBridgeError(
|
|
1540
|
+
"DRIVER_PROTOCOL",
|
|
1541
|
+
`Invalid media currentTime '${String(cmd.value)}'.`
|
|
1542
|
+
);
|
|
1543
|
+
}
|
|
1544
|
+
el.currentTime = nextTime;
|
|
1545
|
+
el.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
|
|
1546
|
+
el.dispatchEvent(new Event("timeupdate"));
|
|
1547
|
+
el.dispatchEvent(new Event("seeked"));
|
|
1548
|
+
return { ok: true, result: null };
|
|
1549
|
+
}
|
|
1550
|
+
const strVal = String(cmd.value);
|
|
1551
|
+
if (el instanceof HTMLElement) el.focus({ preventScroll: true });
|
|
1552
|
+
if (!setReactSafeValue(el, strVal)) {
|
|
1553
|
+
el.setAttribute("aria-valuenow", strVal);
|
|
1554
|
+
}
|
|
1555
|
+
el.dispatchEvent(
|
|
1556
|
+
new InputEvent("input", {
|
|
1557
|
+
bubbles: true,
|
|
1558
|
+
composed: true,
|
|
1559
|
+
data: strVal,
|
|
1560
|
+
inputType: "insertReplacementText"
|
|
1561
|
+
})
|
|
1562
|
+
);
|
|
1563
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
1564
|
+
return { ok: true, result: null };
|
|
1565
|
+
}
|
|
1566
|
+
case "prepareSelect": {
|
|
1567
|
+
if (cmd.recordDialogsBefore) state.dialogsBefore = collectVisibleDialogs();
|
|
1568
|
+
if (cmd.phase === "initial") {
|
|
1569
|
+
const found = await waitForActionable(cmd.target, cmd.timeoutMs, state, false);
|
|
1570
|
+
const el = found.el;
|
|
1571
|
+
state.lastTargetEl = el;
|
|
1572
|
+
if (el instanceof HTMLSelectElement) {
|
|
1573
|
+
el.focus({ preventScroll: true });
|
|
1574
|
+
const opts = Array.from(el.options);
|
|
1575
|
+
const matched = cmd.values.map((val) => {
|
|
1576
|
+
const trimmed = normSpace(val);
|
|
1577
|
+
const opt = opts.find(
|
|
1578
|
+
(o) => o.value === val || normSpace(o.label || o.text) === trimmed
|
|
1579
|
+
);
|
|
1580
|
+
if (!opt) {
|
|
1581
|
+
throw new CodedBridgeError("DRIVER_TARGET_NOT_FOUND", `Option "${val}" not found.`);
|
|
1582
|
+
}
|
|
1583
|
+
if (opt.disabled) {
|
|
1584
|
+
throw new CodedBridgeError("DRIVER_PROTOCOL", `Option "${val}" is disabled.`);
|
|
1585
|
+
}
|
|
1586
|
+
return opt;
|
|
1587
|
+
});
|
|
1588
|
+
if (el.multiple) {
|
|
1589
|
+
const set = new Set(matched);
|
|
1590
|
+
for (const o of opts) o.selected = set.has(o);
|
|
1591
|
+
} else if (matched[0]) {
|
|
1592
|
+
el.value = matched[0].value;
|
|
1593
|
+
matched[0].selected = true;
|
|
1594
|
+
}
|
|
1595
|
+
el.dispatchEvent(new InputEvent("input", { bubbles: true, composed: true }));
|
|
1596
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
1597
|
+
const res2 = {
|
|
1598
|
+
kind: "native",
|
|
1599
|
+
needsOpenClick: false,
|
|
1600
|
+
comboCx: found.cx,
|
|
1601
|
+
comboCy: found.cy,
|
|
1602
|
+
optionPoints: []
|
|
1603
|
+
};
|
|
1604
|
+
return { ok: true, result: res2 };
|
|
1605
|
+
}
|
|
1606
|
+
if (found.isCustomCombobox && !found.ariaExpanded) {
|
|
1607
|
+
const res2 = {
|
|
1608
|
+
kind: "custom",
|
|
1609
|
+
needsOpenClick: true,
|
|
1610
|
+
comboCx: found.cx,
|
|
1611
|
+
comboCy: found.cy,
|
|
1612
|
+
optionPoints: []
|
|
1613
|
+
};
|
|
1614
|
+
return { ok: true, result: res2 };
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
await sleepFrame(16, true);
|
|
1618
|
+
const { items } = scanLiveDom(true);
|
|
1619
|
+
const points = [];
|
|
1620
|
+
for (const val of cmd.values) {
|
|
1621
|
+
const trimmed = normSpace(val);
|
|
1622
|
+
const match = items.find(
|
|
1623
|
+
(c) => c.fingerprint.role === "option" && (c.fingerprint.name === trimmed || c.text === trimmed || c.target.getAttribute("data-value") === val || c.target.getAttribute("value") === val)
|
|
1624
|
+
);
|
|
1625
|
+
if (!match) {
|
|
1626
|
+
throw new CodedBridgeError("DRIVER_TARGET_NOT_FOUND", `Option "${val}" not found.`);
|
|
1627
|
+
}
|
|
1628
|
+
if (isElementDisabled(match.target)) {
|
|
1629
|
+
throw new CodedBridgeError("DRIVER_PROTOCOL", `Option "${val}" is disabled.`);
|
|
1630
|
+
}
|
|
1631
|
+
match.target.scrollIntoView({ block: "nearest", inline: "nearest" });
|
|
1632
|
+
const r = match.target.getBoundingClientRect();
|
|
1633
|
+
points.push({ cx: r.left + r.width / 2, cy: r.top + r.height / 2 });
|
|
1634
|
+
}
|
|
1635
|
+
const res = {
|
|
1636
|
+
kind: "custom",
|
|
1637
|
+
needsOpenClick: false,
|
|
1638
|
+
comboCx: 0,
|
|
1639
|
+
comboCy: 0,
|
|
1640
|
+
optionPoints: points
|
|
1641
|
+
};
|
|
1642
|
+
return { ok: true, result: res };
|
|
1643
|
+
}
|
|
1644
|
+
case "preparePress": {
|
|
1645
|
+
if (cmd.recordDialogsBefore) state.dialogsBefore = collectVisibleDialogs();
|
|
1646
|
+
if (cmd.target !== void 0) {
|
|
1647
|
+
const found = await waitForActionable(cmd.target, cmd.timeoutMs, state, false);
|
|
1648
|
+
if (found.el instanceof HTMLElement) found.el.focus({ preventScroll: true });
|
|
1649
|
+
state.lastTargetEl = found.el;
|
|
1650
|
+
}
|
|
1651
|
+
armNavigationTracker(state);
|
|
1652
|
+
return { ok: true, result: null };
|
|
1653
|
+
}
|
|
1654
|
+
case "executeWaitFor": {
|
|
1655
|
+
if (cmd.recordDialogsBefore) state.dialogsBefore = collectVisibleDialogs();
|
|
1656
|
+
const deadline = performance.now() + cmd.timeoutMs;
|
|
1657
|
+
const desired = cmd.state ?? "visible";
|
|
1658
|
+
const needle = cmd.text !== void 0 ? normSpace(cmd.text).toLowerCase() : void 0;
|
|
1659
|
+
let lastActivity = performance.now();
|
|
1660
|
+
let observer = null;
|
|
1661
|
+
if (cmd.idleMs !== void 0 && document.documentElement) {
|
|
1662
|
+
observer = new MutationObserver((records) => {
|
|
1663
|
+
const onlyDriver = records.every((m) => {
|
|
1664
|
+
const el = m.target instanceof Element ? m.target : m.target instanceof ShadowRoot ? m.target.host : m.target.parentElement;
|
|
1665
|
+
return findComposedAncestor(el, (c) => c.hasAttribute(DRIVER_UI_ATTR), true) !== null;
|
|
1666
|
+
});
|
|
1667
|
+
if (!onlyDriver) lastActivity = performance.now();
|
|
1668
|
+
});
|
|
1669
|
+
observer.observe(document.documentElement, {
|
|
1670
|
+
subtree: true,
|
|
1671
|
+
childList: true,
|
|
1672
|
+
attributes: true,
|
|
1673
|
+
characterData: true
|
|
1674
|
+
});
|
|
1675
|
+
}
|
|
1676
|
+
const checkTarget = (spec) => {
|
|
1677
|
+
let el;
|
|
1678
|
+
try {
|
|
1679
|
+
el = resolveTarget(spec, state);
|
|
1680
|
+
} catch (err) {
|
|
1681
|
+
return (desired === "detached" || desired === "hidden") && err instanceof CodedBridgeError && err.code === "DRIVER_TARGET_NOT_FOUND";
|
|
1682
|
+
}
|
|
1683
|
+
if (desired === "detached") return false;
|
|
1684
|
+
if (desired === "attached") return el.isConnected;
|
|
1685
|
+
const r = el.getBoundingClientRect();
|
|
1686
|
+
const vis = el.isConnected && !isElementHidden(el) && (tag(el) === "audio" || r.width > 0 && r.height > 0);
|
|
1687
|
+
return desired === "visible" ? vis : !vis;
|
|
1688
|
+
};
|
|
1689
|
+
try {
|
|
1690
|
+
while (true) {
|
|
1691
|
+
const targetOk = cmd.target === void 0 || checkTarget(cmd.target);
|
|
1692
|
+
const present = needle === void 0 || !needle || scanLiveDom(true).items.some(
|
|
1693
|
+
(c) => c.text.toLowerCase().includes(needle) || c.fingerprint.name.toLowerCase().includes(needle)
|
|
1694
|
+
);
|
|
1695
|
+
const textOk = needle === void 0 || (desired === "hidden" || desired === "detached" ? !present : present);
|
|
1696
|
+
const idleOk = cmd.idleMs === void 0 || performance.now() - lastActivity >= cmd.idleMs;
|
|
1697
|
+
if (targetOk && textOk && idleOk) {
|
|
1698
|
+
return { ok: true, result: null };
|
|
1699
|
+
}
|
|
1700
|
+
if (performance.now() >= deadline) {
|
|
1701
|
+
break;
|
|
1702
|
+
}
|
|
1703
|
+
await sleepFrame(Math.min(20, Math.max(4, deadline - performance.now())), false);
|
|
1704
|
+
}
|
|
1705
|
+
} finally {
|
|
1706
|
+
observer?.disconnect();
|
|
1707
|
+
}
|
|
1708
|
+
throw new CodedBridgeError("DRIVER_TIMEOUT", "waitFor condition timed out.");
|
|
1709
|
+
}
|
|
1710
|
+
case "settleAndInspect": {
|
|
1711
|
+
state.detachNavTrackers?.();
|
|
1712
|
+
const pendingUnload = state.pendingUnload;
|
|
1713
|
+
state.pendingUnload = false;
|
|
1714
|
+
if (!pendingUnload) {
|
|
1715
|
+
await sleepFrame(0, false);
|
|
1716
|
+
await sleepFrame(16, true);
|
|
1717
|
+
}
|
|
1718
|
+
const currentDialogs = collectVisibleDialogs();
|
|
1719
|
+
let newDomDialogOpened = false;
|
|
1720
|
+
for (const d of currentDialogs) {
|
|
1721
|
+
if (!state.dialogsBefore.has(d)) {
|
|
1722
|
+
newDomDialogOpened = true;
|
|
1723
|
+
break;
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
const res = {
|
|
1727
|
+
pendingUnload,
|
|
1728
|
+
compileOverlay: readCompileOverlay(),
|
|
1729
|
+
newDomDialogOpened
|
|
1730
|
+
};
|
|
1731
|
+
return { ok: true, result: res };
|
|
1732
|
+
}
|
|
1733
|
+
case "resolveScreenshotClip": {
|
|
1734
|
+
const vw = Math.max(1, Math.round(window.innerWidth || 800));
|
|
1735
|
+
const vh = Math.max(1, Math.round(window.innerHeight || 600));
|
|
1736
|
+
if (cmd.target === void 0) {
|
|
1737
|
+
return { ok: true, result: { viewportWidth: vw, viewportHeight: vh, clip: null } };
|
|
1738
|
+
}
|
|
1739
|
+
const el = resolveTarget(cmd.target, state);
|
|
1740
|
+
let rect = el.getBoundingClientRect();
|
|
1741
|
+
if (rect.width <= 0 || rect.height <= 0) {
|
|
1742
|
+
throw new CodedBridgeError("DRIVER_PROTOCOL", "Capture target has zero area.");
|
|
1743
|
+
}
|
|
1744
|
+
if (rect.bottom <= 0 || rect.top >= window.innerHeight || rect.right <= 0 || rect.left >= window.innerWidth) {
|
|
1745
|
+
el.scrollIntoView({ block: "nearest", inline: "nearest" });
|
|
1746
|
+
rect = el.getBoundingClientRect();
|
|
1747
|
+
}
|
|
1748
|
+
const pageLeft = window.visualViewport?.pageLeft ?? window.scrollX;
|
|
1749
|
+
const pageTop = window.visualViewport?.pageTop ?? window.scrollY;
|
|
1750
|
+
return {
|
|
1751
|
+
ok: true,
|
|
1752
|
+
result: {
|
|
1753
|
+
viewportWidth: vw,
|
|
1754
|
+
viewportHeight: vh,
|
|
1755
|
+
clip: {
|
|
1756
|
+
x: Math.max(0, rect.left + pageLeft),
|
|
1757
|
+
y: Math.max(0, rect.top + pageTop),
|
|
1758
|
+
width: rect.width,
|
|
1759
|
+
height: rect.height
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
};
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
} catch (err) {
|
|
1766
|
+
if (err instanceof CodedBridgeError) {
|
|
1767
|
+
return {
|
|
1768
|
+
ok: false,
|
|
1769
|
+
error: {
|
|
1770
|
+
code: err.code,
|
|
1771
|
+
message: err.message,
|
|
1772
|
+
...err.candidates !== void 0 ? { candidates: err.candidates } : {}
|
|
1773
|
+
}
|
|
1774
|
+
};
|
|
1775
|
+
}
|
|
1776
|
+
return {
|
|
1777
|
+
ok: false,
|
|
1778
|
+
error: {
|
|
1779
|
+
code: "DRIVER_PROTOCOL",
|
|
1780
|
+
message: err instanceof Error ? err.message : String(err)
|
|
1781
|
+
}
|
|
1782
|
+
};
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
async function ensurePreloadInCurrentPage(page, preloadSource) {
|
|
1786
|
+
const alreadyInstalled = await page.evaluate(() => {
|
|
1787
|
+
return Reflect.has(window, Symbol.for("@inbrowser/driver:preload-installed:v1"));
|
|
1788
|
+
});
|
|
1789
|
+
if (!alreadyInstalled) {
|
|
1790
|
+
await page.evaluate(preloadSource);
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
async function runBridgeCommand(page, preloadSource, cmd) {
|
|
1794
|
+
await ensurePreloadInCurrentPage(page, preloadSource);
|
|
1795
|
+
const raw = await page.evaluate(executeInPageBridgeCommand, cmd);
|
|
1796
|
+
return unwrapBridgeEnvelope(raw);
|
|
1797
|
+
}
|
|
1798
|
+
var MODIFIER_MAP = {
|
|
1799
|
+
control: "Control",
|
|
1800
|
+
ctrl: "Control",
|
|
1801
|
+
shift: "Shift",
|
|
1802
|
+
alt: "Alt",
|
|
1803
|
+
option: "Alt",
|
|
1804
|
+
meta: "Meta",
|
|
1805
|
+
command: "Meta",
|
|
1806
|
+
cmd: "Meta"
|
|
1807
|
+
};
|
|
1808
|
+
var SPECIAL_KEY_MAP = {
|
|
1809
|
+
space: "Space",
|
|
1810
|
+
esc: "Escape",
|
|
1811
|
+
escape: "Escape",
|
|
1812
|
+
enter: "Enter",
|
|
1813
|
+
tab: "Tab",
|
|
1814
|
+
backspace: "Backspace",
|
|
1815
|
+
delete: "Delete",
|
|
1816
|
+
arrowup: "ArrowUp",
|
|
1817
|
+
arrowdown: "ArrowDown",
|
|
1818
|
+
arrowleft: "ArrowLeft",
|
|
1819
|
+
arrowright: "ArrowRight",
|
|
1820
|
+
home: "Home",
|
|
1821
|
+
end: "End",
|
|
1822
|
+
pageup: "PageUp",
|
|
1823
|
+
pagedown: "PageDown"
|
|
1824
|
+
};
|
|
1825
|
+
function parseKeyChord(rawKey) {
|
|
1826
|
+
if (rawKey === " ") {
|
|
1827
|
+
return { modifiers: [], mainKey: "Space" };
|
|
1828
|
+
}
|
|
1829
|
+
const parts = rawKey === "+" ? ["+"] : rawKey.split("+").filter(Boolean);
|
|
1830
|
+
const modifiers = [];
|
|
1831
|
+
for (let i = 0; i < parts.length - 1; i += 1) {
|
|
1832
|
+
const mod = MODIFIER_MAP[(parts[i] ?? "").trim().toLowerCase()];
|
|
1833
|
+
if (mod !== void 0) {
|
|
1834
|
+
modifiers.push(mod);
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
const last = (parts[parts.length - 1] ?? rawKey).trim();
|
|
1838
|
+
const special = SPECIAL_KEY_MAP[last.toLowerCase()];
|
|
1839
|
+
if (special !== void 0) {
|
|
1840
|
+
return { modifiers, mainKey: special };
|
|
1841
|
+
}
|
|
1842
|
+
if (last.length === 1 && /^[a-z]$/i.test(last)) {
|
|
1843
|
+
const hasShift = modifiers.includes("Shift");
|
|
1844
|
+
const charKey = hasShift ? last.toUpperCase() : last.toLowerCase();
|
|
1845
|
+
return { modifiers, mainKey: charKey };
|
|
1846
|
+
}
|
|
1847
|
+
return {
|
|
1848
|
+
modifiers,
|
|
1849
|
+
mainKey: last
|
|
1850
|
+
// Invariant: caller-provided DOM key name forwarded to CDP Input.dispatchKeyEvent
|
|
1851
|
+
};
|
|
1852
|
+
}
|
|
1853
|
+
function mergeDiagnosticsWithHost(base, extraConsoleErrors) {
|
|
1854
|
+
if (extraConsoleErrors.length === 0) return base;
|
|
1855
|
+
const merged = [...base.consoleErrors];
|
|
1856
|
+
for (const msg of extraConsoleErrors) {
|
|
1857
|
+
if (!merged.includes(msg)) {
|
|
1858
|
+
merged.push(msg);
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1861
|
+
return {
|
|
1862
|
+
compileOverlay: base.compileOverlay,
|
|
1863
|
+
consoleErrors: merged,
|
|
1864
|
+
pageErrors: base.pageErrors,
|
|
1865
|
+
networkFailures: base.networkFailures
|
|
1866
|
+
};
|
|
1867
|
+
}
|
|
1868
|
+
function stripObserveOptions(options) {
|
|
1869
|
+
if (options === void 0) return void 0;
|
|
1870
|
+
return {
|
|
1871
|
+
...options.scope !== void 0 ? { scope: options.scope } : {},
|
|
1872
|
+
...options.includeAllText !== void 0 ? { includeAllText: options.includeAllText } : {}
|
|
1873
|
+
};
|
|
1874
|
+
}
|
|
1875
|
+
async function connectPuppeteerDriver(options) {
|
|
1876
|
+
const defaultTimeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1877
|
+
if (options.signal?.aborted) {
|
|
1878
|
+
throw new DriverError("DRIVER_TIMEOUT", "Puppeteer driver connection aborted by signal.", {
|
|
1879
|
+
cause: options.signal.reason
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
if (options.browserWSEndpoint === void 0 && options.transport === void 0) {
|
|
1883
|
+
throw new DriverError(
|
|
1884
|
+
"DRIVER_PROTOCOL",
|
|
1885
|
+
"connectPuppeteerDriver requires either browserWSEndpoint or transport."
|
|
1886
|
+
);
|
|
1887
|
+
}
|
|
1888
|
+
const preloadSource = getPreloadSource();
|
|
1889
|
+
const connectOptions = {
|
|
1890
|
+
defaultViewport: null,
|
|
1891
|
+
...options.browserWSEndpoint !== void 0 ? { browserWSEndpoint: options.browserWSEndpoint } : {},
|
|
1892
|
+
...options.transport !== void 0 ? { transport: options.transport } : {},
|
|
1893
|
+
...options.timeoutMs !== void 0 ? { protocolTimeout: options.timeoutMs } : {}
|
|
1894
|
+
};
|
|
1895
|
+
let browserInstance = null;
|
|
1896
|
+
const browser = await raceWithAbortAndTimeout(
|
|
1897
|
+
async () => {
|
|
1898
|
+
const connected = await connect(connectOptions);
|
|
1899
|
+
browserInstance = connected;
|
|
1900
|
+
return connected;
|
|
1901
|
+
},
|
|
1902
|
+
defaultTimeoutMs,
|
|
1903
|
+
"connect",
|
|
1904
|
+
options.signal
|
|
1905
|
+
).catch(async (err) => {
|
|
1906
|
+
if (browserInstance !== null) {
|
|
1907
|
+
await browserInstance.disconnect().catch(() => {
|
|
1908
|
+
});
|
|
1909
|
+
}
|
|
1910
|
+
throw err;
|
|
1911
|
+
});
|
|
1912
|
+
let page;
|
|
1913
|
+
try {
|
|
1914
|
+
const resolved = await raceWithAbortAndTimeout(
|
|
1915
|
+
() => resolveTargetPage(browser, options.targetUrl, preloadSource, defaultTimeoutMs),
|
|
1916
|
+
defaultTimeoutMs,
|
|
1917
|
+
"resolveTargetPage",
|
|
1918
|
+
options.signal
|
|
1919
|
+
);
|
|
1920
|
+
page = resolved.page;
|
|
1921
|
+
if (!resolved.preloadRegisteredOnNewDoc) {
|
|
1922
|
+
await page.evaluateOnNewDocument(preloadSource);
|
|
1923
|
+
}
|
|
1924
|
+
await ensurePreloadInCurrentPage(page, preloadSource);
|
|
1925
|
+
} catch (err) {
|
|
1926
|
+
await browser.disconnect().catch(() => {
|
|
1927
|
+
});
|
|
1928
|
+
throw toDriverError(err, "Failed to initialize target page.");
|
|
1929
|
+
}
|
|
1930
|
+
const allowEval = Boolean(options.allowEval);
|
|
1931
|
+
const sessionId = `cdp-${String(nextCdpSessionSeq)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
1932
|
+
nextCdpSessionSeq += 1;
|
|
1933
|
+
let highestRev = 0;
|
|
1934
|
+
let lastFullSnapshot = null;
|
|
1935
|
+
let disposed = false;
|
|
1936
|
+
let pendingHostConsoleErrors = [];
|
|
1937
|
+
let activeActGuard = null;
|
|
1938
|
+
let activeRecording = null;
|
|
1939
|
+
const drainHostConsoleErrors = () => {
|
|
1940
|
+
const drained = pendingHostConsoleErrors;
|
|
1941
|
+
pendingHostConsoleErrors = [];
|
|
1942
|
+
return drained;
|
|
1943
|
+
};
|
|
1944
|
+
const onDialog = (dialog) => {
|
|
1945
|
+
const kind = dialog.type();
|
|
1946
|
+
const text = dialog.message();
|
|
1947
|
+
const formatted = (text ? `[dialog:${kind}] ${text}` : `[dialog:${kind}]`).slice(0, 1e3);
|
|
1948
|
+
pendingHostConsoleErrors.push(formatted);
|
|
1949
|
+
if (activeActGuard !== null) {
|
|
1950
|
+
activeActGuard.dialogOpened = true;
|
|
1951
|
+
}
|
|
1952
|
+
void dialog.dismiss().catch(() => {
|
|
1953
|
+
});
|
|
1954
|
+
};
|
|
1955
|
+
const onPageError = (err) => {
|
|
1956
|
+
if (activeActGuard !== null && activeActGuard.stepPageError === null) {
|
|
1957
|
+
activeActGuard.stepPageError = err instanceof Error ? err.stack ?? err.message : String(err);
|
|
1958
|
+
}
|
|
1959
|
+
};
|
|
1960
|
+
const onConsole = (msg) => {
|
|
1961
|
+
if (msg.type() === "error" && activeActGuard?.capturingOutgoingConsole) {
|
|
1962
|
+
const text = msg.text().trim();
|
|
1963
|
+
if (text) activeActGuard.outgoingConsole.push(text);
|
|
1964
|
+
}
|
|
1965
|
+
};
|
|
1966
|
+
page.on("dialog", onDialog);
|
|
1967
|
+
page.on("pageerror", onPageError);
|
|
1968
|
+
page.on("console", onConsole);
|
|
1969
|
+
const trackRev = (rev) => {
|
|
1970
|
+
if (rev > highestRev) highestRev = rev;
|
|
1971
|
+
};
|
|
1972
|
+
const capabilities = {
|
|
1973
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
1974
|
+
allowEval,
|
|
1975
|
+
captureModes: ["viewport-gpu"],
|
|
1976
|
+
trustedInput: true
|
|
1977
|
+
};
|
|
1978
|
+
const assertActive = () => {
|
|
1979
|
+
if (disposed) {
|
|
1980
|
+
throw new DriverError("DRIVER_DISPOSED", "Driver has been disposed.");
|
|
1981
|
+
}
|
|
1982
|
+
};
|
|
1983
|
+
const observeCore = async (observeOptions) => {
|
|
1984
|
+
const params = stripObserveOptions(observeOptions);
|
|
1985
|
+
const raw = await runBridgeCommand(page, preloadSource, {
|
|
1986
|
+
op: "rpc",
|
|
1987
|
+
sessionId,
|
|
1988
|
+
allowEval,
|
|
1989
|
+
minRev: highestRev,
|
|
1990
|
+
method: "observe",
|
|
1991
|
+
...params !== void 0 ? { params } : {}
|
|
1992
|
+
});
|
|
1993
|
+
if (!isObservationSnapshot(raw)) {
|
|
1994
|
+
throw new DriverError("DRIVER_PROTOCOL", "Invalid observe snapshot payload from page.");
|
|
1995
|
+
}
|
|
1996
|
+
trackRev(raw.rev);
|
|
1997
|
+
const mergedDiag = mergeDiagnosticsWithHost(raw.diagnostics, drainHostConsoleErrors());
|
|
1998
|
+
const snap = mergedDiag === raw.diagnostics ? raw : { ...raw, diagnostics: mergedDiag };
|
|
1999
|
+
if (observeOptions?.scope === void 0 && observeOptions?.includeAllText !== true) {
|
|
2000
|
+
lastFullSnapshot = snap;
|
|
2001
|
+
}
|
|
2002
|
+
return snap;
|
|
2003
|
+
};
|
|
2004
|
+
return {
|
|
2005
|
+
capabilities,
|
|
2006
|
+
async observe(observeOptions) {
|
|
2007
|
+
assertActive();
|
|
2008
|
+
return raceWithAbortAndTimeout(
|
|
2009
|
+
() => observeCore(observeOptions),
|
|
2010
|
+
defaultTimeoutMs,
|
|
2011
|
+
"observe",
|
|
2012
|
+
observeOptions?.signal
|
|
2013
|
+
);
|
|
2014
|
+
},
|
|
2015
|
+
async act(actOptions) {
|
|
2016
|
+
assertActive();
|
|
2017
|
+
trackRev(actOptions.rev);
|
|
2018
|
+
const batchTimeoutMs = actOptions.timeoutMs ?? DEFAULT_ACT_TIMEOUT_MS;
|
|
2019
|
+
return raceWithAbortAndTimeout(
|
|
2020
|
+
async () => {
|
|
2021
|
+
let preBatchDiag = null;
|
|
2022
|
+
let baseline = lastFullSnapshot;
|
|
2023
|
+
if (baseline === null) {
|
|
2024
|
+
baseline = await observeCore();
|
|
2025
|
+
preBatchDiag = baseline.diagnostics;
|
|
2026
|
+
}
|
|
2027
|
+
const deadlineMs = Date.now() + batchTimeoutMs;
|
|
2028
|
+
const remainingMs = () => Math.max(25, deadlineMs - Date.now());
|
|
2029
|
+
const totalSteps = actOptions.steps.length;
|
|
2030
|
+
let completedSteps = 0;
|
|
2031
|
+
let interruptedReason;
|
|
2032
|
+
let stepErrorMsg;
|
|
2033
|
+
const guardState = {
|
|
2034
|
+
dialogOpened: false,
|
|
2035
|
+
stepPageError: null,
|
|
2036
|
+
capturingOutgoingConsole: true,
|
|
2037
|
+
outgoingConsole: []
|
|
2038
|
+
};
|
|
2039
|
+
activeActGuard = guardState;
|
|
2040
|
+
const armNavigationWait = () => page.waitForNavigation({
|
|
2041
|
+
waitUntil: "domcontentloaded",
|
|
2042
|
+
timeout: Math.max(500, remainingMs())
|
|
2043
|
+
}).then(
|
|
2044
|
+
() => true,
|
|
2045
|
+
() => false
|
|
2046
|
+
);
|
|
2047
|
+
const settleStepAndAwaitUnload = async (navPromise) => {
|
|
2048
|
+
try {
|
|
2049
|
+
const post = await runBridgeCommand(page, preloadSource, {
|
|
2050
|
+
op: "settleAndInspect",
|
|
2051
|
+
timeoutMs: remainingMs()
|
|
2052
|
+
});
|
|
2053
|
+
if (post.pendingUnload && navPromise !== void 0) {
|
|
2054
|
+
await navPromise;
|
|
2055
|
+
}
|
|
2056
|
+
return post;
|
|
2057
|
+
} catch (err) {
|
|
2058
|
+
if (isExecutionContextDestroyed(err)) {
|
|
2059
|
+
if (navPromise !== void 0) {
|
|
2060
|
+
await navPromise;
|
|
2061
|
+
}
|
|
2062
|
+
return { pendingUnload: true, compileOverlay: null, newDomDialogOpened: false };
|
|
2063
|
+
}
|
|
2064
|
+
throw err;
|
|
2065
|
+
}
|
|
2066
|
+
};
|
|
2067
|
+
try {
|
|
2068
|
+
for (let i = 0; i < totalSteps; i += 1) {
|
|
2069
|
+
const step = actOptions.steps[i];
|
|
2070
|
+
if (step === void 0) break;
|
|
2071
|
+
if (actOptions.signal?.aborted) {
|
|
2072
|
+
throw new DriverError(
|
|
2073
|
+
"DRIVER_TIMEOUT",
|
|
2074
|
+
"Driver 'act' operation aborted by signal."
|
|
2075
|
+
);
|
|
2076
|
+
}
|
|
2077
|
+
guardState.dialogOpened = false;
|
|
2078
|
+
guardState.stepPageError = null;
|
|
2079
|
+
const urlBefore = originAndPathname(page.url());
|
|
2080
|
+
let postInspection = null;
|
|
2081
|
+
try {
|
|
2082
|
+
switch (step.kind) {
|
|
2083
|
+
case "click": {
|
|
2084
|
+
const targetInfo = await runBridgeCommand(
|
|
2085
|
+
page,
|
|
2086
|
+
preloadSource,
|
|
2087
|
+
{
|
|
2088
|
+
op: "prepareActionTarget",
|
|
2089
|
+
target: step.target,
|
|
2090
|
+
timeoutMs: remainingMs(),
|
|
2091
|
+
allowZeroSizeAudio: false,
|
|
2092
|
+
armNavTracker: true,
|
|
2093
|
+
recordDialogsBefore: true
|
|
2094
|
+
}
|
|
2095
|
+
);
|
|
2096
|
+
const navPromise = armNavigationWait();
|
|
2097
|
+
const btn = step.button ?? "left";
|
|
2098
|
+
const count = step.clickCount ?? 1;
|
|
2099
|
+
await page.mouse.click(targetInfo.cx, targetInfo.cy, {
|
|
2100
|
+
button: btn,
|
|
2101
|
+
count
|
|
2102
|
+
});
|
|
2103
|
+
postInspection = await settleStepAndAwaitUnload(navPromise);
|
|
2104
|
+
break;
|
|
2105
|
+
}
|
|
2106
|
+
case "fill": {
|
|
2107
|
+
const prep = await runBridgeCommand(page, preloadSource, {
|
|
2108
|
+
op: "prepareFill",
|
|
2109
|
+
target: step.target,
|
|
2110
|
+
timeoutMs: remainingMs(),
|
|
2111
|
+
recordDialogsBefore: true
|
|
2112
|
+
});
|
|
2113
|
+
if (prep.hadContent) {
|
|
2114
|
+
await page.keyboard.press("Backspace");
|
|
2115
|
+
}
|
|
2116
|
+
if (step.value.length > 0) {
|
|
2117
|
+
if (step.value.length <= 120) {
|
|
2118
|
+
await page.keyboard.type(step.value);
|
|
2119
|
+
} else {
|
|
2120
|
+
await page.keyboard.sendCharacter(step.value);
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
await runBridgeCommand(page, preloadSource, {
|
|
2124
|
+
op: "finalizeFill",
|
|
2125
|
+
value: step.value,
|
|
2126
|
+
submit: step.submit === true
|
|
2127
|
+
});
|
|
2128
|
+
if (step.submit === true) {
|
|
2129
|
+
const navPromise = armNavigationWait();
|
|
2130
|
+
await page.keyboard.press("Enter");
|
|
2131
|
+
try {
|
|
2132
|
+
await page.evaluate(() => {
|
|
2133
|
+
const active = document.activeElement;
|
|
2134
|
+
if (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement) {
|
|
2135
|
+
const BRIDGE_KEY = Symbol.for("@inbrowser/driver:cdp-bridge:v1");
|
|
2136
|
+
const st = Reflect.get(window, BRIDGE_KEY);
|
|
2137
|
+
const unloadArmed = typeof st === "object" && st !== null && Reflect.get(st, "pendingUnload") === true;
|
|
2138
|
+
if (active.form && !unloadArmed) {
|
|
2139
|
+
active.form.requestSubmit();
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
});
|
|
2143
|
+
} catch (subErr) {
|
|
2144
|
+
if (!isExecutionContextDestroyed(subErr)) {
|
|
2145
|
+
throw subErr;
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
postInspection = await settleStepAndAwaitUnload(navPromise);
|
|
2149
|
+
}
|
|
2150
|
+
break;
|
|
2151
|
+
}
|
|
2152
|
+
case "setValue": {
|
|
2153
|
+
await runBridgeCommand(page, preloadSource, {
|
|
2154
|
+
op: "executeSetValue",
|
|
2155
|
+
target: step.target,
|
|
2156
|
+
value: step.value,
|
|
2157
|
+
timeoutMs: remainingMs(),
|
|
2158
|
+
recordDialogsBefore: true
|
|
2159
|
+
});
|
|
2160
|
+
break;
|
|
2161
|
+
}
|
|
2162
|
+
case "select": {
|
|
2163
|
+
const wanted = typeof step.value === "string" ? [step.value] : [...step.value];
|
|
2164
|
+
let selRes = await runBridgeCommand(page, preloadSource, {
|
|
2165
|
+
op: "prepareSelect",
|
|
2166
|
+
target: step.target,
|
|
2167
|
+
values: wanted,
|
|
2168
|
+
timeoutMs: remainingMs(),
|
|
2169
|
+
phase: "initial",
|
|
2170
|
+
recordDialogsBefore: true
|
|
2171
|
+
});
|
|
2172
|
+
if (selRes.kind === "custom") {
|
|
2173
|
+
if (selRes.needsOpenClick) {
|
|
2174
|
+
await page.mouse.click(selRes.comboCx, selRes.comboCy);
|
|
2175
|
+
selRes = await runBridgeCommand(page, preloadSource, {
|
|
2176
|
+
op: "prepareSelect",
|
|
2177
|
+
target: step.target,
|
|
2178
|
+
values: wanted,
|
|
2179
|
+
timeoutMs: remainingMs(),
|
|
2180
|
+
phase: "options",
|
|
2181
|
+
recordDialogsBefore: false
|
|
2182
|
+
});
|
|
2183
|
+
}
|
|
2184
|
+
for (const pt of selRes.optionPoints) {
|
|
2185
|
+
await page.mouse.click(pt.cx, pt.cy);
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
break;
|
|
2189
|
+
}
|
|
2190
|
+
case "press": {
|
|
2191
|
+
await runBridgeCommand(page, preloadSource, {
|
|
2192
|
+
op: "preparePress",
|
|
2193
|
+
...step.target !== void 0 ? { target: step.target } : {},
|
|
2194
|
+
timeoutMs: remainingMs(),
|
|
2195
|
+
recordDialogsBefore: true
|
|
2196
|
+
});
|
|
2197
|
+
const navPromise = armNavigationWait();
|
|
2198
|
+
const chord = parseKeyChord(step.key);
|
|
2199
|
+
for (const mod of chord.modifiers) {
|
|
2200
|
+
await page.keyboard.down(mod);
|
|
2201
|
+
}
|
|
2202
|
+
try {
|
|
2203
|
+
await page.keyboard.press(chord.mainKey);
|
|
2204
|
+
} finally {
|
|
2205
|
+
for (const mod of [...chord.modifiers].reverse()) {
|
|
2206
|
+
await page.keyboard.up(mod);
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
postInspection = await settleStepAndAwaitUnload(navPromise);
|
|
2210
|
+
break;
|
|
2211
|
+
}
|
|
2212
|
+
case "drag": {
|
|
2213
|
+
const fromInfo = await runBridgeCommand(
|
|
2214
|
+
page,
|
|
2215
|
+
preloadSource,
|
|
2216
|
+
{
|
|
2217
|
+
op: "prepareActionTarget",
|
|
2218
|
+
target: step.from,
|
|
2219
|
+
timeoutMs: remainingMs(),
|
|
2220
|
+
allowZeroSizeAudio: false,
|
|
2221
|
+
armNavTracker: false,
|
|
2222
|
+
recordDialogsBefore: true
|
|
2223
|
+
}
|
|
2224
|
+
);
|
|
2225
|
+
let toX;
|
|
2226
|
+
let toY;
|
|
2227
|
+
if ("target" in step.to) {
|
|
2228
|
+
const toInfo = await runBridgeCommand(
|
|
2229
|
+
page,
|
|
2230
|
+
preloadSource,
|
|
2231
|
+
{
|
|
2232
|
+
op: "prepareActionTarget",
|
|
2233
|
+
target: step.to.target,
|
|
2234
|
+
timeoutMs: remainingMs(),
|
|
2235
|
+
allowZeroSizeAudio: false,
|
|
2236
|
+
armNavTracker: false,
|
|
2237
|
+
recordDialogsBefore: false
|
|
2238
|
+
}
|
|
2239
|
+
);
|
|
2240
|
+
toX = toInfo.cx;
|
|
2241
|
+
toY = toInfo.cy;
|
|
2242
|
+
} else if ("deltaX" in step.to) {
|
|
2243
|
+
toX = fromInfo.cx + step.to.deltaX;
|
|
2244
|
+
toY = fromInfo.cy + step.to.deltaY;
|
|
2245
|
+
} else {
|
|
2246
|
+
toX = step.to.clientX;
|
|
2247
|
+
toY = step.to.clientY;
|
|
2248
|
+
}
|
|
2249
|
+
const count = Math.max(1, step.steps ?? 5);
|
|
2250
|
+
await page.mouse.move(fromInfo.cx, fromInfo.cy);
|
|
2251
|
+
await page.mouse.down();
|
|
2252
|
+
try {
|
|
2253
|
+
for (let s = 1; s <= count; s += 1) {
|
|
2254
|
+
const nx = fromInfo.cx + (toX - fromInfo.cx) * s / count;
|
|
2255
|
+
const ny = fromInfo.cy + (toY - fromInfo.cy) * s / count;
|
|
2256
|
+
await page.mouse.move(nx, ny);
|
|
2257
|
+
}
|
|
2258
|
+
} finally {
|
|
2259
|
+
await page.mouse.up();
|
|
2260
|
+
}
|
|
2261
|
+
break;
|
|
2262
|
+
}
|
|
2263
|
+
case "navigate": {
|
|
2264
|
+
const navTimeout = Math.max(500, remainingMs());
|
|
2265
|
+
if ("url" in step) {
|
|
2266
|
+
const resolvedUrl = new URL(step.url, page.url()).href;
|
|
2267
|
+
await page.goto(resolvedUrl, {
|
|
2268
|
+
waitUntil: "domcontentloaded",
|
|
2269
|
+
timeout: navTimeout
|
|
2270
|
+
});
|
|
2271
|
+
} else if (step.action === "reload") {
|
|
2272
|
+
await page.reload({ waitUntil: "domcontentloaded", timeout: navTimeout });
|
|
2273
|
+
} else if (step.action === "back") {
|
|
2274
|
+
await page.goBack({ waitUntil: "domcontentloaded", timeout: navTimeout });
|
|
2275
|
+
} else {
|
|
2276
|
+
await page.goForward({ waitUntil: "domcontentloaded", timeout: navTimeout });
|
|
2277
|
+
}
|
|
2278
|
+
postInspection = {
|
|
2279
|
+
pendingUnload: true,
|
|
2280
|
+
compileOverlay: null,
|
|
2281
|
+
newDomDialogOpened: false
|
|
2282
|
+
};
|
|
2283
|
+
break;
|
|
2284
|
+
}
|
|
2285
|
+
case "waitFor": {
|
|
2286
|
+
const stepLimit = step.timeoutMs !== void 0 ? actOptions.timeoutMs !== void 0 ? Math.min(remainingMs(), step.timeoutMs) : step.timeoutMs : remainingMs();
|
|
2287
|
+
await runBridgeCommand(page, preloadSource, {
|
|
2288
|
+
op: "executeWaitFor",
|
|
2289
|
+
...step.target !== void 0 ? { target: step.target } : {},
|
|
2290
|
+
...step.text !== void 0 ? { text: step.text } : {},
|
|
2291
|
+
...step.state !== void 0 ? { state: step.state } : {},
|
|
2292
|
+
...step.idleMs !== void 0 ? { idleMs: step.idleMs } : {},
|
|
2293
|
+
timeoutMs: Math.max(10, stepLimit),
|
|
2294
|
+
recordDialogsBefore: true
|
|
2295
|
+
});
|
|
2296
|
+
break;
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
completedSteps = i + 1;
|
|
2300
|
+
if (postInspection === null) {
|
|
2301
|
+
postInspection = await settleStepAndAwaitUnload();
|
|
2302
|
+
}
|
|
2303
|
+
} catch (err) {
|
|
2304
|
+
interruptedReason = "step_error";
|
|
2305
|
+
stepErrorMsg = formatStepError(toDriverError(err, "Step execution failed."));
|
|
2306
|
+
break;
|
|
2307
|
+
}
|
|
2308
|
+
if (guardState.stepPageError !== null) {
|
|
2309
|
+
interruptedReason = "step_error";
|
|
2310
|
+
stepErrorMsg = guardState.stepPageError;
|
|
2311
|
+
break;
|
|
2312
|
+
}
|
|
2313
|
+
if (postInspection.compileOverlay !== null) {
|
|
2314
|
+
interruptedReason = "compile_error";
|
|
2315
|
+
break;
|
|
2316
|
+
}
|
|
2317
|
+
if (guardState.dialogOpened) {
|
|
2318
|
+
interruptedReason = "dialog_opened";
|
|
2319
|
+
break;
|
|
2320
|
+
}
|
|
2321
|
+
if (i < totalSteps - 1) {
|
|
2322
|
+
if (postInspection.newDomDialogOpened) {
|
|
2323
|
+
interruptedReason = "dialog_opened";
|
|
2324
|
+
break;
|
|
2325
|
+
}
|
|
2326
|
+
if (originAndPathname(page.url()) !== urlBefore) {
|
|
2327
|
+
interruptedReason = "navigation";
|
|
2328
|
+
break;
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
} finally {
|
|
2333
|
+
activeActGuard = null;
|
|
2334
|
+
}
|
|
2335
|
+
if (guardState.outgoingConsole.length > 0) {
|
|
2336
|
+
pendingHostConsoleErrors.push(...guardState.outgoingConsole);
|
|
2337
|
+
}
|
|
2338
|
+
const after = await observeCore();
|
|
2339
|
+
let finalDiagnostics = after.diagnostics;
|
|
2340
|
+
if (preBatchDiag !== null) {
|
|
2341
|
+
finalDiagnostics = {
|
|
2342
|
+
compileOverlay: after.diagnostics.compileOverlay ?? preBatchDiag.compileOverlay,
|
|
2343
|
+
consoleErrors: [
|
|
2344
|
+
...preBatchDiag.consoleErrors,
|
|
2345
|
+
...after.diagnostics.consoleErrors.filter(
|
|
2346
|
+
(m) => !preBatchDiag.consoleErrors.includes(m)
|
|
2347
|
+
)
|
|
2348
|
+
],
|
|
2349
|
+
pageErrors: [...preBatchDiag.pageErrors, ...after.diagnostics.pageErrors],
|
|
2350
|
+
networkFailures: [
|
|
2351
|
+
...preBatchDiag.networkFailures,
|
|
2352
|
+
...after.diagnostics.networkFailures
|
|
2353
|
+
]
|
|
2354
|
+
};
|
|
2355
|
+
}
|
|
2356
|
+
return {
|
|
2357
|
+
completedSteps,
|
|
2358
|
+
totalSteps,
|
|
2359
|
+
...interruptedReason !== void 0 ? { interruptedReason } : {},
|
|
2360
|
+
...stepErrorMsg !== void 0 ? { error: stepErrorMsg } : {},
|
|
2361
|
+
rev: after.rev,
|
|
2362
|
+
url: after.url,
|
|
2363
|
+
title: after.title,
|
|
2364
|
+
diff: diffSnapshots(baseline, after),
|
|
2365
|
+
diagnostics: finalDiagnostics
|
|
2366
|
+
};
|
|
2367
|
+
},
|
|
2368
|
+
Math.max(defaultTimeoutMs, batchTimeoutMs + 3e3),
|
|
2369
|
+
"act",
|
|
2370
|
+
actOptions.signal
|
|
2371
|
+
);
|
|
2372
|
+
},
|
|
2373
|
+
async capture(captureOptions) {
|
|
2374
|
+
assertActive();
|
|
2375
|
+
return raceWithAbortAndTimeout(
|
|
2376
|
+
async () => {
|
|
2377
|
+
if (captureOptions.mode === "screenshot") {
|
|
2378
|
+
const format = captureOptions.format ?? "webp";
|
|
2379
|
+
const mimeType = format === "png" ? "image/png" : "image/webp";
|
|
2380
|
+
const webpQuality = Math.max(
|
|
2381
|
+
0,
|
|
2382
|
+
Math.min(100, Math.round((captureOptions.quality ?? 0.85) * 100))
|
|
2383
|
+
);
|
|
2384
|
+
const clipInfo = await runBridgeCommand(page, preloadSource, {
|
|
2385
|
+
op: "resolveScreenshotClip",
|
|
2386
|
+
...captureOptions.target !== void 0 ? { target: captureOptions.target } : {},
|
|
2387
|
+
timeoutMs: defaultTimeoutMs
|
|
2388
|
+
});
|
|
2389
|
+
const rawBytes = await page.screenshot({
|
|
2390
|
+
type: format,
|
|
2391
|
+
...format === "webp" ? { quality: webpQuality } : {},
|
|
2392
|
+
...clipInfo.clip !== null ? { clip: clipInfo.clip } : {}
|
|
2393
|
+
});
|
|
2394
|
+
const bytes = new Uint8Array(
|
|
2395
|
+
rawBytes.buffer,
|
|
2396
|
+
rawBytes.byteOffset,
|
|
2397
|
+
rawBytes.byteLength
|
|
2398
|
+
).slice();
|
|
2399
|
+
const dims = readImageDimensions(
|
|
2400
|
+
bytes,
|
|
2401
|
+
format,
|
|
2402
|
+
clipInfo.clip?.width ?? clipInfo.viewportWidth,
|
|
2403
|
+
clipInfo.clip?.height ?? clipInfo.viewportHeight
|
|
2404
|
+
);
|
|
2405
|
+
return {
|
|
2406
|
+
mimeType,
|
|
2407
|
+
bytes,
|
|
2408
|
+
width: dims.width,
|
|
2409
|
+
height: dims.height,
|
|
2410
|
+
modeUsed: "viewport-gpu"
|
|
2411
|
+
};
|
|
2412
|
+
}
|
|
2413
|
+
if (captureOptions.mode === "start_recording") {
|
|
2414
|
+
if (activeRecording !== null) {
|
|
2415
|
+
throw new DriverError("DRIVER_PROTOCOL", "A capture recording is already active.");
|
|
2416
|
+
}
|
|
2417
|
+
const clipInfo = await runBridgeCommand(page, preloadSource, {
|
|
2418
|
+
op: "resolveScreenshotClip",
|
|
2419
|
+
timeoutMs: defaultTimeoutMs
|
|
2420
|
+
});
|
|
2421
|
+
const cdpSession = await page.createCDPSession();
|
|
2422
|
+
const frames = [];
|
|
2423
|
+
try {
|
|
2424
|
+
const initialFrame = await cdpSession.send("Page.captureScreenshot", {
|
|
2425
|
+
format: "jpeg",
|
|
2426
|
+
quality: 80
|
|
2427
|
+
});
|
|
2428
|
+
if (initialFrame.data.length > 0) {
|
|
2429
|
+
frames.push(initialFrame.data);
|
|
2430
|
+
}
|
|
2431
|
+
const recState = {
|
|
2432
|
+
session: cdpSession,
|
|
2433
|
+
startedAtMs: Date.now(),
|
|
2434
|
+
frames,
|
|
2435
|
+
width: clipInfo.viewportWidth,
|
|
2436
|
+
height: clipInfo.viewportHeight,
|
|
2437
|
+
detachListener: () => {
|
|
2438
|
+
}
|
|
2439
|
+
};
|
|
2440
|
+
const onFrame = (ev) => {
|
|
2441
|
+
if (frames.length < 180 && ev.data.length > 0) {
|
|
2442
|
+
frames.push(ev.data);
|
|
2443
|
+
}
|
|
2444
|
+
if (ev.metadata.deviceWidth > 0 && ev.metadata.deviceHeight > 0) {
|
|
2445
|
+
recState.width = ev.metadata.deviceWidth;
|
|
2446
|
+
recState.height = ev.metadata.deviceHeight;
|
|
2447
|
+
}
|
|
2448
|
+
void cdpSession.send("Page.screencastFrameAck", { sessionId: ev.sessionId }).catch(() => {
|
|
2449
|
+
});
|
|
2450
|
+
};
|
|
2451
|
+
cdpSession.on("Page.screencastFrame", onFrame);
|
|
2452
|
+
const detach = () => {
|
|
2453
|
+
cdpSession.off("Page.screencastFrame", onFrame);
|
|
2454
|
+
};
|
|
2455
|
+
activeRecording = {
|
|
2456
|
+
...recState,
|
|
2457
|
+
detachListener: detach
|
|
2458
|
+
};
|
|
2459
|
+
await cdpSession.send("Page.startScreencast", {
|
|
2460
|
+
format: "jpeg",
|
|
2461
|
+
quality: 80,
|
|
2462
|
+
everyNthFrame: 1
|
|
2463
|
+
});
|
|
2464
|
+
return {
|
|
2465
|
+
mimeType: "video/webm",
|
|
2466
|
+
bytes: new Uint8Array(0),
|
|
2467
|
+
width: clipInfo.viewportWidth,
|
|
2468
|
+
height: clipInfo.viewportHeight,
|
|
2469
|
+
modeUsed: "viewport-gpu",
|
|
2470
|
+
durationMs: 0
|
|
2471
|
+
};
|
|
2472
|
+
} catch (err) {
|
|
2473
|
+
activeRecording = null;
|
|
2474
|
+
await cdpSession.detach().catch(() => {
|
|
2475
|
+
});
|
|
2476
|
+
throw err;
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
if (activeRecording === null) {
|
|
2480
|
+
throw new DriverError("DRIVER_PROTOCOL", "No active capture recording to stop.");
|
|
2481
|
+
}
|
|
2482
|
+
const rec = activeRecording;
|
|
2483
|
+
activeRecording = null;
|
|
2484
|
+
rec.detachListener();
|
|
2485
|
+
await rec.session.send("Page.stopScreencast").catch(() => {
|
|
2486
|
+
});
|
|
2487
|
+
try {
|
|
2488
|
+
const finalShot = await rec.session.send("Page.captureScreenshot", {
|
|
2489
|
+
format: "jpeg",
|
|
2490
|
+
quality: 80
|
|
2491
|
+
});
|
|
2492
|
+
if (finalShot.data.length > 0) {
|
|
2493
|
+
rec.frames.push(finalShot.data);
|
|
2494
|
+
}
|
|
2495
|
+
} catch {
|
|
2496
|
+
}
|
|
2497
|
+
await rec.session.detach().catch(() => {
|
|
2498
|
+
});
|
|
2499
|
+
const durationMs = Math.max(1, Date.now() - rec.startedAtMs);
|
|
2500
|
+
const encoded = await page.evaluate(encodeFramesToWebmInPage, {
|
|
2501
|
+
frames: rec.frames,
|
|
2502
|
+
fallbackWidth: rec.width,
|
|
2503
|
+
fallbackHeight: rec.height
|
|
2504
|
+
});
|
|
2505
|
+
return {
|
|
2506
|
+
mimeType: encoded.mimeType,
|
|
2507
|
+
bytes: new Uint8Array(encoded.bytesArray),
|
|
2508
|
+
width: encoded.width,
|
|
2509
|
+
height: encoded.height,
|
|
2510
|
+
modeUsed: "viewport-gpu",
|
|
2511
|
+
durationMs
|
|
2512
|
+
};
|
|
2513
|
+
},
|
|
2514
|
+
defaultTimeoutMs,
|
|
2515
|
+
"capture",
|
|
2516
|
+
captureOptions.signal
|
|
2517
|
+
);
|
|
2518
|
+
},
|
|
2519
|
+
async eval(evalOptions) {
|
|
2520
|
+
assertActive();
|
|
2521
|
+
if (!allowEval) {
|
|
2522
|
+
throw new DriverError("DRIVER_EVAL_DISABLED", "Evaluation disabled; pass allowEval: true.");
|
|
2523
|
+
}
|
|
2524
|
+
const timeoutMs = evalOptions.timeoutMs ?? defaultTimeoutMs;
|
|
2525
|
+
const params = {
|
|
2526
|
+
expression: evalOptions.expression,
|
|
2527
|
+
...evalOptions.timeoutMs !== void 0 ? { timeoutMs: evalOptions.timeoutMs } : {}
|
|
2528
|
+
};
|
|
2529
|
+
const raw = await raceWithAbortAndTimeout(
|
|
2530
|
+
() => runBridgeCommand(page, preloadSource, {
|
|
2531
|
+
op: "rpc",
|
|
2532
|
+
sessionId,
|
|
2533
|
+
allowEval,
|
|
2534
|
+
minRev: highestRev,
|
|
2535
|
+
method: "eval",
|
|
2536
|
+
params
|
|
2537
|
+
}),
|
|
2538
|
+
Math.max(defaultTimeoutMs, timeoutMs + 2e3),
|
|
2539
|
+
"eval",
|
|
2540
|
+
evalOptions.signal
|
|
2541
|
+
);
|
|
2542
|
+
if (!isEvalResult(raw)) {
|
|
2543
|
+
throw new DriverError("DRIVER_PROTOCOL", "Invalid eval result payload from page.");
|
|
2544
|
+
}
|
|
2545
|
+
const mergedDiag = mergeDiagnosticsWithHost(raw.diagnostics, drainHostConsoleErrors());
|
|
2546
|
+
return mergedDiag === raw.diagnostics ? raw : { value: raw.value, diagnostics: mergedDiag };
|
|
2547
|
+
},
|
|
2548
|
+
dispose() {
|
|
2549
|
+
if (disposed) return;
|
|
2550
|
+
disposed = true;
|
|
2551
|
+
if (activeRecording !== null) {
|
|
2552
|
+
const rec = activeRecording;
|
|
2553
|
+
activeRecording = null;
|
|
2554
|
+
rec.detachListener();
|
|
2555
|
+
void rec.session.detach().catch(() => {
|
|
2556
|
+
});
|
|
2557
|
+
}
|
|
2558
|
+
page.off("dialog", onDialog);
|
|
2559
|
+
page.off("pageerror", onPageError);
|
|
2560
|
+
page.off("console", onConsole);
|
|
2561
|
+
void browser.disconnect().catch(() => {
|
|
2562
|
+
});
|
|
2563
|
+
}
|
|
2564
|
+
};
|
|
2565
|
+
}
|
|
2566
|
+
export {
|
|
2567
|
+
connectPuppeteerDriver
|
|
2568
|
+
};
|
|
2569
|
+
//# sourceMappingURL=puppeteer.js.map
|