@@ -4,11 +4,16 @@ const {targetKey}=require('./browser-wire.cjs');
44const refused = message => Object . assign ( new Error ( message ) , { dispatched :false } ) ;
55const pause = ms => new Promise ( resolve => setTimeout ( resolve , ms ) ) ;
66const BUTTONS = { left :1 , right :2 , middle :4 } ;
7- function normalizeURL ( value ) { const raw = String ( value || '' ) . trim ( ) ; if ( ! raw ) throw refused ( 'Browser URL required' ) ; return / ^ [ a - z ] [ a - z 0 - 9 + . - ] * : / i. test ( raw ) ?raw :'https://' + raw ; }
7+ function normalizeURL ( value ) {
8+ const raw = String ( value || '' ) . trim ( ) ; if ( ! raw ) throw refused ( 'Browser URL required' ) ;
9+ if ( / ^ [ a - z ] [ a - z 0 - 9 + . - ] * : / i. test ( raw ) && ! / ^ [ ^ / ] + : \d + ( \/ | $ ) / . test ( raw ) ) return raw ;
10+ const host = raw . startsWith ( '[' ) ?raw . slice ( 0 , raw . indexOf ( ']' ) + 1 ) :raw . split ( / [ / : ? # ] / ) [ 0 ] . toLowerCase ( ) ;
11+ return ( [ 'localhost' , '127.0.0.1' , '[::1]' , '0.0.0.0' ] . includes ( host ) || host . endsWith ( '.localhost' ) ?'http://' :'https://' ) + raw ;
12+ }
813function createBrowserActions ( ) {
914 const references = new Map ( ) , pressed = new Map ( ) ;
1015 return async function execute ( c ) {
11- const { op, args :a , target} = c . payload , key = targetKey ( target ) , timeout = Math . max ( 1 , Math . min ( 14000 , Number ( a . timeoutMs ) || 14000 ) ) ;
16+ const { op, args :a , target} = c . payload , key = targetKey ( target ) , timeout = Math . max ( 1 , Math . min ( 14000 , Number ( a . timeoutMs ) || 14000 ) ) , deadline = Date . now ( ) + timeout ;
1217 const status = ( ) => { const m = c . metadata ( ) ; return { page :target . owner , url :m . url , title :m . title , loading :m . loading , tabs :c . list ( ) . map ( ( t , index ) => ( { id :t . tabId , index, url :t . url , title :t . title , active :t . active } ) ) , engine :'electron' } ; } ;
1318 const command = async ( method , params ) => { const answer = await c . command ( method , params ) ; return answer . result ; } ;
1419 const evaluate = async ( expression , returnByValue = true ) => {
@@ -21,11 +26,34 @@ function createBrowserActions(){
2126 const backendNodeId = references . get ( key ) ?. get ( String ( a . ref ) ) ; if ( ! backendNodeId ) throw refused ( 'Unknown or stale Browser reference; take a new snapshot' ) ;
2227 return ( await command ( 'DOM.resolveNode' , { backendNodeId} ) ) . object ?. objectId ;
2328 }
24- let selector = a . selector , locator = a . locator ;
25- if ( locator ) { if ( String ( locator ) . startsWith ( 'css=' ) ) selector = String ( locator ) . slice ( 4 ) ; else if ( ! / ^ [ a - z - ] + = / . test ( String ( locator ) ) ) selector = String ( locator ) ; else throw refused ( 'This Browser locator engine is not yet supported; use a snapshot reference or CSS selector' ) ; }
26- if ( ! selector ) return null ;
27- const start = Date . now ( ) ;
28- do { const value = await evaluate ( 'document.querySelector(' + JSON . stringify ( String ( selector ) ) + ')' , false ) ; if ( value ?. objectId ) return value . objectId ; if ( Date . now ( ) - start >= timeout ) break ; await pause ( 75 ) ; } while ( true ) ;
29+ let selector = a . selector , locator = a . locator , role = null , text = null ;
30+ if ( locator ) {
31+ const source = String ( locator ) ;
32+ if ( source . startsWith ( 'css=' ) ) selector = source . slice ( 4 ) ;
33+ else if ( source . startsWith ( 'text=' ) ) { const raw = source . slice ( 5 ) ; text = { value :raw , exact :false } ; if ( / ^ ( [ " ' ] ) .* \1$ / . test ( raw ) ) text = { value :raw . slice ( 1 , - 1 ) , exact :true } ; }
34+ else if ( source . startsWith ( 'role=' ) ) {
35+ const match = / ^ r o l e = ( [ \w - ] + ) (?: \[ n a m e = (?: " ( [ ^ " \\ ] * ) " | ' ( [ ^ ' \\ ] * ) ' ) \] ) ? $ / . exec ( source ) ;
36+ if ( ! match ) throw refused ( 'Use role=button[name="Name"], text=Text, CSS, or a snapshot reference' ) ;
37+ role = { name :match [ 1 ] , label :match [ 2 ] ?? match [ 3 ] } ;
38+ } else if ( ! / ^ [ a - z - ] + = / . test ( source ) ) selector = source ;
39+ else throw refused ( 'Unsupported Browser locator engine; use a snapshot reference or CSS selector' ) ;
40+ }
41+ if ( ! selector && ! role && ! text ) return null ;
42+ do {
43+ if ( role ) {
44+ const ax = await command ( 'Accessibility.getFullAXTree' , { } ) ;
45+ const node = ( ax . nodes || [ ] ) . find ( n => ! n . ignored && n . role ?. value === role . name && ( role . label === undefined || String ( n . name ?. value || '' ) === role . label ) && n . backendDOMNodeId ) ;
46+ if ( node ) return ( await command ( 'DOM.resolveNode' , { backendNodeId :node . backendDOMNodeId } ) ) . object ?. objectId ;
47+ } else {
48+ const expression = text ?'(' + function ( t ) {
49+ const normalize = s => String ( s || '' ) . replace ( / \s + / g, ' ' ) . trim ( ) ;
50+ const matches = e => { const s = normalize ( e . innerText || e . value ) ; return t . exact ?s === normalize ( t . value ) :s . includes ( normalize ( t . value ) ) ; } ;
51+ return [ ...document . querySelectorAll ( 'body *' ) ] . find ( e => ! [ 'SCRIPT' , 'STYLE' , 'NOSCRIPT' ] . includes ( e . tagName ) && e . getClientRects ( ) . length && matches ( e ) && ! [ ...e . children ] . some ( matches ) ) || null ;
52+ } . toString ( ) + ')(' + JSON . stringify ( text ) + ')' :'document.querySelector(' + JSON . stringify ( String ( selector ) ) + ')' ;
53+ const value = await evaluate ( expression , false ) ; if ( value ?. objectId ) return value . objectId ;
54+ }
55+ if ( Date . now ( ) >= deadline ) break ; await pause ( 75 ) ;
56+ } while ( true ) ;
2957 throw refused ( 'Browser target was not found' ) ;
3058 }
3159 async function useObject ( fn ) { const id = await object ( ) ; if ( ! id ) throw refused ( 'Browser target required' ) ; try { return await fn ( id ) ; } finally { void command ( 'Runtime.releaseObject' , { objectId :id } ) . catch ( ( ) => { } ) ; } }
@@ -49,7 +77,7 @@ function createBrowserActions(){
4977 if ( ! a . url && op === 'open' ) return status ( ) ;
5078 const url = normalizeURL ( a . url ) , before = c . navigation ;
5179 if ( c . grant . operations . includes ( 'navigate' ) ) await c . invoke ( 'navigate' , { url} ) ; else await command ( 'Page.navigate' , { url} ) ;
52- await c . waitNavigation ( { before, readiness :a . readiness === 'none' ?'commit' :'load' , timeoutMs :timeout } ) ; return status ( ) ;
80+ await c . waitNavigation ( { before, readiness :a . readiness === 'none' ?'commit' :a . readiness === 'domContentLoaded' ? 'domContentLoaded' : 'load' , timeoutMs :timeout } ) ; return status ( ) ;
5381 }
5482 case 'back' :case 'forward' :case 'reload' :{
5583 if ( c . grant . operations . includes ( 'navigate' ) ) return c . invoke ( op === 'reload' ?'reload' :'history' , op === 'reload' ?{ } :{ direction :op } ) ;
@@ -64,13 +92,19 @@ function createBrowserActions(){
6492 const tabs = c . list ( ) ; return { page :target . owner , active :tabs . findIndex ( t => t . active ) , tabs :tabs . map ( ( t , index ) => ( { id :t . tabId , index, url :t . url , title :t . title , active :t . active } ) ) } ;
6593 }
6694 case 'snapshot' :{
67- if ( a . screenshot ) throw refused ( 'Direct-guest snapshot images require the explicit capture adapter' ) ;
6895 const page = await evaluate ( SNAPSHOT_SCRIPT ) , ax = await command ( 'Accessibility.getFullAXTree' , { } ) , refs = new Map ( ) , lines = [ ] ;
6996 for ( const node of ax . nodes || [ ] ) { if ( node . ignored ) continue ; const role = String ( node . role ?. value || '' ) , name = String ( node . name ?. value || '' ) . slice ( 0 , 300 ) ; if ( ! role || role === 'generic' ) continue ;
7097 const id = node . backendDOMNodeId ; if ( Number . isSafeInteger ( id ) && id > 0 ) refs . set ( 'e' + id , id ) ;
7198 lines . push ( '- ' + role + ( name ?' ' + JSON . stringify ( name ) :'' ) + ( id ?' [ref=e' + id + ']' :'' ) ) ; if ( lines . length >= 600 ) break ;
7299 }
73- references . set ( key , refs ) ; const meta = c . metadata ( ) ; return { url :meta . url , title :meta . title , ...page , outline :lines . join ( '\n' ) , console :meta . console . slice ( - 50 ) } ;
100+ references . set ( key , refs ) ; const meta = c . metadata ( ) ;
101+ let screenshot ;
102+ if ( a . screenshot ) {
103+ const capture = await command ( 'Page.captureScreenshot' , { format :'png' , captureBeyondViewport :false } ) , metrics = await command ( 'Page.getLayoutMetrics' , { } ) , v = metrics . cssVisualViewport || metrics . visualViewport ;
104+ if ( typeof capture . data !== 'string' || capture . data . length > 700000 ) throw refused ( 'Browser screenshot exceeds the private image limit; request a text snapshot' ) ;
105+ screenshot = { mimeType :'image/png' , data :capture . data , width :Math . round ( v . clientWidth ) , height :Math . round ( v . clientHeight ) } ;
106+ }
107+ return { url :meta . url , title :meta . title , ...page , outline :lines . join ( '\n' ) , console :meta . console . slice ( - 50 ) , ...( screenshot ?{ screenshot} :{ } ) } ;
74108 }
75109 case 'text' :{
76110 const full = a . selector || a . locator || a . ref ?await useObject ( id => onObject ( id , 'function(){return this.innerText||"";}' ) ) :await evaluate ( TEXT_SCRIPT ) ;
@@ -100,7 +134,9 @@ function createBrowserActions(){
100134 const modifiers = mods . reduce ( ( v , m ) => v | ( { Alt :1 , Control :2 , Meta :4 , Shift :8 } [ m ] ) , 0 ) , virtual = { Enter :13 , Tab :9 , Escape :27 , Backspace :8 , Delete :46 , ArrowLeft :37 , ArrowUp :38 , ArrowRight :39 , ArrowDown :40 , Home :36 , End :35 , PageUp :33 , PageDown :34 } ;
101135 if ( keyName . length === 1 && ! modifiers ) { await command ( 'Input.insertText' , { text :keyName } ) ; return { } ; }
102136 const windowsVirtualKeyCode = virtual [ keyName ] ?? ( keyName . length === 1 ?keyName . toUpperCase ( ) . charCodeAt ( 0 ) :0 ) ; if ( ! windowsVirtualKeyCode ) throw refused ( 'Unsupported Browser key' ) ;
103- const params = { key :keyName , modifiers, windowsVirtualKeyCode} ; await command ( 'Input.dispatchKeyEvent' , { type :'rawKeyDown' , ...params } ) ; await command ( 'Input.dispatchKeyEvent' , { type :'keyUp' , ...params } ) ; return { } ;
137+ const params = { key :keyName , modifiers, windowsVirtualKeyCode} ;
138+ await command ( 'Input.dispatchKeyEvent' , { type :'keyDown' , ...params , ...( keyName === 'Enter' ?{ text :'\r' , unmodifiedText :'\r' } :{ } ) } ) ;
139+ await command ( 'Input.dispatchKeyEvent' , { type :'keyUp' , ...params } ) ; return { } ;
104140 }
105141 case 'scroll' :{
106142 const dx = Number ( a . dx ?? a . deltaX ?? 0 ) , dy = Number ( a . dy ?? a . deltaY ?? 0 ) ; if ( ! Number . isFinite ( dx ) || ! Number . isFinite ( dy ) ) throw refused ( 'Invalid Browser wheel delta' ) ;
0 commit comments